Programs & Examples On #Gdb

Use this tag for problems related to or involving GDB, the standard debugger for the GNU software system.

Is there a C++ gdb GUI for Linux?

KDevelop works pretty well.

gdb: how to print the current line or find the current line number?

Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.

What you are looking for is called de instruction pointer, i.e:

The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.

more detail here

all registers available on gdb execution can be shown with:

(gdb) info registers

with it you can find which mode your program is running (looking which of these registers exist)

then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):

(gdb)info line *$rip

will show you line number and file source

(gdb) list *$rip

will show you that line with a few before and after

but probably

(gdb) frame

should be enough in many cases.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

Can I set a breakpoint on 'memory access' in GDB?

watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.

You can set read watchpoints on memory locations:

gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface

but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions:

gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.

So you have to expand them yourself:

gdb$ print $ebx 
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f

Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()

Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.

gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.

How do I print the elements of a C++ vector in GDB?

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start 

And the GDB command to print N elements of an array starting at pointer P is:

print P@N

Or, in a short form (for a standard .gdbinit):

p P@N

How to attach a process in gdb

With a running instance of myExecutableName having a PID 15073:

hitting Tab twice after $ gdb myExecu in the command line, will automagically autocompletes to:

$ gdb myExecutableName 15073

and will attach gdb to this process. That's nice!

How do I run a program with commandline arguments using GDB within a Bash script?

You can run gdb with --args parameter,

gdb --args executablename arg1 arg2 arg3

If you want it to run automatically, place some commands in a file (e.g. 'run') and give it as argument: -x /tmp/cmds. Optionally you can run with -batch mode.

gdb -batch -x /tmp/cmds --args executablename arg1 arg2 arg3

How to disassemble a memory range with GDB?

fopen() is a C library function and so you won't see any syscall instructions in your code, just a regular function call. At some point, it does call open(2), but it does that via a trampoline. There is simply a jump to the VDSO page, which is provided by the kernel to every process. The VDSO then provides code to make the system call. On modern processors, the SYSCALL or SYSENTER instructions will be used, but you can also use INT 80h on x86 processors.

gdb: "No symbol table is loaded"

I met this issue this morning because I used the same executable in DIFFERENT OSes: after compiling my program with gcc -ggdb -Wall test.c -o test in my Mac(10.15.2), I ran gdb with the executable in Ubuntu(16.04) in my VirtualBox.

Fix: recompile with the same command under Ubuntu, then you should be good.

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

How to install gdb (debugger) in Mac OSX El Capitan?

Please note that this answer was written for Mac OS El Capitan. For newer versions, beware that it may no longer apply. In particular, the legacy option is quite possibly deprecated.

There are two solutions to the problem, and they are both mentioned in other answers to this question and to How to get gdb to work using macports under OSX 10.11 El Capitan?, but to clear up some confusion here is my summary (as an answer since it got a bit long for a comment):

Which alternative is more secure I guess boils down to the choice between 1) trusting self-signed certificates and 2) giving users more privileges.

Alternative 1: signing the binary

If the signature alternative is used, disabling SIP to add the -p option to taskgated is not required.

However, note that with this alternative, debugging is only allowed for users in the _developer group.

Using codesign to sign using a cert named gdb-cert:

codesign -s gdb-cert /opt/local/bin/ggdb

(using the MacPorts standard path, adopt as necessary)

For detailed code-signing recipes (incl cert creation), see : https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html or https://sourceware.org/gdb/wiki/BuildingOnDarwin

Note that you need to restart the keychain application and the taskgated service during and after the process (the easiest way is to reboot).

Alternative 2: use the legacy option for taskgated

As per the answer by @user14241, disabling SIP and adding the -p option to taskgated is an option. Note that if using this option, signing the binary is not needed, and it also bypasses the dialog for authenticating as a member of the Developer Tools group (_developer).

After adding the -p option (allow groups procmod and procview) to taskgated you also need to add the users that should be allowed to use gdb to the procmod group.

The recipe is:

  1. restart in recovery mode, open a terminal and run csrutil disable

  2. restart machine and edit /System/Library/LaunchDaemons/com.apple.taskgated.plist, adding the -p opion:

    <array>
        <string>/usr/libexec/taskgated</string>
        <string>-sp</string>
    </array>
    
  3. restart in recovery mode to reenable SIP (csrutil enable)

  4. restart machine and add user USERNAME to the group procmod:

    sudo dseditgroup -o edit -a USERNAME -t user procmod

    An alternative that does not involve adding users to groups is to make the executable setgid procmod, as that also makes procmod the effective group id of any user executing the setgid binary (suggested in https://apple.stackexchange.com/a/112132)

    sudo chgrp procmod /path/to/gdb
    sudo chmod g+s /path/to/gdb 
    

How do I print the full value of a long string in gdb?

There is a third option: the x command, which allows you to set a different limit for the specific command instead of changing a global setting. To print the first 300 characters of a string you can use x/300s your_string. The output might be a bit harder to read. For example printing a SQL query results in:

(gdb) x/300sb stmt.c_str()
0x9cd948:    "SELECT article.r"...
0x9cd958:    "owid FROM articl"...
..

Core dump file is not generated

If you call daemon() and then daemonize a process, by default the current working directory will change to /. So if your program is a daemon then you should be looking for a core in / directory and not in the directory of the binary.

How do I remove a single breakpoint with GDB?

Try these (reference):

clear linenum
clear filename:linenum

How to modify memory contents using GDB?

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to print register values in GDB?

There is also:

info all-registers

Then you can get the register name you are interested in -- very useful for finding platform-specific registers (like NEON Q... on ARM).

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

Can I use GDB to debug a running process?

Yes. Use the attach command. Check out this link for more information. Typing help attach at a GDB console gives the following:

(gdb) help attach

Attach to a process or file outside of GDB. This command attaches to another target, of the same type as your last "target" command ("info files" will show your target stack). The command may take as argument a process id, a process name (with an optional process-id as a suffix), or a device file. For a process id, you must have permission to send the process a signal, and it must have the same effective uid as the debugger. When using "attach" to an existing process, the debugger finds the program running in the process, looking first in the current working directory, or (if not found there) using the source file search path (see the "directory" command). You can also use the "file" command to specify the program, and to load its symbol table.


NOTE: You may have difficulty attaching to a process due to improved security in the Linux kernel - for example attaching to the child of one shell from another.

You'll likely need to set /proc/sys/kernel/yama/ptrace_scope depending on your requirements. Many systems now default to 1 or higher.

The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other
    process running under the same uid, as long as it is dumpable (i.e.
    did not transition uids, start privileged, or have called
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is
    unchanged.

1 - restricted ptrace: a process must have a predefined relationship
    with the inferior it wants to call PTRACE_ATTACH on. By default,
    this relationship is that of only its descendants when the above
    classic criteria is also met. To change the relationship, an
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare
    an allowed debugger PID to call PTRACE_ATTACH on the inferior.
    Using PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

How to pass arguments and redirect stdin from a file to program run in gdb?

Start GDB on your project.

  1. Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:

    gdb projectExecutablename

This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)

  1. Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:

    (gdb) b main

  2. Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:

    (gdb) r mulder/xfiles

Hope this helps.

Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

The compiler will start doing very clever things with optimisations turned on. The debugger will show the code jumping forward and backwards alot due to the optimized way variables are stored in registers. This is probably the reason why you can't set your variable (or in some cases see its value) as it has been cleverly distributed between registers for speed, rather than having a direct memory location that the debugger can access.

Compile without optimisations?

How do I analyze a program's core dump file with GDB when it has command-line parameters?

From RMS's GDB debugger tutorial:

prompt > myprogram
Segmentation fault (core dumped)
prompt > gdb myprogram
...
(gdb) core core.pid
...

Make sure your file really is a core image -- check it using file.

no debugging symbols found when using gdb

Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.

Show current assembly instruction in GDB

GDB Dashboard

https://github.com/cyrus-and/gdb-dashboard

This GDB configuration uses the official GDB Python API to show us whatever we want whenever GDB stops after for example next, much like TUI.

However I have found that this implementation is a more robust and configurable alternative to the built-in GDB TUI mode as explained at: gdb split view with code

For example, we can configure GDB Dashboard to show disassembly, source, registers and stack with:

dashboard -layout source assembly registers stack

Here is what it looks like if you enable all available views instead:

enter image description here

Related questions:

GDB: Listing all mapped memory regions for a crashed process

If you have the program and the core file, you can do the following steps.

1) Run the gdb on the program along with core file

 $gdb ./test core

2) type info files and see what different segments are there in the core file.

    (gdb)info files

A sample output:

    (gdb)info files 

    Symbols from "/home/emntech/debugging/test".
    Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
  0x0055f000 - 0x0055f000 is load1
  0x0057b000 - 0x0057c000 is load2
  0x0057c000 - 0x0057d000 is load3
  0x00746000 - 0x00747000 is load4
  0x00c86000 - 0x00c86000 is load5
  0x00de0000 - 0x00de0000 is load6
  0x00de1000 - 0x00de3000 is load7
  0x00de3000 - 0x00de4000 is load8
  0x00de4000 - 0x00de7000 is load9
  0x08048000 - 0x08048000 is load10
  0x08049000 - 0x0804a000 is load11
  0x0804a000 - 0x0804b000 is load12
  0xb77b9000 - 0xb77ba000 is load13
  0xb77cc000 - 0xb77ce000 is load14
  0xbf91d000 - 0xbf93f000 is load15

In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.

3) Search for a pattern in the segment.

(gdb) find /w 0x08049000 0x0804a000 0x8048034
 0x804903c
 0x8049040
 2 patterns found

If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.

 http://emntech.com/programs/printseg.c

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

How do I pass a command line argument while starting up GDB in Linux?

I'm using GDB7.1.1, as --help shows:

gdb [options] --args executable-file [inferior-arguments ...]

IMHO, the order is a bit unintuitive at first.

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

What does <value optimized out> mean in gdb?

You need to turn off the compiler optimisation.

