Programs & Examples On #Fedora

Fedora is an RPM-based, general purpose collection of software, including an operating system based on the Linux kernel, developed by the community-supported Fedora Project and sponsored by Red Hat.

What does "zend_mm_heap corrupted" mean

I had this error using the Mongo 2.2 driver for PHP:

$collection = $db->selectCollection('post');
$collection->ensureIndex(array('someField', 'someOtherField', 'yetAnotherField')); 

^^DOESN'T WORK

$collection = $db->selectCollection('post');
$collection->ensureIndex(array('someField', 'someOtherField')); 
$collection->ensureIndex(array('yetAnotherField')); 

^^ WORKS! (?!)

How do I install g++ for Fedora?

The package you're looking for is confusingly named gcc-c++.

Permission denied on accessing host directory in Docker

I verified that chcon -Rt svirt_sandbox_file_t /path/to/volume does work and you don't have to run as a privileged container.

This is on:

  • Docker version 0.11.1-dev, build 02d20af/0.11.1
  • CentOS 7 as the host and container with SELinux enabled.

curl: (6) Could not resolve host: google.com; Name or service not known

I have today similar problem. But weirder.

  • host - works host pl.archive.ubuntu.com
  • dig - works on default and on all other DNS's dig pl.archive.ubuntu.com, dig @127.0.1.1 pl.archive.ubuntu.com
  • curl - doesn't work! but for some addresses it does. WEIRD! Same in Ruby, APT and many more.
$ curl -v http://google.com/
*   Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact

$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com

Revelation

Eventually I used strace on curl and found that it was connection to nscd deamon.

connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0

Solution

I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!

systemctl restart nscd.service

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

These are the steps to share a folder from Windows to Linux Virtual Box

Step 1 : Install Virtual Box Extension Pack from this link

Step 2: Install Oracle Guest Additions:

By pressing -> Right Ctrl and d together

Run the command sudo /media/VBOXADDITIONS_4.*/VBoxLinuxAdditions.run

Step 3 : Create Shared Folder by Clicking Settings in Vbox Then Shared Folders -> + and give a name to the folder (e.g. VB_Share) Select the Shared Folder path on Windows (e.g. D:\VBox_Share)

Step 4: Create a folder in named VB_share in home\user-name (e.g. home\satish\VB_share) and share mkdir VB_Share chmod 777 VB_share

Step 5: Run the following command sudo mount –t vboxsf vBox_Share VB_Share

How do I check my gcc C++ compiler version for my Eclipse?

#include <stdio.h>

int main() {

  printf("gcc version: %d.%d.%d\n",__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__);
  return 0;
}

How to list the contents of a package using YUM?

rpm -ql [packageName]

Example

# rpm -ql php-fpm

/etc/php-fpm.conf
/etc/php-fpm.d
/etc/php-fpm.d/www.conf
/etc/sysconfig/php-fpm
...
/run/php-fpm
/usr/lib/systemd/system/php-fpm.service
/usr/sbin/php-fpm
/usr/share/doc/php-fpm-5.6.0
/usr/share/man/man8/php-fpm.8.gz
...
/var/lib/php/sessions
/var/log/php-fpm

No need to install yum-utils, or to know the location of the rpm file.

What's the default password of mariadb on fedora?

Lucups, Floris is right, but you comment that this didn't solve your problem. I ran into the same symptoms, where mysql (mariadb) will not accept the blank password it should accept, and '/var/lib/mysql' does not exist.

I found that this Moonpoint.com page was on-point. Perhaps, like me, you tried to start the mysqld service instead of the mariadb service. Try:

systemctl start mariadb.service
systemctl status mysqld service

Followed by the usual:

mysql_secure_installation

How to view unallocated free space on a hard disk through terminal

You might want to use the fdisk -l /dev/sda command to see the partitioning of your sda disk. The "free space" should be some unused partition (or lack of).

How can I find the version of the Fedora I use?

cat /etc/*release

It's universal for almost any major distribution.

Could not reliably determine the server's fully qualified domain name

If you are using windows, remove comment on these lines and set them as:

Line 227 : ServerName 127.0.0.1:80 
Line 235 : AllowOverride all 
Line 236 : Require all granted

Worked for me!

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

Wordpress - Images not showing up in the Media Library

Well, Seems like there was a bug when creating custom post types in the function.php file of the theme... which bugged that.

Difference between a View's Padding and Margin

Padding is the space inside the border, between the border and the actual view's content. Note that padding goes completely around the content: there is padding on the top, bottom, right and left sides (which can be independent).

Margins are the spaces outside the border, between the border and the other elements next to this view. In the image, the margin is the grey area outside the entire object. Note that, like the padding, the margin goes completely around the content: there are margins on the top, bottom, right, and left sides.

An image says more than 1000 words (extracted from Margin Vs Padding - CSS Properties):

alt text

What does "int 0x80" mean in assembly code?

int means interrupt, and the number 0x80 is the interrupt number. An interrupt transfers the program flow to whomever is handling that interrupt, which is interrupt 0x80 in this case. In Linux, 0x80 interrupt handler is the kernel, and is used to make system calls to the kernel by other programs.

The kernel is notified about which system call the program wants to make, by examining the value in the register %eax (AT&T syntax, and EAX in Intel syntax). Each system call have different requirements about the use of the other registers. For example, a value of 1 in %eax means a system call of exit(), and the value in %ebx holds the value of the status code for exit().

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

You can try to add @Transactional annotation to your bean or method (if declaration of all variables places in method).

FtpWebRequest Download File

FYI, Microsoft recommends not using FtpWebRequest for new development:

We don't recommend that you use the FtpWebRequest class for new development. For more information and alternatives to FtpWebRequest, see WebRequest shouldn't be used on GitHub.

The GitHub link directs to this SO page which contains a list of third-party FTP libraries, such as FluentFTP.

AngularJS disable partial caching on dev machine

For Development you can also deactivate the browser cache - In Chrome Dev Tools on the bottom right click on the gear and tick the option

Disable cache (while DevTools is open)

Update: In Firefox there is the same option in Debugger -> Settings -> Advanced Section (checked for Version 33)

Update 2: Although this option appears in Firefox some report it doesn't work. I suggest using firebug and following hadaytullah answer.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

What is the difference between linear regression and logistic regression?

Cannot agree more with the above comments. Above that, there are some more differences like

In Linear Regression, residuals are assumed to be normally distributed. In Logistic Regression, residuals need to be independent but not normally distributed.

Linear Regression assumes that a constant change in the value of the explanatory variable results in constant change in the response variable. This assumption does not hold if the value of the response variable represents a probability (in Logistic Regression)

GLM(Generalized linear models) does not assume a linear relationship between dependent and independent variables. However, it assumes a linear relationship between link function and independent variables in logit model.

Nested attributes unpermitted parameters

or you can simply use

def question_params

  params.require(:question).permit(team_ids: [])

end

onclick on a image to navigate to another page using Javascript

maybe this is what u want?

<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
    <img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>

edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....

What are some alternatives to ReSharper?

CodeRush. Also, Scott Hanselman has a nice post comparing them, ReSharper vs. CodeRush.

A more up-to-date comparison is in Coderush vs Resharper by Jason Irwin.

Fork() function in C

First a link to some documentation of fork()

http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.

So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.

If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().

pid_t pid = fork()
if(pid == 0) {
    printf("this is a child: my new unique pid is %d\n", getpid());
} else {
    printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}

and below is some inline comments on your code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1 == 0){
        /* This is child A */
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        /* This is parent A */
        /* Child B and C will never reach this code */
        pid3=fork(); /* D */
        if(pid3==0) {
            /* This is child D fork'ed from parent A */
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0)) {
            /* pid1 will never be 0 here so this is dead code */
            printf("Level 1\n");
        }
        if(pid1 !=0) {
            /* This is always true for both parent and child E */
            printf("Level 2\n");
        }
        if(pid2 !=0) {
           /* This is parent E (same as parent A) */
           printf("Level 3\n");
        }
        if(pid3 !=0) {
           /* This is parent D (same as parent A) */
           printf("Level 4\n");
        }
    }
    return 0;
}

Copy entire contents of a directory to another using php

I had a similar situation where I needed to copy from one domain to another on the same server, Here is exactly what worked in my case, you can as well adjust to suit yours:

foreach(glob('../folder/*.php') as $file) {
$adjust = substr($file,3);
copy($file, '/home/user/abcde.com/'.$adjust);

Notice the use of "substr()", without it, the destination becomes '/home/user/abcde.com/../folder/', which might be something you don't want. So, I used substr() to eliminate the first 3 characters(../) in order to get the desired destination which is '/home/user/abcde.com/folder/'. So, you can adjust the substr() function and also the glob() function until it fits your personal needs. Hope this helps.

How to specify a multi-line shell variable?

simply insert new line where necessary

sql="
SELECT c1, c2
from Table1, Table2
where ...
"

shell will be looking for the closing quotation mark

Plotting images side by side using matplotlib

You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)

For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html

Onclick event to remove default value in a text input field

You actually want to show a placeholder, HTML 5 offer this feature and it's very sweet !

Try this out :

<input name="Name" placeholder="Enter Your Name">

How can I hide an HTML table row <tr> so that it takes up no space?

I was having the same issue, I even added style="display: none" to each cell.

In the end I used HTML comments <!-- [HTML] -->

How to convert a std::string to const char* or char*?

Given say...

std::string x = "hello";

Getting a `char *` or `const char*` from a `string`

How to get a character pointer that's valid while x remains in scope and isn't modified further

C++11 simplifies things; the following all give access to the same internal string buffer:

const char* p_c_str = x.c_str();
const char* p_data  = x.data();
char* p_writable_data = x.data(); // for non-const x from C++17 
const char* p_x0    = &x[0];

      char* p_x0_rw = &x[0];  // compiles iff x is not const...

All the above pointers will hold the same value - the address of the first character in the buffer. Even an empty string has a "first character in the buffer", because C++11 guarantees to always keep an extra NUL/0 terminator character after the explicitly assigned string content (e.g. std::string("this\0that", 9) will have a buffer holding "this\0that\0").

Given any of the above pointers:

char c = p[n];   // valid for n <= x.size()
                 // i.e. you can safely read the NUL at p[x.size()]

Only for the non-const pointer p_writable_data and from &x[0]:

p_writable_data[n] = c;
p_x0_rw[n] = c;  // valid for n <= x.size() - 1
                 // i.e. don't overwrite the implementation maintained NUL

Writing a NUL elsewhere in the string does not change the string's size(); string's are allowed to contain any number of NULs - they are given no special treatment by std::string (same in C++03).

In C++03, things were considerably more complicated (key differences highlighted):

  • x.data()

    • returns const char* to the string's internal buffer which wasn't required by the Standard to conclude with a NUL (i.e. might be ['h', 'e', 'l', 'l', 'o'] followed by uninitialised or garbage values, with accidental accesses thereto having undefined behaviour).
      • x.size() characters are safe to read, i.e. x[0] through x[x.size() - 1]
      • for empty strings, you're guaranteed some non-NULL pointer to which 0 can be safely added (hurray!), but you shouldn't dereference that pointer.
  • &x[0]

    • for empty strings this has undefined behaviour (21.3.4)
      • e.g. given f(const char* p, size_t n) { if (n == 0) return; ...whatever... } you mustn't call f(&x[0], x.size()); when x.empty() - just use f(x.data(), ...).
    • otherwise, as per x.data() but:
      • for non-const x this yields a non-const char* pointer; you can overwrite string content
  • x.c_str()

    • returns const char* to an ASCIIZ (NUL-terminated) representation of the value (i.e. ['h', 'e', 'l', 'l', 'o', '\0']).
    • although few if any implementations chose to do so, the C++03 Standard was worded to allow the string implementation the freedom to create a distinct NUL-terminated buffer on the fly, from the potentially non-NUL terminated buffer "exposed" by x.data() and &x[0]
    • x.size() + 1 characters are safe to read.
    • guaranteed safe even for empty strings (['\0']).

Consequences of accessing outside legal indices

Whichever way you get a pointer, you must not access memory further along from the pointer than the characters guaranteed present in the descriptions above. Attempts to do so have undefined behaviour, with a very real chance of application crashes and garbage results even for reads, and additionally wholesale data, stack corruption and/or security vulnerabilities for writes.

When do those pointers get invalidated?

If you call some string member function that modifies the string or reserves further capacity, any pointer values returned beforehand by any of the above methods are invalidated. You can use those methods again to get another pointer. (The rules are the same as for iterators into strings).

See also How to get a character pointer valid even after x leaves scope or is modified further below....

So, which is better to use?

From C++11, use .c_str() for ASCIIZ data, and .data() for "binary" data (explained further below).

In C++03, use .c_str() unless certain that .data() is adequate, and prefer .data() over &x[0] as it's safe for empty strings....

...try to understand the program enough to use data() when appropriate, or you'll probably make other mistakes...

The ASCII NUL '\0' character guaranteed by .c_str() is used by many functions as a sentinel value denoting the end of relevant and safe-to-access data. This applies to both C++-only functions like say fstream::fstream(const char* filename, ...) and shared-with-C functions like strchr(), and printf().

