Programs & Examples On #Kernel

In computing, the kernel is a computer program that manages input/output requests from software, and translates them into data processing instructions for the central processing unit and other electronic components of a computer. The kernel is a fundamental part of a modern computer's operating system. This tag is for general questions regarding code that runs in the context of an operating system kernel.

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

What is the difference between Trap and Interrupt?

Traps and interrupts are closely related. Traps are a type of exception, and exceptions are similar to interrupts.

Intel x86 defines two overlapping categories, vectored events (interrupts vs exceptions), and exception classes (faults vs traps vs aborts).

All of the quotes in this post are from the April 2016 version of the Intel Software Developer Manual. For the (definitive and complex) x86 perspective, I recommend reading the SDM's chapter on Interrupt and Exception handling.

Vectored Events

Vectored Events (interrupts and exceptions) cause the processor to jump into an interrupt handler after saving much of the processor's state (enough such that execution can continue from that point later).

Exceptions and interrupts have an ID, called a vector, that determines which interrupt handler the processor jumps to. Interrupt handlers are described within the Interrupt Descriptor Table.

Interrupts

Interrupts occur at random times during the execution of a program, in response to signals from hardware. System hardware uses interrupts to handle events external to the processor, such as requests to service peripheral devices. Software can also generate interrupts by executing the INT n instruction.

Exceptions

Exceptions occur when the processor detects an error condition while executing an instruction, such as division by zero. The processor detects a variety of error conditions including protection violations, page faults, and internal machine faults.

Exception Classifications

Exceptions are classified as faults, traps, or aborts depending on the way they are reported and whether the instruction that caused the exception can be restarted without loss of program or task continuity.

Summary: traps increment the instruction pointer, faults do not, and aborts 'explode'.

Trap

A trap is an exception that is reported immediately following the execution of the trapping instruction. Traps allow execution of a program or task to be continued without loss of program continuity. The return address for the trap handler points to the instruction to be executed after the trapping instruction.

Fault

A fault is an exception that can generally be corrected and that, once corrected, allows the program to be restarted with no loss of continuity. When a fault is reported, the processor restores the machine state to the state prior to the beginning of execution of the faulting instruction. The return address (saved contents of the CS and EIP registers) for the fault handler points to the faulting instruction, rather than to the instruction following the faulting instruction.

Example: A page fault is often recoverable. A piece of an application's address space may have been swapped out to disk from ram. The application will trigger a page fault when it tries to access memory that was swapped out. The kernel can pull that memory from disk to ram, and hand control back to the application. The application will continue where it left off (at the faulting instruction that was accessing swapped out memory), but this time the memory access should succeed without faulting.

An illegal-instruction fault handler that emulates floating-point or other missing instructions would have to manually increment the return address to get the trap-like behaviour it needs, after seeing if the faulting instruction was one it could handle. x86 #UD is a "fault", not a "trap". (The handler would need a pointer to the faulting instruction to figure out which instruction it was.)

Abort

An abort is an exception that does not always report the precise location of the instruction causing the exception and does not allow a restart of the program or task that caused the exception. Aborts are used to report severe errors, such as hardware errors and inconsistent or illegal values in system tables.

Edge Cases

Software invoked interrupts (triggered by the INT instruction) behave in a trap-like manner. The instruction completes before the processor saves its state and jumps to the interrupt handler.

What is __gxx_personality_v0 for?

It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.

The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.

Of course, if nothing is using exceptions, you can disable them with -fno-exceptions (and if nothing is using RTTI, you can also add -fno-rtti). If you are using them, you have to (as other answers already noted) link with g++ instead of gcc, which will add -lstdc++ for you.

What is an OS kernel ? How does it differ from an operating system?

The kernel might be the operating system or it might be a part of the operating system. In Linux, the kernel is loaded and executed first. Then it starts up other bits of the OS (like init) to make the system useful.

This is especially true in a micro-kernel environment. The kernel has minimal functionality. Everything else, like file systems and TCP/IP, run as a user process.

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

What is the difference between the kernel space and the user space?

The correct answer is: There is no such thing as kernel space and user space. The processor instruction set has special permissions to set destructive things like the root of the page table map, or access hardware device memory, etc.

Kernel code has the highest level privileges, and user code the lowest. This prevents user code from crashing the system, modifying other programs, etc.

Generally kernel code is kept under a different memory map than user code (just as user spaces are kept in different memory maps than each other). This is where the "kernel space" and "user space" terms come from. But that is not a hard and fast rule. For example, since the x86 indirectly requires its interrupt/trap handlers to be mapped at all times, part (or some OSes all) of the kernel must be mapped into user space. Again, this does not mean that such code has user privileges.

Why is the kernel/user divide necessary? Some designers disagree that it is, in fact, necessary. Microkernel architecture is based on the idea that the highest privileged sections of code should be as small as possible, with all significant operations done in user privileged code. You would need to study why this might be a good idea, it is not a simple concept (and is famous for both having advantages and drawbacks).

What is difference between monolithic and micro kernel?

Microkernel:

Moves as much from the kernel into “user” space.

Communication takes place between user modules using message passing.

Benefits:

1-Easier to extend a microkernel

2-Easier to port the operating system to new architectures

3-More reliable (less code is running in kernel mode)

4-More secure

Detriments:

1-Performance overhead of user space to kernel space communication

What are some resources for getting started in operating system development?

There are good resources for operating system fundamentals in books. Since there isn't much call to create new OS's from scratch you won't find a ton of hobbyist type information on the internet.

I recommend the standard text book, "Modern Operating Systems" by Tanenbaum. You may also be able to find "Operating System Elements" by Calingaert useful - it's a thin overview of a book which give a rough sketch of what an OS is from a designer's standpoint.

If you have any interest in real time systems (and you should at least understand the differences and reasons for real time OS's) then I'd also recommend "MicroC/OS-II" by Labrosse.

Edit:

Can you specify what you mean by "more technical"? These books give pseudo code implementation details, but are you looking for an example OS, or code snippets for a particular machine/language?

-Adam

Linux Process States

As already explained by others, processes in "D" state (uninterruptible sleep) are responsible for the hang of ps process. To me it has happened many times with RedHat 6.x and automounted NFS home directories.

To list processes in D state you can use the following commands:

cd /proc
for i in [0-9]*;do echo -n "$i :";cat $i/status |grep ^State;done|grep D

To know the current directory of the process and, may be, the mounted NFS disk that has issues you can use a command similar to the following example (replace 31134 with the sleeping process number):

# ls -l /proc/31134/cwd
lrwxrwxrwx 1 pippo users 0 Aug  2 16:25 /proc/31134/cwd -> /auto/pippo

I found that giving the umount command with the -f (force) switch, to the related mounted nfs file system, was able to wake-up the sleeping process:

umount -f /auto/pippo

the file system wasn't unmounted, because it was busy, but the related process did wake-up and I was able to solve the issue without rebooting.

"FATAL: Module not found error" using modprobe

i think there should be entry of your your_module.ko in /lib/modules/uname -r/modules.dep and in /lib/modules/uname -r/modules.dep.bin for "modprobe your_module" command to work

How do I convert dmesg timestamp to custom date format?

For systems without "dmesg -T" such as RHEL/CentOS 6, I liked the "dmesg_with_human_timestamps" function provided by lucas-cimon earlier. It has a bit of trouble with some of our boxes with large uptime though. Turns out that kernel timestamps in dmesg are derived from an uptime value kept by individual CPUs. Over time this gets out of sync with the real time clock. As a result, the most accurate conversion for recent dmesg entries will be based on the CPU clock rather than /proc/uptime. For example, on a particular CentOS 6.6 box here:

# grep "\.clock" /proc/sched_debug  | head -1
  .clock                         : 32103895072.444568
# uptime
 15:54:05 up 371 days, 19:09,  4 users,  load average: 3.41, 3.62, 3.57
# cat /proc/uptime
32123362.57 638648955.00

Accounting for the CPU uptime being in milliseconds, there's an offset of nearly 5 1/2 hours here. So I revised the script and converted it to native bash in the process:

dmesg_with_human_timestamps () {
    FORMAT="%a %b %d %H:%M:%S %Y"

    now=$(date +%s)
    cputime_line=$(grep -m1 "\.clock" /proc/sched_debug)

    if [[ $cputime_line =~ [^0-9]*([0-9]*).* ]]; then
        cputime=$((BASH_REMATCH[1] / 1000))
    fi

    dmesg | while IFS= read -r line; do
        if [[ $line =~ ^\[\ *([0-9]+)\.[0-9]+\]\ (.*) ]]; then
            stamp=$((now-cputime+BASH_REMATCH[1]))
            echo "[$(date +"${FORMAT}" --date=@${stamp})] ${BASH_REMATCH[2]}"
        else
            echo "$line"
        fi
    done
}

alias dmesgt=dmesg_with_human_timestamps

Java JTable getting the data of the selected row

Just simple like this:

    tbl.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
            String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            System.out.println(selectedCellValue);
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });

R cannot be resolved - Android error

You may need to update/install SDK tools. Relaunch Android SDK Manager again and install a new item: Android SDK Build-tools.one by one delete,fix which one work for you.enter image description here

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I was getting this error by saving an object to the shared preferences as a gson converted string. The gson String was no good, so retrieving and deserializing the object was not actually working correctly. This meant any subsequent accesses to the object resulted in this error. Scary :)

What is Turing Complete?

In the simplest terms, a Turing-complete system can solve any possible computational problem.

One of the key requirements is the scratchpad size be unbounded and that is possible to rewind to access prior writes to the scratchpad.

Thus in practice no system is Turing-complete.

Rather some systems approximate Turing-completeness by modeling unbounded memory and performing any possible computation that can fit within the system's memory.

How to debug in Android Studio using adb over WiFi

just open settings / plugins / search " Android wifi adb and download it and connect your mobile using usb cabble once and its done

Create comma separated strings C#?

If you're using .Net 4 you can use the overload for string.Join that takes an IEnumerable if you have them in a List, too:

string.Join(", ", strings);

Javascript to convert UTC to local time

This works for both Chrome and Firefox.
Not tested on other browsers.

_x000D_
_x000D_
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
  if (dateTime !== null && dateTime !== undefined) {
    if (notStanderdFormat) {
      // works for 2021-02-21 04:01:19
      // convert to 2021-02-21T04:01:19.000000Z format before convert to local time
      const splited = dateTime.split(" ");
      let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
      const date = new Date(convertedDateTime);
      return date.toString();
    } else {
      // works for 2021-02-20T17:52:45.000000Z or  1613639329186
      const date = new Date(dateTime);
      return date.toString();
    }
  } else {
    return "Unknown";
  }
};

// TEST

console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
_x000D_
_x000D_
_x000D_

Spring mvc @PathVariable

have a look at the below code snippet.

@RequestMapping(value = "edit.htm", method = RequestMethod.GET) 
    public ModelAndView edit(@RequestParam("id") String id) throws Exception {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("user", userinfoDao.findById(id));
        return new ModelAndView("edit", modelMap);      
    }

If you want the complete project to see how it works then download it from below link:-

UserInfo Project on GitLab

Installing Tomcat 7 as Service on Windows Server 2008

its done through service.bat file in apache tomcat7

visit this blog .. install tomcat7 on windows

Objective-C ARC: strong vs retain and weak vs assign

From the Transitioning to ARC Release Notes (the example in the section on property attributes).

// The following declaration is a synonym for: @property(retain) MyClass *myObject;

@property(strong) MyClass *myObject;

So strong is the same as retain in a property declaration.

For ARC projects I would use strong instead of retain, I would use assign for C primitive properties and weak for weak references to Objective-C objects.

ios Upload Image and Text using HTTP POST

I can show you an example of uploading a .txt file to a server with NSMutableURLRequest and NSURLSessionUploadTask with help of a php script.

-(void)uploadFileToServer : (NSString *) filePath
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
[request setHTTPMethod:@"POST"]; 
[request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];

NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                      {
                                          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                          if (error || [httpResponse statusCode]!=202)
                                          {

                                              //Error
                                          }
                                          else
                                          {
                                             //Success
                                          }
                                          [defaultSession invalidateAndCancel];
                                      }];
[uploadTask resume];
}

php Script