If you are interested in a particular variable in gdb, you can delare the variable as "volatile" and recompile the code. This will make the compiler turn off compiler optimization for that variable.

volatile int quantity = 0;

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

in Xcode 8 use:

DispatchQueue.global(qos: .userInitiated).async { }

Python 3 sort a dict by its values

from collections import OrderedDict
from operator import itemgetter    

d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
print(OrderedDict(sorted(d.items(), key = itemgetter(1), reverse = True)))

prints

OrderedDict([('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)])

Though from your last sentence, it appears that a list of tuples would work just fine, e.g.

from operator import itemgetter  

d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
for key, value in sorted(d.items(), key = itemgetter(1), reverse = True):
    print(key, value)

which prints

bb 4
aa 3
cc 2
dd 1

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

How to get phpmyadmin username and password

I had a problem with this. I didn't even create any passwords so I was confused. I googled it and I found out that I should just write root as username and than click GO. I hope it helps.

Project has no default.properties file! Edit the project properties to set one

May be you are missing Third party library to like actionBarSherlock, slidingMenu, achartengine Add it into lib folder and Add to Build Path..

Its work for me.

Add CSS class to a div in code behind

I'm also looking for the same solution. And I think of

BtnventCss.CssClass = BtnventCss.CssClass + " hom_but_a";

It seems working fine but I'm not sure if it is a good practice

WCF Service, the type provided as the service attribute values…could not be found

Double check projects .net versions. Projects that referenced each other with different .net versions causes problems.

CSS Progress Circle

What about that?

HTML

<div class="chart" id="graph" data-percent="88"></div>

Javascript

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

and CSS

div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

http://jsfiddle.net/Aapn8/3410/

Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

How to use Google App Engine with my own naked domain (not subdomain)?

[Update April 2016] This answer is now outdated, custom naked domain mapping is supported, see Lawrence Mok's answer.

See http://www.google.com/support/a/bin/answer.py?hl=en&answer=91077 for the details. Once you have signed up for Google Apps for Your Domain:

# Sign in to the Google App Engine admin console.
# Go to Administration > Versions
# Click the 'Add Domain...' button under Domain Setup.
# Enter your domain name in the 'Domain Name:' field
# Click 'Add Domain'. You will be directed to the Google Apps administrator console to complete the process.
# Log in to the Google Apps control panel with your administrator account.
# Accept the terms and specify the access URL you'd like to provide for your application.
# Click 'Accept

You can't use a naked domain, though, such as whatever.com (but www.whatever.com does work), because:

Due to recent changes, Google App Engine no longer supports mapping your app to a naked domain. If your domain registrar supports URL redirects, you can redirect from http://yourdomain.com to your app, which can be served from domains like http://www.yourdomain.com or http://appid.yourdomain.com.

as specified at http://www.google.com/support/a/bin/answer.py?answer=91080

Print all key/value pairs in a Java ConcurrentHashMap

You can do something like

Iterator iterator = map.keySet().iterator();

while (iterator.hasNext()) {
   String key = iterator.next().toString();
   Integer value = map.get(key);

   System.out.println(key + " " + value);
}

Here 'map' is your concurrent HashMap.

What exactly does an #if 0 ..... #endif block do?

It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.

Also, I suspect a better way of doing it for debug purpose would be to do:

#ifdef DEBUG
// output to file
#endif

You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.

How can I disable selected attribute from select2() dropdown Jquery?

The right way for Select2 3.x is:

$('select').select2("enable", false)

This works fine.

How to get bitmap from a url in android?

This is a simple one line way to do it:

    try {
        URL url = new URL("http://....");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch(IOException e) {
        System.out.println(e);
    }

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

The blog post Grab the Picture of a Facebook Graph Object might offer another form of solution. Use the code in the tutorial along with the Facebook's Graph API and its PHP SDK library.

... And try not to use file_get_contents (unless you're ready to face the consequences - see file_get_contents vs curl).

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Android Image View Pinch Zooming

Add bellow line in build.gradle:

compile 'com.commit451:PhotoView:1.2.4'

or

compile 'com.github.chrisbanes:PhotoView:1.3.0'

In Java file:

PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();

Detect a finger swipe through JavaScript on the iPhone and Android

jQuery Mobile also includes swipe support: http://api.jquerymobile.com/swipe/

Example

$("#divId").on("swipe", function(event) {
    alert("It's a swipe!");
});

Equivalent to AssemblyInfo in dotnet core/csproj

I do the following for my .NET Standard 2.0 projects.

Create a Directory.Build.props file (e.g. in the root of your repo) and move the properties to be shared from the .csproj file to this file.

MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs.

They also get applied to the nuget package when building one with dotnet pack or via the UI in Visual Studio 2017.

See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build

Example:

<Project>
    <PropertyGroup>
        <Company>Some company</Company>
        <Copyright>Copyright © 2020</Copyright>
        <AssemblyVersion>1.0.0.1</AssemblyVersion>
        <FileVersion>1.0.0.1</FileVersion>
        <Version>1.0.0.1</Version>
        <!-- ... -->
    </PropertyGroup>
</Project>

What is the difference between Python's list methods append and extend?

Append and extend are one of the extensibility mechanisms in python.

Append: Adds an element to the end of the list.

my_list = [1,2,3,4]

To add a new element to the list, we can use append method in the following way.

my_list.append(5)

The default location that the new element will be added is always in the (length+1) position.

Insert: The insert method was used to overcome the limitations of append. With insert, we can explicitly define the exact position we want our new element to be inserted at.

Method descriptor of insert(index, object). It takes two arguments, first being the index we want to insert our element and second the element itself.

Example: my_list = [1,2,3,4]
my_list[4, 'a']
my_list
[1,2,3,4,'a']

Extend: This is very useful when we want to join two or more lists into a single list. Without extend, if we want to join two lists, the resulting object will contain a list of lists.

a = [1,2]
b = [3]
a.append(b)
print (a)
[1,2,[3]]

If we try to access the element at pos 2, we get a list ([3]), instead of the element. To join two lists, we'll have to use append.

a = [1,2]
b = [3]
a.extend(b)
print (a)
[1,2,3]

To join multiple lists

a = [1]
b = [2]
c = [3]
a.extend(b+c)
print (a)
[1,2,3]

How to create cross-domain request?

@RestController
@RequestMapping(value = "/profile")
@CrossOrigin(origins="*")
public class UserProfileController {

SpringREST provides @CrossOrigin annotations where (origins="*") allow access to REST APIS from any source.

We can add it to respective API or entire RestController.

How to select lines between two marker patterns which may occur multiple times with awk/sed

perl -lne 'print if((/abc/../mno/) && !(/abc/||/mno/))' your_file

Runnable with a parameter?

You have two options:

  1. Define a named class. Pass your parameter to the constructor of the named class.

  2. Have your anonymous class close over your "parameter". Be sure to mark it as final.

NSString with \n or line break

If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0

myView.numberOfLines=0;

Grep and Python

You can use python-textops3 :

from textops import *

print('\n'.join(cat(f) | grep(search_term)))

with python-textops3 you can use unix-like commands with pipes

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

apply drop shadow to border-top only?

The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

For usages of Write-Host, PSScriptAnalyzer produces the following diagnostic:

Avoid using Write-Host because it might not work in all hosts, does not work when there is no host, and (prior to PS 5.0) cannot be suppressed, captured, or redirected. Instead, use Write-Output, Write-Verbose, or Write-Information.

See the documentation behind that rule for more information. Excerpts for posterity:

The use of Write-Host is greatly discouraged unless in the use of commands with the Show verb. The Show verb explicitly means "show on the screen, with no other possibilities".

Commands with the Show verb do not have this check applied.

Jeffrey Snover has a blog post Write-Host Considered Harmful in which he claims Write-Host is almost always the wrong thing to do because it interferes with automation and provides more explanation behind the diagnostic, however the above is a good summary.

How do I download a file using VBA (without Internet Explorer)

Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub Example()
    DownloadFile$ = "someFile.ext" 'here the name with extension
    URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
    LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
    MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub

Source

I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.

This was helpful because our organization has Kaspersky AV which blocks active FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

How do I create a new line in Javascript?

If you are using a JavaScript file (.js) then use document.write("\n");. If you are in a html file (.html or . htm) then use document.write("<br/>");.

How to add border radius on table row

Actual Spacing Between Rows

This is an old thread, but I noticed reading the comments from the OP on other answers that the original goal was apparently to have border-radius on the rows, and gaps between the rows. It does not appear that the current solutions exactly do that. theazureshadow's answer is headed in the right direction, but seems to need a bit more.

For those interested in such, here is a fiddle that does separate the rows and applies the radius to each row. (NOTE: Firefox currently has a bug in displaying/clipping background-color at the border radii.)

The code is as follows (and as theazureshadow noted, for earlier browser support, the various vendor prefixes for border-radius need added).

table { 
    border-collapse: separate; 
    border-spacing: 0 10px; 
    margin-top: -10px; /* correct offset on first border spacing if desired */
}
td {
    border: solid 1px #000;
    border-style: solid none;
    padding: 10px;
    background-color: cyan;
}
td:first-child {
    border-left-style: solid;
    border-top-left-radius: 10px; 
    border-bottom-left-radius: 10px;
}
td:last-child {
    border-right-style: solid;
    border-bottom-right-radius: 10px; 
    border-top-right-radius: 10px; 
}

How does one add keyboard languages and switch between them in Linux Mint 16?

Go to menu , search for Regional Settings. Switch to Keyboard layouts tab. Click Options button. Search for Key(s) to change layout. There isn't a default one so you have to tick the combination you like. Enjoy.

Converting DateTime format using razor

For all the given solution, when you try this in a modern browser (like FF), and you have set the correct model

// Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }

// View
<div class="form-group">
    @Html.LabelFor(model => model.Start, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control"} })
    </div>
</div>

mvc(5) wil render (the type of the input is set to date based on your date settings in your model!)

<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" value="01-05-2018" type="date">
        <span class="field-validation-valid text-danger" data-valmsg-for="Start" data-valmsg-replace="true"></span>
</div>

And the browser will show

enter image description here

To fix this you need to change the type to text instead of date (also if you want to use your custom calender)

@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control", @type = "text" } })

Docker error: invalid reference format: repository name must be lowercase

I had the same error, and for some reason it appears to have been cause by uppercase letters in the Jenkins job that ran the docker run command.

How do I get the computer name in .NET

string name = System.Environment.MachineName;

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

Bootstrap 3 Align Text To Bottom of Div

The easiest way I have tested just add a <br> as in the following:

<div class="col-sm-6">
    <br><h3><p class="text-center">Some Text</p></h3>
</div>

The only problem is that a extra line break (generated by that <br>) is generated when the screen gets smaller and it stacks. But it is quick and simple.

How to take last four characters from a varchar?

For Oracle SQL, SUBSTR(column_name, -# of characters requested) will extract last three characters for a given query. e.g.

SELECT SUBSTR(description,-3) FROM student.course;

How can I break up this long line in Python?

For anyone who is also trying to call .format() on a long string, and is unable to use some of the most popular string wrapping techniques without breaking the subsequent .format( call, you can do str.format("", 1, 2) instead of "".format(1, 2). This lets you break the string with whatever technique you like. For example:

logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))

can be

logger.info(str.format(("Skipping {0} because its thumbnail was already"
+ "in our system as {1}"), line[indexes['url']], video.title))

Otherwise, the only possibility is using line ending continuations, which I personally am not a fan of.

How can I stream webcam video with C#?

The usual API for this is DirectShow.

You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.

http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/

http://www.codeproject.com/KB/directx/DirXVidStrm.aspx

To get the streaming part, you probably want to use DirectShow to apply a compression codec to reduce lag, then you can get a Stream and transmit it. You could consider using multicast to reduce network load.

How to do a redirect to another route with react-router?

The simplest solution is:

import { Redirect } from 'react-router';

<Redirect to='/componentURL' />

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

Somehow I had the wrong versions of the DLLs registered in my project.

  • I removed the three references to the Crystal Report dlls from my project. Crystal DLLs
  • I right click References, and click Add Reference
  • In the popup window, I click the Browse menu on the left and the Browse button Reference Manager
  • In the Directory window where your DLLs reside (perhaps your application's bin directory), select the three Crystal Reports DLLs and then click Add. DLLs
  • Back at the Reference Manager window, click in the first column to the left of the three Crystal dlls, and then click OK enter image description here
  • At this point your Crystal Reports should work again.

Setting Oracle 11g Session Timeout

That's generally controlled by the profile associated with the user Tomcat is connecting as.

SQL> SELECT PROFILE, LIMIT FROM DBA_PROFILES WHERE RESOURCE_NAME = 'IDLE_TIME';

PROFILE                        LIMIT
------------------------------ ----------------------------------------
DEFAULT                        UNLIMITED

SQL> SELECT PROFILE FROM DBA_USERS WHERE USERNAME = USER;

PROFILE
------------------------------
DEFAULT

So the user I'm connected to has unlimited idle time - no time out.

Angular 4: How to include Bootstrap?

As i can see you already got lots of answer but you can try this method to .

Its best practice not to use jquery in angular, I prefer https://github.com/valor-software/ngx-bootstrap/blob/development/docs/getting-started/ng-cli.md method to install bootstrap without using bootstrap js component which depends on jquery.

npm install ngx-bootstrap bootstrap --save

or

ng add ngx-bootstrap   (Preferred)

Keep your code jquery free in angular

Key value pairs using JSON

JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.

Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.

So if we have an object:

var myObj = {
    foo:   'bar',
    base:  'ball',
    deep:  {
       java:  'script'
    }
};

We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".

The other way around, we would call window.JSON.parse("a json string like the above");.

JSON.parse() returns a javascript object/array on success.

alert(myObj.deep.java);  // 'script'

window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.

\n or \n in php echo not print

Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:

echo '<p>' . $unit1 . "</p>\n";

PS: One clarification, single quotes strings do accept two escape sequences:

  • \' when you want to use single quote inside single quoted strings
  • \\ when you want to use backslash literally

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

The easiest way is to let NPM do everything for you,

npm --add-python-to-path='true' --debug install --global windows-build-tools

How can JavaScript save to a local file?

So, your real question is: "How can JavaScript save to a local file?"

Take a look at http://www.tiddlywiki.com/

They save their HTML page locally after you have "changed" it internally.

[ UPDATE 2016.01.31 ]

TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.

TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(

[ END OF UPDATE

The trick is, you have to open the page as file:// not as http:// to be able to save locally.

The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.

-Jesse

How to get only filenames within a directory using c#?

string[] fileEntries = Directory.GetFiles(directoryPath);

foreach (var file_name in fileEntries){
    string fileName = file_name.Substring(directoryPath.Length + 1);
    Console.WriteLine(fileName);
}

How does the @property decorator work in Python?

Decorator is a function that takes a function as an argument and returns closure. Closure is a set of inner function and free variable. Inner function is closing over free variable and that is why it is called 'closure'. Free variable is variable that outside the inner function and passed in to inner via docorator.

As the name says, decorator is decorating the received function.

function decorator(undecorated_func):
    print("calling decorator func")
    inner():
       print("I am inside inner")
       return undecorated_func
    return inner

this is a simple decorator function. It received "undecorated_func" and passed it to inner() as a free variable, inner() printed "I am inside inner" and returned undecorated_func. When we call decorator(undecorated_func), it is returning the inner. Here is the key, in decorators we are naming the inner function as the name of the function that we passed.

   undecorated_function= decorator(undecorated_func) 

now inner function is called "undecorated_func". Since inner is now named as "undecorated_func", we passed "undecorated_func" to the decorator and we returned "undecorated_func" plus printed out "I am inside inner". so this print statement decorated our "undecorated_func".

now lets define a class with property decorator:

class Person:
    def __init__(self,name):
        self._name=name
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self.value):
        self._name=value

when we decorated name() with @property(), this is what happened:

name=property(name) # Person.__dict__ you ll see name 

first argument of property() is getter. this is what happened in the second decoration:

   name=name.setter(name) 

As I mentioned above, decorator returns the inner function, and we name the inner function with the name of the function that we passed.

Here is an important thing to be aware of. "name" is immutable. in the first decoration we got this:

  name=property(name)

in the second one we got this

  name=name.setter(name)

We are not modifying name obj. In the second decoration, python sees that this is property object and it already had getter. So python creates a new "name" object, adds the "fget" from the first obj and then sets the "fset".

How to prevent SIGPIPEs (or handle them properly)

What's the best practice to prevent the crash here?

Either disable sigpipes as per everybody, or catch and ignore the error.

Is there a way to check if the other side of the line is still reading?

Yes, use select().

select() doesn't seem to work here as it always says the socket is writable.

You need to select on the read bits. You can probably ignore the write bits.

When the far end closes its file handle, select will tell you that there is data ready to read. When you go and read that, you will get back 0 bytes, which is how the OS tells you that the file handle has been closed.

The only time you can't ignore the write bits is if you are sending large volumes, and there is a risk of the other end getting backlogged, which can cause your buffers to fill. If that happens, then trying to write to the file handle can cause your program/thread to block or fail. Testing select before writing will protect you from that, but it doesn't guarantee that the other end is healthy or that your data is going to arrive.

Note that you can get a sigpipe from close(), as well as when you write.

Close flushes any buffered data. If the other end has already been closed, then close will fail, and you will receive a sigpipe.

If you are using buffered TCPIP, then a successful write just means your data has been queued to send, it doesn't mean it has been sent. Until you successfully call close, you don't know that your data has been sent.

Sigpipe tells you something has gone wrong, it doesn't tell you what, or what you should do about it.

Standard Android Button with a different color

In <Button> use android:background="#33b5e5". or better android:background="@color/navig_button"

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

fatal error LNK1104: cannot open file 'kernel32.lib'

Today in Visual Studio 2017 I had the same problem.

The cause in my case turned out to be a bad environment setting in NETFXSDKDir (NETFXSDKDir=C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1). It needs to be instead NETFXSDKDir=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86. Specifically, as set in this batch file (my directory actually has 4 different files) for the Command Prompt for VS2017:

%comspec% /k "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvars32.bat"

as I am reluctant to change one of the "as installed" batch files… even more as that batch file calls another yet another:

@call "%~dp0vcvarsall.bat" x86 %*

...instead for my specific C++ command-line app, I simply added the explicit path text: ;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86 for a total string in "Library Directories" like this: $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(NETFXKitsDir)Lib\um\x86;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.10240.0\um\x86. (Right click on project, Properties → Configuration Properties → VC++ Directories → Library Directories.) That resolved my "fatal error LNK1104: cannot open file 'kernel32.lib'" error. I found that hint in this GitHub issue.

Note this is reproducible in Visual Studio 2017 Enterprise 2017 Version 15.1 (26403.0) even after successful "repair" install… when creating a new Visual C++ Win32 Console Application and attempting to compile.

In fact, unless a blank application is created, the default template also includes reference to <SDKDDKVer.h> and with that I get this additional error: Error (active) E1696 cannot open source file "SDKDDKVer.h". So I created an empty C++ project.

How to show image using ImageView in Android

If you want to display an image file on the phone, you can do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));

If you want to display an image from your drawable resources, do this:

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);

You'll find the drawable folder(s) in the project res folder. You can put your image files there.

Change One Cell's Data in mysql

UPDATE will change only the columns you specifically list.

UPDATE some_table
SET field1='Value 1'
WHERE primary_key = 7;

The WHERE clause limits which rows are updated. Generally you'd use this to identify your table's primary key (or ID) value, so that you're updating only one row.

The SET clause tells MySQL which columns to update. You can list as many or as few columns as you'd like. Any that you do not list will not get updated.

Use of Application.DoEvents()

Yes.

However, if you need to use Application.DoEvents, this is mostly an indication of a bad application design. Perhaps you'd like to do some work in a separate thread instead?

Array inside a JavaScript Object?

_x000D_
_x000D_
var data = {_x000D_
  name: "Ankit",_x000D_
  age: 24,_x000D_
  workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]_x000D_
};_x000D_
_x000D_
for (const key in data) {_x000D_
  if (data.hasOwnProperty(key)) {_x000D_
    const element = data[key];_x000D_
      console.log(key+": ", element);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Insert HTML with React Variable Statements (JSX)

You can also include this HTML in ReactDOM like this:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

Here are two links link and link2 from React documentation which could be helpful.

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

Static nested class in Java, why?

Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.

As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

How to delete a column from a table in MySQL

If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:

ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;

How to install Hibernate Tools in Eclipse?

uncompress the zip HibernateTools-3.2.4.Beta1-R20081031133 later in eclipse --> menu Help -> Update Sofwate -> add site -> local add, and select de folder uncompress an install automatic

Phone number formatting an EditText in Android

You can use spawns to format phone numbers in Android. This solution is better than the others because it does not change input text. Formatting remains purely visual.

implementation 'com.googlecode.libphonenumber:libphonenumber:7.0.4'

Formatter class:

open class PhoneNumberFormatter : TransformationMethod {
private val mFormatter: AsYouTypeFormatter = PhoneNumberUtil.getInstance().getAsYouTypeFormatter(Locale.getDefault().country)

override fun getTransformation(source: CharSequence, view: View): CharSequence {
    val formatted = format(source)
    if (source is Spannable) {
        setSpans(source, formatted)
        return source
    }
    return formatted
}
override fun onFocusChanged(view: View?, sourceText: CharSequence?, focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) = Unit

private fun setSpans(spannable: Spannable, formatted: CharSequence): CharSequence {

    spannable.clearSpawns()

    var charterIndex = 0
    var formattedIndex = 0
    var spawn = ""
    val spawns: List<String> = spannable
        .map {
            spawn = ""
            charterIndex = formatted.indexOf(it, formattedIndex)
            if (charterIndex != -1){
                spawn = formatted.substring(formattedIndex, charterIndex-1)
                formattedIndex = charterIndex+1
            }
            spawn
        }

    spawns.forEachIndexed { index, sequence ->
        spannable.setSpan(CharterSpan(sequence), index, index + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }

    return formatted
}

private fun Spannable.clearSpawns() =
    this
        .getSpans(0, this.length, CharterSpan::class.java)
        .forEach { this.removeSpan(it) }

private fun format(spannable: CharSequence): String {
    mFormatter.clear()
    var formated = ""
    for (i in 0 until spannable.length) {
        formated = mFormatter.inputDigit(spannable[i])
    }
    return formated
}

private inner class CharterSpan(private val charters: String) : ReplacementSpan() {

    var space = 0

    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
        space = Math.round(paint.measureText(charters, 0, charters.length))
        return Math.round(paint.measureText(text, start, end)) + space
    }

    override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
        space = Math.round(paint.measureText(charters, 0, charters.length))
        canvas.drawText(text, start, end, x + space, y.toFloat(), paint)
        canvas.drawText(charters, x, y.toFloat(), paint)
    }
    }

}

Uasge:

editText.transformationMethod = formatter

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

How to get selected value from Dropdown list in JavaScript

According to Html5 specs you should use -- element.options[e.selectedIndex].text

e.g. if you have select box like below :

<select id="selectbox1">
    <option value="1">First</option>
    <option value="2" selected="selected">Second</option>
    <option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>

you can get value using following script :

<script>
 function GetItemValue(q) {
   var e = document.getElementById(q);
   var selValue = e.options[e.selectedIndex].text ;
   alert("Selected Value: "+selValue);
 }
</script>

Tried and tested.

How to create a JavaScript callback for knowing when an image is loaded?

Image.onload() will often work.

To use it, you'll need to be sure to bind the event handler before you set the src attribute.

Related Links:

Example Usage:

_x000D_
_x000D_
    window.onload = function () {_x000D_
_x000D_
        var logo = document.getElementById('sologo');_x000D_
_x000D_
        logo.onload = function () {_x000D_
            alert ("The image has loaded!");  _x000D_
        };_x000D_
_x000D_
        setTimeout(function(){_x000D_
            logo.src = 'https://edmullen.net/test/rc.jpg';         _x000D_
        }, 5000);_x000D_
    };
_x000D_
 <html>_x000D_
    <head>_x000D_
    <title>Image onload()</title>_x000D_
    </head>_x000D_
    <body>_x000D_
_x000D_
    <img src="#" alt="This image is going to load" id="sologo"/>_x000D_
_x000D_
    <script type="text/javascript">_x000D_
_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

Check that a input to UITextField is numeric only

I wanted a text field that only allowed integers. Here's what I ended up with (using info from here and elsewhere):

Create integer number formatter (in UIApplicationDelegate so it can be reused):

@property (nonatomic, retain) NSNumberFormatter *integerNumberFormatter;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Create and configure an NSNumberFormatter for integers
    integerNumberFormatter = [[NSNumberFormatter alloc] init];
    [integerNumberFormatter setMaximumFractionDigits:0];

    return YES;
}

Use filter in UITextFieldDelegate:

@interface MyTableViewController : UITableViewController <UITextFieldDelegate> {
    ictAppDelegate *appDelegate;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Make sure the proposed string is a number
    NSNumberFormatter *inf = [appDelegate integerNumberFormatter];
    NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSNumber *proposedNumber = [inf numberFromString:proposedString];
    if (proposedNumber) {
        // Make sure the proposed number is an integer
        NSString *integerString = [inf stringFromNumber:proposedNumber];
        if ([integerString isEqualToString:proposedString]) {
            // proposed string is an integer
            return YES;
        }
    }

    // Warn the user we're rejecting the change
    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
    return NO;
}

SyntaxError: Unexpected token o in JSON at position 1

You can simply check the typeof userData & JSON.parse() it only if it's string:

var userData = _data;
var newData;
if (typeof userData === 'object')
  newData = userData.data.userList; // dont parse if its object
else if (typeof userData === 'string')
  newData = JSON.parse(userData).data.userList; // parse if its string

SHA-1 fingerprint of keystore certificate

from a Debug Keystore we can get the SHA1 value in Eclipse. Accessing from the menu: Window -> Preferences -> Android -> Build

but it doesn´t work for a production Keystore. enter image description here

So, to get the SHA1 value from a production Keystore go to: Android Tools -> Export Signed Application Package. Follow the process for signing your apk and the SHA1 will showed as a certificate.

enter image description here

Check if object is a jQuery object

Check out the instanceof operator.

var isJqueryObject = obj instanceof jQuery

Func delegate with no return type

All of the Func delegates take at least one parameter

That's not true. They all take at least one type argument, but that argument determines the return type.

So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

How to asynchronously call a method in Java

You can use @Async annotation from jcabi-aspects and AspectJ:

public class Foo {
  @Async
  public void save() {
    // to be executed in the background
  }
}

When you call save(), a new thread starts and executes its body. Your main thread continues without waiting for the result of save().

SQL Data Reader - handling Null column values

how to about creating helper methods

For String

private static string MyStringConverter(object o)
    {
        if (o == DBNull.Value || o == null)
            return "";

        return o.ToString();
    }

Usage

MyStringConverter(read["indexStringValue"])

For Int

 private static int MyIntonverter(object o)
    {
        if (o == DBNull.Value || o == null)
            return 0;

        return Convert.ToInt32(o);
    }

Usage

MyIntonverter(read["indexIntValue"])

For Date

private static DateTime? MyDateConverter(object o)
    {
        return (o == DBNull.Value || o == null) ? (DateTime?)null : Convert.ToDateTime(o);
    }

Usage

MyDateConverter(read["indexDateValue"])

Note: for DateTime declare varialbe as

DateTime? variable;

Explanation of JSONB introduced by PostgreSQL

  • hstore is more of a "wide column" storage type, it is a flat (non-nested) dictionary of key-value pairs, always stored in a reasonably efficient binary format (a hash table, hence the name).
  • json stores JSON documents as text, performing validation when the documents are stored, and parsing them on output if needed (i.e. accessing individual fields); it should support the entire JSON spec. Since the entire JSON text is stored, its formatting is preserved.
  • jsonb takes shortcuts for performance reasons: JSON data is parsed on input and stored in binary format, key orderings in dictionaries are not maintained, and neither are duplicate keys. Accessing individual elements in the JSONB field is fast as it doesn't require parsing the JSON text all the time. On output, JSON data is reconstructed and initial formatting is lost.

IMO, there is no significant reason for not using jsonb once it is available, if you are working with machine-readable data.

Does Python have an argc argument?

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

Javascript how to parse JSON array

In a for-in-loop the running variable holds the property name, not the property value.

for (var counter in jsonData.counters) {
    console.log(jsonData.counters[counter].counter_name);
}

But as counters is an Array, you have to use a normal for-loop:

for (var i=0; i<jsonData.counters.length; i++) {
    var counter = jsonData.counters[i];
    console.log(counter.counter_name);
}

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

Change background color for selected ListBox item

Or you can apply HighlightBrushKey directly to the ListBox. Setter Property="Background" Value="Transparent" did NOT work. But I did have to set the Foreground to Black.

<ListBox  ... >
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True" >
                    <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="Foreground" Value="Black" />
                </Trigger>
            </Style.Triggers>
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
            </Style.Resources>
        </Style>                
    </ListBox.ItemContainerStyle>
</ListBox>

JavaScript implementation of Gzip

I did not test, but there's a javascript implementation of ZIP, called JSZip:

https://stuk.github.io/jszip/

Does Enter key trigger a click event?

Use (keyup.enter).

Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter pseudo-event.

Append to the end of a Char array in C++

You should have enough space for array1 array and use something like strcat to contact array1 to array2:

char array1[BIG_ENOUGH];
char array2[X];
/* ......             */
/* check array bounds */
/* ......             */

strcat(array1, array2);

How to hide first section header in UITableView (grouped style)

Swift Version: Swift 5.1
Mostly, you can set height in tableView delegate like this:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
   return UIView(frame: CGRect(x: 0, y: 0, width: view.width, height: CGFloat.leastNormalMagnitude))
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
   return CGFloat.leastNormalMagnitude
}

Sometimes when you created UITableView with Xib or Storyboard, the answer of up does not work. you can try the second solution:

let headerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
self.tableView.tableHeaderView = headerView

Hope it works for you!

How do I change the value of a global variable inside of a function

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

_x000D_
_x000D_
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
  // y is local to the function, because it is a function parameter_x000D_
  console.log('local y: should be 10:', y); // local y through function parameter_x000D_
  y = 3; // will only overwrite local y, not 'global' y_x000D_
  console.log('local y: should be 3:', y); // local y_x000D_
  // global value could be accessed by referencing through window object_x000D_
  console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
  var x; // makes x a local variable_x000D_
  x = 4; // only overwrites local x_x000D_
  console.log('local x: should be 4:', x); // local x_x000D_
  _x000D_
  z = 5; // overwrites global z, because there is no local z_x000D_
  console.log('local z: should be 5:', z); // local z, same as global_x000D_
  console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
_x000D_
_x000D_

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

ASP.NET file download from server

protected void DescargarArchivo(string strRuta, string strFile)
{
    FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
    Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
    Response.ContentType = "application/pdf";
    Response.WriteFile(ObjArchivo.FullName);
    Response.End();


}

Swift programmatically navigate to another view controller/scene

OperationQueue.main.addOperation {
   let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let newViewController = storyBoard.instantiateViewController(withIdentifier: "Storyboard ID") as! NewViewController
   self.present(newViewController, animated: true, completion: nil)
}

It worked for me when I put the code inside of the OperationQueue.main.addOperation, that will execute in the main thread for me.

How to display pdf in php

easy if its pdf or img use

return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));

Regular expression to limit number of characters to 10

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

CAST to DECIMAL in MySQL

DECIMAL has two parts: Precision and Scale. So part of your query will look like this:

CAST((COUNT(*) * 1.5) AS DECIMAL(8,2))

Precision represents the number of significant digits that are stored for values.
Scale represents the number of digits that can be stored following the decimal point.

Python convert object to float

  • You can use pandas.Series.astype
  • You can do something like this :

    weather["Temp"] = weather.Temp.astype(float)
    
  • You can also use pd.to_numeric that will convert the column from object to float

  • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
  • Example :

    s = pd.Series(['apple', '1.0', '2', -3])
    print(pd.to_numeric(s, errors='ignore'))
    print("=========================")
    print(pd.to_numeric(s, errors='coerce'))
    
  • Output:

    0    apple
    1      1.0
    2        2
    3       -3
    =========================
    dtype: object
    0    NaN
    1    1.0
    2    2.0
    3   -3.0
    dtype: float64
    
  • In your case you can do something like this:

    weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
    
  • Other option is to use convert_objects
  • Example is as follows

    >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
    
    0     1
    1     2
    2     3
    3     4
    4   NaN
    dtype: float64
    
  • You can use this as follows:

    weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
    
  • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

Find which version of package is installed with pip

You can use the grep command to find out.

pip show <package_name>|grep Version

Example:

pip show urllib3|grep Version

will show only the versions.

Metadata-Version: 2.0
Version: 1.12

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

How do I rename a Git repository?

For Amazon AWS codecommit users,

aws codecommit update-repository-name --old-name MyDemoRepo --new-name MyRenamedDemoRepo

Reference: here

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

count number of characters in nvarchar column

Use the LEN function:

Returns the number of characters of the specified string expression, excluding trailing blanks.

Binding Button click to a method

You have various possibilies. The most simple and the most ugly is:

XAML

<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/> 

Code Behind

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    FrameworkElement fe=sender as FrameworkElement;
    ((YourClass)fe.DataContext).DoYourCommand();     
} 

Another solution (better) is to provide a ICommand-property on your YourClass. This command will have already a reference to your YourClass-object and therefore can execute an action on this class.

XAML

<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>

Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.

SQL WHERE ID IN (id1, id2, ..., idn)

Doing the SELECT * FROM MyTable where id in () command on an Azure SQL table with 500 million records resulted in a wait time of > 7min!

Doing this instead returned results immediately:

select b.id, a.* from MyTable a
join (values (250000), (2500001), (2600000)) as b(id)
ON a.id = b.id

Use a join.

Java: Static vs inner class

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Error: "setFile(null,false) call failed" when using log4j

I suspect that the variable ${file.name} is not substituted correctly. As a result, the value of log4j.appender.FILE.File becomes logs/. As such, Java tries to create a log file named logs/, but probably it is an existing directory, so you get the exception.

As a quick remedy, change the log4j.appender.FILE.File setting to point to file by absolute path, for example /tmp/mytest.log. You should not get an exception.

After that you can proceed to debugging why ${file.name} is not replaced correctly in your runtime environment.

Convert spark DataFrame column to python list

A possible solution is using the collect_list() function from pyspark.sql.functions. This will aggregate all column values into a pyspark array that is converted into a python list when collected:

mvv_list   = df.select(collect_list("mvv")).collect()[0][0]
count_list = df.select(collect_list("count")).collect()[0][0] 

Can I get "&&" or "-and" to work in PowerShell?

A verbose equivalent is to combine $LASTEXITCODE and -eq 0:

msbuild.exe args; if ($LASTEXITCODE -eq 0) { echo 'it built'; } else { echo 'it failed'; }

I'm not sure why if ($?) didn't work for me, but this one did.

How do you find out which version of GTK+ is installed on Ubuntu?

To make the answer more general than Ubuntu (I have Redhat):

gtk is usually installed under /usr, but possibly in other locations. This should be visible in environment variables. Check with

env | grep gtk

Then try to find where your gtk files are stored. For example, use locate and grep.

locate gtk | grep /usr/lib

In this way, I found /usr/lib64/gtk-2.0, which contains the subdirectory 2.10.0, which contains many .so library files. My conclusion is that I have gtk+ version 2.10. This is rather consistent with the rpm command on Redhat: rpm -qa | grep gtk2, so I think my conclusion is right.

Rails 4: assets not loading in production

location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;
  add_header ETag "";
}