Given C++03's .c_str()'s guarantees about the returned buffer are a super-set of .data()'s, you can always safely use .c_str(), but people sometimes don't because:

  • using .data() communicates to other programmers reading the source code that the data is not ASCIIZ (rather, you're using the string to store a block of data (which sometimes isn't even really textual)), or that you're passing it to another function that treats it as a block of "binary" data. This can be a crucial insight in ensuring that other programmers' code changes continue to handle the data properly.
  • C++03 only: there's a slight chance that your string implementation will need to do some extra memory allocation and/or data copying in order to prepare the NUL terminated buffer

As a further hint, if a function's parameters require the (const) char* but don't insist on getting x.size(), the function probably needs an ASCIIZ input, so .c_str() is a good choice (the function needs to know where the text terminates somehow, so if it's not a separate parameter it can only be a convention like a length-prefix or sentinel or some fixed expected length).

How to get a character pointer valid even after x leaves scope or is modified further

You'll need to copy the contents of the string x to a new memory area outside x. This external buffer could be in many places such as another string or character array variable, it may or may not have a different lifetime than x due to being in a different scope (e.g. namespace, global, static, heap, shared memory, memory mapped file).

To copy the text from std::string x into an independent character array:

// USING ANOTHER STRING - AUTO MEMORY MANAGEMENT, EXCEPTION SAFE
std::string old_x = x;
// - old_x will not be affected by subsequent modifications to x...
// - you can use `&old_x[0]` to get a writable char* to old_x's textual content
// - you can use resize() to reduce/expand the string
//   - resizing isn't possible from within a function passed only the char* address

std::string old_x = x.c_str(); // old_x will terminate early if x embeds NUL
// Copies ASCIIZ data but could be less efficient as it needs to scan memory to
// find the NUL terminator indicating string length before allocating that amount
// of memory to copy into, or more efficient if it ends up allocating/copying a
// lot less content.
// Example, x == "ab\0cd" -> old_x == "ab".

// USING A VECTOR OF CHAR - AUTO, EXCEPTION SAFE, HINTS AT BINARY CONTENT, GUARANTEED CONTIGUOUS EVEN IN C++03
std::vector<char> old_x(x.data(), x.data() + x.size());       // without the NUL
std::vector<char> old_x(x.c_str(), x.c_str() + x.size() + 1);  // with the NUL

// USING STACK WHERE MAXIMUM SIZE OF x IS KNOWN TO BE COMPILE-TIME CONSTANT "N"
// (a bit dangerous, as "known" things are sometimes wrong and often become wrong)
char y[N + 1];
strcpy(y, x.c_str());

// USING STACK WHERE UNEXPECTEDLY LONG x IS TRUNCATED (e.g. Hello\0->Hel\0)
char y[N + 1];
strncpy(y, x.c_str(), N);  // copy at most N, zero-padding if shorter
y[N] = '\0';               // ensure NUL terminated

// USING THE STACK TO HANDLE x OF UNKNOWN (BUT SANE) LENGTH
char* y = alloca(x.size() + 1);
strcpy(y, x.c_str());

// USING THE STACK TO HANDLE x OF UNKNOWN LENGTH (NON-STANDARD GCC EXTENSION)
char y[x.size() + 1];
strcpy(y, x.c_str());

// USING new/delete HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY
char* y = new char[x.size() + 1];
strcpy(y, x.c_str());
//     or as a one-liner: char* y = strcpy(new char[x.size() + 1], x.c_str());
// use y...
delete[] y; // make sure no break, return, throw or branching bypasses this

// USING new/delete HEAP MEMORY, SMART POINTER DEALLOCATION, EXCEPTION SAFE
// see boost shared_array usage in Johannes Schaub's answer

// USING malloc/free HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY
char* y = strdup(x.c_str());
// use y...
free(y);

Other reasons to want a char* or const char* generated from a string

So, above you've seen how to get a (const) char*, and how to make a copy of the text independent of the original string, but what can you do with it? A random smattering of examples...

  • give "C" code access to the C++ string's text, as in printf("x is '%s'", x.c_str());
  • copy x's text to a buffer specified by your function's caller (e.g. strncpy(callers_buffer, callers_buffer_size, x.c_str())), or volatile memory used for device I/O (e.g. for (const char* p = x.c_str(); *p; ++p) *p_device = *p;)
  • append x's text to an character array already containing some ASCIIZ text (e.g. strcat(other_buffer, x.c_str())) - be careful not to overrun the buffer (in many situations you may need to use strncat)
  • return a const char* or char* from a function (perhaps for historical reasons - client's using your existing API - or for C compatibility you don't want to return a std::string, but do want to copy your string's data somewhere for the caller)
    • be careful not to return a pointer that may be dereferenced by the caller after a local string variable to which that pointer pointed has left scope
    • some projects with shared objects compiled/linked for different std::string implementations (e.g. STLport and compiler-native) may pass data as ASCIIZ to avoid conflicts

How to use UIVisualEffectView to Blur Image?

If anyone would like the answer in Swift :

var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) // Change .Dark into .Light if you'd like.

var blurView = UIVisualEffectView(effect: blurEffect)

blurView.frame = theImage.bounds // 'theImage' is an image. I think you can apply this to the view too!

Update :

As of now, it's available under the IB so you don't have to code anything for it :)

How to read data from a file in Lua

There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.

Parse JSON from HttpURLConnection object

In addition, if you wish to parse your object in case of http error (400-5** codes), You can use the following code: (just replace 'getInputStream' with 'getErrorStream':

    BufferedReader rd = new BufferedReader(
            new InputStreamReader(conn.getErrorStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    return sb.toString();

Error "initializer element is not constant" when trying to initialize variable with const

In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.

A "large" object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language, the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on), enum members, and results of such operators as sizeof. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

For example, this is NOT a constant

const int N = 5; /* `N` is not a constant in C */

The above N would be a constant in C++, but it is not a constant in C. So, if you try doing

static int j = N; /* ERROR */

you will get the same error: an attempt to initialize a static object with a non-constant.

This is the reason why, in C language, we predominantly use #define to declare named constants, and also resort to #define to create named aggregate initializers.

Is there a Python Library that contains a list of all the ascii characters?

No, there isn't, but you can easily make one:

    #Your ascii.py program:
    def charlist(begin, end):
        charlist = []
        for i in range(begin, end):
            charlist.append(chr(i))
        return ''.join(charlist)

    #Python shell:
    #import ascii
    #print(ascii.charlist(50, 100))
    #Comes out as:

    #23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abc

Flexbox and Internet Explorer 11 (display:flex in <html>?)

According to http://caniuse.com/#feat=flexbox:

"IE10 and IE11 default values for flex are 0 0 auto rather than 0 1 auto, as per the draft spec, as of September 2013"

So in plain words, if somewhere in your CSS you have something like this: flex:1 , that is not translated the same way in all browsers. Try changing it to 1 0 0 and I believe you will immediately see that it -kinda- works.

The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:

@-moz-document url-prefix() {
 #flexible-content{
      flex: 1;
    }
}

Since flexbox is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.

If someone has a better answer I would like to know!

Java String new line

you can use <br> tag in your string for show in html pages

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

I was looking for a listing of macOS but found nothing, maybe this helps someone.

Output on macOS Catalina (10.15.7) using net5.0

# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER

# SpecialFolders (All)
SpecialFolder.AdminTools: 
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonTemplates: 
SpecialFolder.CommonVideos: 
SpecialFolder.Cookies: 
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History: 
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources: 
SpecialFolder.MyComputer: 
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86: 
SpecialFolder.Programs: 
SpecialFolder.Recent: 
SpecialFolder.Resources: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.Startup: 
SpecialFolder.System: /System
SpecialFolder.SystemX86: 
SpecialFolder.Templates: 
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows: 

I have replaced my username with $USER.

Code Snippet from pogosama.

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

How to "properly" print a list?

In Python 2:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

Both return:

[x, 3, b]

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);

"findTop"!! The only one result!

Reverse of JSON.stringify?

Check this out.
http://jsfiddle.net/LD55x/

Code:

var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);

How to delete empty folders using windows command prompt?

from the command line: for /R /D %1 in (*) do rd "%1"

in a batch file for /R /D %%1 in (*) do rd "%%1"

I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.

How to check whether dynamically attached event listener exists or not?

tl;dr: No, you cannot do this in any natively supported way.


The only way I know to achieve this would be to create a custom storage object where you keep a record of the listeners added. Something along the following lines:

/* Create a storage object. */
var CustomEventStorage = [];

Step 1: First, you will need a function that can traverse the storage object and return the record of an element given the element (or false).

/* The function that finds a record in the storage by a given element. */
function findRecordByElement (element) {
    /* Iterate over every entry in the storage object. */
    for (var index = 0, length = CustomEventStorage.length; index < length; index++) {
        /* Cache the record. */
        var record = CustomEventStorage[index];

        /* Check whether the given element exists. */
        if (element == record.element) {
            /* Return the record. */
            return record;
        }
    }

    /* Return false by default. */
    return false;
}

Step 2: Then, you will need a function that can add an event listener but also insert the listener to the storage object.

/* The function that adds an event listener, while storing it in the storage object. */
function insertListener (element, event, listener, options) {
    /* Use the element given to retrieve the record. */
    var record = findRecordByElement(element);

    /* Check whether any record was found. */
    if (record) {
        /* Normalise the event of the listeners object, in case it doesn't exist. */
        record.listeners[event] = record.listeners[event] || [];
    }
    else {
        /* Create an object to insert into the storage object. */
        record = {
            element: element,
            listeners: {}
        };

        /* Create an array for event in the record. */
        record.listeners[event] = [];

        /* Insert the record in the storage. */
        CustomEventStorage.push(record);
    }

    /* Insert the listener to the event array. */
    record.listeners[event].push(listener);

    /* Add the event listener to the element. */
    element.addEventListener(event, listener, options);
}

Step 3: As regards the actual requirement of your question, you will need the following function to check whether an element has been added an event listener for a specified event.

/* The function that checks whether an event listener is set for a given event. */
function listenerExists (element, event, listener) {
    /* Use the element given to retrieve the record. */
    var record = findRecordByElement(element);

    /* Check whether a record was found & if an event array exists for the given event. */
    if (record && event in record.listeners) {
        /* Return whether the given listener exists. */
        return !!~record.listeners[event].indexOf(listener);
    }

    /* Return false by default. */
    return false;
}

Step 4: Finally, you will need a function that can delete a listener from the storage object.

/* The function that removes a listener from a given element & its storage record. */
function removeListener (element, event, listener, options) {
    /* Use the element given to retrieve the record. */
    var record = findRecordByElement(element);

    /* Check whether any record was found and, if found, whether the event exists. */
    if (record && event in record.listeners) {
        /* Cache the index of the listener inside the event array. */
        var index = record.listeners[event].indexOf(listener);

        /* Check whether listener is not -1. */
        if (~index) {
            /* Delete the listener from the event array. */
            record.listeners[event].splice(index, 1);
        }

        /* Check whether the event array is empty or not. */
        if (!record.listeners[event].length) {
            /* Delete the event array. */
            delete record.listeners[event];
        }
    }

    /* Add the event listener to the element. */
    element.removeEventListener(event, listener, options);
}

Snippet:

_x000D_
_x000D_
window.onload = function () {_x000D_
  var_x000D_
    /* Cache the test element. */_x000D_
    element = document.getElementById("test"),_x000D_
_x000D_
    /* Create an event listener. */_x000D_
    listener = function (e) {_x000D_
      console.log(e.type + "triggered!");_x000D_
    };_x000D_
_x000D_
  /* Insert the listener to the element. */_x000D_
  insertListener(element, "mouseover", listener);_x000D_
_x000D_
  /* Log whether the listener exists. */_x000D_
  console.log(listenerExists(element, "mouseover", listener));_x000D_
_x000D_
  /* Remove the listener from the element. */_x000D_
  removeListener(element, "mouseover", listener);_x000D_
_x000D_
  /* Log whether the listener exists. */_x000D_
  console.log(listenerExists(element, "mouseover", listener));_x000D_
};
_x000D_
<!-- Include the Custom Event Storage file -->_x000D_
<script src = "https://cdn.rawgit.com/angelpolitis/custom-event-storage/master/main.js"></script>_x000D_
_x000D_
<!-- A Test HTML element -->_x000D_
<div id = "test" style = "background:#000; height:50px; width: 50px"></div>
_x000D_
_x000D_
_x000D_


Although more than 5 years have passed since the OP posted the question, I believe people who stumble upon it in the future will benefit from this answer, so feel free to make suggestions or improvements to it.

Split large string in n-size chunks in JavaScript

const getChunksFromString = (str, chunkSize) => {
    var regexChunk = new RegExp(`.{1,${chunkSize}}`, 'g')   // '.' represents any character
    return str.match(regexChunk)
}

Call it as needed

console.log(getChunksFromString("Hello world", 3))   // ["Hel", "lo ", "wor", "ld"]

Use a normal link to submit a form

you can use OnClick="document.getElementById('formID_NOT_NAME').SUBMIT()"

What are the main differences between JWT and OAuth authentication?

Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.

XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Check if checkbox is checked with jQuery

This is also an idea I use frequently:

var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;

If cheked, it'll return 1; otherwise it'll return 0.

How to detect if numpy is installed

I think you also may use this

>> import numpy
>> print numpy.__version__

Update: for python3 use print(numpy.__version__)