<?php 
$request_body = @file_get_contents('php://input');
foreach (getallheaders() as $name => $value) 
{
    if ($FileName=="FileName") 
    {
        $header=$value;
        break;
    }
}   
$uploadedDir = "directory/";
@mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);  
?>       

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

A generic list of anonymous class

If you are using C# 7 or above, you can use tuple types instead of anonymous types.

var myList = new List<(int IntProp, string StrProp)>();
myList.Add((IntProp: 123, StrProp: "XYZ"));

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html

geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.

ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

The criteria include account name (whose private key it is associated with), domain, company, expiration date, intended purposes, among other things.

There are many different possible reasons for this error to occur, some have been listed already. Here is another tip: When importing a certificate, be sure you work with the original file received from the certificate authority (CA), or else some of the properties might be lost.

Example: recently I tried to import a certificate exported from a different account on the same machine. The certificate became visible to my account but was not associated with my account, and as a result signtool refused to recognize it without explicitly providing the file name and a password. Which, when done as part of the build process and written out explicitly in a batch file or source file, may not be sufficiently secure. (Importing the original CA-issued certificate solved it.)

Creating email templates with Django

I have made django-templated-email in an effort to solve this problem, inspired by this solution (and the need to, at some point, switch from using django templates to using a mailchimp etc. set of templates for transactional, templated emails for my own project). It is still a work-in-progress though, but for the example above, you would do:

from templated_email import send_templated_mail
send_templated_mail(
        'email',
        '[email protected]',
        ['[email protected]'],
        { 'username':username }
    )

With the addition of the following to settings.py (to complete the example):

TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}

This will automatically look for templates named 'templated_email/email.txt' and 'templated_email/email.html' for the plain and html parts respectively, in the normal django template dirs/loaders (complaining if it cannot find at least one of those).

How to apply style classes to td classes?

Give the table a class name and then you target the td's with the following:

table.classname td {
    font-size: 90%;
}

How to change TextField's height and width?

use contentPadding, it will reduce the textbox or dropdown list height

InputDecorator(
                  decoration: InputDecoration(
                      errorStyle: TextStyle(
                          color: Colors.redAccent, fontSize: 16.0),
                      hintText: 'Please select expense',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(1.0),
                      ),
                      contentPadding: EdgeInsets.all(8)),//Add this edge option
                  child: DropdownButton(
                    isExpanded: true,
                    isDense: true,
                    itemHeight: 50.0,

                    hint: Text(
                        'Please choose a location'), // Not necessary for Option 1
                    value: _selectedLocation,
                    onChanged: (newValue) {
                      setState(() {
                        _selectedLocation = newValue;
                      });
                    },
                    items: citys.map((location) {
                      return DropdownMenuItem(
                        child: new Text(location.name),
                        value: location.id,
                      );
                    }).toList(),
                  ),
                ),

How do I release memory used by a pandas dataframe?

As noted in the comments, there are some things to try: gc.collect (@EdChum) may clear stuff, for example. At least from my experience, these things sometimes work and often don't.

There is one thing that always works, however, because it is done at the OS, not language, level.

Suppose you have a function that creates an intermediate huge DataFrame, and returns a smaller result (which might also be a DataFrame):

def huge_intermediate_calc(something):
    ...
    huge_df = pd.DataFrame(...)
    ...
    return some_aggregate

Then if you do something like

import multiprocessing

result = multiprocessing.Pool(1).map(huge_intermediate_calc, [something_])[0]

Then the function is executed at a different process. When that process completes, the OS retakes all the resources it used. There's really nothing Python, pandas, the garbage collector, could do to stop that.

jQuery check if an input is type checkbox?

You can use the pseudo-selector :checkbox with a call to jQuery's is function:

$('#myinput').is(':checkbox')

Binding Combobox Using Dictionary as the Datasource

I know this is a pretty old topic, but I also had a same problem.

My solution:

how we fill the combobox:

foreach (KeyValuePair<int, string> item in listRegion)
{
    combo.Items.Add(item.Value);
    combo.ValueMember = item.Value.ToString();
    combo.DisplayMember = item.Key.ToString();
    combo.SelectedIndex = 0;
}

and that's how we get inside:

 MessageBox.Show(combo_region.DisplayMember.ToString());

I hope it help someone

How to use glob() to find files recursively?

This is a working code on Python 2.7. As part of my devops work, I was required to write a script which would move the config files marked with live-appName.properties to appName.properties. There could be other extension files as well like live-appName.xml.

Below is a working code for this, which finds the files in the given directories (nested level) and then renames (moves) it to the required filename

def flipProperties(searchDir):
   print "Flipping properties to point to live DB"
   for root, dirnames, filenames in os.walk(searchDir):
      for filename in fnmatch.filter(filenames, 'live-*.*'):
        targetFileName = os.path.join(root, filename.split("live-")[1])
        print "File "+ os.path.join(root, filename) + "will be moved to " + targetFileName
        shutil.move(os.path.join(root, filename), targetFileName)

This function is called from a main script

flipProperties(searchDir)

Hope this helps someone struggling with similar issues.

How to format a float in javascript?

I use this code to format floats. It is based on toPrecision() but it strips unnecessary zeros. I would welcome suggestions for how to simplify the regex.

function round(x, n) {
    var exp = Math.pow(10, n);
    return Math.floor(x*exp + 0.5)/exp;
}

Usage example:

function test(x, n, d) {
    var rounded = rnd(x, d);
    var result = rounded.toPrecision(n);
    result = result.replace(/\.?0*$/, '');
    result = result.replace(/\.?0*e/, 'e');
    result = result.replace('e+', 'e');
    return result;  
}

document.write(test(1.2000e45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2000e+45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2340e45, 3, 2) + '=' + '1.23e45' + '<br>');
document.write(test(1.2350e45, 3, 2) + '=' + '1.24e45' + '<br>');
document.write(test(1.0000, 3, 2) + '=' + '1' + '<br>');
document.write(test(1.0100, 3, 2) + '=' + '1.01' + '<br>');
document.write(test(1.2340, 4, 2) + '=' + '1.23' + '<br>');
document.write(test(1.2350, 4, 2) + '=' + '1.24' + '<br>');

Excel - programm cells to change colour based on another cell

Select ColumnB and as two CF formula rules apply:

Green: =AND(B1048576="X",B1="Y")

Red: =AND(B1048576="X",B1="W")

enter image description here

how to align img inside the div to the right?

<div style="width:300px; text-align:right;">
        <img src="someimgage.gif">
</div>

Left Join With Where Clause

When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.

  SELECT  s.*, 
          cs.`value`
     FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
                               AND cs.character_id = 1

Get Root Directory Path of a PHP project

echo $pathInPieces = explode(DIRECTORY_SEPARATOR , __FILE__);
echo $pathInPieces[0].DIRECTORY_SEPARATOR;

Simple prime number generator in Python

Just studied the topic, look for the examples in the thread and try to make my version:

from collections import defaultdict
# from pprint import pprint

import re


def gen_primes(limit=None):
    """Sieve of Eratosthenes"""
    not_prime = defaultdict(list)
    num = 2
    while limit is None or num <= limit:
        if num in not_prime:
            for prime in not_prime[num]:
                not_prime[prime + num].append(prime)
            del not_prime[num]
        else:  # Prime number
            yield num
            not_prime[num * num] = [num]
        # It's amazing to debug it this way:
        # pprint([num, dict(not_prime)], width=1)
        # input()
        num += 1


def is_prime(num):
    """Check if number is prime based on Sieve of Eratosthenes"""
    return num > 1 and list(gen_primes(limit=num)).pop() == num


def oneliner_is_prime(num):
    """Simple check if number is prime"""
    return num > 1 and not any([num % x == 0 for x in range(2, num)])


def regex_is_prime(num):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None


def simple_is_prime(num):
    """Simple check if number is prime
    More efficient than oneliner_is_prime as it breaks the loop
    """
    for x in range(2, num):
        if num % x == 0:
            return False
    return num > 1


def simple_gen_primes(limit=None):
    """Prime number generator based on simple gen"""
    num = 2
    while limit is None or num <= limit:
        if simple_is_prime(num):
            yield num
        num += 1


if __name__ == "__main__":
    less1000primes = list(gen_primes(limit=1000))
    assert less1000primes == list(simple_gen_primes(limit=1000))
    for num in range(1000):
        assert (
            (num in less1000primes)
            == is_prime(num)
            == oneliner_is_prime(num)
            == regex_is_prime(num)
            == simple_is_prime(num)
        )
    print("Primes less than 1000:")
    print(less1000primes)

    from timeit import timeit

    print("\nTimeit:")
    print(
        "gen_primes:",
        timeit(
            "list(gen_primes(limit=1000))",
            setup="from __main__ import gen_primes",
            number=1000,
        ),
    )
    print(
        "simple_gen_primes:",
        timeit(
            "list(simple_gen_primes(limit=1000))",
            setup="from __main__ import simple_gen_primes",
            number=1000,
        ),
    )
    print(
        "is_prime:",
        timeit(
            "[is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import is_prime",
            number=100,
        ),
    )
    print(
        "oneliner_is_prime:",
        timeit(
            "[oneliner_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import oneliner_is_prime",
            number=100,
        ),
    )
    print(
        "regex_is_prime:",
        timeit(
            "[regex_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import regex_is_prime",
            number=100,
        ),
    )
    print(
        "simple_is_prime:",
        timeit(
            "[simple_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import simple_is_prime",
            number=100,
        ),
    )

The result of running this code show interesting results:

$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096

So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

This works, but I am always open to better ways to make is_prime function.

Facebook share link without JavaScript

How to share content: https://developers.facebook.com/docs/share/

You have to choose use the deprecated function without JS, and check every day, or follow the way use JS and have fun.

NULL values inside NOT IN clause

Null signifies and absence of data, that is it is unknown, not a data value of nothing. It's very easy for people from a programming background to confuse this because in C type languages when using pointers null is indeed nothing.

Hence in the first case 3 is indeed in the set of (1,2,3,null) so true is returned

In the second however you can reduce it to

select 'true' where 3 not in (null)

So nothing is returned because the parser knows nothing about the set to which you are comparing it - it's not an empty set but an unknown set. Using (1, 2, null) doesn't help because the (1,2) set is obviously false, but then you're and'ing that against unknown, which is unknown.

Call a url from javascript

var req ;

// Browser compatibility check          
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

 try {
   req = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {

   try {
     req = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}
 }

}


var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
    //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}

req.send(null);

Using jQuery to build table rows from AJAX response(json)

Use .append instead of .html

var response = "[{
      "rank":"9",
      "content":"Alon",
      "UID":"5"
     },
     {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
    }]";

// convert string to JSON
response = $.parseJSON(response);

$(function() {
    $.each(response, function(i, item) {
        var $tr = $('<tr>').append(
            $('<td>').text(item.rank),
            $('<td>').text(item.content),
            $('<td>').text(item.UID)
        ); //.appendTo('#records_table');
        console.log($tr.wrap('<p>').html());
    });
});

How do I tell matplotlib that I am done with a plot?

You can use figure to create a new plot, for example, or use close after the first plot.

Does a favicon have to be 32x32 or 16x16?

You will need separate files for each resolution I am afraid. There is a really good article on campaign monitor describing how they created and implemented their icons for each iOS device too:

http://www.campaignmonitor.com/blog/post/3234/designing-campaign-monitor-ios-icons/

Multiple HttpPost method in Web API controller

A much better solution to your problem would be to use Route which lets you specify the route on the method by annotation:

[RoutePrefix("api/VTRouting")]
public class VTRoutingController : ApiController
{
    [HttpPost]
    [Route("Route")]
    public MyResult Route(MyRequestTemplate routingRequestTemplate)
    {
        return null;
    }

    [HttpPost]
    [Route("TSPRoute")]
    public MyResult TSPRoute(MyRequestTemplate routingRequestTemplate)
    {
        return null;
    }
}

How to commit and rollback transaction in sql server?

Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

create procedure [usp_my_procedure_name]
as
begin
    set nocount on;
    declare @trancount int;
    set @trancount = @@trancount;
    begin try
        if @trancount = 0
            begin transaction
        else
            save transaction usp_my_procedure_name;

        -- Do the actual work here