This fixed the problem for me in production. Put it into the nginx config.

Angular2 Material Dialog css, dialog size

This worked for me:

dialogRef.updateSize("300px", "300px");

How to Call Controller Actions using JQuery in ASP.NET MVC

You can easily call any controller's action using jQuery AJAX method like this:

Note in this example my controller name is Student

Controller Action

 public ActionResult Test()
 {
     return View();
 }

In Any View of this above controller you can call the Test() action like this:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "@Url.Action("Test", "Student")",
            success: function (result, status, xhr) {
                alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
            },
            error: function (xhr, status, error) {
                alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    });
</script>

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

NodeJS - What does "socket hang up" actually mean?

I was using nano, and it took me a long time to figure out this error. My problem was I was using the wrong port. I had port 5948 instead of 5984.

var nano = require('nano')('http://localhost:5984');
var db = nano.use('address');
var app = express();

Set width of dropdown element in HTML select dropdown options

HTML:

<select class="shortenedSelect">
    <option value="0" disabled>Please select an item</option>
    <option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>

CSS:

.shortenedSelect {
    max-width: 350px;
}

Javascript:

// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
    var curText = $(optionElement).text();
    $(this).attr('title', curText);

    // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
    var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
    }
});

// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
    $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});

Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/

Java Synchronized list