Time part of a DateTime Field in SQL

In SQL Server if you need only the hh:mi, you can use:

DECLARE @datetime datetime

SELECT @datetime = GETDATE()

SELECT RIGHT('0'+CAST(DATEPART(hour, @datetime) as varchar(2)),2) + ':' +
       RIGHT('0'+CAST(DATEPART(minute, @datetime)as varchar(2)),2)

How to remove "href" with Jquery?

If you want your anchor to still appear to be clickable:

$("a").removeAttr("href").css("cursor","pointer");

And if you wanted to remove the href from only anchors with certain attributes (eg ones that just have a hash mark as the href - this can be useful in asp.net)

$("a[href='#']").removeAttr("href").css("cursor","pointer");

Moment.js transform to date object

Use this to transform a moment object into a date object:

From http://momentjs.com/docs/#/displaying/as-javascript-date/

moment().toDate();

Yields:

Tue Nov 04 2014 14:04:01 GMT-0600 (CST)

Setting selected option in laravel form

You can also try this for limited options:

          <select class="form-control required" id="assignedRole">
            <option id = "employeeRole" selected ="@if($employee->employee_role=='Employee'){'selected'}else{''} @endif">Employee</option>
            <option id = "adminRole" selected ="@if($employee->employee_role=='Admin'){'selected'}else{''} @endif">Admin</option>
            <option id = "employerRole" selected ="@if($employee->employee_role=='Employer'){'selected'}else{''} @endif">Employer</option>
          </select>

Forbidden :You don't have permission to access /phpmyadmin on this server

To allow from all:

#Require ip 127.0.0.1
#Require ip ::1
Require all granted

Handlebars.js Else If

Handlebars now supports {{else if}} as of 3.0.0. Therefore, your code should now work.