lbexit:
        if @trancount = 0   
            commit;
    end try
    begin catch
        declare @error int, @message varchar(4000), @xstate int;
        select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
        if @xstate = -1
            rollback;
        if @xstate = 1 and @trancount = 0
            rollback
        if @xstate = 1 and @trancount > 0
            rollback transaction usp_my_procedure_name;

        raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
        return;
    end catch   
end

How to correctly link php-fpm and Nginx Docker containers?

For anyone else getting

Nginx 403 error: directory index of [folder] is forbidden

when using index.php while index.html works perfectly and having included index.php in the index in the server block of their site config in sites-enabled

server {
    listen 80;

    # this path MUST be exactly as docker-compose php volumes
    root /usr/share/nginx/html;

    index index.php

    ...
}

Make sure your nginx.conf file at /etc/nginx/nginx.conf actually loads your site config in the http block...

http {

    ...

    include /etc/nginx/conf.d/*.conf;

    # Load our websites config 
    include /etc/nginx/sites-enabled/*;
}

C error: Expected expression before int

{ } -->

defines scope, so if(a==1) { int b = 10; } says, you are defining int b, for {}- this scope. For

if(a==1)
  int b =10;

there is no scope. And you will not be able to use b anywhere.

NameError: global name 'unicode' is not defined - in Python 3

One can replace unicode with u''.__class__ to handle the missing unicode class in Python 3. For both Python 2 and 3, you can use the construct

isinstance(unicode_or_str, u''.__class__)

or

type(unicode_or_str) == type(u'')

Depending on your further processing, consider the different outcome:

Python 3

>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True

Python 2

>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False

Check array position for null/empty

There is no bound checking in array in C programming. If you declare array as

int arr[50];

Then you can even write as

arr[51] = 10;

The compiler would not throw an error. Hope this answers your question.

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

Java Enum return Int

You can try this code .

private enum DownloadType {
    AUDIO , VIDEO , AUDIO_AND_VIDEO ;

}

You can use this enumeration as like this : DownloadType.AUDIO.ordinal(). Hope this code snippet will help you .

Ping with timestamp on Windows CLI

I also need this to monitor the network issue for my database mirroring time out issue. I use the command code as below:

ping -t Google.com|cmd /q /v /c "(pause&pause)>nul & for /l %a in () do (set /p "data=" && echo(!date! !time! !data!)&ping -n 2 Google.com>nul" >C:\pingtest.txt

You just need to modify Google.com to your server name. It works perfectly for me. and remember to stop this when you finished. The pingtest.txt file will increase by 4.5 KB per min (around).

Thank for raymond.cc. https://www.raymond.cc/blog/timestamp-ping-with-hrping/

How to `wget` a list of URLs in a text file?

try:

wget -i text_file.txt

(check man wget)

Should I use != or <> for not equal in T-SQL?

Although they function the same way, != means exactly "not equal to", while <> means greater than and less than the value stored.

Consider >= or <=, and this will make sense when factoring in your indexes to queries... <> will run faster in some cases (with the right index), but in some other cases (index free) they will run just the same.

This also depends on how your databases system reads the values != and <>. The database provider may just shortcut it and make them function the same, so there isn't any benefit either way.PostgreSQL and SQL Server do not shortcut this; it is read as it appears above.

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

How to make the 'cut' command treat same sequental delimiters as one?

shortest/friendliest solution

After becoming frustrated with the too many limitations of cut, I wrote my own replacement, which I called cuts for "cut on steroids".

cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.

One example, out of many, addressing this particular question:

$ cat text.txt
0   1        2 3
0 1          2   3 4

$ cuts 2 text.txt
2
2

cuts supports:

  • auto-detection of most common field-delimiters in files (+ ability to override defaults)
  • multi-char, mixed-char, and regex matched delimiters
  • extracting columns from multiple files with mixed delimiters
  • offsets from end of line (using negative numbers) in addition to start of line
  • automatic side-by-side pasting of columns (no need to invoke paste separately)
  • support for field reordering
  • a config file where users can change their personal preferences
  • great emphasis on user friendliness & minimalist required typing

and much more. None of which is provided by standard cut.

See also: https://stackoverflow.com/a/24543231/1296044

Source and documentation (free software): http://arielf.github.io/cuts/

Import multiple csv files into pandas and concatenate into one DataFrame

Edit: I googled my way into https://stackoverflow.com/a/21232849/186078. However of late I am finding it faster to do any manipulation using numpy and then assigning it once to dataframe rather than manipulating the dataframe itself on an iterative basis and it seems to work in this solution too.

I do sincerely want anyone hitting this page to consider this approach, but don't want to attach this huge piece of code as a comment and making it less readable.

You can leverage numpy to really speed up the dataframe concatenation.

import os
import glob
import pandas as pd
import numpy as np

path = "my_dir_full_path"
allFiles = glob.glob(os.path.join(path,"*.csv"))


np_array_list = []
for file_ in allFiles:
    df = pd.read_csv(file_,index_col=None, header=0)
    np_array_list.append(df.as_matrix())

comb_np_array = np.vstack(np_array_list)
big_frame = pd.DataFrame(comb_np_array)

big_frame.columns = ["col1","col2"....]

Timing stats:

total files :192
avg lines per file :8492
--approach 1 without numpy -- 8.248656988143921 seconds ---
total records old :1630571
--approach 2 with numpy -- 2.289292573928833 seconds ---

.map() a Javascript ES6 Map?

You can use myMap.forEach, and in each loop, using map.set to change value.

_x000D_
_x000D_
myMap = new Map([_x000D_
  ["a", 1],_x000D_
  ["b", 2],_x000D_
  ["c", 3]_x000D_
]);_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
  console.log(key + ' = ' + value);_x000D_
}_x000D_
_x000D_
_x000D_
myMap.forEach((value, key, map) => {_x000D_
  map.set(key, value+1)_x000D_
})_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
  console.log(key + ' = ' + value);_x000D_
}
_x000D_
_x000D_
_x000D_

How do I make an HTML text box show a hint when empty?

You could easily have a box read "Search" then when the focus is changed to it have the text be removed. Something like this:

<input onfocus="this.value=''" type="text" value="Search" />

Of course if you do that the user's own text will disappear when they click. So you probably want to use something more robust:

<input name="keyword_" type="text" size="25"  style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">

How do I schedule jobs in Jenkins?

The steps for schedule jobs in Jenkins:

  1. click on "Configure" of the job requirement
  2. scroll down to "Build Triggers" - subtitle
  3. Click on the checkBox of Build periodically
  4. Add time schedule in the Schedule field, for example, @midnight

enter image description here

Note: under the schedule field, can see the last and the next date-time run.

Jenkins also supports predefined aliases to schedule build:

@hourly, @daily, @weekly, @monthly, @midnight

@hourly --> Build every hour at the beginning of the hour --> 0 * * * *

@daily, @midnight --> Build every day at midnight --> 0 0 * * *

@weekly --> Build every week at midnight on Sunday morning --> 0 0 * * 0

@monthly --> Build every month at midnight of the first day of the month --> 0 0 1 * *

psql: FATAL: database "<user>" does not exist

From the terminal, just Run the command on your command prompt window. (Not inside psql).

createdb <user>

And then try to run postgres again.

Insert and set value with max()+1 problems

Your sub-query is just incomplete, that's all. See the query below with my addictions:

INSERT INTO customers ( customer_id, firstname, surname ) 
VALUES ((SELECT MAX( customer_id ) FROM customers) +1), 'jim', 'sock')

Sequelize OR condition object

String based operators will be deprecated in the future (You've probably seen the warning in console).

Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.

Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

(13: Permission denied) while connecting to upstream:[nginx]

13-permission-denied-while-connecting-to-upstreamnginx on centos server -

setsebool -P httpd_can_network_connect 1

window.onload vs <body onload=""/>

window.onload can work without body. Create page with only the script tags and open it in a browser. The page doesn't contain any body, but it still works..

<script>
  function testSp()
  {
    alert("hit");
  }
  window.onload=testSp;
</script>

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

Python strptime() and timezones?

I recommend using python-dateutil. Its parser has been able to parse every date format I've thrown at it so far.

>>> from dateutil import parser
>>> parser.parse("Tue Jun 22 07:46:22 EST 2010")
datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal())
>>> parser.parse("Fri, 11 Nov 2011 03:18:09 -0400")
datetime.datetime(2011, 11, 11, 3, 18, 9, tzinfo=tzoffset(None, -14400))
>>> parser.parse("Sun")
datetime.datetime(2011, 12, 18, 0, 0)
>>> parser.parse("10-11-08")
datetime.datetime(2008, 10, 11, 0, 0)

and so on. No dealing with strptime() format nonsense... just throw a date at it and it Does The Right Thing.

Update: Oops. I missed in your original question that you mentioned that you used dateutil, sorry about that. But I hope this answer is still useful to other people who stumble across this question when they have date parsing questions and see the utility of that module.

How to display images from a folder using php - PHP

You had a mistake on the statement below. Use . not ,

echo '<img src="', $dir, '/', $file, '" alt="', $file, $

to

echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $

and

echo 'Directory \'', $dir, '\' not found!';

to

echo 'Directory \''. $dir. '\' not found!';

Array to Hash Ruby

a = ["item 1", "item 2", "item 3", "item 4"]
Hash[ a.each_slice( 2 ).map { |e| e } ]

or, if you hate Hash[ ... ]:

a.each_slice( 2 ).each_with_object Hash.new do |(k, v), h| h[k] = v end

or, if you are a lazy fan of broken functional programming:

h = a.lazy.each_slice( 2 ).tap { |a|
  break Hash.new { |h, k| h[k] = a.find { |e, _| e == k }[1] }
}
#=> {}
h["item 1"] #=> "item 2"
h["item 3"] #=> "item 4"

Xcode: Could not locate device support files

Get latest iOS-device-support-files (GitHub) (updated regularly). Download and copy iOS-device-support-files to:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Chrome DevTools Devices does not detect device when plugged in

Chrome appears to have bug renegotiating the device authentication. You can try disabling USB Debugging and enabling it again. Sometimes you'll get a pop-up asking you to trust your computer key again.

Or you can go to your Android SDK and run adb devices which will force a renegotiation.

After either (or both), Chrome should start working.

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      stack()
      {element=new int[10];
      top=-1;
      }
      void push(int item)
      {top++;
      if(top==9)
          System.out.println("Overflow");
      else
              {
               top++;
      element[top]=item;

      }

      void pop()
      {if(top==-1)
          System.out.println("Underflow");
      else  
      top--;
      }
      void display()
      {
          System.out.println("\nTop="+top+"\nElement="+element[top]);
      }

      public static void main(String args[])
      {
        stack s1=new stack();
        s1.push(10);
        s1.display();
        s1.push(20);
        s1.display();
        s1.push(30);
        s1.display();
        s1.pop();
        s1.display();
      }

  }

Output

Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

Get git branch name in Jenkins Pipeline/Jenkinsfile

Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME which describes the branch.

In my script..

stage('Build') {
    node {
        echo 'Pulling...' + env.BRANCH_NAME
        checkout scm
        
    }
}

Yields...

Pulling...master

Send JSON data from Javascript to PHP?

I've gotten lots of information here so I wanted to post a solution I discovered.

The problem: Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it.

Environment: Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu.

What works (version 1):
1) JSON is just text. Text in a certain format, but just a text string.

2) In Javascript, var str_json = JSON.stringify(myObject) gives me the JSON string.

3) I use the AJAX XMLHttpRequest object in Javascript to send data to the server:

request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]

4) On the server, PHP code to read the JSON string:

$str_json = file_get_contents('php://input');

This reads the raw POST data. $str_json now contains the exact JSON string from the browser.

What works (version 2):
1) If I want to use the "application/x-www-form-urlencoded" request header, I need to create a standard POST string of "x=y&a=b[etc]" so that when PHP gets it, it can put it in the $_POST associative array. So, in Javascript in the browser:

var str_json = "json_string=" + (JSON.stringify(myObject))

PHP will now be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest as in version 1 above.

Displaying the contents of $_POST['json_string'] will display the JSON string. Using json_decode() on the $_POST array element with the json string will correctly decode that data and put it in an array/object.

The pitfall I ran into:
Initially, I tried to send the JSON string with the header of application/x-www-form-urlencoded and then tried to immediately read it out of the $_POST array in PHP. The $_POST array was always empty. That's because it is expecting data of the form yval=xval&[rinse_and_repeat]. It found no such data, only the JSON string, and it simply threw it away. I examined the request headers, and the POST data was being sent correctly.

Similarly, if I use the application/json header, I again cannot access the sent data via the $_POST array. If you want to use the application/json content-type header, then you must access the raw POST data in PHP, via php://input, not with $_POST.

References:
1) How to access POST data in PHP: How to access POST data in PHP?
2) Details on the application/json type, with some sample objects which can be converted to JSON strings and sent to the server: http://www.ietf.org/rfc/rfc4627.txt

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close() method:

>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor

The line del f deletes the last reference to the file object, causing its destructor file.__del__ to be called. The internal state of the file object indicates the file is still open since f.close() was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.

Since the implementation of os.system() does not create any Python file objects, it does not seem likely that the system() call is the origin of the error. Maybe you could show a bit more code?

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

.col-xs-$   Extra Small     Phones Less than 768px 
.col-sm-$   Small Devices   Tablets 768px and Up 
.col-md-$   Medium Devices  Desktops 992px and Up 
.col-lg-$   Large Devices   Large Desktops 1200px and Up 

module.exports vs. export default in Node.js and ES6

Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs

module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export

// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

If you have 32-bit Windows, this method is not working without following settings.

  1. Run prompt cmd.exe (important : Run As Administrator)
  2. type bcdedit.exe and run
  3. Look at the "increaseuserva" params and there is no then write following statement
  4. bcdedit /set increaseuserva 3072
  5. and again step 2 and check params

We added this settings and this block started.

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

More info - command increaseuserva: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set

Using Python's os.path, how do I go up one directory?

This might be useful for other cases where you want to go x folders up. Just run walk_up_folder(path, 6) to go up 6 folders.

def walk_up_folder(path, depth=1):
    _cur_depth = 1        
    while _cur_depth < depth:
        path = os.path.dirname(path)
        _cur_depth += 1
    return path   

not-null property references a null or transient value

Every InvoiceItem must have an Invoice attached to it because of the not-null="true" in the many-to-one mapping.

So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems method. I do NOT see an addInvoiceItem method. When you set items, you need to loop through the set and call item.setInvoice(this) on all of the items. If you implement an addItem method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem in the collection.

What's the difference between a web site and a web application?

The technical difference according to two features:
1. Where the "work" is done
2. What is being transferred to/from the server

Web app
1. The "work" is done at the browser (JavaScript)
2. Data is being transferred from/to the server
In comparison: Faster

Website
1. The "work" (most of it) is done at the server
2. Rendered pages (data + UI) are being transferred from the server
In comparison: Easier SEO

How do I detect IE 8 with jQuery?

Note:

1) $.browser appears to be dropped in jQuery 1.9+ (as noted by Mandeep Jain). It is recommended to use .support instead.

2) $.browser.version can return "7" in IE >7 when the browser is in "compatibility" mode.

3) As of IE 10, conditional comments will no longer work.

4) jQuery 2.0+ will drop support for IE 6/7/8

5) document.documentMode appears to be defined only in Internet Explorer 8+ browsers. The value returned will tell you in what "compatibility" mode Internet Explorer is running. Still not a good solution though.

I tried numerous .support() options, but it appears that when an IE browser (9+) is in compatibility mode, it will simply behave like IE 7 ... :(

So far I only found this to work (kind-a):

(if documentMode is not defined and htmlSerialize and opacity are not supported, then you're very likely looking at IE <8 ...)

if(!document.documentMode && !$.support.htmlSerialize && !$.support.opacity) 
{
    // IE 6/7 code
}

Specify an SSH key for git push for a given domain

You can utilize git environment variable GIT_SSH_COMMAND. Run this in your terminal under your git repository:

GIT_SSH_COMMAND='ssh -i ~/.ssh/your_private_key' git submodule update --init

Replace ~/.ssh/your_private_key with the path of ssh private key you wanna use. And you can change the subsequent git command (in the example is git submodule update --init) to others like git pull, git fetch, etc.

Get MAC address using shell script

I have used command hcicongif with two greps to separate the PC Mac address and I saved the MAC address to variable:

PCMAC=$( hciconfig -a | grep -E 'BD Address:' | grep -Eo '[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}' )

You can also use this command to check if MAC address is in valid format. Note, that only big chars A-F are allowed and also you need to add input for this grep command:

grep -E '[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}'

Replace all spaces in a string with '+'

var str = 'a b c';
var replaced = str.replace(/\s/g, '+');

Reason: no suitable image found

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

Java: print contents of text file to screen

Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

Príliš žlutoucký kun
úpel dábelské ódy

and the file uses windows-1250 format. If you use FileReader you will get this result:

P??li? ?lu?ou?k? k??
?p?l ??belsk? ?dy

So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

Example:

String encoding = "Cp1250";
File file = new File("foo.txt");

if (file.exists()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
else {
    System.out.println("file doesn't exist");
}

In case you want to read the file character after character do not use BufferedReader.

try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
    int data = isr.read();
    while (data != -1) {
        System.out.print((char) data);
        data = isr.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

How to remove old Docker containers

I wanted to add this simple answer as I didn't see it, and the question is specifically "old" not "all".

sudo docker container prune --filter "until=24h"

Adjust the 24h for whatever time span you want to remove containers that are older than.

Most Useful Attributes

// on configuration sections
[ConfigurationProperty] 

// in asp.net
[NotifyParentProperty(true)]

MVC 4 client side validation not working

There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:

@using (Html.BeginForm())
{
    ...
    @Html.TextBoxFor(x => x.AgreementNumber)
}

Also I don't know what the jquery.validate.inline.js script is but if it somehow depends on the jquery.validate.js plugin make sure that it is referenced after it.

In all cases look at your javascript console in the browser for potential errors or missing scripts.

How to detect when facebook's FB.init is complete

Sometimes fbAsyncInit doesnt work. I dont know why and use this workaround then:

 var interval = window.setInterval(function(){
    if(typeof FB != 'undefined'){
        FB.init({
            appId      : 'your ID',
            cookie     : true,  // enable cookies to allow the server to access// the session
            xfbml      : true,  // parse social plugins on this page
            version    : 'v2.3' // use version 2.3
        });

        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
        });
        clearInterval(interval);
    }
},100);

How to convert datetime to integer in python

I think I have a shortcut for that:

# Importing datetime.
from datetime import datetime

# Creating a datetime object so we can test.
a = datetime.now()

# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))

Swift - Integer conversion to Hours/Minutes/Seconds

Define

func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
  return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

Use

> secondsToHoursMinutesSeconds(27005)
(7,30,5)

or

let (h,m,s) = secondsToHoursMinutesSeconds(27005)

The above function makes use of Swift tuples to return three values at once. You destructure the tuple using the let (var, ...) syntax or can access individual tuple members, if need be.

If you actually need to print it out with the words Hours etc then use something like this:

func printSecondsToHoursMinutesSeconds (seconds:Int) -> () {
  let (h, m, s) = secondsToHoursMinutesSeconds (seconds)
  print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}

Note that the above implementation of secondsToHoursMinutesSeconds() works for Int arguments. If you want a Double version you'll need to decide what the return values are - could be (Int, Int, Double) or could be (Double, Double, Double). You could try something like:

func secondsToHoursMinutesSeconds (seconds : Double) -> (Double, Double, Double) {
  let (hr,  minf) = modf (seconds / 3600)
  let (min, secf) = modf (60 * minf)
  return (hr, min, 60 * secf)
}

Horizontal ListView in Android?

Paul doesn't bother to fix bugs of his library or accept users fixes. That's why I am suggesting another library which has similar functionality:

https://github.com/sephiroth74/HorizontalVariableListView

Update: on Jul 24, 2013 author (sephiroth74) released completely rewritten version based on code of android 4.2.2 ListView. I must say that it doesn't have all the errors which previous version had and works great!

Simple if else onclick then do?

You may use jQuery in it like

$('#yesh').click(function(){
     *****HERE GOES THE FUNCTION*****
});

Besides jQuery is easy to use.

You can make changes in colors etc using simple jQUery or Javascript.

Get the Highlighted/Selected text

Get highlighted text this way:

window.getSelection().toString()

and of course a special treatment for ie:

document.selection.createRange().htmlText

How many concurrent requests does a single Flask process receive?

When running the development server - which is what you get by running app.run(), you get a single synchronous process, which means at most 1 request is being processed at a time.

By sticking Gunicorn in front of it in its default configuration and simply increasing the number of --workers, what you get is essentially a number of processes (managed by Gunicorn) that each behave like the app.run() development server. 4 workers == 4 concurrent requests. This is because Gunicorn uses its included sync worker type by default.

It is important to note that Gunicorn also includes asynchronous workers, namely eventlet and gevent (and also tornado, but that's best used with the Tornado framework, it seems). By specifying one of these async workers with the --worker-class flag, what you get is Gunicorn managing a number of async processes, each of which managing its own concurrency. These processes don't use threads, but instead coroutines. Basically, within each process, still only 1 thing can be happening at a time (1 thread), but objects can be 'paused' when they are waiting on external processes to finish (think database queries or waiting on network I/O).

This means, if you're using one of Gunicorn's async workers, each worker can handle many more than a single request at a time. Just how many workers is best depends on the nature of your app, its environment, the hardware it runs on, etc. More details can be found on Gunicorn's design page and notes on how gevent works on its intro page.

Input jQuery get old value before onchange and get value after on change

The upvoted solution works for some situations but is not the ideal solution. The solution Bhojendra Rauniyar provided will only work in certain scenarios. The var inputVal will always remain the same, so changing the input multiple times would break the function.

The function may also break when using focus, because of the ?? (up/down) spinner on html number input. That is why J.T. Taylor has the best solution. By adding a data attribute you can avoid these problems:

<input id="my-textbox" type="text" data-initial-value="6" value="6" />

How to open an external file from HTML

If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.

You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).

Skip certain tables with mysqldump

You can use the mysqlpump command with the

--exclude-tables=name

command. It specifies a comma-separated list of tables to exclude.

Syntax of mysqlpump is very similar to mysqldump, buts its way more performant. More information of how to use the exclude option you can read here: https://dev.mysql.com/doc/refman/5.7/en/mysqlpump.html#mysqlpump-filtering

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

How to get AM/PM from a datetime in PHP

for flexibility with different formats, use:

$dt = DateTime::createFromFormat('m/d/Y H:i:s', '08/04/2010 22:15:00');
echo $dt->format('g:i A')

Check the php manual for additional format options.

Eclipse JPA Project Change Event Handler (waiting)

The issue seems to be resolved with the new Eclipse. The plugin isn't available with Java Enterprise suite.

Use ASP.NET MVC validation with jquery ajax?

Client Side

Using the jQuery.validate library should be pretty simple to set up.

Specify the following settings in your Web.config file:

<appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings>

When you build up your view, you would define things like this:

@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                                new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)

NOTE: These need to be defined within a form element

Then you would need to include the following libraries:

<script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>

This should be able to set you up for client side validation

Resources

Server Side

NOTE: This is only for additional server side validation on top of jQuery.validation library

Perhaps something like this could help:

[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
    //Save data
    return Json(new { Success = true } );
}

Where ValidateAjax is an attribute defined as:

public class ValidateAjaxAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
            return;

        var modelState = filterContext.Controller.ViewData.ModelState;
        if (!modelState.IsValid)
        {
            var errorModel = 
                    from x in modelState.Keys
                    where modelState[x].Errors.Count > 0
                    select new
                           {
                               key = x,
                               errors = modelState[x].Errors.
                                                      Select(y => y.ErrorMessage).
                                                      ToArray()
                           };
            filterContext.Result = new JsonResult()
                                       {
                                           Data = errorModel
                                       };
            filterContext.HttpContext.Response.StatusCode = 
                                                  (int) HttpStatusCode.BadRequest;
        }
    }
}

What this does is return a JSON object specifying all of your model errors.

Example response would be

[{
    "key":"Name",
    "errors":["The Name field is required."]
},
{
    "key":"Description",
    "errors":["The Description field is required."]
}]

This would be returned to your error handling callback of the $.ajax call

You can loop through the returned data to set the error messages as needed based on the Keys returned (I think something like $('input[name="' + err.key + '"]') would find your input element

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    ... do something
}

Explanation:

document.documentMode

An IE only property, first available in IE8.

/Edge/

A regular expression to search for the string 'Edge' - which we then test against the 'navigator.userAgent' property

Update Mar 2020

@Jam comments that the latest version of Edge now reports Edg as the user agent. So the check would be:

if (document.documentMode || /Edge/.test(navigator.userAgent) || /Edg/.test(navigator.userAgent)) {
    ... do something
}

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

How to uninstall Anaconda completely from macOS

In my case (Mac High Sierra) it was installed at ~/opt/anaconda3.

https://docs.anaconda.com/anaconda/install/uninstall/

How can I split a text into sentences?

No doubt that NLTK is the most suitable for the purpose. But getting started with NLTK is quite painful (But once you install it - you just reap the rewards)

So here is simple re based code available at http://pythonicprose.blogspot.com/2009/09/python-split-paragraph-into-sentences.html

# split up a paragraph into sentences
# using regular expressions


def splitParagraphIntoSentences(paragraph):
    ''' break a paragraph into sentences
        and return a list '''
    import re
    # to split by multile characters

    #   regular expressions are easiest (and fastest)
    sentenceEnders = re.compile('[.!?]')
    sentenceList = sentenceEnders.split(paragraph)
    return sentenceList


if __name__ == '__main__':
    p = """This is a sentence.  This is an excited sentence! And do you think this is a question?"""

    sentences = splitParagraphIntoSentences(p)
    for s in sentences:
        print s.strip()

#output:
#   This is a sentence
#   This is an excited sentence

#   And do you think this is a question 

Using a scanner to accept String input and storing in a String Array

One of the problem with this code is here :

name += contactName[];

This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.

Instead use this:

contactName[index] = name;

this instruction will store the variable name in the contactName array at the index index.

The second problem you have is that you don't have the variable index.

What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make a hyperlink in telegram without using bots?

My phone is xiaomi Redmi note 8 with MIUI 11.0.9 . There is no option for create hyperlink :enter image description here So I use Telegram desktop or Telegram X for create hyperlink because Telegram X supports markdown. Type url and send message (in Telegram X) or there is an alternate way which is the easiest!

Select the text using Xiaomi's Word Editor and click in the three dots on the top right corner of the chat. It is usually used for accessing settings but if you select a text and click there, you can see Telegram's own Formatter!

String length in bytes in JavaScript

For simple UTF-8 encoding, with slightly better compatibility than TextEncoder, Blob does the trick. Won't work in very old browsers though.

new Blob([""]).size; // -> 4  

window.onload vs $(document).ready()

The $(document).ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window.onload event occurs later, when everything including images on the page loaded.

Also window.onload is a pure javascript event in the DOM, while the $(document).ready() event is a method in jQuery.

$(document).ready() is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...

Look at to jQuery source code to understand how it's working:

jQuery.ready.promise = function( obj ) {
    if ( !readyList ) {

        readyList = jQuery.Deferred();

        // Catch cases where $(document).ready() is called after the browser event has already occurred.
        // we once tried to use readyState "interactive" here, but it caused issues like the one
        // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", completed, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", completed, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", completed );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", completed );

            // If IE and not a frame
            // continually check to see if the document is ready
            var top = false;

            try {
                top = window.frameElement == null && document.documentElement;
            } catch(e) {}

            if ( top && top.doScroll ) {
                (function doScrollCheck() {
                    if ( !jQuery.isReady ) {

                        try {
                            // Use the trick by Diego Perini
                            // http://javascript.nwbox.com/IEContentLoaded/
                            top.doScroll("left");
                        } catch(e) {
                            return setTimeout( doScrollCheck, 50 );
                        }

                        // detach all dom ready events
                        detach();

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

Also I have created the image below as a quick references for both:

enter image description here

How can I delete a user in linux when the system says its currently used in a process

First use pkill or kill -9 <pid> to kill the process.

Then use following userdel command to delete user,

userdel -f cafe_fixer

According to userdel man page:

-f, --force

This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.

Edit 1: (by @Ajedi32)

Note: This option (i.e. --force) is dangerous and may leave your system in an inconsistent state.

Edit 2: (by @socketpair)

In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir / before, because this command will also remove home directory.

How do I read CSV data into a record array in NumPy?

You can also try recfromcsv() which can guess data types and return a properly formatted record array.

Disable EditText blinking cursor

The problem with setting cursor visibility to true and false may be a problem since it removes the cursor until you again set it again and at the same time field is editable which is not good user experience.

so instead of using

setCursorVisible(false)

just do it like this

        editText2.setFocusableInTouchMode(false)
        editText2.clearFocus()
        editText2.setFocusableInTouchMode(true)

The above code removes the focus which in turn removes the cursor. And enables it again so that you can again touch it and able to edit it. Just like normal user experience.

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

In one of my projects I run tests against Python 2 and 3. For that I wrote a small script which starts a local server independently:

$ python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')
Serving HTTP on 0.0.0.0 port 8000 ...

As an alias:

$ alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"
$ serve
Serving HTTP on 0.0.0.0 port 8000 ...

Please note that I control my Python version via conda environments, because of that I can use python instead of python3 for using Python 3.

Finding multiple occurrences of a string within a string in Python

The following function finds all the occurrences of a string inside another while informing the position where each occurrence is found.

You can call the function using the test cases in the table below. You can try with words, spaces and numbers all mixed up.

The function works well with overlaping characteres.

|         theString          | aString |
| -------------------------- | ------- |
| "661444444423666455678966" |  "55"   |
| "661444444423666455678966" |  "44"   |
| "6123666455678966"         |  "666"  |
| "66123666455678966"        |  "66"   |

Calling examples:
1. print("Number of occurrences: ", find_all("123666455556785555966", "5555"))
   
   output:
           Found in position:  7
           Found in position:  14
           Number of occurrences:  2
   
2. print("Number of occorrences: ", find_all("Allowed Hello Hollow", "ll "))

   output:
          Found in position:  1
          Found in position:  10
          Found in position:  16
          Number of occurrences:  3

3. print("Number of occorrences: ", find_all("Aaa bbbcd$#@@abWebbrbbbbrr 123", "bbb"))

   output:
         Found in position:  4
         Found in position:  21
         Number of occurrences:  2
         

def find_all(theString, aString):
    count = 0
    i = len(aString)
    x = 0

    while x < len(theString) - (i-1): 
        if theString[x:x+i] == aString:        
            print("Found in position: ", x)
            x=x+i
            count=count+1
        else:
            x=x+1
    return count

Return char[]/string from a function

If you want to return a char* from a function, make sure you malloc() it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.

change it to

char* createStr() {
    char char1= 'm';
    char char2= 'y';
    char *str = malloc(3 * sizeof(char));
    if(str == NULL) return NULL;
    str[0] = char1;
    str[1] = char2;
    str[2] = '\0';
    return str;
}

setting multiple column using one update

UPDATE some_table 
   SET this_column=x, that_column=y 
   WHERE something LIKE 'them'

How to check if array element is null to avoid NullPointerException in Java

The given code works for me. Notice that someArray[i] is always null since you have not initialized the second dimension of the array.

What does a lazy val do?

A demonstration of lazy - as defined above - execution when defined vs execution when accessed: (using 2.12.7 scala shell)

// compiler says this is ok when it is lazy
scala> lazy val t: Int = t 
t: Int = <lazy>
//however when executed, t recursively calls itself, and causes a StackOverflowError
scala> t             
java.lang.StackOverflowError
...

// when the t is initialized to itself un-lazily, the compiler warns you of the recursive call
scala> val t: Int = t
<console>:12: warning: value t does nothing other than call itself recursively
   val t: Int = t

Error on renaming database in SQL Server 2008 R2

1.database set 1st single user mode

ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE

2.RENAME THE DATABASE

ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]

3.DATABAE SET MULIUSER MODE

ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER WITH ROLLBACK IMMEDIATE

Getting last month's date in php

$prevmonth = date('M Y', strtotime("last month"));

Vendor code 17002 to connect to SQLDeveloper

In your case the "Vendor code 17002" is the equivalent of the ORA-12541 error: It's most likely that your listener is down, or has an improper port or service name. From the docs:

ORA-12541: TNS no listener

Cause: Listener for the source repository has not been started.

Action: Start the Listener on the machine where the source repository resides.

Write applications in C or C++ for Android?

Normally, you have to:

  1. Install Google Android NDK. It contains libs, headers, makfile examples and gcc toolchain
  2. Build an executable from your C code for ARM, optimize and link it with provided libs if required
  3. Connect to a phone using provided adb interface and test your executable

If you are looking to sell an app:

  1. Build a library from your C code
  2. Create simple Java code which will use this library
  3. Embed this library into application package file
  4. Test your app
  5. Sell it or distribute it for free

MySQL command line client for Windows

Its pretty simple. I saved the mysql community server in my D:\ drive. Hence this is how i did it.

Goto D:\mysql-5.7.18-winx64\bin and in the address bar type cmd and press enter, so command prompt will open. Now if you're using it for the first time type as mysql -u root -ppress enter. Then it will ask for password, again press enter. Thats it you are connected to the mysql server.

Before this make sure wamp or xampp any of the local server is running because i couldn't able to connect to mysql wihthout xampp running. enter image description here

enter image description here

Happy Coding.

How to add a class to a given element?

find your target element "d" however you wish and then:

d.className += ' additionalClass'; //note the space

you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

Error: Cannot find module 'gulp-sass'

I had this issue for days looking for answers. My error log was similar to this npm just won't install node sass The only problem was the node version. Maybe it can help some of you.

I downgraded my Node.js from 9.3.0 to 6.12.2 and run:

npm update

How to access site through IP address when website is on a shared host?

serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.

As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.

67.225.235.59 somerandomservice.com www.somerandomservice.com

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Percentage calculation

(current / maximum) * 100. In your case, (2 / 10) * 100.

How to get text of an input text box during onKeyPress?

I normally concatenate the field's value (i.e. before it's updated) with the key associated with the key event. The following uses recent JS so would need adjusting for support in older IE's.

Recent JS example

document.querySelector('#test').addEventListener('keypress', function(evt) {
    var real_val = this.value + String.fromCharCode(evt.which);
    if (evt.which == 8) real_val = real_val.substr(0, real_val.length - 2);
    alert(real_val);
}, false);

Support for older IEs example

//get field
var field = document.getElementById('test');

//bind, somehow
if (window.addEventListener)
    field.addEventListener('keypress', keypress_cb, false);
else
    field.attachEvent('onkeypress', keypress_cb);

//callback
function keypress_cb(evt) {
    evt = evt || window.event;
    var code = evt.which || evt.keyCode,
        real_val = this.value + String.fromCharCode(code);
    if (code == 8) real_val = real_val.substr(0, real_val.length - 2);
}

[EDIT - this approach, by default, disables key presses for things like back space, CTRL+A. The code above accommodates for the former, but would need further tinkering to allow for the latter, and a few other eventualities. See Ian Boyd's comment below.]

How do I access store state in React Redux?

Import connect from react-redux and use it to connect the component with the state connect(mapStates,mapDispatch)(component)

import React from "react";
import { connect } from "react-redux";


const MyComponent = (props) => {
    return (
      <div>
        <h1>{props.title}</h1>
      </div>
    );
  }
}

Finally you need to map the states to the props to access them with this.props

const mapStateToProps = state => {
  return {
    title: state.title
  };
};
export default connect(mapStateToProps)(MyComponent);

Only the states that you map will be accessible via props

Check out this answer: https://stackoverflow.com/a/36214059/4040563

For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

OSError - Errno 13 Permission denied

This may also happen if you have a slash before the folder name:

path = '/folder1/folder2'

OSError: [Errno 13] Permission denied: '/folder1'

comes up with an error but this one works fine:

path = 'folder1/folder2'

PowerShell to remove text from a string

Another way to do this is with operator -replace.

$TestString = "test=keep this, but not this."

$NewString = $TestString -replace ".*=" -replace ",.*"

.*= means any number of characters up to and including an equals sign.

,.* means a comma followed by any number of characters.

Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.

Bootstrap-select - how to fire event on change

When Bootstrap Select initializes, it'll build a set of custom divs that run alongside the original <select> element and will typically synchronize state between the two input mechanisms.

BS Select Elements

Which is to say that one way to handle events on bootstrap select is to listen for events on the original select that it modifies, regardless of who updated it.

Solution 1 - Native Events

Just listen for a change event and get the selected value using javascript or jQuery like this:

$('select').on('change', function(e){
  console.log(this.value,
              this.options[this.selectedIndex].value,
              $(this).find("option:selected").val(),);
});

*NOTE: As with any script reliant on the DOM, make sure you wait for the DOM ready event before executing

Demo in Stack Snippets:

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('select').on('change', function(e){_x000D_
    console.log(this.value,_x000D_
                this.options[this.selectedIndex].value,_x000D_
                $(this).find("option:selected").val(),);_x000D_
  });_x000D_
  _x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
  <option val="Must"> Mustard </option>_x000D_
  <option val="Cat" > Ketchup </option>_x000D_
  <option val="Rel" > Relish  </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Solution 2 - Bootstrap Select Custom Events

As this answer alludes, Bootstrap Select has their own set of custom events, including changed.bs.select which:

fires after the select's value has been changed. It passes through event, clickedIndex, newValue, oldValue.

And you can use that like this:

$("select").on("changed.bs.select", 
      function(e, clickedIndex, newValue, oldValue) {
    console.log(this.value, clickedIndex, newValue, oldValue)
});

Demo in Stack Snippets:

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $("select").on("changed.bs.select", _x000D_
        function(e, clickedIndex, newValue, oldValue) {_x000D_
      console.log(this.value, clickedIndex, newValue, oldValue)_x000D_
  });_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
  <option val="Must"> Mustard </option>_x000D_
  <option val="Cat" > Ketchup </option>_x000D_
  <option val="Rel" > Relish  </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

Setting sourceCompatibility = JavaVersion.VERSION_1_8 enables desugaring, but it is currently unable to desugar all the Java 8 features that the Kotlin compiler uses.

enter image description here

Fix - Setting kotlinOptions.jvmTarget to JavaVersion.VERSION_1_8 in the app module Gradle would fix the issue.

Use Java 8 language features: https://developer.android.com/studio/write/java8-support

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  // For Kotlin projects
  kotlinOptions {
    jvmTarget = "1.8"
  }
}

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

CURL alternative in Python

If you are using a command to just call curl like that, you can do the same thing in Python with subprocess. Example:

subprocess.call(['curl', '-i', '-H', '"Accept: application/xml"', '-u', 'login:key', '"https://app.streamsend.com/emails"'])

Or you could try PycURL if you want to have it as a more structured api like what PHP has.

How do I use select with date condition?

I always get the filter date into a datetime, with no time (time= 00:00:00.000)

DECLARE @FilterDate  datetime --final destination, will not have any time on it
DECLARE @GivenDateD  datetime --if you're given a datetime
DECLARE @GivenDateS  char(23) --if you're given a string, it can be any valid date format, not just the yyyy/mm/dd hh:mm:ss.mmm that I'm using

SET @GivenDateD='2009/03/30 13:42:50.123'
SET @GivenDateS='2009/03/30 13:42:50.123'

--remove the time and assign it to the datetime
@FilterDate=dateadd(dd, datediff(dd, 0, @FilterDateD), 0)
--OR
@FilterDate=dateadd(dd, datediff(dd, 0, @FilterDateS), 0)

You can use this WHERE clause to then filter:

WHERE ColumnDateTime>=@FilterDate AND ColumnDateTime<@FilterDate+1

this will give all matches that are on or after the beginning of the day on 2009/03/30 up to and including the complete day on 2009/03/30

you can do the same for START and END filter parameters as well. Always make the start date a datetime and use zero time on the day you want, and make the condition ">=". Always make the end date the zero time on the day after you want and use "<". Doing that, you will always include any dates properly, regardless of the time portion of the date.

Android Service needs to run always (Never pause or stop)

In order to start a service in its own process, you must specify the following in the xml declaration.

<service
  android:name="WordService"
  android:process=":my_process" 
  android:icon="@drawable/icon"
  android:label="@string/service_name"
  >
</service> 

Here you can find a good tutorial that was really useful to me

http://www.vogella.com/articles/AndroidServices/article.html

Hope this helps

How to refresh Android listview?

while using SimpleCursorAdapter can call changeCursor(newCursor) on the adapter.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Very Short and concise Answer

lateinit: It initialize non-null properties lately

Unlike lazy initialization, lateinit allows the compiler to recognize that the value of the non-null property is not stored in the constructor stage to compile normally.

lazy Initialization

by lazy may be very useful when implementing read-only(val) properties that perform lazy-initialization in Kotlin.

by lazy { ... } performs its initializer where the defined property is first used, not its declaration.

Response to preflight request doesn't pass access control check

I am using AWS sdk for uploads, after spending some time searching online i stumbled upon this thread. thanks to @lsimoneau 45581857 it turns out the exact same thing was happening. I simply pointed my request Url to the region on my bucket by attaching the region option and it worked.

 const s3 = new AWS.S3({
 accessKeyId: config.awsAccessKeyID,
 secretAccessKey: config.awsSecretAccessKey,
 region: 'eu-west-2'  // add region here });

Deactivate or remove the scrollbar on HTML

What I would try in this case is put this in the stylesheet

html, body{overflow:hidden;}

this way one disables the scrollbar, and as a cumulative effect they disable scrolling with the keyboard

How do you find all subclasses of a given class in Java?

If you intend to load all subclassess of given class which are in the same package, you can do so:

public static List<Class> loadAllSubClasses(Class pClazz) throws IOException, ClassNotFoundException {
    ClassLoader classLoader = pClazz.getClassLoader();
    assert classLoader != null;
    String packageName = pClazz.getPackage().getName();
    String dirPath = packageName.replace(".", "/");
    Enumeration<URL> srcList = classLoader.getResources(dirPath);

    List<Class> subClassList = new ArrayList<>();
    while (srcList.hasMoreElements()) {
        File dirFile = new File(srcList.nextElement().getFile());
        File[] files = dirFile.listFiles();
        if (files != null) {
            for (File file : files) {
                String subClassName = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                if (! subClassName.equals(pClazz.getName())) {
                    subClassList.add(Class.forName(subClassName));
                }
            }
        }
    }

    return subClassList;
}

What is the scope of variables in JavaScript?

1) There is a global scope, a function scope, and the with and catch scopes. There is no 'block' level scope in general for variable's -- the with and the catch statements add names to their blocks.

2) Scopes are nested by functions all the way to the global scope.

3) Properties are resolved by going through the prototype chain. The with statement brings object property names into the lexical scope defined by the with block.

EDIT: ECMAAScript 6 (Harmony) is spec'ed to support let, and I know chrome allows a 'harmony' flag, so perhaps it does support it..

Let would be a support for block level scoping, but you have to use the keyword to make it happen.

EDIT: Based on Benjamin's pointing out of the with and catch statements in the comments, I've edited the post, and added more. Both the with and the catch statements introduce variables into their respective blocks, and that is a block scope. These variables are aliased to the properties of the objects passed into them.

 //chrome (v8)

 var a = { 'test1':'test1val' }
 test1   // error not defined
 with (a) { var test1 = 'replaced' }
 test1   // undefined
 a       // a.test1 = 'replaced'

EDIT: Clarifying example:

test1 is scoped to the with block, but is aliased to a.test1. 'Var test1' creates a new variable test1 in the upper lexical context (function, or global), unless it is a property of a -- which it is.

Yikes! Be careful using 'with' -- just like var is a noop if the variable is already defined in the function, it is also a noop with respect to names imported from the object! A little heads up on the name already being defined would make this much safer. I personally will never use with because of this.

How can I stop the browser back button using JavaScript?

In a modern browser this seems to work:

// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
  if (confirm('Go back?')) {
    window.history.back() 
  } else {
    window.history.forward()
    setTimeout(() => {
      window.addEventListener('popstate', popHandler, {once: true})
    }, 50) // delay needed since the above is an async operation for some reason
  }
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)

Standard Android Button with a different color

The DroidUX component library has a ColorButton widget whose color can be changed easily, both via xml definition and programmatically at run time, so you can even let the user to set the button's color/theme if your app allows it.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

How is CountDownLatch used in Java Multithreading?

One good example of when to use something like this is with Java Simple Serial Connector, accessing serial ports. Typically you'll write something to the port, and asyncronously, on another thread, the device will respond on a SerialPortEventListener. Typically, you'll want to pause after writing to the port to wait for the response. Handling the thread locks for this scenario manually is extremely tricky, but using Countdownlatch is easy. Before you go thinking you can do it another way, be careful about race conditions you never thought of!!

Pseudocode:

CountDownLatch latch;
void writeData() { 
   latch = new CountDownLatch(1);
   serialPort.writeBytes(sb.toString().getBytes())
   try {
      latch.await(4, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
   }
}
class SerialPortReader implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR()){//If data is available
            byte buffer[] = serialPort.readBytes(event.getEventValue());
            latch.countDown();
         }
     }
}

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Set UILabel line spacing

This guy created a class to get line-height (without using CoreText, as MTLabel library) : https://github.com/LemonCake/MSLabel

Pagination on a list using ng-repeat

I just made a JSFiddle that show pagination + search + order by on each column using Build with Twitter Bootstrap code: http://jsfiddle.net/SAWsA/11/

Selecting only first-level elements in jquery

Simply you can use this..

$("ul li a").click(function() {
  $(this).parent().find(">ul")...Something;
}

See example : https://codepen.io/gmkhussain/pen/XzjgRE

Angular JS Uncaught Error: [$injector:modulerr]

I got this error because I had a dependency on another module that was not loaded.

angular.module("app", ["kendo.directives"]).controller("MyCtrl", function(){}...

so even though I had all the Angular modules, I didn't have the kendo one.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)

And then make sure you use that directory in your SELECT statement's INTO OUTFILE clause:

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Original answer

I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.

In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

On linux the two most common locations are /etc/my.cnf or /etc/mysql/my.cnf.

MySQL56 Service

Opening this file I can see that the secure-file-priv option has been added under the [mysqld] group in this new version of MySQL Server with a default value:

secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"

You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = "" in order to disable the default). Don't forget to restart the service after making changes.

Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

It's more common to have comma seperate values using FIELDS TERMINATED BY ','. See below for an example (also showing a Linux path):

SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ESCAPED BY ''
    LINES TERMINATED BY '\n';

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

data.frame Group By column

This is a common question. In base, the option you're looking for is aggregate. Assuming your data.frame is called "mydf", you can use the following.

> aggregate(B ~ A, mydf, sum)
  A  B
1 1  5
2 2  3
3 3 11

I would also recommend looking into the "data.table" package.

> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
   A V1
1: 1  5
2: 2  3
3: 3 11

What’s the difference between Response.Write() andResponse.Output.Write()?

See this:

The difference between Response.Write() and Response.Output.Write() in ASP.NET. The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.

In ASP.NET the Response object is of type HttpResponse and when you say Response.Write you're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse.

Response.Write then calls .Write() on it's internal TextWriter object:

public void Write(object obj){ this._writer.Write(obj);} 

HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:

public TextWriter get_Output(){ return this._writer; } 

Which means you can do the Response whatever a TextWriter will let you. Now, TextWriters support a Write() method aka String.Format, so you can do this:

Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);

But internally, of course, this is happening:

public virtual void Write(string format, params object[] arg)
{ 
this.Write(string.Format(format, arg)); 
}

Bundling data files with PyInstaller (--onefile)

Perhaps i missed a step or did something wrong but the methods which are above, didn't bundle data files with PyInstaller into one exe file. Let me share the steps what i have done.

  1. step:Write one of the above methods into your py file with importing sys and os modules. I tried both of them. The last one is:

    def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        return os.path.join(base_path, relative_path)
    
  2. step: Write, pyi-makespec file.py, to the console, to create a file.spec file.

  3. step: Open, file.spec with Notepad++ to add the data files like below:

    a = Analysis(['C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.py'],
                 pathex=['C:\\Users\\TCK\\Desktop\\Projeler'],
                 binaries=[],
                 datas=[],
                 hiddenimports=[],
                 hookspath=[],
                 runtime_hooks=[],
                 excludes=[],
                 win_no_prefer_redirects=False,
                 win_private_assemblies=False,
                 cipher=block_cipher)
    #Add the file like the below example
    a.datas += [('Converter-GUI.ico', 'C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico', 'DATA')]
    pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)
    exe = EXE(pyz,
              a.scripts,
              exclude_binaries=True,
              name='Converter-GUI',
              debug=False,
              strip=False,
              upx=True,
              #Turn the console option False if you don't want to see the console while executing the program.
              console=False,
              #Add an icon to the program.
              icon='C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico')
    
    coll = COLLECT(exe,
                   a.binaries,
                   a.zipfiles,
                   a.datas,
                   strip=False,
                   upx=True,
                   name='Converter-GUI')
    
  4. step: I followed the above steps, then saved the spec file. At last opened the console and write, pyinstaller file.spec (in my case, file=Converter-GUI).

Conclusion: There's still more than one file in the dist folder.

Note: I'm using Python 3.5.

EDIT: Finally it works with Jonathan Reinhart's method.

  1. step: Add the below codes to your python file with importing sys and os.

    def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        return os.path.join(base_path, relative_path)
    
  2. step: Call the above function with adding the path of your file:

    image_path = resource_path("Converter-GUI.ico")
    
  3. step: Write the above variable that call the function to where your codes need the path. In my case it's:

        self.window.iconbitmap(image_path)
    
  4. step: Open the console in the same directory of your python file, write the codes like below:

        pyinstaller --onefile your_file.py
    
  5. step: Open the .spec file of the python file and append the a.datas array and add the icon to the exe class, which was given above before the edit in 3'rd step.
  6. step: Save and exit the path file. Go to your folder which include the spec and py file. Open again the console window and type the below command:

        pyinstaller your_file.spec
    

After the 6. step your one file is ready to use.

How to do fade-in and fade-out with JavaScript and CSS

Here's my attempt with Javascript and CSS3 animation So the HTML:

 <div id="handle">Fade</div> 
 <div id="slideSource">Whatever you want images or  text here</div>

The CSS3 with transitions:

div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;     
transition: opacity 3s; 
}

div#slideSource.fade {
opacity:0;
}

The Javascript part. Check if the className exists, if it does then add the class and transitions.

document.getElementById('handle').onclick = function(){
    if(slideSource.className){
        document.getElementById('slideSource').className = '';
    } else {
        document.getElementById('slideSource').className = 'fade';
    }
}

Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

Add overflow: auto; to the style and the two finger scroll should work.

jQuery convert line breaks to br (nl2br equivalent)

Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.

How to parse a query string into a NameValueCollection in .NET

    private void button1_Click( object sender, EventArgs e )
    {
        string s = @"p1=6&p2=7&p3=8";
        NameValueCollection nvc = new NameValueCollection();

        foreach ( string vp in Regex.Split( s, "&" ) )
        {
            string[] singlePair = Regex.Split( vp, "=" );
            if ( singlePair.Length == 2 )
            {
                nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );    
            }    
        }
    }

Why can't I define a static method in a Java interface?

While I realize that Java 8 resolves this issue, I thought I'd chime in with a scenario I am currently working on (locked into using Java 7) where being able to specify static methods in an interface would be helpful.

I have several enum definitions where I've defined "id" and "displayName" fields along with helper methods evaluating the values for various reasons. Implementing an interface allows me to ensure that the getter methods are in place but not the static helper methods. Being an enum, there really isn't a clean way to offload the helper methods into an inherited abstract class or something of the like so the methods have to be defined in the enum itself. Also because it is an enum, you wouldn't ever be able to actually pass it as an instanced object and treat it as the interface type, but being able to require the existence of the static helper methods through an interface is what I like about it being supported in Java 8.

Here's code illustrating my point.

Interface definition:

public interface IGenericEnum <T extends Enum<T>> {
    String getId();
    String getDisplayName();
    //If I was using Java 8 static helper methods would go here
}

Example of one enum definition:

public enum ExecutionModeType implements IGenericEnum<ExecutionModeType> {
    STANDARD ("Standard", "Standard Mode"),
    DEBUG ("Debug", "Debug Mode");

    String id;
    String displayName;

    //Getter methods
    public String getId() {
        return id;
    }

    public String getDisplayName() {
        return displayName;
    }

    //Constructor
    private ExecutionModeType(String id, String displayName) {
        this.id = id;
        this.displayName = displayName;
    }

    //Helper methods - not enforced by Interface
    public static boolean isValidId(String id) {
        return GenericEnumUtility.isValidId(ExecutionModeType.class, id);
    }

    public static String printIdOptions(String delimiter){
        return GenericEnumUtility.printIdOptions(ExecutionModeType.class, delimiter);
    }

    public static String[] getIdArray(){
        return GenericEnumUtility.getIdArray(ExecutionModeType.class);
    }

    public static ExecutionModeType getById(String id) throws NoSuchObjectException {
        return GenericEnumUtility.getById(ExecutionModeType.class, id);
    }
}

Generic enum utility definition:

public class GenericEnumUtility {
    public static <T extends Enum<T> & IGenericEnum<T>> boolean isValidId(Class<T> enumType, String id) {       
        for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
            if(enumOption.getId().equals(id)) {
                return true;
            }
        }

        return false;
    }

    public static <T extends Enum<T> & IGenericEnum<T>> String printIdOptions(Class<T> enumType, String delimiter){
        String ret = "";
        delimiter = delimiter == null ? " " : delimiter;

        int i = 0;
        for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
            if(i == 0) {
                ret = enumOption.getId();
            } else {
                ret += delimiter + enumOption.getId();
            }           
            i++;
        }

        return ret;
    }

    public static <T extends Enum<T> & IGenericEnum<T>> String[] getIdArray(Class<T> enumType){
        List<String> idValues = new ArrayList<String>();

        for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
            idValues.add(enumOption.getId());
        }

        return idValues.toArray(new String[idValues.size()]);
    }

    @SuppressWarnings("unchecked")
    public static <T extends Enum<T> & IGenericEnum<T>> T getById(Class<T> enumType, String id) throws NoSuchObjectException {
        id = id == null ? "" : id;
        for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
            if(id.equals(enumOption.getId())) {
                return (T)enumOption;
            }
        }

        throw new NoSuchObjectException(String.format("ERROR: \"%s\" is not a valid ID. Valid IDs are: %s.", id, printIdOptions(enumType, " , ")));
    }
}

Comparing Java enum members: == or equals()?

In case of enum both are correct and right!!

enable cors in .htaccess

I tried @abimelex solution, but in Slim 3.0, mapping the OPTIONS requests goes like:

$app = new \Slim\App();
$app->options('/books/{id}', function ($request, $response, $args) {
    // Return response headers
});

https://www.slimframework.com/docs/objects/router.html#options-route

How to select/get drop down option in Selenium 2

driver.findElement(By.id("id_dropdown_menu")).click();
driver.findElement(By.xpath("xpath_from_seleniumIDE")).click();

good luck

Cannot connect to Database server (mysql workbench)

My problem was that the MySQL server wasn't actually installed. I had run the MySQL Installer, but it didn't install the MySQL server.

I reran the installer, click "Add", and then added MySQL server to the list. Now it works fine.

Quantile-Quantile Plot using SciPy

To add to the confusion around Q-Q plots and probability plots in the Python and R worlds, this is what the SciPy manual says:

"probplot generates a probability plot, which should not be confused with a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this type, see statsmodels.api.ProbPlot."

If you try out scipy.stats.probplot, you'll see that indeed it compares a dataset to a theoretical distribution. Q-Q plots, OTOH, compare two datasets (samples).

R has functions qqnorm, qqplot and qqline. From the R help (Version 3.6.3):

qqnorm is a generic function the default method of which produces a normal QQ plot of the values in y. qqline adds a line to a “theoretical”, by default normal, quantile-quantile plot which passes through the probs quantiles, by default the first and third quartiles.

qqplot produces a QQ plot of two datasets.

In short, R's qqnorm offers the same functionality that scipy.stats.probplot provides with the default setting dist=norm. But the fact that they called it qqnorm and that it's supposed to "produce a normal QQ plot" may easily confuse users.

Finally, a word of warning. These plots don't replace proper statistical testing and should be used for illustrative purposes only.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

MVC Razor view nested foreach's model

The quick answer is to use a for() loop in place of your foreach() loops. Something like:

@for(var themeIndex = 0; themeIndex < Model.Theme.Count(); themeIndex++)
{
   @Html.LabelFor(model => model.Theme[themeIndex])

   @for(var productIndex=0; productIndex < Model.Theme[themeIndex].Products.Count(); productIndex++)
   {
      @Html.LabelFor(model=>model.Theme[themeIndex].Products[productIndex].name)
      @for(var orderIndex=0; orderIndex < Model.Theme[themeIndex].Products[productIndex].Orders; orderIndex++)
      {
          @Html.TextBoxFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Quantity)
          @Html.TextAreaFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Note)
          @Html.EditorFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].DateRequestedDeliveryFor)
      }
   }
}

But this glosses over why this fixes the problem.

There are three things that you have at least a cursory understanding before you can resolve this issue. I have to admit that I cargo-culted this for a long time when I started working with the framework. And it took me quite a while to really get what was going on.

Those three things are:

  • How do the LabelFor and other ...For helpers work in MVC?
  • What is an Expression Tree?
  • How does the Model Binder work?

All three of these concepts link together to get an answer.

How do the LabelFor and other ...For helpers work in MVC?

So, you've used the HtmlHelper<T> extensions for LabelFor and TextBoxFor and others, and you probably noticed that when you invoke them, you pass them a lambda and it magically generates some html. But how?

So the first thing to notice is the signature for these helpers. Lets look at the simplest overload for TextBoxFor

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression
) 

First, this is an extension method for a strongly typed HtmlHelper, of type <TModel>. So, to simply state what happens behind the scenes, when razor renders this view it generates a class. Inside of this class is an instance of HtmlHelper<TModel> (as the property Html, which is why you can use @Html...), where TModel is the type defined in your @model statement. So in your case, when you are looking at this view TModel will always be of the type ViewModels.MyViewModels.Theme.

Now, the next argument is a bit tricky. So lets look at an invocation

@Html.TextBoxFor(model=>model.SomeProperty);

It looks like we have a little lambda, And if one were to guess the signature, one might think that the type for this argument would simply be a Func<TModel, TProperty>, where TModel is the type of the view model and TProperty is inferred as the type of the property.

But thats not quite right, if you look at the actual type of the argument its Expression<Func<TModel, TProperty>>.

So when you normally generate a lambda, the compiler takes the lambda and compiles it down into MSIL, just like any other function (which is why you can use delegates, method groups, and lambdas more or less interchangeably, because they are just code references.)

However, when the compiler sees that the type is an Expression<>, it doesn't immediately compile the lambda down to MSIL, instead it generates an Expression Tree!

What is an Expression Tree?

So, what the heck is an expression tree. Well, it's not complicated but its not a walk in the park either. To quote ms:

| Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

Simply put, an expression tree is a representation of a function as a collection of "actions".

In the case of model=>model.SomeProperty, the expression tree would have a node in it that says: "Get 'Some Property' from a 'model'"

This expression tree can be compiled into a function that can be invoked, but as long as it's an expression tree, it's just a collection of nodes.

So what is that good for?

So Func<> or Action<>, once you have them, they are pretty much atomic. All you can really do is Invoke() them, aka tell them to do the work they are supposed to do.

Expression<Func<>> on the other hand, represents a collection of actions, which can be appended, manipulated, visited, or compiled and invoked.

So why are you telling me all this?

So with that understanding of what an Expression<> is, we can go back to Html.TextBoxFor. When it renders a textbox, it needs to generate a few things about the property that you are giving it. Things like attributes on the property for validation, and specifically in this case it needs to figure out what to name the <input> tag.

It does this by "walking" the expression tree and building a name. So for an expression like model=>model.SomeProperty, it walks the expression gathering the properties that you are asking for and builds <input name='SomeProperty'>.

For a more complicated example, like model=>model.Foo.Bar.Baz.FooBar, it might generate <input name="Foo.Bar.Baz.FooBar" value="[whatever FooBar is]" />

Make sense? It is not just the work that the Func<> does, but how it does its work is important here.

(Note other frameworks like LINQ to SQL do similar things by walking an expression tree and building a different grammar, that this case a SQL query)

How does the Model Binder work?

So once you get that, we have to briefly talk about the model binder. When the form gets posted, it's simply like a flat Dictionary<string, string>, we have lost the hierarchical structure our nested view model may have had. It's the model binder's job to take this key-value pair combo and attempt to rehydrate an object with some properties. How does it do this? You guessed it, by using the "key" or name of the input that got posted.

So if the form post looks like

Foo.Bar.Baz.FooBar = Hello

And you are posting to a model called SomeViewModel, then it does the reverse of what the helper did in the first place. It looks for a property called "Foo". Then it looks for a property called "Bar" off of "Foo", then it looks for "Baz"... and so on...

Finally it tries to parse the value into the type of "FooBar" and assign it to "FooBar".

PHEW!!!

And voila, you have your model. The instance the Model Binder just constructed gets handed into requested Action.


So your solution doesn't work because the Html.[Type]For() helpers need an expression. And you are just giving them a value. It has no idea what the context is for that value, and it doesn't know what to do with it.

Now some people suggested using partials to render. Now this in theory will work, but probably not the way that you expect. When you render a partial, you are changing the type of TModel, because you are in a different view context. This means that you can describe your property with a shorter expression. It also means when the helper generates the name for your expression, it will be shallow. It will only generate based on the expression it's given (not the entire context).

So lets say you had a partial that just rendered "Baz" (from our example before). Inside that partial you could just say:

@Html.TextBoxFor(model=>model.FooBar)

Rather than

@Html.TextBoxFor(model=>model.Foo.Bar.Baz.FooBar)

That means that it will generate an input tag like this:

<input name="FooBar" />

Which, if you are posting this form to an action that is expecting a large deeply nested ViewModel, then it will try to hydrate a property called FooBar off of TModel. Which at best isn't there, and at worst is something else entirely. If you were posting to a specific action that was accepting a Baz, rather than the root model, then this would work great! In fact, partials are a good way to change your view context, for example if you had a page with multiple forms that all post to different actions, then rendering a partial for each one would be a great idea.


Now once you get all of this, you can start to do really interesting things with Expression<>, by programatically extending them and doing other neat things with them. I won't get into any of that. But, hopefully, this will give you a better understanding of what is going on behind the scenes and why things are acting the way that they are.

How to convert a GUID to a string in C#?

You need

String guid = System.Guid.NewGuid().ToString();

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

This command loads class of Oracle jdbc driver to be available for DriverManager instance. After the class is loaded system can connect to Oracle using it. As an alternative you can use registerDriver method of DriverManager and pass it with instance of JDBC driver you need.

Table fixed header and scrollable body

You can place two div where 1st div (Header) will have transparent scroll bar and 2nd div will be have data with visible/auto scroll bar. Sample has angular code snippet for looping through the data.

Below code worked for me -

<div id="transparentScrollbarDiv" class="container-fluid" style="overflow-y: scroll;">
    <div class="row">
        <div class="col-lg-3 col-xs-3"><strong>{{col1}}</strong></div>
        <div class="col-lg-6 col-xs-6"><strong>{{col2}}</strong></div>
        <div class="col-lg-3 col-xs-3"><strong>{{col3}}</strong></div>
    </div>
</div>
<div class="container-fluid" style="height: 150px; overflow-y: auto">
    <div>
        <div class="row" ng-repeat="row in rows">
            <div class="col-lg-3 col-xs-3">{{row.col1}}</div>
            <div class="col-lg-6 col-xs-6">{{row.col2}}</div>
            <div class="col-lg-3 col-xs-3">{{row.col3}}</div>
        </div>
    </div>
</div>

Additional style to hide header scroll bar -

<style>
        #transparentScrollbarDiv::-webkit-scrollbar {
            width: inherit;
        }

        /* this targets the default scrollbar (compulsory) */

        #transparentScrollbarDiv::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* the new scrollbar will have a flat appearance with the set background color */

        #transparentScrollbarDiv::-webkit-scrollbar-thumb {
            background-color: transparent;
        }

        /* this will style the thumb, ignoring the track */

        #transparentScrollbarDiv::-webkit-scrollbar-button {
            background-color: transparent;
        }

        /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

        #transparentScrollbarDiv::-webkit-scrollbar-corner {
            background-color: transparent;
        }

        /* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */
    </style>