Yes, it will work fine as you have synchronized the list . I would suggest you to use CopyOnWriteArrayList.

CopyOnWriteArrayList<String> cpList=new CopyOnWriteArrayList<String>(new ArrayList<String>());

    void remove(String item)
    {
         do something; (doesn't work on the list)
                 cpList..remove(item);
    }

CSS endless rotation animation

Works in all modern browsers

.rotate{
 animation: loading 3s linear infinite;
 @keyframes loading {
  0% { 
    transform: rotate(0); 
  }
  100% { 
    transform: rotate(360deg);
  }
 }
}

How to find out when a particular table was created in Oracle?

You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)

select * 
  from all_objects 
 where owner = '<name of schema owner>'
   and object_name = '<name of table>'

The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.

As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

How can strings be concatenated?

Just a comment, as someone may find it useful - you can concatenate more than one string in one go:

>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

How to escape a single quote inside awk

awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'

Do subclasses inherit private fields?

No. Private fields are not inherited... and that's why Protected was invented. It is by design. I guess this justified the existence of protected modifier.


Now coming to the contexts. What you mean by inherited -- if it is there in the object created from derived class? yes, it is.

If you mean can it be useful to derived class. Well, no.

Now, when you come to functional programming the private field of super class is not inherited in a meaningful way for the subclass. For the subclass, a private field of super class is same as a private field of any other class.