You can see an example under "conditionals" (slightly revised here with an added {{else}}:

    {{#if isActive}}
      <img src="star.gif" alt="Active">
    {{else if isInactive}}
      <img src="cry.gif" alt="Inactive">
    {{else}}
      <img src="default.gif" alt="default">
    {{/if}}

http://handlebarsjs.com/block_helpers.html

How do you print in a Go test using the "testing" package?

For testing sometimes I do

fmt.Fprintln(os.Stdout, "hello")

Also, you can print to:

fmt.Fprintln(os.Stderr, "hello)

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Frame Buster Buster ... buster code needed

Ok, so we know that were in a frame. So we location.href to another special page with the path as a GET variable. We now explain to the user what is going on and provide a link with a target="_TOP" option. It's simple and would probably work (haven't tested it), but it requires some user interaction. Maybe you could point out the offending site to the user and make a hall of shame of click jackers to your site somewhere.. Just an idea, but it night work..

How to make MySQL handle UTF-8 properly

Your answer is you can configure by MySql Settings. In My Answer may be something gone out of context but this is also know is help for you.
how to configure Character Set and Collation.

For applications that store data using the default MySQL character set and collation (latin1, latin1_swedish_ci), no special configuration should be needed. If applications require data storage using a different character set or collation, you can configure character set information several ways:

  • Specify character settings per database. For example, applications that use one database might require utf8, whereas applications that use another database might require sjis.
  • Specify character settings at server startup. This causes the server to use the given settings for all applications that do not make other arrangements.
  • Specify character settings at configuration time, if you build MySQL from source. This causes the server to use the given settings for all applications, without having to specify them at server startup.

The examples shown here for your question to set utf8 character set , here also set collation for more helpful(utf8_general_ci collation`).

Specify character settings per database

  CREATE DATABASE new_db
  DEFAULT CHARACTER SET utf8
  DEFAULT COLLATE utf8_general_ci;

Specify character settings at server startup

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

Specify character settings at MySQL configuration time

shell> cmake . -DDEFAULT_CHARSET=utf8 \
           -DDEFAULT_COLLATION=utf8_general_ci

To see the values of the character set and collation system variables that apply to your connection, use these statements:

SHOW VARIABLES LIKE 'character_set%';
SHOW VARIABLES LIKE 'collation%';

This May be lengthy answer but there is all way, you can use. Hopeful my answer is helpful for you. for more information http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html

SQL Server error on update command - "A severe error occurred on the current command"

This error is exactly what it means: Something bad happened, that would not normally happen.

In my most recent case, the REAL error was:

Msg 9002, Level 17, State 2, Procedure MyProcedure, Line 2 [Batch Start Line 3]
The transaction log for database 'MyDb' is full due to 'LOG_BACKUP'.

Here is my checklist of things to try, perhaps in this exact order:

  1. Check if you're out of disk space (this was my real problem; our NOC did not catch this)
  2. Check if you're low on memory
  3. Check if the Windows Event Log shows any serious system failures like hard drives failing
  4. Check if you have any unsafe code loaded through extended procedures or SQLCLR unsafe assemblies that could de-stabilize the SQLServer.exe process.
  5. Run CheckDB to see if your database has any corruption issues. On a very large database, if this stored procedure only touches a sub-set of tables, you can save time by seeing which partitions (filegroups) the stored procedure touches, and only checking those specific filegroups.
    1. I would do this for your database and master db as well.

How to pass the -D System properties while testing on Eclipse?

This will work for junit. for TestNG use following command

-ea -Dmykey="value" -Dmykey2="value2"

Batch file to delete folders older than 10 days in Windows 7

If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:

@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d

and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).

Eg.:

YourBatchFileName c:\temp

(you may use quotation marks if needed)

will remove all empty subdirs under c:\temp folder

YourBatchFileName

will remove all empty subdirs under the current directory.

How to get Current Directory?

An easy way to do this is:

int main(int argc, char * argv[]){
    std::cout << argv[0]; 
    std::cin.get();
}

argv[] is pretty much an array containing arguments you ran the .exe with, but the first one is always a path to the executable. If I build this the console shows: C:\Users\Ulisse\source\repos\altcmd\Debug\currentdir.exe

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Declare @Username varchar(20)
Set @Username = 'Mike'

if not exists 
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')

Begin
    Create table tblEmp (ID int primary key, Name varchar(50))
    Print (@Username + ' Table created successfully')
End

Else

Begin
    Print (@Username + ' : this Table Already exists in the database')
End

How to extract a string between two delimiters

  String s = "ABC[This is to extract]";

    System.out.println(s);
    int startIndex = s.indexOf('[');
    System.out.println("indexOf([) = " + startIndex);
    int endIndex = s.indexOf(']');
    System.out.println("indexOf(]) = " + endIndex);
    System.out.println(s.substring(startIndex + 1, endIndex));

Entity Framework vs LINQ to SQL

Linq-to-SQL

It is provider it supports SQL Server only. It's a mapping technology to map SQL Server database tables to .NET objects. Is Microsoft's first attempt at an ORM - Object-Relational Mapper.

Linq-to-Entities

Is the same idea, but using Entity Framework in the background, as the ORM - again from Microsoft, It supporting multiple database main advantage of entity framework is developer can work on any database no need to learn syntax to perform any operation on different different databases

According to my personal experience Ef is better (if you have no idea about SQL) performance in LINQ is little bit faster as compare to EF reason LINQ language written in lambda.

How to Resize a Bitmap in Android?

Keeping the aspect ratio,

  public Bitmap resizeBitmap(Bitmap source, int width,int height) {
    if(source.getHeight() == height && source.getWidth() == width) return source;
    int maxLength=Math.min(width,height);
    try {
        source=source.copy(source.getConfig(),true);
        if (source.getHeight() <= source.getWidth()) {
            if (source.getHeight() <= maxLength) { // if image already smaller than the required height
                return source;
            }

            double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
            int targetWidth = (int) (maxLength * aspectRatio);

            return Bitmap.createScaledBitmap(source, targetWidth, maxLength, false);
        } else {

            if (source.getWidth() <= maxLength) { // if image already smaller than the required height
                return source;
            }

            double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
            int targetHeight = (int) (maxLength * aspectRatio);

            return Bitmap.createScaledBitmap(source, maxLength, targetHeight, false);

        }
    }
    catch (Exception e)
    {
        return source;
    }
}

jQuery find() method not working in AngularJS directive

I used

elm.children('.class-name-or-whatever') 

to get children of the current element

Selecting/excluding sets of columns in pandas

Here's how to create a copy of a DataFrame excluding a list of columns:

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
df2 = df.drop(['B', 'D'], axis=1)

But be careful! You mention views in your question, suggesting that if you changed df, you'd want df2 to change too. (Like a view would in a database.)

This method doesn't achieve that:

>>> df.loc[0, 'A'] = 999 # Change the first value in df
>>> df.head(1)
     A         B         C         D
0  999 -0.742688 -1.980673 -0.920133
>>> df2.head(1) # df2 is unchanged. It's not a view, it's a copy!
          A         C
0  0.251262 -1.980673

Note also that this is also true of @piggybox's method. (Although that method is nice and slick and Pythonic. I'm not doing it down!!)

For more on views vs. copies see this SO answer and this part of the Pandas docs which that answer refers to.

How to position a DIV in a specific coordinates?

Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;

var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';

Or do it as a function so you can attach it to an event like onmousedown

function placeDiv(x_pos, y_pos) {
  var d = document.getElementById('yourDivId');
  d.style.position = "absolute";
  d.style.left = x_pos+'px';
  d.style.top = y_pos+'px';
}

Detect element content changes with jQuery

Try this, it was created by James Padolsey(J-P here on SO) and does exactly what you want (I think)

http://james.padolsey.com/javascript/monitoring-dom-properties/

Difference between size and length methods?

  • .length is a field, containing the capacity (NOT the number of elements the array contains at the moment) of arrays.

  • length() is a method used by Strings (amongst others), it returns the number of chars in the String; with Strings, capacity and number of containing elements (chars) have the same value.

  • size() is a method implemented by all members of Collection (lists, sets, stacks,...). It returns the number of elements (NOT the capacity; some collections even don´t have a defined capacity) the collection contains.

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

How do I remove the top margin in a web page?

Is your first element h1 or similar? That element's margin-top could be causing what seems like a margin on body.

What is a lambda expression in C++11?

The problem

C++ includes useful generic functions like std::for_each and std::transform, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function.

#include <algorithm>
#include <vector>

namespace {
  struct f {
    void operator()(int) {
      // do something
    }
  };
}

void func(std::vector<int>& v) {
  f f;
  std::for_each(v.begin(), v.end(), f);
}

If you only use f once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off.

In C++03 you might be tempted to write something like the following, to keep the functor local:

void func2(std::vector<int>& v) {
  struct {
    void operator()(int) {
       // do something
    }
  } f;
  std::for_each(v.begin(), v.end(), f);
}

however this is not allowed, f cannot be passed to a template function in C++03.

The new solution

C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form:

void func3(std::vector<int>& v) {
  std::for_each(v.begin(), v.end(), [](int) { /* do something here*/ });
}

Lambda functions are just syntactic sugar for anonymous functors.

Return types

In simple cases the return type of the lambda is deduced for you, e.g.:

void func4(std::vector<double>& v) {
  std::transform(v.begin(), v.end(), v.begin(),
                 [](double d) { return d < 0.00001 ? 0 : d; }
                 );
}

however when you start to write more complex lambdas you will quickly encounter cases where the return type cannot be deduced by the compiler, e.g.:

void func4(std::vector<double>& v) {
    std::transform(v.begin(), v.end(), v.begin(),
        [](double d) {
            if (d < 0.0001) {
                return 0;
            } else {
                return d;
            }
        });
}

To resolve this you are allowed to explicitly specify a return type for a lambda function, using -> T:

void func4(std::vector<double>& v) {
    std::transform(v.begin(), v.end(), v.begin(),
        [](double d) -> double {
            if (d < 0.0001) {
                return 0;
            } else {
                return d;
            }
        });
}

"Capturing" variables

So far we've not used anything other than what was passed to the lambda within it, but we can also use other variables, within the lambda. If you want to access other variables you can use the capture clause (the [] of the expression), which has so far been unused in these examples, e.g.:

void func5(std::vector<double>& v, const double& epsilon) {
    std::transform(v.begin(), v.end(), v.begin(),
        [epsilon](double d) -> double {
            if (d < epsilon) {
                return 0;
            } else {
                return d;
            }
        });
}

You can capture by both reference and value, which you can specify using & and = respectively:

  • [&epsilon] capture by reference
  • [&] captures all variables used in the lambda by reference
  • [=] captures all variables used in the lambda by value
  • [&, epsilon] captures variables like with [&], but epsilon by value
  • [=, &epsilon] captures variables like with [=], but epsilon by reference

The generated operator() is const by default, with the implication that captures will be const when you access them by default. This has the effect that each call with the same input would produce the same result, however you can mark the lambda as mutable to request that the operator() that is produced is not const.

Maven with Eclipse Juno

All the info you need, is provided in the release announcement for m2e 1.1:

m2e 1.1 has been released as part of Eclipse Juno simultaneous release today.

[...]

m2e 1.1 is already included in "Eclipse IDE for Java Developers" package available from http://eclipse.org/downloads/ or it can be installed from Eclipse Juno release repository [2]. Eclipse 3.7/Indigo users can install the new version from m2e release repository [3]

[...]

[2] http://download.eclipse.org/releases/juno

[3] http://download.eclipse.org/technology/m2e/releases

How to check if a String contains any letter from a to z?

For a minimal change:

for(int i=0; i<str.Length; i++ )
   if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
      errorCount++;

You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.

Configuring diff tool with .gitconfig

Reproducing my answer from this thread which was more specific to setting beyond compare as diff tool for Git. All the details that I've shared are equally useful for any diff tool in general so sharing it here:

The first command that we run is as below:

git config --global diff.tool bc3

The above command creates below entry in .gitconfig found in %userprofile% directory:

[diff]
    tool = bc3

Then you run below command (Running this command is redundant in this particular case and is required in some specialized cases only. You will know it in a short while):

git config --global difftool.bc3.path "c:/program files/beyond compare 3/bcomp.exe"

Above command creates below entry in .gitconfig file:

[difftool "bc3"]
    path = c:/program files/Beyond Compare 3/bcomp.exe

The thing to know here is the key bc3. This is a well known key to git corresponding to a particular version of well known comparison tools available in market (bc3 corresponds to 3rd version of Beyond Compare tool). If you want to see all pre-defined keys just run git difftool --tool-help command on git bash. It returns below list:

vimdiff
vimdiff2
vimdiff3
araxis
bc
bc3
codecompare
deltawalker
diffmerge
diffuse
ecmerge
emerge
examdiff
gvimdiff
gvimdiff2
gvimdiff3
kdiff3
kompare
meld
opendiff
p4merge
tkdiff
winmerge
xxdiff

You can use any of the above keys or define a custom key of your own. If you want to setup a new tool altogether(or a newly released version of well-known tool) which doesn't map to any of the keys listed above then you are free to map it to any of keys listed above or to a new custom key of your own.

What if you have to setup a comparison tool which is

  • Absolutely new in market

OR

  • A new version of an existing well known tool has got released which is not mapped to any pre-defined keys in git?

Like in my case, I had installed beyond compare 4. beyond compare is a well-known tool to git but its version 4 release is not mapped to any of the existing keys by default. So you can follow any of the below approaches:

  1. I can map beyond compare 4 tool to already existing key bc3 which corresponds to beyond compare 3 version. I didn't have beyond compare version 3 on my computer so I didn't care. If I wanted I could have mapped it to any of the pre-defined keys in the above list also e.g. examdiff.

    If you map well known version of tools to appropriate already existing/well- known key then you would not need to run the second command as their install path is already known to git.

    For e.g. if I had installed beyond compare version 3 on my box then having below configuration in my .gitconfig file would have been sufficient to get going:

    [diff]
    tool = bc3
    

    But if you want to change the default associated tool then you end up mentioning the path attribute separately so that git gets to know the path from where you new tool's exe has to be launched. Here is the entry which foxes git to launch beyond compare 4 instead. Note the exe's path:

    [difftool "bc3"]
    path = c:/program files/Beyond Compare 4/bcomp.exe
    
  2. Most cleanest approach is to define a new key altogether for the new comparison tool or a new version of an well known tool. Like in my case I defined a new key bc4 so that it is easy to remember. In such a case you have to run two commands in all but your second command will not be setting path of your new tool's executable. Instead you have to set cmd attribute for your new tool as shown below:

    git config --global diff.tool bc4
    
    git config --global difftool.bc4.cmd "\"C:\\Program Files\\Beyond Compare 4\\bcomp.exe\" -s \"\$LOCAL\" -d \"\$REMOTE\""
    

    Running above commands creates below entries in your .gitconfig file:

    [diff]
    tool = bc4
    [difftool "bc4"]
    cmd = \"C:\\Program Files\\Beyond Compare 4\\bcomp.exe\" -s \"$LOCAL\" -d \"$REMOTE\"
    

I would strongly recommend you to follow approach # 2 to avoid any confusion for yourself in future.

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.

You can check this by running in Windows PowerShell:

> Get-Service ssh-agent

And then check the output of status is not running.

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

Then check that the service has been disabled by running

> Get-Service ssh-agent | Select StartType

StartType
---------
Disabled

I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:

 > Get-Service -Name ssh-agent | Set-Service -StartupType Manual

Alternatively, you can set it through the GUI if you prefer.

services.msc showing the properties of the OpenSSH Agent

Fastest way to Remove Duplicate Value from a list<> by lambda

You can use this extension method for enumerables containing more complex types:

IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    var knownKeys = new HashSet<TKey>();
    return source.Where(element => knownKeys.Add(keySelector(element)));
}

How can I reorder my divs using only CSS?

Well, with a bit of absolute positioning and some dodgy margin setting, I can get close, but it's not perfect or pretty:

#wrapper { position: relative; margin-top: 4em; }
#firstDiv { position: absolute; top: 0; width: 100%; }
#secondDiv { position: absolute; bottom: 0; width: 100%; }

The "margin-top: 4em" is the particularly nasty bit: this margin needs to be adjusted according to the amount of content in the firstDiv. Depending on your exact requirements, this might be possible, but I'm hoping anyway that someone might be able to build on this for a solid solution.

Eric's comment about JavaScript should probably be pursued.

Google maps Marker Label with multiple characters

A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.

for (i = 0; i < locations.length; i++) 
      { 
      k = i + 1;
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),     
      map: map,
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});

--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

Converting List<String> to String[] in Java

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

Ignoring SSL certificate in Apache HttpClient 4.3

After trying various options, following configuration worked for both http and https:

SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

Registry<ConnectionSocketFactory> registry = RegistryBuilder. 
                 <ConnectionSocketFactory> create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", sslsf)
                .build();

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(2000);

CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .build();

I am using http-client 4.3.3 : compile 'org.apache.httpcomponents:httpclient:4.3.3'

How to style the menu items on an Android action bar

My guess is that you have to also style the views that are generated from the menu information in your onCreateOptionsMenu(). The styling you applied so far is working, but I doubt that the menu items, when rendered with text use a style that is the same as the title part of the ActionBar.

You may want to look at Menu.getActionView() to get the view for the menu action and then adjust it accordingly.

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

How do I concatenate two arrays in C#?

I know the OP was only mildly curious about performance. That larger arrays may get a different result (see @kurdishTree). And that it usually does not matter (@jordan.peoples). None the less, I was curious and therefore lost my mind ( as @TigerShark was explaining).... I mean that I wrote a simple test based on the original question.... and all the answers....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace concat
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] x = new int [] { 1, 2, 3};
            int[] y = new int [] { 4, 5 };


            int itter = 50000;
            Console.WriteLine("test iterations: {0}", itter);

            DateTime startTest = DateTime.Now;
            for(int  i = 0; i < itter; i++)
            {
                int[] z;
                z = x.Concat(y).ToArray();
            }
            Console.WriteLine ("Concat Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks );

            startTest = DateTime.Now;
            for(int  i = 0; i < itter; i++)
            {
                var vz = new int[x.Length + y.Length];
                x.CopyTo(vz, 0);
                y.CopyTo(vz, x.Length);
            }
            Console.WriteLine ("CopyTo Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks );

            startTest = DateTime.Now;
            for(int  i = 0; i < itter; i++)
            {
                List<int> list = new List<int>();
                list.AddRange(x);
                list.AddRange(y);
                int[] z = list.ToArray();
            }
            Console.WriteLine("list.AddRange Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.Concat(x, y);
            }
            Console.WriteLine("Concat(x, y) Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.ConcatArrays(x, y);
            }
            Console.WriteLine("ConcatArrays Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.SSConcat(x, y);
            }
            Console.WriteLine("SSConcat Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int k = 0; k < itter; k++)
            {
                int[] three = new int[x.Length + y.Length];

                int idx = 0;

                for (int i = 0; i < x.Length; i++)
                    three[idx++] = x[i];
                for (int j = 0; j < y.Length; j++)
                    three[idx++] = y[j];
            }
            Console.WriteLine("Roll your own Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);


            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.ConcatArraysLinq(x, y);
            }
            Console.WriteLine("ConcatArraysLinq Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.ConcatArraysLambda(x, y);
            }
            Console.WriteLine("ConcatArraysLambda Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                List<int> targetList = new List<int>(x);
                targetList.Concat(y);
            }
            Console.WriteLine("targetList.Concat(y) Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] result = x.ToList().Concat(y.ToList()).ToArray();
            }
            Console.WriteLine("x.ToList().Concat(y.ToList()).ToArray() Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);
        }
    }
    static class Methods
    {
        public static T[] Concat<T>(this T[] x, T[] y)
        {
            if (x == null) throw new ArgumentNullException("x");
            if (y == null) throw new ArgumentNullException("y");
            int oldLen = x.Length;
            Array.Resize<T>(ref x, x.Length + y.Length);
            Array.Copy(y, 0, x, oldLen, y.Length);
            return x;
        }

        public static T[] ConcatArrays<T>(params T[][] list)
        {
            var result = new T[list.Sum(a => a.Length)];
            int offset = 0;
            for (int x = 0; x < list.Length; x++)
            {
                list[x].CopyTo(result, offset);
                offset += list[x].Length;
            }
            return result;
        }


        public static T[] SSConcat<T>(this T[] first, params T[][] arrays)
        {
            int length = first.Length;
            foreach (T[] array in arrays)
            {
                length += array.Length;
            }
            T[] result = new T[length];
            length = first.Length;
            Array.Copy(first, 0, result, 0, first.Length);
            foreach (T[] array in arrays)
            {
                Array.Copy(array, 0, result, length, array.Length);
                length += array.Length;
            }
            return result;
        }

        public static T[] ConcatArraysLinq<T>(params T[][] arrays)
        {
            return (from array in arrays
                    from arr in array
                    select arr).ToArray();
        }

        public static T[] ConcatArraysLambda<T>(params T[][] arrays)
        {
            return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
        }
    }

}

The result was:

enter image description here

Roll your own wins.

jQuery not working with IE 11

Place this meta tag after head tag

<meta http-equiv="x-ua-compatible" content="IE=edge">

How to monitor SQL Server table changes by using c#?

Since SQL Server 2005 you have the option of using Query Notifications, which can be leveraged by ADO.NET see http://msdn.microsoft.com/en-us/library/t9x04ed2.aspx

Regular expression to match numbers with or without commas and decimals in text

\b\d+,

\b------->word boundary

\d+------>one or digit

,-------->containing commas,

Eg:

sddsgg 70,000 sdsfdsf fdgfdg70,00

sfsfsd 5,44,4343 5.7788,44 555

It will match:

70,

5,

44,

,44

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

How do you check what version of SQL Server for a database using TSQL?

Try this:

SELECT
    'the sqlserver is ' + substring(@@VERSION, 21, 5) AS [sql version]

Unable to install pyodbc on Linux

How about installing pyobdc from zip file? From How to connect to Microsoft Sql Server from Ubuntu using pyODBC:

Download source vs apt-get

The apt-get utility in Ubuntu does have a version of pyODBC. (version 2.1.7).
However, it is badly out-of-date (2.1.7 vs 3.0.6) and may not work well with the newer versions of unixODBC and freetds.
This is especially important if you are trying to connect to later versions of Microsoft Sql Server (2008 onwards).
It is recommended that you use the latest versions of unixODBC, freetds and pyODBC when working with the latest Microsoft Sql Server instead of relying on packages in apt-get.

ImportError: No module named pythoncom

Just go to cmd and install pip install pywin32 pythoncom is part of pywin32 for API window extension.... good luck

Gradle: How to Display Test Results in the Console in Real Time?

My favourite minimalistic version based on Shubham Chaudhary answer. enter image description here

Put this in build.gradle file:

test {
    afterSuite { desc, result ->
    if (!desc.parent)
        println("${result.resultType} " +
            "(${result.testCount} tests, " +
            "${result.successfulTestCount} successes, " +
            "${result.failedTestCount} failures, " +
            "${result.skippedTestCount} skipped)")
    }
}

Spring boot - Not a managed type

I got this error because I stupidly wrote

public interface FooBarRepository extends CrudRepository<FooBarRepository, Long> { ...

A brief explanation: One typically creates a FooBarRepository class to manage FooBar objects (often representing data in a table called something like foo_bar.) When extending the CrudRepository to create the specialized repository class, one needs to specify the type that's being managed -- in this case, FooBar. What I mistakenly typed, though, was FooBarRepository rather than FooBar. FooBarRepository is not the type (the class) I'm trying to manage with the FooBarRepository. Therefore, the compiler issues this error.

I highlighted the mistaken bit of typing in bold. Delete the highlighted word Repository in my example and the code compiles.

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

How can I indent multiple lines in Xcode?

If you use synergy (to share one keyboard for two PCs) and PC(MAC) in which you are using xcode is slave, and master PC is Windows PC

keyboard shortcuts are alt+] for indent and alt+[ for un-indent.

Update:

But from synergy version 1.5 working ?+[ for indent and ?+] for un-indent

Listing information about all database files in SQL Server

This script lists most of what you are looking for and can hopefully be modified to you needs. Note that it is creating a permanent table in there - you might want to change it. It is a subset from a larger script that also summarises backup and job information on various servers.

IF OBJECT_ID('tempdb..#DriveInfo') IS NOT NULL
 DROP TABLE #DriveInfo
CREATE TABLE #DriveInfo
 (
    Drive CHAR(1)
    ,MBFree INT
 ) 

INSERT  INTO #DriveInfo
      EXEC master..xp_fixeddrives


IF OBJECT_ID('[dbo].[Tmp_tblDatabaseInfo]', 'U') IS NOT NULL 
   DROP TABLE [dbo].[Tmp_tblDatabaseInfo]
CREATE TABLE [dbo].[Tmp_tblDatabaseInfo](
      [ServerName] [nvarchar](128) NULL
      ,[DBName] [nvarchar](128)  NULL
      ,[database_id] [int] NULL
      ,[create_date] datetime NULL
      ,[CompatibilityLevel] [int] NULL
      ,[collation_name] [nvarchar](128) NULL
      ,[state_desc] [nvarchar](60) NULL
      ,[recovery_model_desc] [nvarchar](60) NULL
      ,[DataFileLocations] [nvarchar](4000)
      ,[DataFilesMB] money null
      ,DataVolumeFreeSpaceMB INT NULL
      ,[LogFileLocations] [nvarchar](4000)
      ,[LogFilesMB] money null
      ,LogVolumeFreeSpaceMB INT NULL

) ON [PRIMARY]

INSERT INTO [dbo].[Tmp_tblDatabaseInfo] 
SELECT 
      @@SERVERNAME AS [ServerName] 
      ,d.name AS DBName 
      ,d.database_id
      ,d.create_date
      ,d.compatibility_level  
      ,CAST(d.collation_name AS [nvarchar](128)) AS collation_name
      ,d.[state_desc]
      ,d.recovery_model_desc
      ,(select physical_name + ' | ' AS [text()]
         from sys.master_files m
         WHERE m.type = 0 and m.database_id = d.database_id
         ORDER BY file_id
         FOR XML PATH ('')) AS DataFileLocations
      ,(select sum(size) from sys.master_files m WHERE m.type = 0 and m.database_id = d.database_id)  AS DataFilesMB
      ,NULL
      ,(select physical_name + ' | ' AS [text()]
         from sys.master_files m
         WHERE m.type = 1 and m.database_id = d.database_id
         ORDER BY file_id
         FOR XML PATH ('')) AS LogFileLocations
      ,(select sum(size) from sys.master_files m WHERE m.type = 1 and m.database_id = d.database_id)  AS LogFilesMB
      ,NULL
FROM  sys.databases d  

WHERE d.database_id > 4 --Exclude basic system databases
UPDATE [dbo].[Tmp_tblDatabaseInfo] 
   SET DataFileLocations = 
      CASE WHEN LEN(DataFileLocations) > 4 THEN  LEFT(DataFileLocations,LEN(DataFileLocations)-2) ELSE NULL END
   ,LogFileLocations =
      CASE WHEN LEN(LogFileLocations) > 4 THEN  LEFT(LogFileLocations,LEN(LogFileLocations)-2) ELSE NULL END
   ,DataFilesMB = 
      CASE WHEN DataFilesMB > 0 THEN  DataFilesMB * 8 / 1024.0   ELSE NULL END
   ,LogFilesMB = 
      CASE WHEN LogFilesMB > 0 THEN  LogFilesMB * 8 / 1024.0  ELSE NULL END
   ,DataVolumeFreeSpaceMB = 
      (SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( DataFileLocations,1))
   ,LogVolumeFreeSpaceMB = 
      (SELECT MBFree FROM #DriveInfo WHERE Drive = LEFT( LogFileLocations,1))

select * from [dbo].[Tmp_tblDatabaseInfo] 

Set database from SINGLE USER mode to MULTI USER

I actually had an issue where my db was pretty much locked by the processes and a race condition with them, by the time I got one command executed refreshed and they had it locked again... I had to run the following commands back to back in SSMS and got me offline and from there I did my restore and came back online just fine, the two queries where:

First ran:

USE master
GO

DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses 
WHERE dbid = db_id('<yourDbName>')

EXEC(@kill);

Then immediately after (in second query window):

USE master ALTER DATABASE <yourDbName> SET OFFLINE WITH ROLLBACK IMMEDIATE

Did what I needed and then brought it back online. Thanks to all who wrote these pieces out for me to combine and solve my problem.

How to set max width of an image in CSS

Your css is almost correct. You are just missing display: block; in image css. Also one typo in your id. It should be <div id="ImageContainer">

_x000D_
_x000D_
img.Image { max-width: 100%; display: block; }_x000D_
div#ImageContainer { width: 600px; }
_x000D_
<div id="ImageContainer">_x000D_
    <img src="http://placehold.it/1000x600" class="Image">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert a double into a string in C++?

sprintf is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

You can also use Boost.LexicalCast:

#include <boost/lexical_cast.hpp>
#include <string>

// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);

In both instances, str should be "453.23" afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstreams internally.

How to get the real and total length of char * (char array)?

You could try this:

int lengthChar(const char* chararray) {
   int n = 0;
   while(chararray[n] != '\0')
     n ++;
   return n;  
}

How I can filter a Datatable?

It is better to use DataView for this task.

Example of the using it you can find in this post: How to filter data in dataview

Accessing post variables using Java Servlets

For getting all post parameters there is Map which contains request param name as key and param value as key.

Map params = servReq.getParameterMap();

And to get parameters with known name normal

String userId=servReq.getParameter("user_id");

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

Oracle's default date format is YYYY-MM-DD, WHY?

This is a "problem" on the client side, not really an Oracle problem.

It's the client application which formats and displays the date this way.

In your case it's SQL*Plus which does this formatting.
Other SQL clients have other defaults.

Compression/Decompression string with C#

The code to compress/decompress a string

public static void CopyTo(Stream src, Stream dest) {
    byte[] bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
    }
}

public static byte[] Zip(string str) {
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}

public static string Unzip(byte[] bytes) {
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            //gs.CopyTo(mso);
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

static void Main(string[] args) {
    byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
    string r2 = Unzip(r1);
}

Remember that Zip returns a byte[], while Unzip returns a string. If you want a string from Zip you can Base64 encode it (for example by using Convert.ToBase64String(r1)) (the result of Zip is VERY binary! It isn't something you can print to the screen or write directly in an XML)

The version suggested is for .NET 2.0, for .NET 4.0 use the MemoryStream.CopyTo.

IMPORTANT: The compressed contents cannot be written to the output stream until the GZipStream knows that it has all of the input (i.e., to effectively compress it needs all of the data). You need to make sure that you Dispose() of the GZipStream before inspecting the output stream (e.g., mso.ToArray()). This is done with the using() { } block above. Note that the GZipStream is the innermost block and the contents are accessed outside of it. The same goes for decompressing: Dispose() of the GZipStream before attempting to access the data.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

If non of above works for you, make sure tomcat has access to manager folder under webapps (chown ...). The message is the exact same message, and It took me 2 hours to figure out the problem. :-)

just for someone else who came here for the same issue as me.

Java: Check the date format of current string is according to required format or not

Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)

    public Boolean checkDateformat(String dateToCheck){   
        String rex="([0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})+
        \/([0]{1}[1-9]{1}|[1]{1}[0-2]{2})+
        \/([1]{1}[9]{1}[5-9]{1}[0-9]{1}|[2]{1}[0]{1}([0-4]{1}+
        [0-9]{1}|[5]{1}[0]{1}))";

        return(dateToCheck.matches(rex));
    }

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

Best way to store passwords in MYSQL database

Store a unique salt for the user (generated from username + email for example), and store a password. On login, get the salt from database and hash salt + password.
Use bcrypt to hash the passwords.

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

There are two ways to handle this.

1) Check the event.target result in your callback to see if it matches your parent div

var g_ParentDiv;

function OnMouseOut(event) {
    if (event.target != g_ParentDiv) {
        return;
    }
    // handle mouse event here!
};


window.onload = function() {
    g_ParentDiv = document.getElementById("parentdiv");
    g_ParentDiv.onmouseout = OnMouseOut;
};

<div id="parentdiv">
    <img src="childimage.jpg" id="childimg" />
</div>

2) Or use event capturing and call event.stopPropagation in the callback function

var g_ParentDiv;

function OnMouseOut(event) {

    event.stopPropagation(); // don't let the event recurse into children

    // handle mouse event here!
};


window.onload = function() {
    g_ParentDiv = document.getElementById("parentdiv");
    g_ParentDiv.addEventListener("mouseout", OnMouseOut, true); // pass true to enable event capturing so parent gets event callback before children
};

<div id="parentdiv">
    <img src="childimage.jpg" id="childimg" />
</div>

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

Switch firefox to use a different DNS than what is in the windows.host file

I use this to override system's DNS with localserver
in about:config
change this value:

  • network.dns.forceResolve
  • network.dns.ipv4OnlyDomains
  • network.dns.localDomains
  • with IP address of local DNS server (for exsample 192.168.1.88)
    Sorry for my english

    How do you specify the Java compiler version in a pom.xml file?

    I faced same issue in eclipse neon simple maven java project

    But I add below details inside pom.xml file

       <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    

    After right click on project > maven > update project (checked force update)

    Its resolve me to display error on project

    Hope it's will helpful

    Thansk

    Mail not sending with PHPMailer over SSL using SMTP

    I got a similar failure with SMTP whenever my client machine changes network connection (e.g., home vs. office network) and somehow restarting network service (or rebooting the machine) resolves the issue for me. Not sure if this would apply to your case, but just in case.

    sudo /etc/init.d/networking restart   # for ubuntu
    

    Apache error: _default_ virtualhost overlap on port 443

    On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

    {apache_dir}/conf.d/ssl.conf
    

    This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

    To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

    Finding smallest value in an array most efficiently

    int small=a[0];
    for (int x: a.length)
    {
        if(a[x]<small)
            small=a[x];
    }
    

    How to align a div inside td element using CSS class

    I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

    What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

    If you do go down the inline-block route then you may have to consider my favorite IE hack.

    width:100px;
    display:inline-block;
    zoom:1; //IE only
    *display:inline; //IE only
    

    Happy Coding :)

    equivalent of vbCrLf in c#

    You are looking for System.Environment.NewLine.

    On Windows, this is equivalent to \r\n though it could be different under another .NET implementation, such as Mono on Linux, for example.

    PHP Regex to check date is in YYYY-MM-DD format

    From Laravel 5.7 and date format i.e.: 12/31/2019

    function checkDateFormat(string $date): bool
    {
        return preg_match("/^(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\/[0-9]{4}$/", $date);
    }
    

    RegEx for matching "A-Z, a-z, 0-9, _" and "."

    regex: /^[a-zA-Z0-9_.]$/i

    This works

    Where does Internet Explorer store saved passwords?

    No guarantee, but I suspect IE uses the older Protected Storage API.

    Illegal pattern character 'T' when parsing a date string to java.util.Date

    tl;dr

    Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

    Instant.parse( "2010-10-02T12:23:23Z" )
    

    ISO 8601

    That format is defined by the ISO 8601 standard for date-time string formats.

    Both:

    …use ISO 8601 formats by default for parsing and generating strings.

    You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

    java.time

    Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

    Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.
    

    Convert to the old class.

    java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.
    

    Time Zone

    If needed, you can assign a time zone.

    ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
    ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.
    

    Convert.

    java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.
    

    Joda-Time

    UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

    Here is some example code in Joda-Time 2.8.

    org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.
    

    Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

    java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.
    

    Time Zone

    If needed, you can assign a time zone.

    DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
    DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );
    

    Table of date-time types in Java, both modern and legacy.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?

    Table of which java.time library to use with which version of Java or Android.

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

    no default constructor exists for class

    If you define a class without any constructor, the compiler will synthesize a constructor for you (and that will be a default constructor -- i.e., one that doesn't require any arguments). If, however, you do define a constructor, (even if it does take one or more arguments) the compiler will not synthesize a constructor for you -- at that point, you've taken responsibility for constructing objects of that class, so the compiler "steps back", so to speak, and leaves that job to you.

    You have two choices. You need to either provide a default constructor, or you need to supply the correct parameter when you define an object. For example, you could change your constructor to look something like:

    Blowfish(BlowfishAlgorithm algorithm = CBC);
    

    ...so the ctor could be invoked without (explicitly) specifying an algorithm (in which case it would use CBC as the algorithm).

    The other alternative would be to explicitly specify the algorithm when you define a Blowfish object:

    class GameCryptography { 
        Blowfish blowfish_;
    public:
        GameCryptography() : blowfish_(ECB) {}
        // ...
    };
    

    In C++ 11 (or later) you have one more option available. You can define your constructor that takes an argument, but then tell the compiler to generate the constructor it would have if you didn't define one:

    class GameCryptography { 
    public:
    
        // define our ctor that takes an argument
        GameCryptography(BlofishAlgorithm); 
    
        // Tell the compiler to do what it would have if we didn't define a ctor:
        GameCryptography() = default;
    };
    

    As a final note, I think it's worth mentioning that ECB, CBC, CFB, etc., are modes of operation, not really encryption algorithms themselves. Calling them algorithms won't bother the compiler, but is unreasonably likely to cause a problem for others reading the code.

    html button to send email

     <form action="mailto:[email protected]" method="post"               enctype="text/plain">
     Name:<br>
    <input type="text" name="name"><br>
     E-mail:<br>
    <input type="text" name="mail"><br>
    Comment:<br>
    <input type="text" name="comment" size="50"><br><br>
    <input type="submit" value="Send">
    <input type="reset" value="Reset">
    

    File tree view in Notepad++

    You can also use you own computer built-in functions:

    • Create a file, write this on it:
    tree /a /f >tree.txt
    • Save the file as any_name_you_want.BAT
    • Launch it, it will create a file named tree.txt that contains you directory TREE.

    What is the function __construct used for?

    I believe that function __construct () {...} is a piece of code that can be reused again and again in substitution for TheActualFunctionName () {...}. If you change the CLASS Name you do not have to change within the code because the generic __construct refers always to the actual class name...whatever it is. You code less...or?

    How to bind a List to a ComboBox?

    If you are using a ToolStripComboBox there is no DataSource exposed (.NET 4.0):

    List<string> someList = new List<string>();
    someList.Add("value");
    someList.Add("value");
    someList.Add("value");
    
    toolStripComboBox1.Items.AddRange(someList.ToArray());
    

    Convert hours:minutes:seconds into total minutes in excel

    The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:

    =HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
    

    enter image description here

    How to darken an image on mouseover?

    Make the image 100% bright so it is clear. And then on Img hover reduce it to whatever brightness you want.

    _x000D_
    _x000D_
    img {_x000D_
       -webkit-transition: all 1s ease;_x000D_
       -moz-transition: all 1s ease;_x000D_
       -o-transition: all 1s ease;_x000D_
       -ms-transition: all 1s ease;_x000D_
       transition: all 1s ease;_x000D_
    }_x000D_
    _x000D_
    img:hover {_x000D_
       -webkit-filter: brightness(70%);_x000D_
       filter: brightness(70%);_x000D_
    }
    _x000D_
    <img src="http://dummyimage.com/300x150/ebebeb/000.jpg">
    _x000D_
    _x000D_
    _x000D_

    That will do it, Hope that helps

    UICollectionView auto scroll to cell at IndexPath

    All answers here - hacks. I've found better way to scroll collection view somewhere after relaodData:
    Subclass collection view layout what ever layout you use, override method prepareLayout, after super call set what ever offset you need.
    ex: https://stackoverflow.com/a/34192787/1400119

    String concatenation in MySQL

    Try:

    select concat(first_name,last_name) as "Name" from test.student
    

    or, better:

    select concat(first_name," ",last_name) as "Name" from test.student
    

    Getting Image from URL (Java)

    You are getting an HTTP 400 (Bad Request) error because there is a space in your URL. If you fix it (before the zoom parameter), you will get an HTTP 400 error (Unauthorized). Maybe you need some HTTP header to identify your download as a recognised browser (use the "User-Agent" header) or additional authentication parameter.

    For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:

    URLConnection connection = url.openConnection();
    connection.setRequestProperty("User-Agent", "xxxxxx");
    

    Use whatever needed for xxxxxx

    How do I get git to default to ssh and not https for new repositories

    Set up a repository's origin branch to be SSH

    The GitHub repository setup page is just a suggested list of commands (and GitHub now suggests using the HTTPS protocol). Unless you have administrative access to GitHub's site, I don't know of any way to change their suggested commands.

    If you'd rather use the SSH protocol, simply add a remote branch like so (i.e. use this command in place of GitHub's suggested command). To modify an existing branch, see the next section.

    $ git remote add origin [email protected]:nikhilbhardwaj/abc.git
    

    Modify a pre-existing repository

    As you already know, to switch a pre-existing repository to use SSH instead of HTTPS, you can change the remote url within your .git/config file.

    [remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        -url = https://github.com/nikhilbhardwaj/abc.git
        +url = [email protected]:nikhilbhardwaj/abc.git
    

    A shortcut is to use the set-url command:

    $ git remote set-url origin [email protected]:nikhilbhardwaj/abc.git
    

    More information about the SSH-HTTPS switch

    How can I select all rows with sqlalchemy?

    I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import create_engine, Sequence
    from sqlalchemy import String, Integer, Float, Boolean, Column
    from sqlalchemy.orm import sessionmaker
    
    Base = declarative_base()
    
    class MyTable(Base):
        __tablename__ = 'MyTable'
        id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
        some_col = Column(String(500))
    
        def __init__(self, some_col):
            self.some_col = some_col
    
    engine = create_engine('sqlite:///sqllight.db', echo=True)
    Session = sessionmaker(bind=engine)
    session = Session()
    
    for class_instance in session.query(MyTable).all():
        print(vars(class_instance))
    
    session.close()
    

    Passing capturing lambda as function pointer

    A lambda can only be converted to a function pointer if it does not capture, from the draft C++11 standard section 5.1.2 [expr.prim.lambda] says (emphasis mine):

    The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

    Note, cppreference also covers this in their section on Lambda functions.

    So the following alternatives would work:

    typedef bool(*DecisionFn)(int);
    
    Decide greaterThanThree{ []( int x ){ return x > 3; } };
    

    and so would this:

    typedef bool(*DecisionFn)();
    
    Decide greaterThanThree{ [](){ return true ; } };
    

    and as 5gon12eder points out, you can also use std::function, but note that std::function is heavy weight, so it is not a cost-less trade-off.

    How to get value of Radio Buttons?

    You can also use a Common Event for your RadioButtons, and you can use the Tag property to pass information to your string or you can use the Text Property if you want your string to hold the same value as the Text of your RadioButton.

    Something like this.

    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        if (((RadioButton)sender).Checked == true)
            sex = ((RadioButton)sender).Tag.ToString();
    }
    

    nodejs - first argument must be a string or Buffer - when using response.write with http.request

    response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.

    res.write(response.statusCode.toString());
    

    You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.

    Storing image in database directly or as base64 data?

    I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database

    How to determine if a type implements an interface with C# reflection

    As someone else already mentioned: Benjamin Apr 10 '13 at 22:21"

    It sure was easy to not pay attention and get the arguments for IsAssignableFrom backwards. I will go with GetInterfaces now :p –

    Well, another way around is just to create a short extension method that fulfills, to some extent, the "most usual" way of thinking (and agreed this is a very little personal choice to make it slightly "more natural" based on one's preferences):

    public static class TypeExtensions
    {
        public static bool IsAssignableTo(this Type type, Type assignableType)
        {
            return assignableType.IsAssignableFrom(type);
        }
    }
    

    And why not going a bit more generic (well not sure if it is really that interesting, well I assume I'm just passing another pinch of 'syntaxing' sugar):

    public static class TypeExtensions
    {
        public static bool IsAssignableTo(this Type type, Type assignableType)
        {
            return assignableType.IsAssignableFrom(type);
        }
    
        public static bool IsAssignableTo<TAssignable>(this Type type)
        {
            return IsAssignableTo(type, typeof(TAssignable));
        }
    }
    

    I think it might be much more natural that way, but once again just a matter of very personal opinions:

    var isTrue = michelleType.IsAssignableTo<IMaBelle>();
    

    How to get a date in YYYY-MM-DD format from a TSQL datetime field?

    In your cast and convert link, use style 126 thus:

    CONVERT (varchar(10), DTvalue, 126)

    This truncates the time. Your requirement to have it in yyyy-mm-dd means it must be a string datatype and datetime.

    Frankly though, I'd do it on the client unless you have good reasons not to.

    Running code after Spring Boot starts

    The "Spring Boot" way is to use a CommandLineRunner. Just add beans of that type and you are good to go. In Spring 4.1 (Boot 1.2) there is also a SmartInitializingBean which gets a callback after everything has initialized. And there is SmartLifecycle (from Spring 3).

    cURL not working (Error #77) for SSL connections on CentOS for non-root users

    Windows users, add this to PHP.ini:

    curl.cainfo = "C:/cacert.pem";
    

    Path needs to be changed to your own and you can download cacert.pem from a google search

    (yes I know its a CentOS question)

    Ruby, remove last N characters from a string?

    You can always use something like

     "string".sub!(/.{X}$/,'')
    

    Where X is the number of characters to remove.

    Or with assigning/using the result:

    myvar = "string"[0..-X]
    

    where X is the number of characters plus one to remove.

    What are the differences among grep, awk & sed?

    Short definition:

    grep: search for specific terms in a file

    #usage
    $ grep This file.txt
    Every line containing "This"
    Every line containing "This"
    Every line containing "This"
    Every line containing "This"
    
    $ cat file.txt
    Every line containing "This"
    Every line containing "This"
    Every line containing "That"
    Every line containing "This"
    Every line containing "This"
    

    Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

    awk is mostly used for data extraction and reporting. sed is a stream editor
    Each one of them has its own functionality and specialties.

    Example
    Sed

    $ sed -i 's/cat/dog/' file.txt
    # this will replace any occurrence of the characters 'cat' by 'dog'
    

    Awk

    $ awk '{print $2}' file.txt
    # this will print the second column of file.txt
    

    Basic awk usage:
    Compute sum/average/max/min/etc. what ever you may need.

    $ cat file.txt
    A 10
    B 20
    C 60
    $ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
    Average:    30
    

    I recommend that you read this book: Sed & Awk: 2nd Ed.

    It will help you become a proficient sed/awk user on any unix-like environment.

    MySQL OPTIMIZE all tables?

    I made this 'simple' script:

    set @tables_like = null;
    set @optimize = null;
    set @show_tables = concat("show tables where", ifnull(concat(" `Tables_in_", database(), "` like '", @tables_like, "' and"), ''), " (@optimize:=concat_ws(',',@optimize,`Tables_in_", database() ,"`))");
    
    Prepare `bd` from @show_tables;
    EXECUTE `bd`;
    DEALLOCATE PREPARE `bd`;
    
    set @optimize := concat('optimize table ', @optimize);
    PREPARE `sql` FROM @optimize;
    EXECUTE `sql`;
    DEALLOCATE PREPARE `sql`;
    
    set @show_tables = null, @optimize = null, @tables_like = null;
    

    To run it, simply paste it in any SQL IDE connected to your database.

    Notice: this code WON'T work on phpmyadmin.

    How it works

    It runs a show tables statement and stores it in a prepared statement. Then it runs a optimize table in the selected set.

    You can control which tables to optimize by setting a different value in the var @tables_like (e.g.: set @tables_like = '%test%';).

    Search input with an icon Bootstrap 4

    Here is an input box with a search icon on the right.

      <div class="input-group">
          <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
          <div class="input-group-append">
              <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
          </div>
      </div>
    

    Here is an input box with a search icon on the left.

      <div class="input-group">
          <div class="input-group-prepend">
              <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
          </div>
          <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      </div>
    

    CSS Styling for a Button: Using <input type="button> instead of <button>

    Float:left... Although I presume you want the input to be styled not the div?

    .button input{
        color:#08233e;float:left;
        font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
        font-size:70%;
        padding:14px;
        background:url(overlay.png) repeat-x center #ffcc00;
        background-color:rgba(255,204,0,1);
        border:1px solid #ffcc00;
        -moz-border-radius:10px;
        -webkit-border-radius:10px;
        border-radius:10px;
        border-bottom:1px solid #9f9f9f;
        -moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
        -webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
        box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
        cursor:pointer;
    }
    .button input:hover{
        background-color:rgba(255,204,0,0.8);
    }
    

    Reading Space separated input in python

    a=[]
    for j in range(3):
        a.append([int(i) for  i in input().split()])
    

    In this above code the given input i.e Mike 18 Kevin 35 Angel 56, will be stored in an array 'a' and gives the output as [['Mike', '18'], ['Kevin', '35'], ['Angel', '56']].

    How to iterate over a string in C?

    You want:

    for (i = 0; i < strlen(source); i++){
    

    sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:

    char source[] = "This is an example.";
    

    but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:

    int len = strlen( source );
    for (i = 0; i < len; i++){
    

    or rewrite the loop:

    for (i = 0; source[i] != 0; i++){
    

    How to specify the default error page in web.xml?

    You can also do something like that:

    <error-page>
        <error-code>403</error-code>
        <location>/403.html</location>
    </error-page>
    
    <error-page>
        <location>/error.html</location>
    </error-page>
    

    For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

    Convert a dta file to csv without Stata software

    For those who have Stata (even though the asker does not) you can use this:

    outsheet produces a tab-delimited file so you need to specify the comma option like below

    outsheet [varlist] using file.csv , comma
    

    also, if you want to remove labels (which are included by default

    outsheet [varlist] using file.csv, comma nolabel
    

    hat tip to:

    http://www.ats.ucla.edu/stat/stata/faq/outsheet.htm

    How can I remove a button or make it invisible in Android?

    To remove button in java code:

    Button btn=(Button)findViewById(R.id.btn);
    btn.setVisibility(View.GONE);
    

    To transparent Button in java code:

    Button btn=(Button)findViewById(R.id.btn);
    btn.setVisibility(View.INVISIBLE);
    

    To remove button in Xml file:

    <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"/>
    

    To transparent button in Xml file:

    <Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="invisible"/>
    

    How to list the contents of a package using YUM?

    I don't think you can list the contents of a package using yum, but if you have the .rpm file on your local system (as will most likely be the case for all installed packages), you can use the rpm command to list the contents of that package like so:

    rpm -qlp /path/to/fileToList.rpm
    

    If you don't have the package file (.rpm), but you have the package installed, try this:

    rpm -ql packageName
    

    extract column value based on another column pandas dataframe

    male_avgtip=(tips_data.loc[tips_data['sex'] == 'Male', 'tip']).mean()
    

    I have also worked on this clausing and extraction operations for my assignment.

    lodash multi-column sortBy descending

    Deep field & multi field & different direction ordering Lodash >4

    var sortedArray = _.orderBy(mixedArray,
                                ['foo','foo.bar','bar.foo.bar'],               
                                ['desc','asc','desc']);
    

    What does mvn install in maven exactly do

    As you might be aware of, Maven is a build automation tool provided by Apache which does more than dependency management. We can make it as a peer of Ant and Makefile which downloads all of the dependencies required.

    On a mvn install, it frames a dependency tree based on the project configuration pom.xml on all the sub projects under the super pom.xml (the root POM) and downloads/compiles all the needed components in a directory called .m2 under the user's folder. These dependencies will have to be resolved for the project to be built without any errors, and mvn install is one utility that could download most of the dependencies.

    Further, there are other utils within Maven like dependency:resolve which can be used separately in any specific cases. The build life cycle of the mvn is as below: LifeCycle Bindings

    1. process-resources
    2. compile
    3. process-test-resources
    4. test-compile
    5. test
    6. package
    7. install
    8. deploy

    The test phase of this mvn can be ignored by using a flag -DskipTests=true.

    How to update a plot in matplotlib?

    In case anyone comes across this article looking for what I was looking for, I found examples at

    How to visualize scalar 2D data with Matplotlib?

    and

    http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop (on web.archive.org)

    then modified them to use imshow with an input stack of frames, instead of generating and using contours on the fly.


    Starting with a 3D array of images of shape (nBins, nBins, nBins), called frames.

    def animate_frames(frames):
        nBins   = frames.shape[0]
        frame   = frames[0]
        tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
        for k in range(nBins):
            frame   = frames[k]
            tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
            del tempCS1
            fig.canvas.draw()
            #time.sleep(1e-2) #unnecessary, but useful
            fig.clf()
    
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    
    win = fig.canvas.manager.window
    fig.canvas.manager.window.after(100, animate_frames, frames)
    

    I also found a much simpler way to go about this whole process, albeit less robust:

    fig = plt.figure()
    
    for k in range(nBins):
        plt.clf()
        plt.imshow(frames[k],cmap=plt.cm.gray)
        fig.canvas.draw()
        time.sleep(1e-6) #unnecessary, but useful
    

    Note that both of these only seem to work with ipython --pylab=tk, a.k.a.backend = TkAgg

    Thank you for the help with everything.

    ReferenceError: document is not defined (in plain JavaScript)

    try: window.document......

    var body = window.document.getElementsByTagName("body")[0];
    

    How to manage a redirect request after a jQuery Ajax call

    I didn't have any success with the header solution - they were never picked up in my ajaxSuccess / ajaxComplete method. I used Steg's answer with the custom response, but I modified the JS side some. I setup a method that I call in each function so I can use standard $.get and $.post methods.

    function handleAjaxResponse(data, callback) {
        //Try to convert and parse object
        try {
            if (jQuery.type(data) === "string") {
                data = jQuery.parseJSON(data);
            }
            if (data.error) {
                if (data.error == 'login') {
                    window.location.reload();
                    return;
                }
                else if (data.error.length > 0) {
                    alert(data.error);
                    return;
                }
            }
        }
        catch(ex) { }
    
        if (callback) {
            callback(data);
        }
    }
    

    Example of it in use...

    function submitAjaxForm(form, url, action) {
        //Lock form
        form.find('.ajax-submit').hide();
        form.find('.loader').show();
    
        $.post(url, form.serialize(), function (d) {
            //Unlock form
            form.find('.ajax-submit').show();
            form.find('.loader').hide();
    
            handleAjaxResponse(d, function (data) {
                // ... more code for if auth passes ...
            });
        });
        return false;
    }
    

    Check if one date is between two dates

    Simplified way of doing this based on the accepted answer.

    In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.

    
    var currentDate = new Date().toJSON().slice(0,10);
    var from = new Date('2020/01/01');
    var to   = new Date('2020/01/31');
    var check = new Date(currentDate);
    
    console.log(check > from && check < to);
    
    

    jQuery ajax success error

    I had the same problem;

    textStatus = 'error'
    errorThrown = (empty)
    xhr.status = 0
    

    That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

    I have tried calling it this way also:

    var request = $.ajax({
    url: "http://crossdomain.url.net/somefile.php", dataType: "text",
    crossDomain: true,
    xhrFields: {
    withCredentials: true
    }
    });
    

    but without success.

    This post solved it for me: jQuery AJAX cross domain

    How to center an iframe horizontally?

    Add display:block; to your iframe css.

    _x000D_
    _x000D_
    div, iframe {
        width: 100px;
        height: 50px;
        margin: 0 auto;
        background-color: #777;
    }
    
    iframe {
        display: block;
        border-style:none;
    }
    _x000D_
    <div>div</div>
    <iframe src="data:,iframe"></iframe>
    _x000D_
    _x000D_
    _x000D_

    How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

    What I did : On my production server, I create a config file (confthin.yml) for Thin (I'm using it) and add the following information :

    environment: production
    user: www-data
    group: www-data
    SECRET_KEY_BASE: mysecretkeyproduction
    

    I then launch the app with

    thin start -C /whereeveristhefieonprod/configthin.yml
    

    Work like a charm and then no need to have the secret key on version control

    Hope it could help, but I'm sure the same thing could be done with Unicorn and others.

    PHP cURL not working - WAMP on Windows 7 64 bit

    I had the same exact issue. After trying almost everything and digging on Stack Overflow, I finally found the reason. Try downloading "fixed curl extension" separately from PHP 5.4.3 and PHP 5.3.13 x64 (64 bit) for Windows.

    I've downloaded "php_curl-5.4.3-VC9-x64", and it worked for me. I hope it helps.

    Delete certain lines in a txt file via a batch file

    If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}" should do the trick.

    Comparing two java.util.Dates to see if they are in the same day

    private boolean isSameDay(Date date1, Date date2) {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(date1);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(date2);
            boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
            boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
            boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
            return (sameDay && sameMonth && sameYear);
        }
    

    How do I get the domain originating the request in express.js?

    In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.:

    // Host: "example.com:3000"
    req.hostname
    // => "example.com"
    

    See: http://expressjs.com/en/4x/api.html#req.hostname

    How to get current domain name in ASP.NET

    Try this:

    @Request.Url.GetLeftPart(UriPartial.Authority)

    ComboBox: Adding Text and Value to an Item (no Binding Source)

    //set 
    comboBox1.DisplayMember = "Value"; 
    //to add 
    comboBox1.Items.Add(new KeyValuePair("2", "This text is displayed")); 
    //to access the 'tag' property 
    string tag = ((KeyValuePair< string, string >)comboBox1.SelectedItem).Key; 
    MessageBox.Show(tag);
    

    How to clear APC cache entries?

    If you want to clear apc cache in command : (use sudo if you need it)

    APCu

    php -r "apcu_clear_cache();" 
    

    APC

    php -r "apc_clear_cache(); apc_clear_cache('user'); apc_clear_cache('opcode');"
    

    A top-like utility for monitoring CUDA activity on a GPU

    Just use watch nvidia-smi, it will output the message by 2s interval in default.

    For example, as the below image:

    enter image description here

    You can also use watch -n 5 nvidia-smi (-n 5 by 5s interval).

    Session timeout in ASP.NET

    I don't know about web.config or IIS. But I believe that from C# code you can do it like

    Session.Timeout = 60; // 60 is number of minutes
    

    How to import or copy images to the "res" folder in Android Studio?

    Goto Settings > Plugin > Browse Repository > Serach Android Drawable Import

    This plugin consists of 4 main features.

    • AndroidIcons Drawable Import
    • Material Icons Drawable Import
    • Scaled Drawable
    • Multisource-Drawable

    Edit : After Android Studios 1.5 android support Vector Asset Studio.


    Follow this, which says:

    To start Vector Asset Studio:

    1. In Android Studio, open an Android app project.
    2. In the Project window, select the Android view.
    3. Right-click the res folder and select New > Vector Asset.

    enter image description here

    How to get max value of a column using Entity Framework?

    int maxAge = context.Persons.Max(p => p.Age);
    

    This version, if the list is empty:

    • Returns null - for nullable overloads
    • Throws Sequence contains no element exception - for non-nullable overloads

    -

    int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();
    

    This version handles the empty list case, but it generates more complex query, and for some reason doesn't work with EF Core.

    -

    int maxAge = context.Persons.Max(p => (int?)p.Age) ?? 0;
    

    This version is elegant and performant (simple query and single round-trip to the database), works with EF Core. It handles the mentioned exception above by casting the non-nullable type to nullable and then applying the default value using the ?? operator.

    How do you test to see if a double is equal to NaN?

    If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:

    (value==null || Double.isNaN(value))

    Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.

    The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

    I had this same problem, my solution:
    In the web.config file :

    <compilation debug="true>
    had to be changed to
    <compilation debug="true" targetFramework="4.0">

    Flutter does not find android sdk

    Flutter provides a command to update the Android SDK path:

    flutter config --android-sdk < path to your sdk >
    

    OR

    If you are facing this issue --> sdk file is not found in android-sdk\build-tools\28.0.3\aapt.

    You may have probably not installed build tools for this Api level, Which can be installed through this link https://androidsdkmanager.azurewebsites.net/Buildtools

    How to vertically align an image inside a div

    The only (and the best cross-browser) way as I know is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.

    So there is a solution: http://jsfiddle.net/kizu/4RPFa/4570/

    _x000D_
    _x000D_
    .frame {_x000D_
        height: 25px;      /* Equals maximum image height */_x000D_
        width: 160px;_x000D_
        border: 1px solid red;_x000D_
        white-space: nowrap; /* This is required unless you put the helper span closely near the img */_x000D_
    _x000D_
        text-align: center;_x000D_
        margin: 1em 0;_x000D_
    }_x000D_
    _x000D_
    .helper {_x000D_
        display: inline-block;_x000D_
        height: 100%;_x000D_
        vertical-align: middle;_x000D_
    }_x000D_
    _x000D_
    img {_x000D_
        background: #3A6F9A;_x000D_
        vertical-align: middle;_x000D_
        max-height: 25px;_x000D_
        max-width: 160px;_x000D_
    }
    _x000D_
    <div class="frame">_x000D_
        <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=17px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=15px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=13px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=11px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=9px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=7px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=5px />_x000D_
    </div>_x000D_
    <div class="frame">_x000D_
        <span class="helper"></span>_x000D_
        <img src="http://jsfiddle.net/img/logo.png" height=3px />_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Or, if you don't want to have an extra element in modern browsers and don't mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won't be any performance issues:

    The solution with :before and expression() for Internet Explorer: http://jsfiddle.net/kizu/4RPFa/4571/

    _x000D_
    _x000D_
    .frame {_x000D_
        height: 25px;      /* Equals maximum image height */_x000D_
        width: 160px;_x000D_
        border: 1px solid red;_x000D_
        white-space: nowrap;_x000D_
    _x000D_
        text-align: center;_x000D_
        margin: 1em 0;_x000D_
    }_x000D_
    _x000D_
    .frame:before,_x000D_
    .frame_before {_x000D_
        content: "";_x000D_
        display: inline-block;_x000D_
        height: 100%;_x000D_
        vertical-align: middle;_x000D_
    }_x000D_
    _x000D_
    img {_x000D_
        background: #3A6F9A;_x000D_
        vertical-align: middle;_x000D_
        max-height: 25px;_x000D_
        max-width: 160px;_x000D_
    }_x000D_
    _x000D_
    /* Move this to conditional comments */_x000D_
    .frame {_x000D_
        list-style:none;_x000D_
        behavior: expression(_x000D_
            function(t){_x000D_
                t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');_x000D_
                t.runtimeStyle.behavior = 'none';_x000D_
            }(this)_x000D_
        );_x000D_
    }
    _x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>_x000D_
    <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>
    _x000D_
    _x000D_
    _x000D_


    How it works:

    1. When you have two inline-block elements near each other, you can align each to other's side, so with vertical-align: middle you'll get something like this:

      Two aligned blocks

    2. When you have a block with fixed height (in px, em or another absolute unit), you can set the height of inner blocks in %.

    3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it (<img/> in your case) vertically near it.

    How to set a variable to be "Today's" date in Python/Pandas

    import datetime
    def today_date():
        '''
        utils:
        get the datetime of today
        '''
        date=datetime.datetime.now().date()
        date=pd.to_datetime(date)
        return date
    Df['Date'] = today_date()
    

    this could be safely used in pandas dataframes.

    Adjust list style image position?

    Another option you can do, is the following:

    li:before{
        content:'';
        padding: 0 0 0 25px;
        background:url(../includes/images/layouts/featured-list-arrow.png) no-repeat 0 3px;
    }
    

    Use (0 3px) to position the list image.

    Works in IE8+, Chrome, Firefox, and Opera.

    I use this option because you can swap out list-style easily and a good chance you may not even have to use an image at all. (fiddle below)

    http://jsfiddle.net/flashminddesign/cYAzV/1/

    UPDATE:

    This will account for text / content going into the second line:

    ul{ 
        list-style-type:none;
    }
    
    li{
        position:relative;
    }
    
    ul li:before{
        content:'>';
        padding:0 10px 0 0;
        position:absolute;
        top:0; left:-10px;
    }
    

    Add padding-left: to the li if you want more space between the bullet and content.

    http://jsfiddle.net/McLeodWebDev/wfzwm0zy/

    Get first word of string

    const getFirstWord = string => {
        const firstWord = [];
        for (let i = 0; i < string.length; i += 1) {
            if (string[i] === ' ') break;
            firstWord.push(string[i]);
        }
        return firstWord.join('');
    };
    console.log(getFirstWord('Hello World'));
    

    or simplify it:

    const getFirstWord = string => {
        const words = string.split(' ');
        return words[0];
    };
    console.log(getFirstWord('Hello World'));
    

    Invalid shorthand property initializer

    In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

        var rishabh = {
            class:"final year",
            roll:123,
            percent: function(marks1, marks2, marks3){
                          total = marks1 + marks2 + marks3;
                          this.percentage = total/3 }
                        };
    
    john.percent(85,89,95);
    console.log(rishabh.percentage);
    

    here we have to use commas "," after each property. but you can use another style to create and initialize an object.

    var john = new Object():
    john.father = "raja";  //1st way to assign using dot operator
    john["mother"] = "rani";// 2nd way to assign using brackets and key must be string
    

    MD5 hashing in Android

    The provided solutions for the Scala language (a little shorter):

    def getMd5(content: Array[Byte]) =
        try {
            val md = MessageDigest.getInstance("MD5")
            val bytes = md.digest(content)
            bytes.map(b => Integer.toHexString((b + 0x100) % 0x100)).mkString
        } catch {
            case ex: Throwable => null
        }
    

    how to parse json using groovy

    That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

    JSONObject userJson = JSON.parse(jsonResponse)
    userJson.each { id, data -> println data.link }
    

    If you know it's a single-element Map then you can directly access the link:

    def data = userJson.values().iterator().next()
    String link = data.link
    

    And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

    String id = '212315952136472'
    ...
    String link = userJson[id].link
    

    Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

    I ran into a similar issue today - my ruby version didn't match my rvm installs.

    > ruby -v
    ruby 2.0.0p481
    
    > rvm list
    rvm rubies
       ruby-2.1.2 [ x86_64 ]
    =* ruby-2.2.1 [ x86_64 ]
       ruby-2.2.3 [ x86_64 ]
    

    Also, rvm current failed.

    > rvm current
    Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
    

    The error message recommended this useful command, which resolved the issue for me:

    > rvm get stable --auto-dotfiles
    

    How to access Anaconda command prompt in Windows 10 (64-bit)

    Go with the mouse to the Windows Icon (lower left) and start typing "Anaconda". There should show up some matching entries. Select "Anaconda Prompt". A new command window, named "Anaconda Prompt" will open. Now, you can work from there with Python, conda and other tools.

    bypass invalid SSL certificate in .net core

    Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

    using (var httpClientHandler = new HttpClientHandler())
    {
        httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;   //Is valid
            }
    
            if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
            {
                return true;
            }
            return false;
        };
        using (var httpClient = new HttpClient(httpClientHandler))
        {
            var httpResponse = httpClient.GetAsync("https://example.com").Result;
        }
    }
    

    Original source:

    https://stackoverflow.com/a/44140506/3850405

    form serialize javascript (no framework)

    I refactored TibTibs answer into something that's much clearer to read. It is a bit longer because of the 80 character width and a few comments.

    Additionally, it ignores blank field names and blank values.

    // Serialize the specified form into a query string.
    //
    // Returns a blank string if +form+ is not actually a form element.
    function $serialize(form, evt) {
      if(typeof(form) !== 'object' && form.nodeName !== "FORM")
        return '';
    
      var evt    = evt || window.event || { target: null };
      evt.target = evt.target || evt.srcElement || null;
      var field, query = '';
    
      // Transform a form field into a query-string-friendly
      // serialized form.
      //
      // [NOTE]: Replaces blank spaces from its standard '%20' representation
      //         into the non-standard (though widely used) '+'.
      var encode = function(field, name) {
        if (field.disabled) return '';
    
        return '&' + (name || field.name) + '=' +
               encodeURIComponent(field.value).replace(/%20/g,'+');
      }
    
      // Fields without names can't be serialized.
      var hasName = function(el) {
        return (el.name && el.name.length > 0)
      }
    
      // Ignore the usual suspects: file inputs, reset buttons,
      // buttons that did not submit the form and unchecked
      // radio buttons and checkboxes.
      var ignorableField = function(el, evt) {
        return ((el.type == 'file' || el.type == 'reset')
            || ((el.type == 'submit' || el.type == 'button') && evt.target != el)
            || ((el.type == 'checkbox' || el.type == 'radio') && !el.checked))
      }
    
      var parseMultiSelect = function(field) {
        var q = '';
    
        for (var j=field.options.length-1; j>=0; j--) {
          if (field.options[j].selected) {
            q += encode(field.options[j], field.name);
          }
        }
    
        return q;
      };
    
      for(i = form.elements.length - 1; i >= 0; i--) {
        field = form.elements[i];
    
        if (!hasName(field) || field.value == '' || ignorableField(field, evt))
          continue;
    
        query += (field.type == 'select-multiple') ? parseMultiSelect(field)
                                                   : encode(field);
      }
    
      return (query.length == 0) ? '' : query.substr(1);
    }
    

    How can you detect the version of a browser?

    You can see what the browser says, and use that information for logging or testing multiple browsers.

    _x000D_
    _x000D_
    navigator.sayswho= (function(){_x000D_
        var ua= navigator.userAgent, tem, _x000D_
        M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];_x000D_
        if(/trident/i.test(M[1])){_x000D_
            tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];_x000D_
            return 'IE '+(tem[1] || '');_x000D_
        }_x000D_
        if(M[1]=== 'Chrome'){_x000D_
            tem= ua.match(/\b(OPR|Edge)\/(\d+)/);_x000D_
            if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');_x000D_
        }_x000D_
        M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];_x000D_
        if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);_x000D_
        return M.join(' ');_x000D_
    })();_x000D_
    _x000D_
    console.log(navigator.sayswho); // outputs: `Chrome 62`
    _x000D_
    _x000D_
    _x000D_

    How to handle change of checkbox using jQuery?

    Use :checkbox selector:

    $(':checkbox').change(function() {
    
            // do stuff here. It will fire on any checkbox change
    
    }); 
    

    Code: http://jsfiddle.net/s6fe9/

    How to get image height and width using java?

    To get a Buffered Image with ImageIO.read is a very heavy method, as it's creating a complete uncompressed copy of the image in memory. For png's you may also use pngj and the code:

    if (png)
        PngReader pngr = new PngReader(file);
        width = pngr.imgInfo.cols;
        height = pngr.imgInfo.rows;
        pngr.close();
    }
    

    How to easily map c++ enums to strings

    I just wanted to show this possible elegant solution using macros. This doesn t solve the problem but I think it is a good way to rethik about the problem.

    #define MY_LIST(X) X(value1), X(value2), X(value3)
    
    enum eMyEnum
        {
        MY_LIST(PLAIN)
        };
    
    const char *szMyEnum[] =
        {
        MY_LIST(STRINGY)
        };
    
    
    int main(int argc, char *argv[])
    {
    
    std::cout << szMyEnum[value1] << value1 <<" " <<  szMyEnum[value2] << value2 << std::endl;
    
    return 0;
    }
    

    ---- EDIT ----

    After some internet research and some own experements I came to the following solution:

    //this is the enum definition
    #define COLOR_LIST(X) \
      X( RED    ,=21)      \
      X( GREEN  )      \
      X( BLUE   )      \
      X( PURPLE , =242)      \
      X( ORANGE )      \
      X( YELLOW )
    
    //these are the macros
    #define enumfunc(enums,value) enums,
    #define enumfunc2(enums,value) enums value,
    #define ENUM2SWITCHCASE(enums) case(enums): return #enums;
    
    #define AUTOENUM(enumname,listname) enum enumname{listname(enumfunc2)};
    #define ENUM2STRTABLE(funname,listname) char* funname(int val) {switch(val) {listname(ENUM2SWITCHCASE) default: return "undef";}}
    #define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int values[] = {listname(enumfunc)};int N = sizeof(values)/sizeof(int);ENUM2STRTABLE(enum2str,listname)};
    
    //here the enum and the string enum map table are generated
    AUTOENUM(testenum,COLOR_LIST)
    ENUM2STRTABLE(testfunenum,COLOR_LIST)
    ENUM2STRUCTINFO(colorinfo,COLOR_LIST)//colorinfo structur {int values[]; int N; char * enum2str(int);}
    
    //debug macros
    #define str(a) #a
    #define xstr(a) str(a)
    
    
    int main( int argc, char** argv )
    {
    testenum x = YELLOW;
    std::cout << testfunenum(GREEN) << "   " << testfunenum(PURPLE) << PURPLE << "  " << testfunenum(x);
    
    for (int i=0;i< colorinfo::N;i++)
    std::cout << std::endl << colorinfo::values[i] <<  "  "<< colorinfo::enum2str(colorinfo::values[i]);
    
      return EXIT_SUCCESS;
    }
    

    I just wanted to post it maybe someone could find this solution useful. There is no need of templates classes no need of c++11 and no need of boost so this could also be used for simple C.

    ---- EDIT2 ----

    the information table can produce some problems when using more than 2 enums (compiler problem). The following workaround worked:

    #define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int spacename##_##values[] = {listname(enumfunc)};int spacename##_##N = sizeof(spacename##_##values)/sizeof(int);ENUM2STRTABLE(spacename##_##enum2str,listname)};
    

    Check if current date is between two dates Oracle SQL

    TSQL: Dates- need to look for gaps in dates between Two Date

    select
    distinct
    e1.enddate,
    e3.startdate,
    DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
    from #temp e1 
       join #temp e3 on e1.enddate < e3.startdate          
           /* Finds the next start Time */
    and e3.startdate = (select min(startdate) from #temp e5
    where e5.startdate > e1.enddate)
    and not exists (select *  /* Eliminates e1 rows if it is overlapped */
    from #temp e5 
    where e5.startdate < e1.enddate and e5.enddate > e1.enddate);
    

    How to create a numpy array of arbitrary length strings?

    You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

    >>> a = numpy.array(['apples', 'foobar', 'cowboy'])
    >>> a[2] = 'bananas'
    >>> a
    array(['apples', 'foobar', 'banana'], 
          dtype='|S6')
    

    But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

    >>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
    >>> a
    array([apples, foobar, cowboy], dtype=object)
    >>> a[2] = 'bananas'
    >>> a
    array([apples, foobar, bananas], dtype=object)
    

    Indeed, because it's an array of objects, you can assign any kind of python object to the array:

    >>> a[2] = {1:2, 3:4}
    >>> a
    array([apples, foobar, {1: 2, 3: 4}], dtype=object)
    

    However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

    >>> a = numpy.array(['abba' for _ in range(10000)])
    >>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
    >>> %timeit a.copy()
    100000 loops, best of 3: 2.51 us per loop
    >>> %timeit b.copy()
    10000 loops, best of 3: 48.4 us per loop
    

    How to adjust an UIButton's imageSize?

    Tim's answer is correct, however I wanted to add another suggestion, because in my case there was a simpler solution altogether.

    I was looking to set the UIButton image insets because I didn't realize that I could set the content mode on the button's UIImageView, which would have prevented the need to use UIEdgeInsets and hard-coded values altogether. Simply access the underlying imageview on the button and set the content mode:

    myButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    

    See UIButton doesn't listen to content mode setting?

    Swift 3

    myButton.imageView?.contentMode = .scaleAspectFit
    

    What is REST? Slightly confused

    It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.

    REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.

    In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."

    Worth reading:

    UIDevice uniqueIdentifier deprecated - What to do now?

    Dont use these libraries - libOmnitureAppMeasurement, It does use uniqueIdentifier which apple doesnt support anymore

    How do I simulate a low bandwidth, high latency environment?

    To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.

    How do I check whether an array contains a string in TypeScript?

    Use JavaScript Array includes() Method

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    var n = fruits.includes("Mango");
    

    Try it Yourself » link

    Definition

    The includes() method determines whether an array contains a specified element.

    This method returns true if the array contains the element, and false if not.

    Most efficient way to remove special characters from string

    I'm not sure it is the most efficient way, but It works for me

     Public Function RemoverTildes(stIn As String) As String
        Dim stFormD As String = stIn.Normalize(NormalizationForm.FormD)
        Dim sb As New StringBuilder()
    
        For ich As Integer = 0 To stFormD.Length - 1
            Dim uc As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(stFormD(ich))
            If uc <> UnicodeCategory.NonSpacingMark Then
                sb.Append(stFormD(ich))
            End If
        Next
        Return (sb.ToString().Normalize(NormalizationForm.FormC))
    End Function
    

    Cannot implicitly convert type from Task<>

    You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

    public Task<List<int>> TestGetMethod()
    {
        return GetIdList();
    }    
    
    async Task<List<int>> GetIdList()
    {
        using (HttpClient proxy = new HttpClient())
        {
            string response = await proxy.GetStringAsync("www.test.com");
            List<int> idList = JsonConvert.DeserializeObject<List<int>>();
            return idList;
        }
    }
    

    Another option

    public async void TestGetMethod(List<int> results)
    {
        results = await GetIdList(); // await will unwrap the List<int>
    }