"Keep Me Logged In" - the best approach

I read all the answers and still found it difficult to extract what I was supposed to do. If a picture is worth 1k words I hope this helps others implement a secure persistent storage based on Barry Jaspan's Improved Persistent Login Cookie Best Practice

enter image description here

If you have questions, feedback, or suggestions, I will try to update the diagram to reflect for the newbie trying to implement a secure persistent login.

How to get IntPtr from byte[] in C#

Here's a twist on @user65157's answer (+1 for that, BTW):

I created an IDisposable wrapper for the pinned object:

class AutoPinner : IDisposable
{
   GCHandle _pinnedArray;
   public AutoPinner(Object obj)
   {
      _pinnedArray = GCHandle.Alloc(obj, GCHandleType.Pinned);
   }
   public static implicit operator IntPtr(AutoPinner ap)
   {
      return ap._pinnedArray.AddrOfPinnedObject(); 
   }
   public void Dispose()
   {
      _pinnedArray.Free();
   }
}

then use it like thusly:

using (AutoPinner ap = new AutoPinner(MyManagedObject))
{
   UnmanagedIntPtr = ap;  // Use the operator to retrieve the IntPtr
   //do your stuff
}

I found this to be a nice way of not forgetting to call Free() :)

SQL - ORDER BY 'datetime' DESC

  1. use single quotes for strings
  2. do NOT put single quotes around table names(use ` instead)
  3. do NOT put single quotes around numbers (you can, but it's harder to read)
  4. do NOT put AND between ORDER BY and LIMIT
  5. do NOT put = between ORDER BY, LIMIT keywords and condition

So you query will look like:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

Programmatically Creating UILabel

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 300, 50)];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = @"Your Text";
[self.view addSubview:label];

HTTP requests and JSON parsing in Python

Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.

import json, requests, pprint

url = 'http://maps.googleapis.com/maps/api/directions/json?'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)


data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)

# test to see if the request was valid
#print output['status']

# output all of the results
#pprint.pprint(output)

# step-by-step directions
for route in output['routes']:
        for leg in route['legs']:
            for step in leg['steps']:
                print step['html_instructions']

Find when a file was deleted in Git

git log --full-history -- [file path] shows the changes of a file and works even if the file was deleted.

Example:

git log --full-history  -- myfile

If you want to see only the last commit, which deleted the file, use -1 in addition to the command above. Example:

git log --full-history -1 -- [file path]

See also my article: Which commit deleted a file.

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

Twitter - share button, but with image

To create a Twitter share link with a photo, you first need to tweet out the photo from your Twitter account. Once you've tweeted it out, you need to grab the pic.twitter.com link and place that inside your twitter share url.

note: You won't be able to see the pic.twitter.com url so what I do is use a separate account and hit the retweet button. A modal will pop up with the link inside.

You Twitter share link will look something like this:

<a href="https://twitter.com/home?status=This%20photo%20is%20awesome!%20Check%20it%20out:%20pic.twitter.com/9Ee63f7aVp">Share on Twitter</a>

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

The *_test.go file is a Go source like the others, you can initialize a new logger every time if you need to dump complex data structure, here an example:

// initZapLog is delegated to initialize a new 'log manager'
func initZapLog() *zap.Logger {
    config := zap.NewDevelopmentConfig()
    config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
    config.EncoderConfig.TimeKey = "timestamp"
    config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    logger, _ := config.Build()
    return logger
}

Then, every time, in every test:

func TestCreateDB(t *testing.T) {
    loggerMgr := initZapLog()
    // Make logger avaible everywhere
    zap.ReplaceGlobals(loggerMgr)
    defer loggerMgr.Sync() // flushes buffer, if any
    logger := loggerMgr.Sugar()
    logger.Debug("START")
    conf := initConf()
    /* Your test here
    if false {
        t.Fail()
    }*/
}

Shell script : How to cut part of a string

You can have awk do it all without using cut:

awk '{print substr($7,index($7,"=")+1)}' inputfile

You could use split() instead of substr(index()).

Javascript callback when IFRAME is finished loading?

I think the load event is right. What is not right is the way you use to retreive the content from iframe content dom.

What you need is the html of the page loaded in the iframe not the html of the iframe object.

What you have to do is to access the content document with iFrameObj.contentDocument. This returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.

I would retreive the content before removing the iframe.

I've tested in firefox and opera.

Then i think you can retreive your data with $(childDom).html() or $(childDom).find('some selector') ...

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

The solution for me was to update guest additions

(click Devices -> Insert Guest Additions CD image)

Importing variables from another file?

from file1 import *  

will import all objects and methods in file1

virtualenvwrapper and Python 3

virtualenvwrapper now lets you specify the python executable without the path.

So (on OSX at least)mkvirtualenv --python=python3 nameOfEnvironment will suffice.

LINQ: Distinct values

For any one still looking; here's another way of implementing a custom lambda comparer.

public class LambdaComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> _expression;

        public LambdaComparer(Func<T, T, bool> lambda)
        {
            _expression = lambda;
        }

        public bool Equals(T x, T y)
        {
            return _expression(x, y);
        }

        public int GetHashCode(T obj)
        {
            /*
             If you just return 0 for the hash the Equals comparer will kick in. 
             The underlying evaluation checks the hash and then short circuits the evaluation if it is false.
             Otherwise, it checks the Equals. If you force the hash to be true (by assuming 0 for both objects), 
             you will always fall through to the Equals check which is what we are always going for.
            */
            return 0;
        }
    }

you can then create an extension for the linq Distinct that can take in lambda's

   public static IEnumerable<T> Distinct<T>(this IEnumerable<T> list,  Func<T, T, bool> lambda)
        {
            return list.Distinct(new LambdaComparer<T>(lambda));
        }  

Usage:

var availableItems = list.Distinct((p, p1) => p.Id== p1.Id);

How to get date, month, year in jQuery UI datepicker?

Hi you can try viewing this jsFiddle.

I used this code:

var day = $(this).datepicker('getDate').getDate();  
var month = $(this).datepicker('getDate').getMonth();  
var year = $(this).datepicker('getDate').getYear();  

I hope this helps.

How do I download NLTK data?

Try

nltk.download('all')

this will download all the data and no need to download individually.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I had the same issue, but none of the above worked for me. They did put me in to the right direction though.

For example when I set the "Copy Local" to "true" for System.Web.Mvc reference, it automatically sets it back to False.

I have multiple projects which depend on the System.Web.Mvc reference in my solution, but only one caused this problem. In VS 2012 this reference is labeled with the yellow attention triangle.

Find this reference => remove it => re-add it

That fixed it for me. Hope this helps

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

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

brew install python
brew tap homebrew/science
brew install opencv

Python regex for integer?

I prefer ^[-+]?([1-9]\d*|0)$ because ^[-+]?[0-9]+$ allows the string starting with 0.

RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')


class TestRE(unittest.TestCase):
    def test_int(self):
        self.assertFalse(RE_INT.match('+'))
        self.assertFalse(RE_INT.match('-'))

        self.assertTrue(RE_INT.match('1'))
        self.assertTrue(RE_INT.match('+1'))
        self.assertTrue(RE_INT.match('-1'))
        self.assertTrue(RE_INT.match('0'))
        self.assertTrue(RE_INT.match('+0'))
        self.assertTrue(RE_INT.match('-0'))

        self.assertTrue(RE_INT.match('11'))
        self.assertFalse(RE_INT.match('00'))
        self.assertFalse(RE_INT.match('01'))
        self.assertTrue(RE_INT.match('+11'))
        self.assertFalse(RE_INT.match('+00'))
        self.assertFalse(RE_INT.match('+01'))
        self.assertTrue(RE_INT.match('-11'))
        self.assertFalse(RE_INT.match('-00'))
        self.assertFalse(RE_INT.match('-01'))

        self.assertTrue(RE_INT.match('1234567890'))
        self.assertTrue(RE_INT.match('+1234567890'))
        self.assertTrue(RE_INT.match('-1234567890'))

Regex for empty string or white space

If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():

"    your string contents  ".trim();

// => "your string contents"

Add JavaScript object to JavaScript object

As my first object is a native javascript object (used like a list of objects), push didn't work in my escenario, but I resolved it by adding new key as following:

MyObjList['newKey'] = obj;

In addition to this, may be usefull to know how to delete same object inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me;