Functionally, it's not inherited. But ideally, it is.


OK, just looked into Java tutorial they quote this:

Private Members in a Superclass

A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

refer: http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

I agree, that the field is there. But, subclass does not get any privilege on that private field. To a subclass, the private field is same as any private field of any other class.

I believe it's purely matter of point-of-view. You may mould the argument either side. It's better justify both way.

 

Find an element in DOM based on an attribute value

FindByAttributeValue("Attribute-Name", "Attribute-Value");   

p.s. if you know exact element-type, you add 3rd parameter (i.e.div, a, p ...etc...):

FindByAttributeValue("Attribute-Name", "Attribute-Value", "div");   

but at first, define this function:

function FindByAttributeValue(attribute, value, element_type)    {
  element_type = element_type || "*";
  var All = document.getElementsByTagName(element_type);
  for (var i = 0; i < All.length; i++)       {
    if (All[i].getAttribute(attribute) == value) { return All[i]; }
  }
}

p.s. updated per comments recommendations.

center aligning a fixed position div

Normal divs should use margin-left: auto and margin-right: auto, but that doesn't work for fixed divs. The way around this is similar to Andrew's answer, but doesn't use the deprecated <center> thing. Basically, just give the fixed div a wrapper.

_x000D_
_x000D_
#wrapper {_x000D_
    width: 100%;_x000D_
    position: fixed;_x000D_
    background: gray;_x000D_
}_x000D_
#fixed_div {_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    position: relative;_x000D_
    width: 100px;_x000D_
    height: 30px;_x000D_
    text-align: center;_x000D_
    background: lightgreen;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="fixed_div"></div>_x000D_
</div
_x000D_
_x000D_
_x000D_

This will center a fixed div within a div while allowing the div to react with the browser. i.e. The div will be centered if there's enough space, but will collide with the edge of the browser if there isn't; similar to how a regular centered div reacts.

Why is textarea filled with mysterious white spaces?

Please make sure there is no linebreak or space after , it's to make sure there is no whitespace or tab, just copy and paste this code :) I had fix it for you

<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php if($siteLink_val) echo trim($siteLink_val);?></textarea>

About catching ANY exception

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

PowerShell script to return versions of .NET Framework on a machine?

I found this through tab completion in powershell for osx:

[System.Runtime.InteropServices.RuntimeInformation]::get_FrameworkDescription() .NET Core 4.6.25009.03

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

CSS selector for first element with class

you could use first-of-type or nth-of-type(1)

_x000D_
_x000D_
.red {_x000D_
  color: green;  _x000D_
}_x000D_
_x000D_
/* .red:nth-of-type(1) */_x000D_
.red:first-of-type {_x000D_
  color: red;  _x000D_
}
_x000D_
<div class="home">_x000D_
  <span>blah</span>_x000D_
  <p class="red">first</p>_x000D_
  <p class="red">second</p>_x000D_
  <p class="red">third</p>_x000D_
  <p class="red">fourth</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I create a dynamic button click event on a dynamic button?

The easier one for newbies:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

Name does not exist in the current context

I had this problem in my main project when I referenced a dll file.

The problem was that the main project that referenced the dll was targeting a lower framework version than that of the dll.

So I upped my target framework version (Right-click project -> Application -> Target framework) and the error disappeared.

Converting a string to a date in JavaScript

Timestamps should be casted to a Number

var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works

var invalidDate = new Date('1471793029764'); // does not work. Invalid Date

How to increase font size in the Xcode editor?

I found that in the Preferences, there is no fonts and colors selection. Guess the version is different, following is the one that works for the latest version.

Method 1

enter image description here

  • Go to Xcode -> Preferences
  • Click Themes
  • Click the T symbol in the middle of the font
  • Adjust the size at the bottom right corner

Method 2

Simply adjust with cmd + or cmd -

Is it possible to run .APK/Android apps on iPad/iPhone devices?

It is not natively possible to run Android application under iOS (which powers iPhone, iPad, iPod, etc.)

This is because both runtime stacks use entirely different approaches. Android runs Dalvik (a "variant of Java") bytecode packaged in APK files while iOS runs Compiled (from Obj-C) code from IPA files. Excepting time/effort/money and litigations (!), there is nothing inherently preventing an Android implementation on Apple hardware, however.

It looks to package a small Dalvik VM with each application and targeted towards developers.

See iPhoDroid:

Looks to be a dual-boot solution for 2G/3G jailbroken devices. Very little information available, but there are some YouTube videos.

See iAndroid:

iAndroid is a new iOS application for jailbroken devices that simulates the Android operating system experience on the iPhone or iPod touch. While it’s still very far from completion, the project is taking shape.

I am not sure the approach(es) it uses to enable this: it could be emulation or just a simulation (e.g. "looks like"). The requirement of being jailbroken makes it sound like emulation might be used ..

See BlueStacks, per the Holo Dev's comment:

It looks to be an "Android App Player" for OS X (and Windows). However, afaik, it does not [currently] target iOS devices ..

YMMV

Can I use break to exit multiple nested 'for' loops?

I know this is an old thread but I feel this really needs saying and don't have anywhere else to say it. For everybody here, use goto. I just used it.

Like almost everything, goto is not 100% either/xor "bad" or "good". There are at least two uses where I'd say that if you use a goto for them - and don't use it for anything else - you should not only be 100% okay, but your program will be even more readable than without it, as it makes your intention that much clearer (there are ways to avoid it, but I've found all of them to be much clunkier):

  1. Breaking out of nested loops, and
  2. Error handling (i.e. to jump to a cleanup routine at the end of a function in order to return a failure code and deallocate memory.).

Instead of just dogmatically accepting rules like "so-so is 'evil'", understand why that sentiment is claimed, and follow the "why", not the letter of the sentiment. Not knowing this got me in a lot of trouble, too, to the point I'd say calling things dogmatically "evil" can be more harmful than the thing itself. At worst, you just get bad code - and then you know you weren't using it right so long as you heard to be wary, but if you are wracking yourself trying to satisfy the dogmatism, I'd say that's worse.

Why "goto" is called "evil" is because you should never use it to replace ordinary ifs, fors, and whiles. And why that? Try it, try using "goto" instead of ordinary control logic statements, all the time, then try writing the same code again with the control logic, and tell me which one looks nicer and more understandable, and which one looks more like a mess. There you go. (Bonus: try and add a new feature now to the goto-only code.) That's why it's "evil", with suitable scope qualification around the "evil". Using it to short-circuit the shortcomings of C's "break" command is not a problematic usage, so long as you make it clear from the code what your goto is supposed to accomplish (e.g. using a label like "nestedBreak" or something). Breaking out of a nested loop is very natural.

(Or to put it more simply: Use goto to break out of the loop. I'd say that's even preferable. Don't use goto to create the loop. That's "evil".)

And how do you know if you're being dogmatic? If following an "xyz is evil" rule leads your code to be less understandable because you're contorting yourself trying to get around it (such as by adding extra conditionals on each loop, or some flag variable, or some other trick like that), then you're quite likely being dogmatic.

There's no substitute for learning good thinking habits, moreso than good coding habits. The former are prior to the latter and the latter will often follow once the former are adopted. The problem is, however, that far too often I find, the latter are not explicated enough. Too many simply say "this is bad" and "this needs more thought" without saying what to think, what to think about, and why. And that's a big shame.

(FWIW, in C++, the need to break out of nested loops still exists, but the need for error codes does not: in that case, always use exceptions to handle error codes, never return them unless it's going to be so frequent that the exception throw and catch will be causing a performance problem, e.g. in a tight loop in a high demand server code, perhaps [some may say that 'exceptions' should be 'used rarely' but that's another part of ill-thought-out dogmatism: no, at least in my experience after bucking that dogma I find they make things much clearer - just don't abuse them to do something other than error handling, like using them as control flow; effectively the same as with "goto". If you use them all and only for error handling, that's what they're there for.].)

Create Excel file in Java

Changing the extension of a file does not in any way change its contents. The extension is just a label.

If you want to work with Excel spreadsheets using Java, read up on the Apache POI library.

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

You must analyse the actual HTML output, for the hint.

By giving the path like this means "from current location", on the other hand if you start with a / that would mean "from the context".

Adding space/padding to a UILabel

Swift 5 Example with UILabel Extension

With the code below setting your margins is as easy as label.setMargins(15).

extension UILabel {
    func setMargins(_ margin: CGFloat = 10) {
        if let textString = self.text {
            var paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.firstLineHeadIndent = margin
            paragraphStyle.headIndent = margin
            paragraphStyle.tailIndent = -margin
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
            attributedText = attributedString
        }
    }
}

Print range of numbers on same line

for i in range(10):
    print(i, end = ' ')

You can provide any delimiter to the end field (space, comma etc.)

This is for Python 3

Where is GACUTIL for .net Framework 4.0 in windows 7?

If you've got VS2010 installed, you ought to find a .NET 4.0 gacutil at

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

The 7.0A Windows SDK should have been installed alongside VS2010 - 6.0A will have been installed with VS2008, and hence won't have .NET 4.0 support.

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

Casting a number to a string in TypeScript

const page_number = 3;

window.location.hash = page_number as string; // Error

"Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." -> You will get this error if you try to typecast number to string. So, first convert it to unknown and then to string.

window.location.hash = (page_number as unknown) as string; // Correct way

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

If you are dealing with a table and one of the dates happens to be null, you can code it like this:

  @{
     if (Model.SomeCollection[i].date_due == null)
       {
         <td><input type='date' id="@("dd" + i)" name="dd" /></td>
       }
       else
       {
         <td><input type='date' value="@Model.SomeCollection[i].date_due.Value.ToString("yyyy-MM-dd")" id="@("dd" + i)" name="dd" /></td>
       }
   }

change background image in body

If you have JQuery loaded already, you can just do this:

$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');

EDIT:

First load JQuery in the head tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

Then call the Javascript to change the background image when something happens on the page, like when it finishes loading:

<script type="text/javascript">
    $(document).ready(function() {
        $('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
    });
</script>

How to start activity in another application?

If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest

android:exported="true"

Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.

finish();

The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class in the code, so compile will fail.

I searched on the web and found something like this below, and it works well.

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

You can also use the setClassName method:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

You can also pass the values from one app to another app :

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

Bat file to run a .exe at the command prompt

If your folders are set to "hide file extensions", you'll name the file *.bat or *.cmd and it will still be a text file (hidden .txt extension). Be sure you can properly name a file!

How to comment lines in rails html.erb files?

ruby on rails notes has a very nice blogpost about commenting in erb-files

the short version is

to comment a single line use

<%# commented line %>

to comment a whole block use a if false to surrond your code like this

<% if false %>
code to comment
<% end %>

What does "xmlns" in XML mean?

You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.

For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns. For example, mash up friend of a friend with vCard, etc.

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

You can use the tee command to redirect output:

/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz)  | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1

see documentation here

Open directory using C

Some feedback on the segment of code, though for the most part, it should work...

void main(int c,char **args)
  • int main - the standard defines main as returning an int.
  • c and args are typically named argc and argv, respectfully, but you are allowed to name them anything

...

{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
  • You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...

...

dir=opendir(buffer);   //this part

If this returning NULL, it can be for a few reasons:

  • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
  • You lack permissions to the directory
  • There's insufficient memory. (This is unlikely.)

How to render a DateTime in a specific format in ASP.NET MVC 3?

works for me

<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>

Configure WAMP server to send email

Using an open source program call Send Mail, you can send via wamp rather easily actually. I'm still setting it up, but here's a great tutorial by jo jordan. Takes less than 2 mins to setup.

Just tried it and it worked like a charm! Once I uncommented the error log and found out that it was stalling on the pop3 authentication, I just removed that and it sent nicely. Best of luck!

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

Find all CSV files in a directory using Python

import os

path = 'C:/Users/Shashank/Desktop/'
os.chdir(path)

for p,n,f in os.walk(os.getcwd()):
    for a in f:
        a = str(a)
        if a.endswith('.csv'):
            print(a)
            print(p)

This will help to identify path also of these csv files

Error "can't load package: package my_prog: found packages my_prog and main"

Make sure that your package is installed in your $GOPATH directory or already inside your workspace/package.

For example: if your $GOPATH = "c:\go", make sure that the package inside C:\Go\src\pkgName

flutter corner radius with transparent background

Use transparent background color for the modalbottomsheet and give separate color for box decoration


   showModalBottomSheet(
      backgroundColor: Colors.transparent,
      context: context, builder: (context) {
    return Container(

      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
            topLeft:Radius.circular(40) ,
            topRight: Radius.circular(40)
        ),
      ),
      padding: EdgeInsets.symmetric(vertical: 20,horizontal: 60),
      child: Settings_Form(),
    );
  });

What is the difference between char * const and const char *?

const char* is a pointer to a constant character
char* const is a constant pointer to a character
const char* const is a constant pointer to a constant character

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

this happened to me too after adding the version tag, that was missing, to the maven-war-plugin (not sure what version was using by default, i changed to the latest, 2.6 in my case). I had to wipe .m2/repository to have the build succeed again.

I tried first to clean the maven-filtering folder (in the repo) but then instead of a MavenFilterException i was getting an ArchiverException. So i concluded the local repository was corrupted (for a version upgrade?) and i deleted everything.

That fixed it for me. Just clean your local repo.

What's the use of session.flush() in Hibernate

The flush() method causes Hibernate to flush the session. You can configure Hibernate to use flushing mode for the session by using setFlushMode() method. To get the flush mode for the current session, you can use getFlushMode() method. To check, whether session is dirty, you can use isDirty() method. By default, Hibernate manages flushing of the sessions.

As stated in the documentation:

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/flushing/Flushing.html

Flushing

Flushing is the process of synchronizing the state of the persistence context with the underlying database. The EntityManager and the Hibernate Session expose a set of methods, through which the application developer can change the persistent state of an entity.

The persistence context acts as a transactional write-behind cache, queuing any entity state change. Like any write-behind cache, changes are first applied in-memory and synchronized with the database during flush time. The flush operation takes every entity state change and translates it to an INSERT, UPDATE or DELETE statement.

The flushing strategy is given by the flushMode of the current running Hibernate Session. Although JPA defines only two flushing strategies (AUTO and COMMIT), Hibernate has a much broader spectrum of flush types:

  • ALWAYS: Flushes the Session before every query;
  • AUTO: This is the default mode and it flushes the Session only if necessary;
  • COMMIT: The Session tries to delay the flush until the current Transaction is committed, although it might flush prematurely too;
  • MANUAL: The Session flushing is delegated to the application, which must call Session.flush() explicitly in order to apply the persistence context changes.

By default, Hibernate uses the AUTO flush mode which triggers a flush in the following circumstances:

  • prior to committing a Transaction;
  • prior to executing a JPQL/HQL query that overlaps with the queued entity actions;
  • before executing any native SQL query that has no registered synchronization.

What does "ulimit -s unlimited" do?

When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.

To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s. If we remove that limit via ulimit -s unlimited, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.

int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.

Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.

Impact on performace is minor but does exist. Using the time command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

I've posted my jQuery plugin solution here: Frozen table header inside scrollable div

It does exactly what you want and is really lightweight and easy to use.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

In case you do need to define dataSource(), for example when you have multiple data sources, you can use:

@Autowired Environment env;

@Primary
@Bean
public DataSource customDataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("custom.datasource.url"));
    dataSource.setUsername(env.getProperty("custom.datasource.username"));
    dataSource.setPassword(env.getProperty("custom.datasource.password"));

    return dataSource;

}

By setting up the dataSource yourself (instead of using DataSourceBuilder), it fixed my problem which you also had.

The always knowledgeable Baeldung has a tutorial which explains in depth.

Response::json() - Laravel 5.1

However, the previous answer could still be confusing for some programmers. Most especially beginners who are most probably using an older book or tutorial. Or perhaps you still feel the facade is needed. Sure you can use it. Me for one I still love to use the facade, this is because some times while building my api I forget to use the '\' before the Response.

if you are like me, simply add

   "use Response;"

above your class ...extends contoller. this should do.

with this you can now use:

$response = Response::json($posts, 200);

instead of:

$response = \Response::json($posts, 200);

How to enable loglevel debug on Apache2 server

Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.

For older version apache:

For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:

RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"

How to send authorization header with axios

This has worked for me:

let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });

When to Redis? When to MongoDB?

I just noticed that this question is quite old. Nevertheless, I consider the following aspects to be worth adding:

  • Use MongoDB if you don't know yet how you're going to query your data.

    MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.

  • Use Redis in order to speed up your existing application.

    Redis can be easily integrated as a LRU cache. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). Websites like Craigslist use Redis next to their primary database. Antirez (developer of Redis) demonstrated using Lamernews that it is indeed possible to use Redis as a stand alone database system.

  • Redis does not make any assumptions based on your data.

    Redis provides a bunch of useful data structures (e.g. Sets, Hashes, Lists), but you have to explicitly define how you want to store you data. To put it in a nutshell, Redis and MongoDB can be used in order to achieve similar things. Redis is simply faster, but not suited for prototyping. That's one use case where you would typically prefer MongoDB. Besides that, Redis is really flexible. The underlying data structures it provides are the building blocks of high-performance DB systems.

When to use Redis?

  • Caching

    Caching using MongoDB simply doesn't make a lot of sense. It would be too slow.

  • If you have enough time to think about your DB design.

    You can't simply throw in your documents into Redis. You have to think of the way you in which you want to store and organize your data. One example are hashes in Redis. They are quite different from "traditional", nested objects, which means you'll have to rethink the way you store nested documents. One solution would be to store a reference inside the hash to another hash (something like key: [id of second hash]). Another idea would be to store it as JSON, which seems counter-intuitive to most people with a *SQL-background.

  • If you need really high performance.

    Beating the performance Redis provides is nearly impossible. Imagine you database being as fast as your cache. That's what it feels like using Redis as a real database.

  • If you don't care that much about scaling.

    Scaling Redis is not as hard as it used to be. For instance, you could use a kind of proxy server in order to distribute the data among multiple Redis instances. Master-slave replication is not that complicated, but distributing you keys among multiple Redis-instances needs to be done on the application site (e.g. using a hash-function, Modulo etc.). Scaling MongoDB by comparison is much simpler.

When to use MongoDB

  • Prototyping, Startups, Hackathons

    MongoDB is perfectly suited for rapid prototyping. Nevertheless, performance isn't that good. Also keep in mind that you'll most likely have to define some sort of schema in your application.

  • When you need to change your schema quickly.

    Because there is no schema! Altering tables in traditional, relational DBMS is painfully expensive and slow. MongoDB solves this problem by not making a lot of assumptions on your underlying data. Nevertheless, it tries to optimize as far as possible without requiring you to define a schema.

TL;DR - Use Redis if performance is important and you are willing to spend time optimizing and organizing your data. - Use MongoDB if you need to build a prototype without worrying too much about your DB.

Further reading:

Disabling browser print options (headers, footers, margins) from page?

The CSS standard enables some advanced formatting. There is a @page directive in CSS that enables some formatting that applies only to paged media (like paper). See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.

Downside is that behavior in different browsers is not consistent. Safari still does not support setting printer page margin at all, but all the other major browsers now support it.

With the @page directive, you can specify printer margin of the page (which is not the same as normal CSS margin of an HTML element):

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Print Test</title>
    <style type="text/css" media="print">
    @page 
    {
        size:  auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }

    html
    {
        background-color: #FFFFFF; 
        margin: 0px;  /* this affects the margin on the html before sending to printer */
    }

    body
    {
        border: solid 1px blue ;
        margin: 10mm 15mm 10mm 15mm; /* margin you want for the content */
    }
    </style>
</head>
<body>
  <div>Top line</div>
  <div>Line 2</div>
</body>
</html>

Note that we basically disables the page-specific margins here to achieve the effect of removing the header and footer, so the margin we set on the body will not be used in page breaks (as commented by Konrad) This means that it will only work properly if the printed content is only one page.

This does not work in Firefox 3.6, IE 7, Safari 5.1.7 or Google Chrome 4.1.

Setting the @page margin does have effect in IE 8, Opera 10, Google Chrome 21 and Firefox 19.
Although the page margins are set correctly for your content in these browsers, the behavior is not ideal in trying to solve the hiding of the header/footer.

This is how it behaves in different browsers:

  • In Internet Explorer, the margin is actually set to 0mm in the settings for this printing, and if you do Preview you will get 0mm as default, but the user can change it in the preview.
    You will see that the page content actually are positioned correctly, but the browser print header and footer is shown with non-transparent background, and so effectively hiding the page content at that position.

  • In Firefox newer versions, it is positioned correctly, but both the header/footer text and content text is displayed, so it looks like a bad mix of browser header text and your page content.

  • In Opera, the page content hides the header when using a non-transparent background in the standard css and the header/footer position conflicts with content. Quite good, but looks strange if margin is set to a small value that causes the header to be partially visible. Also the page margin is not set properly.

  • In Chrome newer versions, the browser header and footer is hidden if the @page margin is set so small that the header/footer position conflicts with content. In my opinion, this is exactly how this should behave.

So the conclusion is that Chrome has the best implementation of this in respect to hiding the header/footer.

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

How to ignore the first line of data when processing CSV data?

In a similar use case I had to skip annoying lines before the line with my actual column names. This solution worked nicely. Read the file first, then pass the list to csv.DictReader.

with open('all16.csv') as tmp:
    # Skip first line (if any)
    next(tmp, None)

    # {line_num: row}
    data = dict(enumerate(csv.DictReader(tmp)))

jquery how to catch enter key and change event to tab

If you're using IE, this worked great for me:

    <body onkeydown="tabOnEnter()">
    <script type="text/javascript">
    //prevents the enter key from submitting the form, instead it tabs to the next field
    function tabOnEnter() {
        if (event.keyCode==13) 
        {
            event.keyCode=9; return event.keyCode 
        }
    }
    </script>

H2 in-memory database. Table not found

Hard to tell. I created a program to test this:

package com.gigaspaces.compass;

import org.testng.annotations.Test;

import java.sql.*;

public class H2Test {
@Test
public void testDatabaseNoMem() throws SQLException {
    testDatabase("jdbc:h2:test");
}
@Test
public void testDatabaseMem() throws SQLException {
    testDatabase("jdbc:h2:mem:test");
}

private void testDatabase(String url) throws SQLException {
    Connection connection= DriverManager.getConnection(url);
    Statement s=connection.createStatement();
    try {
    s.execute("DROP TABLE PERSON");
    } catch(SQLException sqle) {
        System.out.println("Table not found, not dropping");
    }
    s.execute("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
    PreparedStatement ps=connection.prepareStatement("select * from PERSON");
    ResultSet r=ps.executeQuery();
    if(r.next()) {
        System.out.println("data?");
    }
    r.close();
    ps.close();
    s.close();
    connection.close();
}
}

The test ran to completion, with no failures and no unexpected output. Which version of h2 are you running?

Installing PDO driver on MySQL Linux server

That's a good question, but I think you just misunderstand what you read.

Install PDO

The ./config --with-pdo-mysql is something you have to put on only if you compile your own PHP code. If you install it with package managers, you just have to use the command line given by Jany Hartikainen: sudo apt-get install php5-mysql and also sudo apt-get install pdo-mysql

Compatibility with mysql_

Apart from the fact mysql_ is really discouraged, they are both independent. If you use PDO mysql_ is not implicated, and if you use mysql_ PDO is not required.

If you turn off PDO without changing any line in your code, you won't have a problem. But since you started to connect and write queries with PDO, you have to keep it and give up mysql_.

Several years ago the MySQL team published a script to migrate to MySQLi. I don't know if it can be customised, but it's official.

Purpose of a constructor in Java?

As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.

Example:

Say you have an Animal class something like

class Animal{
   private String name;
   private String type;
}

Lets see what happens when you try to create an instance of Animal class, say a Dog named Puppy. Now you have have to initialize name = Puppy and type = Dog. So, how can you do that. A way of doing it is having a constructor like

    Animal(String nameProvided, String typeProvided){
         this.name = nameProvided;
         this.type = typeProvided;
     }

Now when you create an object of class Animal, something like Animal dog = new Animal("Puppy", "Dog"); your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.

Now you might ask what if I didn't provide an argument to my constructor something like

Animal xyz = new Animal();

This is a default Constructor which initializes the object with default values i.e. in our Animal class name and type values corresponding to xyz object would be name = null and type = null

Fastest way to count number of occurrences in a Python list

You can use pandas, by transforming the list to a pd.Series then simply use .value_counts()

import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()

Input  >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)

How to show loading spinner in jQuery?

You can insert the animated image into the DOM right before the AJAX call, and do an inline function to remove it...

$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
  $("#myDiv").html('');
});

This will make sure your animation starts at the same frame on subsequent requests (if that matters). Note that old versions of IE might have difficulties with the animation.

Good luck!

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

You have to initialize variables before using them.?

If you try to evaluate the variables before initializing them you'll run into: FailedPreconditionError: Attempting to use uninitialized value tensor.

The easiest way is initializing all variables at once using: tf.global_variables_initializer()

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)

You use sess.run(init) to run the initializer, without fetching any value.

To initialize only a subset of variables, you use tf.variables_initializer() listing the variables:

var_ab = tf.variables_initializer([a, b], name="a_and_b")
with tf.Session() as sess:
    sess.run(var_ab)

You can also initialize each variable separately using tf.Variable.initializer

# create variable W as 784 x 10 tensor, filled with zeros
W = tf.Variable(tf.zeros([784,10])) with tf.Session() as sess:
    sess.run(W.initializer)

How to check if PHP array is associative or sequential?

I compare the difference between the keys of the array and the keys of the result of array_values() of the array, which will always be an array with integer indices. If the keys are the same, it's not an associative array.

function isHash($array) {
    if (!is_array($array)) return false;
    $diff = array_diff_assoc($array, array_values($array));
    return (empty($diff)) ? false : true;
}

MySQL Orderby a number, Nulls last

You can coalesce your NULLs in the ORDER BY statement:

select * from tablename
where <conditions>
order by
    coalesce(position, 0) ASC, 
    id DESC

If you want the NULLs to sort on the bottom, try coalesce(position, 100000). (Make the second number bigger than all of the other position's in the db.)

MySQL Job failed to start

First make a backup of your /var/lib/mysql/ directory just to be safe.

sudo mkdir /home/<your username>/mysql/
cd /var/lib/mysql/
sudo cp * /home/<your username>/mysql/ -R

Next purge MySQL (this will remove php5-mysql and phpmyadmin as well as a number of other libraries so be prepared to re-install some items after this.

sudo apt-get purge mysql-server-5.1 mysql-common

Remove the folder /etc/mysql/ and it's contents

sudo rm /etc/mysql/ -R

Next check that your old database files are still in /var/lib/mysql/ if they are not then copy them back in to the folder then chown root:root

(only run these if the files are no longer there)

sudo mkdir /var/lib/mysql/
sudo chown root:root /var/lib/mysql/ -R
cd ~/mysql/
sudo cp * /var/lib/mysql/ -R

Next install mysql server

sudo apt-get install mysql-server

Finally re-install any missing packages like phpmyadmin and php5-mysql.

Javascript: Extend a Function

With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.

But here's a literal answer:

If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:

// Original code in main.js
var theProperty = init;

function init(){
     doSomething();
}

// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
    function extendsInit() {
        old();
        doSomething();
    }

    return extendsInit;
})(theProperty);

If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:

// In main.js
var MyLibrary = {
    init: function init() {
    }
};

// In extended.js
(function() {
    var oldInit = MyLibrary.init;
    MyLibrary.init = extendedInit;
    function extendedInit() {
        oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
        doSomething();
    }
})();

But there are better ways to do that. Like for instance, providing a means of registering init functions.

// In main.js
var MyLibrary = (function() {
    var initFunctions = [];
    return {
        init: function init() {
            var fns = initFunctions;
            initFunctions = undefined;
            for (var index = 0; index < fns.length; ++index) {
                try { fns[index](); } catch (e) { }
            }
        },
        addInitFunction: function addInitFunction(fn) {
            if (initFunctions) {
                // Init hasn't run yet, remember it
                initFunctions.push(fn);
            } else {
                // `init` has already run, call it almost immediately
                // but *asynchronously* (so the caller never sees the
                // call synchronously)
                setTimeout(fn, 0);
            }
        }
    };
})();

Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:

// In main.js
const MyLibrary = (() => {
    let initFunctions = [];
    return {
        init() {
            const fns = initFunctions;
            initFunctions = undefined;
            for (const fn of fns) {
                try { fn(); } catch (e) { }
            }
        },
        addInitFunction(fn) {
            if (initFunctions) {
                // Init hasn't run yet, remember it
                initFunctions.push(fn);
            } else {
                // `init` has already run, call it almost immediately
                // but *asynchronously* (so the caller never sees the
                // call synchronously)
                setTimeout(fn, 0);
                // Or: `Promise.resolve().then(() => fn());`
                // (Not `.then(fn)` just to avoid passing it an argument)
            }
        }
    };
})();

Output grep results to text file, need cleaner output

grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post

jQuery Ajax File Upload

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);

$.ajax({
       url : 'upload.php',
       type : 'POST',
       data : formData,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       success : function(data) {
           console.log(data);
           alert(data);
       }
});

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

Here is more information: - How to upload a file using jQuery.ajax and FormData - Uploading files via jQuery, object FormData is provided and no file name, GET request

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no terminó la acción de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningún archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

A 'for' loop to iterate over an enum in Java

Try to use a for each

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

How do I get the last character of a string?

 public char lastChar(String s) {
     if (s == "" || s == null)
        return ' ';
    char lc = s.charAt(s.length() - 1);
    return lc;
}

width:auto for <input> fields

Answer 1 - "response" gave a nice answer/link for it. To put it in short, "auto" is the default, so it is like removing any changes in the width of an element

Answer 2 - use width: 100% instead. It will fill the 100% of the parent container, in this case, the "form".

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How to find difference between two columns data?

Yes, you can select the data, calculate the difference, and insert all values in the other table:

insert into #temp2 (Difference)
select previous - Present
from #TEMP1

Exiting from python Command Line

This message is the __str__ attribute of exit

look at these examples :

1

>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit

2

>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

3

>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'

Python: Making a beep noise

There's a Windows answer, and a Debian answer, so here's a Mac one:

This assumes you're just here looking for a quick way to make a customisable alert sound, and not specifically the piezeoelectric beep you get on Windows:

os.system( "say beep" )

Disclaimer: You can replace os.system with a call to the subprocess module if you're worried about someone hacking on your beep code.

See: How to make the hardware beep sound in Mac OS X 10.6