Programs & Examples On #Apache stringutils

StringUtils is a class belonging to Apache Commons package. It offers utility methods for dealing with strings.

Extract digits from string - StringUtils Java

Extending the best answer for finding floating point numbers

       String str="2.53GHz";
       String decimal_values= str.replaceAll("[^0-9\\.]", "");
       System.out.println(decimal_values);

What is href="#" and why is it used?

The problem with using href="#" for an empty link is that it will take you to the top of the page which may not be the desired action. To avoid this, for older browsers or non-HTML5 doctypes, use

<a href="javascript:void(0)">Goes Nowhere</a>

javascript multiple OR conditions in IF statement

This is an example:

false && true || true   // returns true
false && (true || true) // returns false
(true || true || true)  // returns true
false || true           // returns true
true || false           // returns true

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

Converting String to Int with Swift

edit/update: Xcode 11.4 • Swift 5.2

Please check the comments through the code


IntegerField.swift file contents:

import UIKit

class IntegerField: UITextField {

    // returns the textfield contents, removes non digit characters and converts the result to an integer value
    var value: Int { string.digits.integer ?? 0 }

    var maxValue: Int = 999_999_999
    private var lastValue: Int = 0

    override func willMove(toSuperview newSuperview: UIView?) {
        // adds a target to the textfield to monitor when the text changes
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        // sets the keyboard type to digits only
        keyboardType = .numberPad
        // set the text alignment to right
        textAlignment = .right
        // sends an editingChanged action to force the textfield to be updated
        sendActions(for: .editingChanged)
    }
    // deletes the last digit of the text field
    override func deleteBackward() {
        // note that the field text property default value is an empty string so force unwrap its value is safe
        // note also that collection remove at requires a non empty collection which is true as well in this case so no need to check if the collection is not empty.
        text!.remove(at: text!.index(before: text!.endIndex))
        // sends an editingChanged action to force the textfield to be updated
        sendActions(for: .editingChanged)
    }
    @objc func editingChanged() {
        guard value <= maxValue else {
            text = Formatter.decimal.string(for: lastValue)
            return
        }
        // This will format the textfield respecting the user device locale and settings
        text = Formatter.decimal.string(for: value)
        print("Value:", value)
        lastValue = value
    }
}

You would need to add those extensions to your project as well:


Extensions UITextField.swift file contents:

import UIKit
extension UITextField {
    var string: String { text ?? "" }
}

Extensions Formatter.swift file contents:

import Foundation
extension Formatter {
    static let decimal = NumberFormatter(numberStyle: .decimal)
}

Extensions NumberFormatter.swift file contents:

import Foundation
extension NumberFormatter {
    convenience init(numberStyle: Style) {
        self.init()
        self.numberStyle = numberStyle
    }
}

Extensions StringProtocol.swift file contents:

extension StringProtocol where Self: RangeReplaceableCollection {
    var digits: Self { filter(\.isWholeNumber) }
    var integer: Int? { Int(self) }
}

Sample project

List tables in a PostgreSQL schema

Alternatively to information_schema it is possible to use pg_tables:

select * from pg_tables where schemaname='public';

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

As answered above, the right answer is to compile everything with VS2015, but for interest the following is my analysis of the problem.

This symbol does not appear to be defined in any static library provided by Microsoft as part of VS2015, which is rather peculiar since all others are. To discover why, we need to look at the declaration of that function and, more importantly, how it's used.

Here's a snippet from the Visual Studio 2008 headers:

_CRTIMP FILE * __cdecl __iob_func(void);
#define stdin (&__iob_func()[0])
#define stdout (&__iob_func()[1])
#define stderr (&__iob_func()[2])

So we can see that the job of the function is to return the start of an array of FILE objects (not handles, the "FILE *" is the handle, FILE is the underlying opaque data structure storing the important state goodies). The users of this function are the three macros stdin, stdout and stderr which are used for various fscanf, fprintf style calls.

Now let's take a look at how Visual Studio 2015 defines the same things:

_ACRTIMP_ALT FILE* __cdecl __acrt_iob_func(unsigned);
#define stdin (__acrt_iob_func(0))
#define stdout (__acrt_iob_func(1))
#define stderr (__acrt_iob_func(2))

So the approach has changed for the replacement function to now return the file handle rather than the address of the array of file objects, and the macros have changed to simply call the function passing in an identifying number.

So why can't they/we provide a compatible API? There are two key rules which Microsoft can't contravene in terms of their original implementation via __iob_func:

  1. There must be an array of three FILE structures which can be indexed in the same manner as before.
  2. The structural layout of FILE cannot change.

Any change in either of the above would mean existing compiled code linked against that would go badly wrong if that API is called.

Let's take a look at how FILE was/is defined.

First the VS2008 FILE definition:

struct _iobuf {
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
        };
typedef struct _iobuf FILE;

And now the VS2015 FILE definition:

typedef struct _iobuf
{
    void* _Placeholder;
} FILE;

So there is the crux of it: the structure has changed shape. Existing compiled code referring to __iob_func relies upon the fact that the data returned is both an array that can be indexed and that in that array the elements are the same distance apart.

The possible solutions mentioned in the answers above along these lines would not work (if called) for a few reasons:

FILE _iob[] = {*stdin, *stdout, *stderr};

extern "C" FILE * __cdecl __iob_func(void)
{
    return _iob;
}

The FILE array _iob would be compiled with VS2015 and so it would be laid out as a block of structures containing a void*. Assuming 32-bit alignment, these elements would be 4 bytes apart. So _iob[0] is at offset 0, _iob[1] is at offset 4 and _iob[2] is at offset 8. The calling code will instead expect FILE to be much longer, aligned at 32 bytes on my system, and so it will take the address of the returned array and add 0 bytes to get to element zero (that one is okay), but for _iob[1] it will deduce that it needs to add 32 bytes and for _iob[2] it will deduce that it needs to add 64-bytes (because that's how it looked in the VS2008 headers). And indeed the disassembled code for VS2008 demonstrates this.

A secondary issue with the above solution is that it copies the content of the FILE structure (*stdin), not the FILE * handle. So any VS2008 code would be looking at a different underlying structure to VS2015. This might work if the structure only contained pointers, but that's a big risk. In any case the first issue renders this irrelevant.

The only hack I've been able to dream up is one in which __iob_func walks the call stack to work out which actual file handle they are looking for (based on the offset added to the returned address) and returns a computed value such that it gives the right answer. This is every bit as insane as it sounds, but the prototype for x86 only (not x64) is listed below for your amusement. It worked okay in my experiments, but your mileage may vary - not recommended for production use!

#include <windows.h>
#include <stdio.h>
#include <dbghelp.h>

/* #define LOG */

#if defined(_M_IX86)

#define GET_CURRENT_CONTEXT(c, contextFlags) \
  do { \
    c.ContextFlags = contextFlags; \
    __asm    call x \
    __asm x: pop eax \
    __asm    mov c.Eip, eax \
    __asm    mov c.Ebp, ebp \
    __asm    mov c.Esp, esp \
  } while(0);

#else

/* This should work for 64-bit apps, but doesn't */
#define GET_CURRENT_CONTEXT(c, contextFlags) \
  do { \
    c.ContextFlags = contextFlags; \
    RtlCaptureContext(&c); \
} while(0);

#endif

FILE * __cdecl __iob_func(void)
{
    CONTEXT c = { 0 };
    STACKFRAME64 s = { 0 };
    DWORD imageType;
    HANDLE hThread = GetCurrentThread();
    HANDLE hProcess = GetCurrentProcess();

    GET_CURRENT_CONTEXT(c, CONTEXT_FULL);

#ifdef _M_IX86
    imageType = IMAGE_FILE_MACHINE_I386;
    s.AddrPC.Offset = c.Eip;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.Ebp;
    s.AddrFrame.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.Esp;
    s.AddrStack.Mode = AddrModeFlat;
#elif _M_X64
    imageType = IMAGE_FILE_MACHINE_AMD64;
    s.AddrPC.Offset = c.Rip;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.Rsp;
    s.AddrFrame.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.Rsp;
    s.AddrStack.Mode = AddrModeFlat;
#elif _M_IA64
    imageType = IMAGE_FILE_MACHINE_IA64;
    s.AddrPC.Offset = c.StIIP;
    s.AddrPC.Mode = AddrModeFlat;
    s.AddrFrame.Offset = c.IntSp;
    s.AddrFrame.Mode = AddrModeFlat;
    s.AddrBStore.Offset = c.RsBSP;
    s.AddrBStore.Mode = AddrModeFlat;
    s.AddrStack.Offset = c.IntSp;
    s.AddrStack.Mode = AddrModeFlat;
#else
#error "Platform not supported!"
#endif

    if (!StackWalk64(imageType, hProcess, hThread, &s, &c, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
    {
#ifdef LOG
        printf("Error: 0x%08X (Address: %p)\n", GetLastError(), (LPVOID)s.AddrPC.Offset);
#endif
        return NULL;
    }

    if (s.AddrReturn.Offset == 0)
    {
        return NULL;
    }

    {
        unsigned char const * assembly = (unsigned char const *)(s.AddrReturn.Offset);
#ifdef LOG
        printf("Code bytes proceeding call to __iob_func: %p: %02X,%02X,%02X\n", assembly, *assembly, *(assembly + 1), *(assembly + 2));
#endif
        if (*assembly == 0x83 && *(assembly + 1) == 0xC0 && (*(assembly + 2) == 0x20 || *(assembly + 2) == 0x40))
        {
            if (*(assembly + 2) == 32)
            {
                return (FILE*)((unsigned char *)stdout - 32);
            }
            if (*(assembly + 2) == 64)
            {
                return (FILE*)((unsigned char *)stderr - 64);
            }

        }
        else
        {
            return stdin;
        }
    }
    return NULL;
}

Java 8 Filter Array Using Lambda

even simpler, adding up to String[],

use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

import org.apache.commons.lang3.StringUtils;

    String test = "a\nb\n\nc\n";
    String[] lines = test.split("\\n", -1);


    String[]  result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
    System.out.println(Arrays.toString(lines));
    System.out.println(Arrays.toString(result));

and output: [a, b, , c, ] [a, b, c]

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Difference between Pig and Hive? Why have both?

Have a look at Pig Vs Hive Comparison in a nut shell from a "dezyre" article

Hive is better than PIG in: Partitions, Server, Web interface & JDBC/ODBC support.

Some differences:

  1. Hive is best for structured Data & PIG is best for semi structured data

  2. Hive is used for reporting & PIG for programming

  3. Hive is used as a declarative SQL & PIG as a procedural language

  4. Hive supports partitions & PIG does not

  5. Hive can start an optional thrift based server & PIG cannot

  6. Hive defines tables beforehand (schema) + stores schema information in a database & PIG doesn't have a dedicated metadata of database

  7. Hive does not support Avro but PIG does. EDIT: Hive supports Avro, specify the serde as org.apache.hadoop.hive.serde2.avro

  8. Pig also supports additional COGROUP feature for performing outer joins but hive does not. But both Hive & PIG can join, order & sort dynamically.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

Java - Convert int to Byte Array of 4 Bytes?

public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Regular expression search replace in Sublime Text 2

By the way, in the question above:

For:

Hello, my name is bob

Find part:

my name is (\w)+

With replace part:

my name used to be \1

Would return:

Hello, my name used to be b

Change find part to:

my name is (\w+)

And replace will be what you expect:

Hello, my name used to be bob

While (\w)+ will match "bob", it is not the grouping you want for replacement.

Just get column names from hive table

If you simply want to see the column names this one line should provide it without changing any settings:

describe database.tablename;

However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:

use database;
describe tablename;

jQuery getTime function

Annoyingly Javascript's date.getSeconds() et al will not pad the result with zeros 11:0:0 instead of 11:00:00.

So I like to use

date.toLocaleTimestring()

Which renders 11:00:00 AM. Just beware when using the extra options, some browsers don't support them (Safari)

Documentation

Running ASP.Net on a Linux based server

You can use Mono to run ASP.NET applications on Apache/Linux, however it has a limited subset of what you can do under Windows. As for "they" saying Windows is more vulnerable to attack - it's not true. IIS has had less security problems over the last couple of years that Apache, but in either case it's all down to the administration of the boxes - both OSes can be easily secured. These days the attack points are not the OS or web server software, but the applications themselves.

How do I change UIView Size?

Hi create this extends if you want. Update 2021 Swift 5

Create File Extends.Swift and add this code (add import foundation where you want change height)

extension UIView {
    /**
    Get Set x Position
    
    - parameter x: CGFloat
    */
    var x:CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame.origin.x = newValue
        }
    }
    /**
    Get Set y Position
    
    - parameter y: CGFloat
    */
    var y:CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame.origin.y = newValue
        }
    }
    /**
    Get Set Height
    
    - parameter height: CGFloat
    */
    var height:CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            self.frame.size.height = newValue
        }
    }
    /**
    Get Set Width
    
    - parameter width: CGFloat
    */
    var width:CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            self.frame.size.width = newValue
        }
    }
}

For Use (inherits Of UIView)

inheritsOfUIView.height = 100
button.height = 100
print(view.height)

How to align checkboxes and their labels consistently cross-browsers

try vertical-align: middle

also your code seems like it should be:

_x000D_
_x000D_
<form>_x000D_
    <div>_x000D_
        <input id="blah" type="checkbox"><label for="blah">Label text</label>_x000D_
    </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Checking to see if a DateTime variable has had a value assigned

I just found out that GetHashCode() for an unassigned datetime is always zero. I am not sure if this is a good way to check for null datetime, because, I can't find any documentation on why this behavior is displayed.

if(dt.GetHashCode()==0)
{
    Console.WriteLine("DateTime is unassigned"); 
} 

$.focus() not working

Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.

How to sort a Collection<T>?

Assuming you have a list of object of type Person, using Lambda expression, you can sort the last names of users for instance by doing the following:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
        private String firstName;
        private String lastName;

        public Person(String firstName, String lastName){
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getLastName(){
            return this.lastName;
        }

        public String getFirstName(){
            return this.firstName;
        }

        @Override
        public String toString(){
            return "Person: "+ this.getFirstName() + " " + this.getLastName();
        }
    }

    class TestSort {
        public static void main(String[] args){
            List<Person> people = Arrays.asList(
                                  new Person("John", "Max"), 
                                  new Person("Coolio", "Doe"), 
                                  new Person("Judith", "Dan")
            );

            //Making use of lambda expression to sort the collection
            people.sort((p1, p2)->p1.getLastName().compareTo(p2.getLastName()));

            //Print sorted 
            printPeople(people);
        }

        public static void printPeople(List<Person> people){
            for(Person p : people){
                System.out.println(p);
            }
        }
    }

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

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

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

I encountered an issue like this using the Maven Release Plugin. Resolving using relative paths (i.e. for the parent pom in the child module ../parent/pom.xml) did not seem to work in this scenario, it keeps looking for the released parent pom in the Nexus repository. Moving the parent pom to the parent folder of the module resolved this.

What does the exclamation mark do before the function?

! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.

Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.

Instead, use the closing parenthesis and the BANG (!) if needed.

// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.

(function(){ return false; }());
=> false

!(function(){ return false; }());
=> true

!!(function(){ return false; }());
=> false

!!!(function(){ return false; }());
=> true

Other Operators that work...

+(function(){ return false; }());
=> 0

-(function(){ return false; }());
=> -0

~(function(){ return false; }());
=> -1

Combined Operators...

+!(function(){ return false; }());
=> 1

-!(function(){ return false; }());
=> -1

!+(function(){ return false; }());
=> true

!-(function(){ return false; }());
=> true

~!(function(){ return false; }());
=> -2

~!!(function(){ return false; }());
=> -1

+~(function(){ return false; }());
+> -1

CONVERT Image url to Base64

This is your html-

    <img id="imageid" src="">
    <canvas id="imgCanvas" />

Javascript should be-

   var can = document.getElementById("imgCanvas");
   var img = document.getElementById("imageid");
   var ctx = can.getContext("2d");
   ctx.drawImage(img, 10, 10);
   var encodedBase = can.toDataURL();

'encodedBase' Contains Base64 Encoding of Image.

ADB No Devices Found

Normally SDB will download the driver in the **android-sdk-windows\extras\google\usb_driver** path

Here are the steps that worked for me:

  1. Enable USB debugging.
  2. Do to device manager, right click on ADB device and click update driver software.
  3. Select "Browse my computer for Driver Software"
  4. Select "Let me pick from list of Device drivers on my computer"
  5. Click on "Have Disk" option.
  6. Select the driver path **android-sdk-windows\extras\google\usb_driver** (path of sdk) 7.Select 1st driver out of list of drivers shown.

And hopefully, it will work.

String to HashMap JAVA

You can do that with Guava's Splitter.MapSplitter:

Map<String, String> properties = Splitter.on(",").withKeyValueSeparator(":").split(inputString);

Loading inline content using FancyBox

The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.

If you view the code that is used for the demo website and basically copy/paste, you'll be fine.

To get an inline Fancybox working, you will need to have this code present in your index.html file:

  <head>
    <link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
    <script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

    $("#various1").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
    });
    </script>
  </head>

 <body>

    <a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
    <div style="display: none;">
        <div id="inline1" style="width:400px;height:100px;overflow:auto;">
                   Write whatever text you want right here!!
        </div>
    </div> 

</body>

Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.

Regular Expression with wildcards to match any character

Without knowing the exact regex implementation you're making use of, I can only give general advice. (The syntax I will be perl as that's what I know, some languages will require tweaking)

Looking at ABC: (z) jan 02 1999 \n

  • The first thing to match is ABC: So using our regex is /ABC:/

  • You say ABC is always at the start of the string so /^ABC/ will ensure that ABC is at the start of the string.

  • You can match spaces with the \s (note the case) directive. With all directives you can match one or more with + (or 0 or more with *)

  • You need to escape the usage of ( and ) as it's a reserved character. so \(\)

  • You can match any non space or newline character with .

  • You can match anything at all with .* but you need to be careful you're not too greedy and capture everything.

So in order to capture what you've asked. I would use /^ABC:\s*\(.+?\)\s*(.+)$/

Which I read as:

Begins with ABC:

May have some spaces

has (

has some characters

has )

may have some spaces

then capture everything until the end of the line (which is $).

I highly recommend keeping a copy of the following laying about http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

Java equivalent to Explode and Implode(PHP)

The Javadoc for String reveals that String.split() is what you're looking for in regard to explode.

Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder is one:

String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
    sb.append(split[i]);
    if (i != split.length - 1) {
        sb.append(" ");
    }
}
String joined = sb.toString();

Convert all data frame character columns to factors

DF <- data.frame(x=letters[1:5], y=1:5, stringsAsFactors=FALSE)

str(DF)
#'data.frame':  5 obs. of  2 variables:
# $ x: chr  "a" "b" "c" "d" ...
# $ y: int  1 2 3 4 5

The (annoying) default of as.data.frame is to turn all character columns into factor columns. You can use that here:

DF <- as.data.frame(unclass(DF))
str(DF)
#'data.frame':  5 obs. of  2 variables:
# $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
# $ y: int  1 2 3 4 5

Dynamically change color to lighter or darker by percentage CSS (Javascript)

In LESS, you would use the following variables:

@primary-color: #999;
@primary-color-lighter: lighten(@primary-color, 20%);

This would take the 1st variable and lighten it by 20% (or any other percentage). In this example, you'd end up with your lighter color being: #ccc

How do I get the command-line for an Eclipse run configuration?

Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

Which tool to build a simple web front-end to my database

If you are experienced with SQL Server, I would recommend ASP.NET.

ADO.NET gives you good access to SQL Server, and with SMO, you will also have just about the best access to SQL Server features. You can access SQL Server from other environments, but nothing is quite as integrated or predictable.

You can call your stored procs with SqlCommand and process the results the SqlDataReader and you'll be in business.

Add custom buttons on Slick Carousel

From the docs

prevArrow/nextArrow

Type: string (html|jQuery selector) | object (DOM node|jQuery object)

Some example code

$(document).ready(function(){
    $('.slick-carousel-1').slick({
        // @type {string} html
        nextArrow: '<button class="any-class-name-you-want-next">Next</button>',
        prevArrow: '<button class="any-class-name-you-want-previous">Previous</button>'
    });

    $('.slick-carousel-2').slick({
        // @type {string} jQuery Selector
        nextArrow: '.next',
        prevArrow: '.previous'
    });

    $('.slick-carousel-3').slick({
        // @type {object} DOM node
        nextArrow: document.getElementById('slick-next'),
        prevArrow: document.getElementById('slick-previous')
    });

    $('.slick-carousel-4').slick({
        // @type {object} jQuery Object
        nextArrow: $('.example-4 .next'),
        prevArrow: $('.example-4 .previous')
    });
});

A little note on styling

Once Slick knows about your new buttons, you can style them to your heart's content; looking at the above example, you could target them based on class name, id name or even element.

Did somebody say JSFiddle?

Generate random numbers with a given (numerical) distribution

Maybe it is kind of late. But you can use numpy.random.choice(), passing the p parameter:

val = numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])

Pretty printing XML in Python

Use etree.indent and etree.tostring

import lxml.etree as etree

root = etree.fromstring('<html><head></head><body><h1>Welcome</h1></body></html>')
etree.indent(root, space="  ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)

output

<html>
  <head/>
  <body>
    <h1>Welcome</h1>
  </body>
</html>

Removing namespaces and prefixes

import lxml.etree as etree


def dump_xml(element):
    for item in element.getiterator():
        item.tag = etree.QName(item).localname

    etree.cleanup_namespaces(element)
    etree.indent(element, space="  ")
    result = etree.tostring(element, pretty_print=True).decode()
    return result


root = etree.fromstring('<cs:document xmlns:cs="http://blabla.com"><name>hello world</name></cs:document>')
xml_string = dump_xml(root)
print(xml_string)

output

<document>
  <name>hello world</name>
</document>

How to study design patterns?

The notion that read design patterns, practice coding them is not really going to help IMO. When you read these books 1. Look for the basic problem that a particular design pattern solves,starting with Creational Patterns is your best bet. 2. I am sure you have written code in past, analyze if you faced the same problems that design patterns aim at providing a solution. 3. Try to redesign/re factor code or perhaps start off fresh.

About resources you can check these

  1. www.dofactory.com
  2. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) by Erich Gamma, Richard Helm, Ralph Johnson, and John M. Vlissides
  3. Patterns of Enterprise Application Architecture by Martin Fowler

1 is quick start, 2 will be in depth study..3 will explain or should make you think what you learnt in 2 fits in enterprise software.

My 2 cents...

Where are the Android icon drawables within the SDK?

i found mine here:

~/android-sdks/platforms/android-23/data/res/drawable...

Default value of function parameter

The first way would be preferred to the second.

This is because the header file will show that the parameter is optional and what its default value will be. Additionally, this will ensure that the default value will be the same, no matter the implementation of the corresponding .cpp file.

In the second way, there is no guarantee of a default value for the second parameter. The default value could change, depending on how the corresponding .cpp file is implemented.

Best way to integrate Python and JavaScript?

How about pyjs?

From the above website:

pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python.

Console.WriteLine does not show up in Output window

If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.

If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.

If you absolutely must use the console, then you can attach a console in the program's Main method.

How to support placeholder attribute in IE8 and 9

For others landing here. This is what worked for me:

//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
    }
}).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur();

$('[placeholder]').parents('form').submit(function() {
    $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
        }
    })
});

Just add this in you script.js file. Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Read only the first line of a file?

fline=open("myfile").readline().rstrip()

Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_151 contains a valid JDK installation

My issue was two-fold:

  1. I had the JRE installed, but not the JDK.
  2. I did not have a JAVA_HOME environment variable set.

Note: I am using Fedora Linux.

To resolve the first issue, I followed these instructions

To resolve the second, I merely added the following line to my ~/.bashrc file:

export JAVA_HOME=/usr/lib/jvm/java/

I had to restart my IDE and terminals to ensure the change to the ~/.bashrc took affect.

filters on ng-model in an input

If you are doing complex, async input validation it might be worth it to abstract ng-model up one level as part of a custom class with its own validation methods.

https://plnkr.co/edit/gUnUjs0qHQwkq2vPZlpO?p=preview

html

<div>

  <label for="a">input a</label>
  <input 
    ng-class="{'is-valid': vm.store.a.isValid == true, 'is-invalid': vm.store.a.isValid == false}"
    ng-keyup="vm.store.a.validate(['isEmpty'])"
    ng-model="vm.store.a.model"
    placeholder="{{vm.store.a.isValid === false ? vm.store.a.warning : ''}}"
    id="a" />

  <label for="b">input b</label>
  <input 
    ng-class="{'is-valid': vm.store.b.isValid == true, 'is-invalid': vm.store.b.isValid == false}"
    ng-keyup="vm.store.b.validate(['isEmpty'])"
    ng-model="vm.store.b.model"
    placeholder="{{vm.store.b.isValid === false ? vm.store.b.warning : ''}}"
    id="b" />

</div>

code

(function() {

  const _ = window._;

  angular
    .module('app', [])
    .directive('componentLayout', layout)
    .controller('Layout', ['Validator', Layout])
    .factory('Validator', function() { return Validator; });

  /** Layout controller */

  function Layout(Validator) {
    this.store = {
      a: new Validator({title: 'input a'}),
      b: new Validator({title: 'input b'})
    };
  }

  /** layout directive */

  function layout() {
    return {
      restrict: 'EA',
      templateUrl: 'layout.html',
      controller: 'Layout',
      controllerAs: 'vm',
      bindToController: true
    };
  }

  /** Validator factory */  

  function Validator(config) {
    this.model = null;
    this.isValid = null;
    this.title = config.title;
  }

  Validator.prototype.isEmpty = function(checkName) {
    return new Promise((resolve, reject) => {
      if (/^\s+$/.test(this.model) || this.model.length === 0) {
        this.isValid = false;
        this.warning = `${this.title} cannot be empty`;
        reject(_.merge(this, {test: checkName}));
      }
      else {
        this.isValid = true;
        resolve(_.merge(this, {test: checkName}));
      }
    });
  };

  /**
   * @memberof Validator
   * @param {array} checks - array of strings, must match defined Validator class methods
   */

  Validator.prototype.validate = function(checks) {
    Promise
      .all(checks.map(check => this[check](check)))
      .then(res => { console.log('pass', res)  })
      .catch(e => { console.log('fail', e) })
  };

})();

How do I draw a set of vertical lines in gnuplot?

alternatively you can also do this:

p '< echo "x y"' w impulse

x and y are the coordinates of the point to which you draw a vertical bar

Print content of JavaScript object?

If you are using Firefox, alert(object.toSource()) should suffice for simple debugging purposes.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

How to validate white spaces/empty spaces? [Angular 2]

You can create a custom validator to handle this.

new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])

Add noWhitespaceValidator method to your component

public noWhitespaceValidator(control: FormControl) {
    const isWhitespace = (control.value || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true };
}

and in the HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>

How to install a private NPM module without my own registry?

Config to install from public Github repository, even if machine is under firewall:

dependencies: {
   "foo": "https://github.com/package/foo/tarball/master"
}

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Angular/RxJs When should I unsubscribe from `Subscription`

You don't need to have bunch of subscriptions and unsubscribe manually. Use Subject and takeUntil combo to handle subscriptions like a boss:

import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"

@Component({
  moduleId: __moduleName,
  selector: "my-view",
  templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
  componentDestroyed$: Subject<boolean> = new Subject()

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.emitter1$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 1 */ })

    this.titleService.emitter2$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 2 */ })

    //...

    this.titleService.emitterN$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something N */ })
  }

  ngOnDestroy() {
    this.componentDestroyed$.next(true)
    this.componentDestroyed$.complete()
  }
}

Alternative approach, which was proposed by @acumartini in comments, uses takeWhile instead of takeUntil. You may prefer it, but mind that this way your Observable execution will not be cancelled on ngDestroy of your component (e.g. when you make time consuming calculations or wait for data from server). Method, which is based on takeUntil, doesn't have this drawback and leads to immediate cancellation of request. Thanks to @AlexChe for detailed explanation in comments.

So here is the code:

@Component({
  moduleId: __moduleName,
  selector: "my-view",
  templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
  alive: boolean = true

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.emitter1$
      .pipe(takeWhile(() => this.alive))
      .subscribe((data: any) => { /* ... do something 1 */ })

    this.titleService.emitter2$
      .pipe(takeWhile(() => this.alive))
      .subscribe((data: any) => { /* ... do something 2 */ })

    // ...

    this.titleService.emitterN$
      .pipe(takeWhile(() => this.alive))
      .subscribe((data: any) => { /* ... do something N */ })
  }

  ngOnDestroy() {
    this.alive = false
  }
}

Count number of objects in list

I spent ages trying to figure this out but it is simple! You can use length(·). length(mylist) will tell you the number of objects mylist contains.

... and just realised someone had already answered this- sorry!

How do I ignore files in a directory in Git?

A leading slash indicates that the ignore entry is only to be valid with respect to the directory in which the .gitignore file resides. Specifying *.o would ignore all .o files in this directory and all subdirs, while /*.o would just ignore them in that dir, while again, /foo/*.o would only ignore them in /foo/*.o.

NSUserDefaults - How to tell if a key exists

Swift version to get Bool?

NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool

T-SQL get SELECTed value of stored procedure

There is also a combination, you can use a return value with a recordset:

--Stored Procedure--

CREATE PROCEDURE [TestProc]

AS
BEGIN

    DECLARE @Temp TABLE
    (
        [Name] VARCHAR(50)
    )

    INSERT INTO @Temp VALUES ('Mark') 
    INSERT INTO @Temp VALUES ('John') 
    INSERT INTO @Temp VALUES ('Jane') 
    INSERT INTO @Temp VALUES ('Mary') 

    -- Get recordset
    SELECT * FROM @Temp

    DECLARE @ReturnValue INT
    SELECT @ReturnValue = COUNT([Name]) FROM @Temp

    -- Return count
    RETURN @ReturnValue

END

--Calling Code--

DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc] 

SELECT @SelectedValue

--Results--

enter image description here

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

warning: incompatible implicit declaration of built-in function ‘xyz’

In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.

To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-* flags if possible.

Instead of stdlib.h, you should try:

#include <string.h>

That's where strcpy and strncpy are defined, at least according to the strcpy(2) man page.

The exit function is defined in stdlib.h, though, so I don't know what's going on there.

Internet Access in Ubuntu on VirtualBox

I had the same problem.

Solved by sharing internet connection (on the hosting OS).

Network Connection Properties -> advanced -> Allow other users to connect...

How to iterate a loop with index and element in Swift

You can simply use loop of enumeration to get your desired result:

Swift 2:

for (index, element) in elements.enumerate() {
    print("\(index): \(element)")
}

Swift 3 & 4:

for (index, element) in elements.enumerated() {
    print("\(index): \(element)")
}

Or you can simply go through a for loop to get the same result:

for index in 0..<elements.count {
    let element = elements[index]
    print("\(index): \(element)")
}

Hope it helps.

Android WebView not loading an HTTPS URL

My website is a subdomain which is developed on angular 8 which is also using localstorage and cookies. website showed after setting the below line, along with other solutions mentioned above.

webSettings.setDomStorageEnabled(true);

Basic communication between two fragments

I recently created a library that uses annotations to generate those type casting boilerplate code for you. https://github.com/zeroarst/callbackfragment

Here is an example. Click a TextView on DialogFragment triggers a callback to MainActivity in onTextClicked then grab the MyFagment instance to interact with.

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {

private static final String MY_FRAGM = "MY_FRAGMENT";
private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getSupportFragmentManager().beginTransaction()
        .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
        .commit();

    findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
        }
    });
}

Toast mToast;

@Override
public void onClickButton(MyFragment fragment) {
    if (mToast != null)
        mToast.cancel();
    mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
    mToast.show();
}

@Override
public void onTextClicked(MyDialogFragment fragment) {
    MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
    if (myFragm != null) {
        myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
    }
}

}

jQuery Datepicker close datepicker after selected date

This is my edited version : you just need to add an extra argument "autoClose".

example :

 $('input[name="fieldName"]').datepicker({ autoClose: true});

also you can specify a close callback if you want. :)

replace datepicker.js with this:

!function( $ ) {

// Picker object

var Datepicker = function(element, options , closeCallBack){
    this.element = $(element);
    this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
    this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
    this.closeCallback = closeCallBack || function(){};
    this.picker = $(DPGlobal.template)
                        .appendTo('body')
                        .on({
                            click: $.proxy(this.click, this)//,
                            //mousedown: $.proxy(this.mousedown, this)
                        });
    this.isInput = this.element.is('input');
    this.component = this.element.is('.date') ? this.element.find('.add-on') : false;

    if (this.isInput) {
        this.element.on({
            focus: $.proxy(this.show, this),
            //blur: $.proxy(this.hide, this),
            keyup: $.proxy(this.update, this)
        });
    } else {
        if (this.component){
            this.component.on('click', $.proxy(this.show, this));
        } else {
            this.element.on('click', $.proxy(this.show, this));
        }
    }

    this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
    if (typeof this.minViewMode === 'string') {
        switch (this.minViewMode) {
            case 'months':
                this.minViewMode = 1;
                break;
            case 'years':
                this.minViewMode = 2;
                break;
            default:
                this.minViewMode = 0;
                break;
        }
    }
    this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
    if (typeof this.viewMode === 'string') {
        switch (this.viewMode) {
            case 'months':
                this.viewMode = 1;
                break;
            case 'years':
                this.viewMode = 2;
                break;
            default:
                this.viewMode = 0;
                break;
        }
    }
    this.startViewMode = this.viewMode;
    this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
    this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
    this.onRender = options.onRender;
    this.fillDow();
    this.fillMonths();
    this.update();
    this.showMode();
};

Datepicker.prototype = {
    constructor: Datepicker,

    show: function(e) {
        this.picker.show();
        this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
        this.place();
        $(window).on('resize', $.proxy(this.place, this));
        if (e ) {
            e.stopPropagation();
            e.preventDefault();
        }
        if (!this.isInput) {
        }
        var that = this;
        $(document).on('mousedown', function(ev){
            if ($(ev.target).closest('.datepicker').length == 0) {
                that.hide();
            }
        });
        this.element.trigger({
            type: 'show',
            date: this.date
        });
    },

    hide: function(){
        this.picker.hide();
        $(window).off('resize', this.place);
        this.viewMode = this.startViewMode;
        this.showMode();
        if (!this.isInput) {
            $(document).off('mousedown', this.hide);
        }
        //this.set();
        this.element.trigger({
            type: 'hide',
            date: this.date
        });
    },

    set: function() {
        var formated = DPGlobal.formatDate(this.date, this.format);
        if (!this.isInput) {
            if (this.component){
                this.element.find('input').prop('value', formated);
            }
            this.element.data('date', formated);
        } else {
            this.element.prop('value', formated);
        }
    },

    setValue: function(newDate) {
        if (typeof newDate === 'string') {
            this.date = DPGlobal.parseDate(newDate, this.format);
        } else {
            this.date = new Date(newDate);
        }
        this.set();
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    place: function(){
        var offset = this.component ? this.component.offset() : this.element.offset();
        this.picker.css({
            top: offset.top + this.height,
            left: offset.left
        });
    },

    update: function(newDate){
        this.date = DPGlobal.parseDate(
            typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
            this.format
        );
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    fillDow: function(){
        var dowCnt = this.weekStart;
        var html = '<tr>';
        while (dowCnt < this.weekStart + 7) {
            html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
        }
        html += '</tr>';
        this.picker.find('.datepicker-days thead').append(html);
    },

    fillMonths: function(){
        var html = '';
        var i = 0
        while (i < 12) {
            html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
        }
        this.picker.find('.datepicker-months td').append(html);
    },

    fill: function() {
        var d = new Date(this.viewDate),
            year = d.getFullYear(),
            month = d.getMonth(),
            currentDate = this.date.valueOf();
        this.picker.find('.datepicker-days th:eq(1)')
                    .text(DPGlobal.dates.months[month]+' '+year);
        var prevMonth = new Date(year, month-1, 28,0,0,0,0),
            day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
        prevMonth.setDate(day);
        prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
        var nextMonth = new Date(prevMonth);
        nextMonth.setDate(nextMonth.getDate() + 42);
        nextMonth = nextMonth.valueOf();
        var html = [];
        var clsName,
            prevY,
            prevM;
        while(prevMonth.valueOf() < nextMonth) {zs
            if (prevMonth.getDay() === this.weekStart) {
                html.push('<tr>');
            }
            clsName = this.onRender(prevMonth);
            prevY = prevMonth.getFullYear();
            prevM = prevMonth.getMonth();
            if ((prevM < month &&  prevY === year) ||  prevY < year) {
                clsName += ' old';
            } else if ((prevM > month && prevY === year) || prevY > year) {
                clsName += ' new';
            }
            if (prevMonth.valueOf() === currentDate) {
                clsName += ' active';
            }
            html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
            if (prevMonth.getDay() === this.weekEnd) {
                html.push('</tr>');
            }
            prevMonth.setDate(prevMonth.getDate()+1);
        }
        this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
        var currentYear = this.date.getFullYear();

        var months = this.picker.find('.datepicker-months')
                    .find('th:eq(1)')
                        .text(year)
                        .end()
                    .find('span').removeClass('active');
        if (currentYear === year) {
            months.eq(this.date.getMonth()).addClass('active');
        }

        html = '';
        year = parseInt(year/10, 10) * 10;
        var yearCont = this.picker.find('.datepicker-years')
                            .find('th:eq(1)')
                                .text(year + '-' + (year + 9))
                                .end()
                            .find('td');
        year -= 1;
        for (var i = -1; i < 11; i++) {
            html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
            year += 1;
        }
        yearCont.html(html);
    },

    click: function(e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('span, td, th');
        if (target.length === 1) {
            switch(target[0].nodeName.toLowerCase()) {
                case 'th':
                    switch(target[0].className) {
                        case 'switch':
                            this.showMode(1);
                            break;
                        case 'prev':
                        case 'next':
                            this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
                                this.viewDate,
                                this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
                                DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
                            );
                            this.fill();
                            this.set();
                            break;
                    }
                    break;
                case 'span':
                    if (target.is('.month')) {
                        var month = target.parent().find('span').index(target);
                        this.viewDate.setMonth(month);
                    } else {
                        var year = parseInt(target.text(), 10)||0;
                        this.viewDate.setFullYear(year);
                    }
                    if (this.viewMode !== 0) {
                        this.date = new Date(this.viewDate);
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                    }
                    this.showMode(-1);
                    this.fill();
                    this.set();
                    break;
                case 'td':
                    if (target.is('.day') && !target.is('.disabled')){
                        var day = parseInt(target.text(), 10)||1;
                        var month = this.viewDate.getMonth();
                        if (target.is('.old')) {
                            month -= 1;
                        } else if (target.is('.new')) {
                            month += 1;
                        }
                        var year = this.viewDate.getFullYear();
                        this.date = new Date(year, month, day,0,0,0,0);
                        this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
                        this.fill();
                        this.set();
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                        if(this.autoClose === true){
                            this.hide();
                            this.closeCallback();
                        }

                    }
                    break;
            }
        }
    },

    mousedown: function(e){
        e.stopPropagation();
        e.preventDefault();
    },

    showMode: function(dir) {
        if (dir) {
            this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
        }
        this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
    }
};

$.fn.datepicker = function ( option, val ) {
    return this.each(function () {
        var $this = $(this);
        var datePicker = $this.data('datepicker');
        var options = typeof option === 'object' && option;
        if (!datePicker) {
            if (typeof val === 'function')
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
            else{
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
            }
        }
        if (typeof option === 'string') datePicker[option](val);

    });
};

$.fn.datepicker.defaults = {
    onRender: function(date) {
        return '';
    }
};
$.fn.datepicker.Constructor = Datepicker;

var DPGlobal = {
    modes: [
        {
            clsName: 'days',
            navFnc: 'Month',
            navStep: 1
        },
        {
            clsName: 'months',
            navFnc: 'FullYear',
            navStep: 1
        },
        {
            clsName: 'years',
            navFnc: 'FullYear',
            navStep: 10
    }],
    dates:{
        days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
                    daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
                    daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
                    months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
                    monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
                    today: "Aujourd'hui",
                    clear: "Effacer",
                    weekStart: 1,
                    format: "dd/mm/yyyy"
    },
    isLeapYear: function (year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth: function (year, month) {
        return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    parseFormat: function(format){
        var separator = format.match(/[.\/\-\s].*?/),
            parts = format.split(/\W+/);
        if (!separator || !parts || parts.length === 0){
            throw new Error("Invalid date format.");
        }
        return {separator: separator, parts: parts};
    },
    parseDate: function(date, format) {
        var parts = date.split(format.separator),
            date = new Date(),
            val;
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        if (parts.length === format.parts.length) {
            var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
            for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                val = parseInt(parts[i], 10)||1;
                switch(format.parts[i]) {
                    case 'dd':
                    case 'd':
                        day = val;
                        date.setDate(val);
                        break;
                    case 'mm':
                    case 'm':
                        month = val - 1;
                        date.setMonth(val - 1);
                        break;
                    case 'yy':
                        year = 2000 + val;
                        date.setFullYear(2000 + val);
                        break;
                    case 'yyyy':
                        year = val;
                        date.setFullYear(val);
                        break;
                }
            }
            date = new Date(year, month, day, 0 ,0 ,0);
        }
        return date;
    },
    formatDate: function(date, format){
        var val = {
            d: date.getDate(),
            m: date.getMonth() + 1,
            yy: date.getFullYear().toString().substring(2),
            yyyy: date.getFullYear()
        };
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
        var date = [];
        for (var i=0, cnt = format.parts.length; i < cnt; i++) {
            date.push(val[format.parts[i]]);
        }
        return date.join(format.separator);
    },
    headTemplate: '<thead>'+
                        '<tr>'+
                            '<th class="prev">&lsaquo;</th>'+
                            '<th colspan="5" class="switch"></th>'+
                            '<th class="next">&rsaquo;</th>'+
                        '</tr>'+
                    '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
                        '<div class="datepicker-days">'+
                            '<table class=" table-condensed">'+
                                DPGlobal.headTemplate+
                                '<tbody></tbody>'+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-months">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-years">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                    '</div>';

}( window.jQuery );

Generate an HTML Response in a Java Servlet

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

Kickoff example:

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "Hello World";
        request.setAttribute("message", message); // This will be available as ${message}
        request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
    }

}

And /WEB-INF/hello.jsp look like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>

When opening http://localhost:8080/contextpath/hello this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

How to check if array element exists or not in javascript?

var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}

Convert a String In C++ To Upper Case

My solution (clearing 6th bit for alpha):

#include <ctype.h>

inline void toupper(char* str)
{
    while (str[i]) {
        if (islower(str[i]))
            str[i] &= ~32; // Clear bit 6 as it is what differs (32) between Upper and Lowercases
        i++;
    }
}

ASP.NET MVC 3 - redirect to another action

You have to write this code instead of return View(); :

return RedirectToAction("ActionName", "ControllerName");

Can you delete multiple branches in one command with Git?

Use the following command to remove all branches (checked out branch will not be deleted).

git branch | cut -d '*' -f 1 | tr -d " \t\r" | xargs git branch -d

Edit: I am using a Mac Os

Trimming text strings in SQL Server 2008

I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):

_x000D_
_x000D_
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
 IF (@c IS NULL) RETURN NULL;_x000D_
 DECLARE @WHITESPACE NCHAR(31);_x000D_
 SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
 IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
 RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
 -- Check tiny strings (NULL, 0 or 1 chars)_x000D_
 IF @TEXT IS NULL RETURN N'';_x000D_
 DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
 IF @TEXTLENGTH < 2 BEGIN_x000D_
  IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
  IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
  RETURN @TEXT;_x000D_
 END_x000D_
 -- Check whether we have to LTRIM/RTRIM_x000D_
 DECLARE @SKIPSTART INT;_x000D_
 SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
 DECLARE @SKIPEND INT;_x000D_
 SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
 DECLARE @INDEX INT;_x000D_
 IF (@SKIPSTART = 1) BEGIN_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- FULLTRIM_x000D_
   -- Determine start white-space length_x000D_
   SELECT @INDEX = 2;_x000D_
   WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise assign index as @SKIPSTART_x000D_
    SELECT @SKIPSTART = @INDEX;_x000D_
    -- Increase character index_x000D_
    SELECT @INDEX = (@INDEX + 1);_x000D_
   END_x000D_
   -- Return '' if the whole string is white-space_x000D_
   IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
  END _x000D_
  -- LTRIM_x000D_
  -- Determine start white-space length_x000D_
  SELECT @INDEX = 2;_x000D_
  WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
   -- Stop loop if no white-space_x000D_
   IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
   -- Otherwise assign index as @SKIPSTART_x000D_
   SELECT @SKIPSTART = @INDEX;_x000D_
   -- Increase character index_x000D_
   SELECT @INDEX = (@INDEX + 1);_x000D_
  END_x000D_
  -- Return trimmed string_x000D_
  RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
 END ELSE BEGIN_x000D_
  -- RTRIM_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   END_x000D_
   -- Return trimmed string_x000D_
   RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
  END _x000D_
 END_x000D_
 -- NO TRIM_x000D_
 RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
_x000D_
_x000D_

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Another possible solution:

? Restart your Visual Studio Instance with Administrator Rights

enter image description here

PHP: How to check if a date is today, yesterday or tomorrow

First. You have mistake in using function strtotime see PHP documentation

int strtotime ( string $time [, int $now = time() ] )

You need modify your code to pass integer timestamp into this function.

Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``

Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp and returns 01.01.1970 02:00 into $match_date

$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";

You need to check if strtotime($timestamp) returns correct date string. If no, you need to specify format which is used in $timestamp variable. You can do this using one of functions date_parse_from_format or DateTime::createFromFormat

This is a work example:

$timestamp = "2014.09.02T13:34";

$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval

switch( $diffDays ) {
    case 0:
        echo "//Today";
        break;
    case -1:
        echo "//Yesterday";
        break;
    case +1:
        echo "//Tomorrow";
        break;
    default:
        echo "//Sometime";
}

YouTube iframe API: how do I control an iframe player that's already in the HTML?

My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.

$(function() {
    callPlayer($('#iframe')[0], 'unMute');
});

function callPlayer(iframe, func, args) {
    if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
        iframe.contentWindow.postMessage( JSON.stringify({
            'event': 'command',
            'func': func,
            'args': args || []
        } ), '*');
    }
}

AngularJs ReferenceError: angular is not defined

If you've downloaded the angular.js file from Google, you need to make sure that Everyone has Read access to it, or it will not be loaded by your HTML file. By default, it seems to download with No access permissions, so you'll also be getting a message such as:

GET http://localhost/myApp/js/angular.js

This maddened me for about half an hour!

MSSQL Select statement with incremental integer column... not from a table

You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:

select @StartChequeNumber = 3446;
SELECT 
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable

will give the correct cheque number for each row.

correct quoting for cmd.exe for multiple arguments

Note the "" at the beginning and at the end!

Run a program and pass a Long Filename

cmd /c write.exe "c:\sample documents\sample.txt"

Spaces in Program Path

cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in Program Path + parameters

cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2

Spaces in Program Path + parameters with spaces

cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch Demo1 and then Launch Demo2

cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

CMD.exe (Command Shell)

CURL and HTTPS, "Cannot resolve host"

Just a note which may be helpful- I was having this trouble with Apache on my laptop (which connects by wifi AFTER startup), and restarting the server (after connect) fixed the issue. I guess in my case this may be to do with apache starting offline and perhaps there noting that DNS lookups fail?

add class with JavaScript

document.getElementsByClassName returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...

var buttons = document.getElementsByClassName("navButton");

for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseover = function() {
        this.setAttribute("class", "active");
        this.setAttribute("src", "images/arrows/top_o.png");
    }
}

pip broke. how to fix DistributionNotFound error?

Try re-installing with the get-pip script:

wget https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

This is sourced from the pip Github page, and worked for me.

How to change the remote a branch is tracking?

For me the fix was:

git remote set-url origin https://some_url/some_repo

Then:

git push

pandas dataframe columns scaling with sklearn

(Tested for pandas 1.0.5)
Based on @athlonshi answer (it had ValueError: could not convert string to float: 'big', on C column), full working example without warning:

import pandas as pd
from sklearn.preprocessing import MinMaxScaler
scale = preprocessing.MinMaxScaler()

df = pd.DataFrame({
           'A':[14.00,90.20,90.95,96.27,91.21],
           'B':[103.02,107.26,110.35,114.23,114.68], 
           'C':['big','small','big','small','small']
         })
print(df)
df[["A","B"]] = pd.DataFrame(scale.fit_transform(df[["A","B"]].values), columns=["A","B"], index=df.index)
print(df)

       A       B      C
0  14.00  103.02    big
1  90.20  107.26  small
2  90.95  110.35    big
3  96.27  114.23  small
4  91.21  114.68  small
          A         B      C
0  0.000000  0.000000    big
1  0.926219  0.363636  small
2  0.935335  0.628645    big
3  1.000000  0.961407  small
4  0.938495  1.000000  small

sqlite database default time value 'now'

according to dr. hipp in a recent list post:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);

How to sort a List of objects by their date (java collections, List<Object>)

In Java 8, it's now as simple as:

movieItems.sort(Comparator.comparing(Movie::getDate));

Fatal error: Class 'PHPMailer' not found

Just from reading what you have written, you will need to add the file class.phpmailer.php to your directory as well.

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

How to add a primary key to a MySQL table?

Try this,

alter table goods add column `id` int(10) unsigned primary key auto_increment

Curly braces in string in PHP

Example:

$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";

Without curly braces PHP would try to find a variable named $numberth, that doesn't exist!

Regular Expression - 2 letters and 2 numbers in C#

Just for fun, here's a non-regex (more readable/maintainable for simpletons like me) solution:

string myString = "AB12";

if( Char.IsLetter(myString, 0) && 
    Char.IsLetter(myString, 1) && 
    Char.IsNumber(myString, 2) &&
    Char.IsNumber(myString, 3)) {
    // First two are letters, second two are numbers
}
else {
    // Validation failed
}

EDIT

It seems that I've misunderstood the requirements. The code below will ensure that the first two characters and last two characters of a string validate (so long as the length of the string is > 3)

string myString = "AB12";

if(myString.Length > 3) {    
    if( Char.IsLetter(myString, 0) && 
        Char.IsLetter(myString, 1) && 
        Char.IsNumber(myString, (myString.Length - 2)) &&
        Char.IsNumber(myString, (myString.Length - 1))) {
        // First two are letters, second two are numbers
      }
      else {
        // Validation failed
    }
}
else {
   // Validation failed
}

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Just finally fixed this for my single solution that was having this. Two of the projects in the solution were set as sites in IIS. I went in and enabled ASP.Net Impersonation under Authentication for both projects...and VIOLA! FINALLY, no more of this annoying error!

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)


           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
              )
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                  )
                   SELECT @Type = 'U'
               ELSE
                   SELECT @Type = 'I'
           ELSE
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           IF @PKCols IS NULL
           BEGIN
               RAISERROR('no PK on table %s', 16, -1, @TableName)

               RETURN
           END

           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName


                  MAX(
                      COLUMNPROPERTY(
                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          COLUMN_NAME,
                          'ColumnID'
                      )
                  )
           FROM   INFORMATION_SCHEMA.COLUMNS
           WHERE  TABLE_NAME = @TableName






           WHILE @field < @maxfield
           BEGIN
               SELECT @field = MIN(
                          COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          )
                      )
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1





               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
               BEGIN
                   SELECT @fieldname = COLUMN_NAME
                   FROM   INFORMATION_SCHEMA.COLUMNS
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                                  COLUMN_NAME,
                                  'ColumnID'
                              ) = @field



                   SELECT @sql = 
                          '
           insert into Audit (    Type, 
           TableName, 
           PK, 
           FieldName, 
           OldValue, 
           NewValue, 
           UpdateDate, 
           UserName)
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 



                   EXEC (@sql)
               END
           END

Cannot lower case button text in android studio

This is fixable in the application code by setting the button's TransformationMethod null, e.g.

mButton.setTransformationMethod(null);

DataRow: Select cell value by a given column name

On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType along with the necessary null checks:

public T GetColumnValue<T>(DataRow row, string columnName)
  {
        T value = default(T);
        if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
        {
            value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
        }

        return value;
  }

sql delete statement where date is greater than 30 days

GETDATE() didn't work for me using mySQL 8

ERROR 1305 (42000): FUNCTION mydatabase.GETDATE does not exist

but this does:

DELETE FROM table_name WHERE date_column < CURRENT_DATE - 30;

Call a child class method from a parent class object

NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.

However.. you should be able to do it like:

void calculate(Person p) {
    ((Student)p).method();
}

a safe way would be:

void calculate(Person p) {
    if(p instanceof Student) ((Student)p).method();
}

Conversion failed when converting date and/or time from character string while inserting datetime

set Culture to english from web.config file

  <globalization uiCulture="en-US" culture="en-US" />

for example if you set the culture to arabic the thime will be

?22?/09?/2017? 02:16:57 ?

and you get the error:Conversion failed when converting date and/or time from character string while inserting datetime

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

Connection refused on docker container

In Docker Quickstart Terminal run following command: $ docker-machine ip 192.168.99.100

Add CSS or JavaScript files to layout head from views or partial views

Try the out-of-the-box solution (ASP.NET MVC 4 or later):

@{
    var bundle = BundleTable.Bundles.GetRegisteredBundles().First(b => b.Path == "~/js");

    bundle.Include("~/Scripts/myFile.js");
}

Notepad++ Regular expression find and delete a line

Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:

  • If your file have linux (LF) line ending : $\n?
  • If your file have windows (CRLF) line ending : $(\r\n)?

For instance, in your case :

.*#RedirectMatch Permanent.*$\n?

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This error happens when you have a ViewBag Non-Existent in your razor code calling a method.

Controller

public ActionResult Accept(int id)
{
    return View();
}

razor:

<div class="form-group">
      @Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.Flag(Model.from)
     </div>
</div>
<div class="form-group">
     <div class="col-md-10">
          <input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@ 
     </div>
</div>

For some reason, the .net aren't able to show the error in the correct line.

Normally this causes a lot of wasted time.

Microsoft Web API: How do you do a Server.MapPath?

string root = HttpContext.Current.Server.MapPath("~/App_Data");

How to get an element's top position relative to the browser's viewport?

I am assuming an element having an id of btn1 exists in the web page, and also that jQuery is included. This has worked across all modern browsers of Chrome, FireFox, IE >=9 and Edge. jQuery is only being used to determine the position relative to document.

var screenRelativeTop =  $("#btn1").offset().top - (window.scrollY || 
                                            window.pageYOffset || document.body.scrollTop);

var screenRelativeLeft =  $("#btn1").offset().left - (window.scrollX ||
                                           window.pageXOffset || document.body.scrollLeft);

How to hide action bar before activity is created, and then show it again?

I was also trying to hide Action Bar on Android 2.2, but none of these solution worked. Everything ends with a crash. I checked the DDMS LOg, It was telling me to use 'Theme.AppCompat'.At last I Solved the problem by changing the android:theme="@android:style/Theme.Holo.Light.NoActionBar"Line

into android:theme="@style/Theme.AppCompat.NoActionBar"and it worked, but the the Interface was dark.

then i tried android:theme="@style/Theme.AppCompat.Light.NoActionBar" and finally got what i wanted.

After that when I Searched about 'AppCompat' on Developer Site I got This.

So I think the Solution for Android 2.2 is

<activity
    android:name=".MainActivity"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

And Sorry for my bad English Like Always.

How to change port for jenkins window service when 8080 is being used

For jenkins in a docker container you can use port publish option in docker run command to map jenkins port in container to different outside port.

e.g. map docker container internal jenkins GUI port 8080 to port 9090 external

docker run -it -d --name jenkins42 --restart always \
   -p <ip>:9090:8080 <image>

How to remove all MySQL tables from the command-line without DROP database permissions?

You can generate statement like this: DROP TABLE t1, t2, t3, ... and then use prepared statements to execute it:

SET FOREIGN_KEY_CHECKS = 0; 
SET @tables = NULL;
SELECT GROUP_CONCAT('`', table_schema, '`.`', table_name, '`') INTO @tables
  FROM information_schema.tables 
  WHERE table_schema = 'database_name'; -- specify DB name here.

SET @tables = CONCAT('DROP TABLE ', @tables);
PREPARE stmt FROM @tables;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1; 

To the power of in C?

just use pow(a,b),which is exactly 3**4 in python

MongoDB: How to query for records where field is null or not set?

If the sent_at field is not there when its not set then:

db.emails.count({sent_at: {$exists: false}})

If its there and null, or not there at all:

db.emails.count({sent_at: null})

Refer here for querying and null

What is a difference between unsigned int and signed int in C?

Assuming int is a 16 bit integer (which depends on the C implementation, most are 32 bit nowadays) the bit representation differs like the following:

 5 = 0000000000000101
-5 = 1111111111111011

if binary 1111111111111011 would be set to an unsigned int, it would be decimal 65531.

How would one write object-oriented code in C?

Yes. In fact Axel Schreiner provides his book "Object-oriented Programming in ANSI-C" for free which covers the subject quite thoroughly.

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

You can use RawGit:
https://rawgit.com/necolas/css3-social-signin-buttons/master/index.html

It works better (at the time of this writing) than http://htmlpreview.github.com/, serving files with proper Content-Type headers. Additionally, it also provides CDN URL for use in production.

Insert current date/time using now() in a field using MySQL/PHP

NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:

date('Y-m-d H:i:s')

But I wouldn't recommend this.

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

You want:

grep -A 5 '19:55' file

From man grep:

Context Line Control

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines.  
Places a line containing a gup separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-B NUM, --before-context=NUM

Print NUM lines of leading context before matching lines.  
Places a line containing a group separator (described under --group-separator) 
between contiguous groups of matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

-C NUM, -NUM, --context=NUM

Print NUM lines of output context.  Places a line containing a group separator
(described under --group-separator) between contiguous groups of matches.  
With the -o or --only-matching option,  this  has  no effect and a warning
is given.

--group-separator=SEP

Use SEP as a group separator. By default SEP is double hyphen (--).

--no-group-separator

Use empty string as a group separator.

Plot different DataFrames in the same figure

To do this for multiple dataframes, you can do a for loop over them:

fig = plt.figure(num=None, figsize=(10, 8))
ax = dict_of_dfs['FOO'].column.plot()
for BAR in dict_of_dfs.keys():
    if BAR == 'FOO':
        pass
    else:
        dict_of_dfs[BAR].column.plot(ax=ax)

Restart pods when configmap updates in Kubernetes?

The best way I've found to do it is run Reloader

It allows you to define configmaps or secrets to watch, when they get updated, a rolling update of your deployment is performed. Here's an example:

You have a deployment foo and a ConfigMap called foo-configmap. You want to roll the pods of the deployment every time the configmap is changed. You need to run Reloader with:

kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

Then specify this annotation in your deployment:

kind: Deployment
metadata:
  annotations:
    configmap.reloader.stakater.com/reload: "foo-configmap"
  name: foo
...

Passing in class names to react components

For anyone interested, I ran into this same issue when using css modules and react css modules.

Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo

So the styleable Button looks like this:

Button.js

import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'

class Button extends Component {

  render() {

    let button = null,
        className = ''

    if(this.props.className !== undefined){
        className = this.props.className
    }

    button = (
      <button className={className} styleName='button'>
        {this.props.children}
      </button>
    )

    return (
        button
    );
  }
};

export default CSSModules(Button, styles, {allowMultiple: true} )

In the above Button component the Button.css styles handle the common button styles. In this example just a .button class

Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css and pass through as the className prop. In this example again called .button class. I could have called it anything e.g. promoButton.

Of course with css modules this class will be .Promo__button___2MVMD whereas the button one will be something like .Button__button___3972N

Promo.js

import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';

import Button from './Button/Button'

class Promo extends Component {

  render() {

    return (
        <div styleName='promo' >
          <h1>Testing the button</h1>
          <Button className={styles.button} >
            <span>Hello button</span>
          </Button>
        </div>
      </Block>
    );
  }
};

export default CSSModules(Promo, styles, {allowMultiple: true} );

Bootstrap 3: Keep selected tab on page refresh

In addition to Xavi Martínez's answer avoiding the jump on click

Avoiding Jump

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    $('a[href=' + anchor + ']').tab('show');
});

Nested tabs

implementation with "_" character as separator

$(document).ready(function(){

    // show active tab

    if(location.hash) {

        var tabs = location.hash.substring(1).split('_');

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });         

        $('a[href=' + location.hash + ']').tab('show');
    }

    // set hash on click without jumb

    $(document.body).on("click", "a[data-toggle]", function(e) {

        e.preventDefault();

        if(history.pushState) {

            history.pushState(null, null, this.getAttribute("href"));
        }
        else {

            location.hash = this.getAttribute("href");
        }

        var tabs = location.hash.substring(1).split('_');

        //console.log(tabs);

        $.each(tabs,function(n){

            $('a[href=#' + tabs[n] + ']').tab('show');
        });

        $('a[href=' + location.hash + ']').tab('show');

        return false;
    });
});

// set hash on popstate

$(window).on('popstate', function() {

    var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");

    var tabs = anchor.substring(1).split('_');

    $.each(tabs,function(n){

        $('a[href=#' + tabs[n] + ']').tab('show');
    });

    $('a[href=' + anchor + ']').tab('show');
});

Is there a method to generate a UUID with go language

This library is our standard for uuid generation and parsing:

https://github.com/pborman/uuid

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

Printing the correct number of decimal points with cout

this an example using a matrix.

cout<<setprecision(4)<<fixed<<m[i][j]

HTTP GET Request in Node.js Express

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network. so these two lines would change:

https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......

How to obfuscate Python code effectively?

Maybe you can try on pyconcrete

encrypt .pyc to .pye and decrypt when import it

encrypt & decrypt by library OpenAES

Usage

Full encrypted

  • convert all of your .py to *.pye

    $ pyconcrete-admin.py compile --source={your py script}  --pye
    $ pyconcrete-admin.py compile --source={your py module dir} --pye
    
  • remove *.py *.pyc or copy *.pye to other folder

  • main.py encrypted as main.pye, it can't be executed by normal python. You must use pyconcrete to process the main.pye script. pyconcrete(exe) will be installed in your system path (ex: /usr/local/bin)

    pyconcrete main.pye
    src/*.pye  # your libs
    

Partial encrypted (pyconcrete as lib)

  • download pyconcrete source and install by setup.py

    $ python setup.py install \
      --install-lib={your project path} \
      --install-scripts={where you want to execute pyconcrete-admin.py and pyconcrete(exe)}
    
  • import pyconcrete in your main script

  • recommendation project layout

    main.py       # import pyconcrete and your lib
    pyconcrete/*  # put pyconcrete lib in project root, keep it as original files
    src/*.pye     # your libs
    

gcloud command not found - while installing Google Cloud SDK

Using .zsh shell you can just try to add glcoud in plugin list in the ~/.zshrc file.

plugins=(
  gcloud
)

If that doesn't work, try this: (updated Krishna's answer)

  1. Update the ~/.zshrc file
# Updates PATH for the Google Cloud SDK.
source /Users/austris/google-cloud-sdk/path.zsh.inc

# Enables zsh completion for gcloud.
source /Users/austris/google-cloud-sdk/completion.zsh.inc
  1. Update the google-cloud-sdk/path.zsh.inc file with following
script_link="$( readlink "$0" )" || script_link="$0" 
apparent_sdk_dir="${script_link%/*}" 
if [[ "$apparent_sdk_dir" == "$script_link" ]]; then
  apparent_sdk_dir=. 
fi
sdk_dir="$( cd -P "$apparent_sdk_dir" && pwd -P )" 
bin_path="$sdk_dir/bin" 
export PATH=$bin_path:$PATH

*double square brackets at the third line were missing from the original answer

Data binding for TextBox

I Recommend you implement INotifyPropertyChanged and change your databinding code to this:

this.textBox.DataBindings.Add("Text",
                                this.Food,
                                "Name",
                                false,
                                DataSourceUpdateMode.OnPropertyChanged);

That'll fix it.

Note that the default DataSourceUpdateMode is OnValidation, so if you don't specify OnPropertyChanged, the model object won't be updated until after your validations have occurred.

CSS media queries for screen sizes

Put it all in one document and use this:

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
  /* Styles */
}

/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
  /* Styles */
}

/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px) 
only screen and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px) 
only screen and (-webkit-device-pixel-ratio: 3) {
  /*** You've spent way too much on a phone ***/
}

/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
 /* Styles */
}

Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

At this point, I would definitely consider using em values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

Create an empty list in python with certain size

I'm surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists

x = [[] for i in range(10)]

How to create a file in Android?

Write to a file test.txt:

String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
        fos = new FileOutputStream(filepath);
        byte[] buffer = "This will be writtent in test.txt".getBytes();
        fos.write(buffer, 0, buffer.length);
        fos.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fos != null)
            fos.close();
    }

Read from file test.txt:

String filepath ="/mnt/sdcard/test.txt";        
FileInputStream fis = null;
try {
       fis = new FileInputStream(filepath);
       int length = (int) new File(filepath).length();
       byte[] buffer = new byte[length];
       fis.read(buffer, 0, length);
       fis.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fis != null)
            fis.close();
   }

Note: don't forget to add these two permission in AndroidManifest.xml

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

Set background image according to screen resolution

I know it's too old question but thought to answer, it might will help someone. If you see twitter, you will find something very tricky but pure css approach to achieve this.

<div class="background"><img src="home-bg.png" /></div>
Applied CSS
.background {
    background: none repeat scroll 0 0 #FFFFFF;
    height: 200%;
    left: -50%;
    position: fixed;
    width: 200%;}

.background img{
    bottom: 0;
    display: block;
    left: 0;
    margin: auto;
    min-height: 50%;
    min-width: 50%;
    right: 0;
    top: 0;}

This background images fits to all size. even portrait view of ipad. it always adjust the image in center. if you zoom out; image will remain the same.

Trying to merge 2 dataframes but get ValueError

I found that my dfs both had the same type column (str) but switching from join to merge solved the issue.

Creating a new empty branch for a new project

Let's say you have a master branch with files/directories:

> git branch  
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n

Step by step how to make an empty branch:

  1. git checkout —orphan new_branch_name
  2. Make sure you are in the right directory before executing the following command:
    ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
  3. git rm -rf .
  4. touch new_file
  5. git add new_file
  6. git commit -m 'added first file in the new branch'
  7. git push origin new_branch_name

In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master branch. Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.

Once you're done, you can easily switch between your branches:

git checkout master 
git checkout new_branch

No resource found - Theme.AppCompat.Light.DarkActionBar

AppCompat is a library project. You need to reference the library project in your android project.

Check the topic Adding libraries with resources.

Update

Adding material theme should be the way. Check https://material.io/develop/android/docs/getting-started for more details.

Is it possible to deserialize XML into List<T>?

Yes, it will serialize and deserialize a List<>. Just make sure you use the [XmlArray] attribute if in doubt.

[Serializable]
public class A
{
    [XmlArray]
    public List<string> strings;
}

This works with both Serialize() and Deserialize().

How to display a date as iso 8601 format with PHP

Using the DateTime class available in PHP version 5.2 it would be done like this:

$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');

See it in action

As of PHP 5.4 you can do this as a one-liner:

echo (new DateTime('17 Oct 2008'))->format('c');

Sprintf equivalent in Java

// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );

See format and its syntax

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

find without recursion

If you look for POSIX compliant solution:

cd DirsRoot && find . -type f -print -o -name . -o -prune

-maxdepth is not POSIX compliant option.

Specify a Root Path of your HTML directory for script links?

You can use ResolveUrl

<link type="text/css" rel="stylesheet" href="<%=Page.ResolveUrl("~/Content/table-sorter.css")%>" />

.NET Console Application Exit Event

Here is a complete, very simple .Net solution that works in all versions of windows. Simply paste it into a new project, run it and try CTRL-C to view how it handles it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace TestTrapCtrlC{
    public class Program{
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
         CTRL_C_EVENT = 0,
         CTRL_BREAK_EVENT = 1,
         CTRL_CLOSE_EVENT = 2,
         CTRL_LOGOFF_EVENT = 5,
         CTRL_SHUTDOWN_EVENT = 6
         }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
             exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some biolerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while(!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }
 }

Calculate Age in MySQL (InnoDb)

Since the question is being tagged for mysql, I have the following implementation that works for me and I hope similar alternatives would be there for other RDBMS's. Here's the sql:

select YEAR(now()) - YEAR(dob) - ( DAYOFYEAR(now()) < DAYOFYEAR(dob) ) as age 
from table 
where ...

$ is not a function - jQuery error

In Wordpress jQuery.noConflict() is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $ doesn't work, but jQuery does, so your code should look like this:

<script type="text/javascript">
  jQuery(function($) {
    for(var i=0; i <= 20; i++) 
      $("ol li:nth-child(" + i + ")").addClass('olli' + i);
  });
</script>

Html encode in PHP

By encode, do you mean: Convert all applicable characters to HTML entities?

htmlspecialchars or htmlentities

You can also use strip_tags if you want to remove all HTML tags :

strip_tags

Note: this will NOT stop all XSS attacks

How to run a PowerShell script from a batch file

If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:

powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"

It is better to use Bypass...

CMAKE_MAKE_PROGRAM not found

In the GUI, select the "Advanced" checkbox. It should now show several entries below. Rename your mingw32-make.exe file to make.exe (you can just make a copy) and set the CMAKE_MAKE_PROGRAM filepath variable to the location of said file.

How to count how many values per level in a given factor?

In case I just want to know how many unique factor levels exist in the data, I use:

length(unique(df$factorcolumn))

How to remove the bottom border of a box with CSS

You can either set

border-bottom: none;

or

border-bottom: 0;

One sets the border-style to none.
One sets the border-width to 0px.

_x000D_
_x000D_
div {_x000D_
  border: 3px solid #900;_x000D_
_x000D_
  background-color: limegreen; _x000D_
  width:  28vw;_x000D_
  height: 10vw;_x000D_
  margin:  1vw;_x000D_
  text-align: center;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.stylenone {_x000D_
  border-bottom: none;_x000D_
}_x000D_
.widthzero {_x000D_
  border-bottom: 0;_x000D_
}
_x000D_
<div>_x000D_
(full border)_x000D_
</div>_x000D_
<div class="stylenone">_x000D_
(style)<br><br>_x000D_
_x000D_
border-bottom: none;_x000D_
</div>_x000D_
<div class="widthzero">_x000D_
(width)<br><br>_x000D_
border-bottom: 0;_x000D_
</div>
_x000D_
_x000D_
_x000D_

Side Note:
If you ever have to track down why a border is not showing when you expect it to, It is also good to know that either of these could be the culprit. Also verify the border-color is not the same as the background-color.

How to save LogCat contents to file?

If you are in the console window for the device and if you use Teraterm, then from the Menu do a File | Log and it will automatically save to file.

SQL ORDER BY date problem

It seems that your date column is not of type datetime but varchar. You have to convert it to datetime when sorting:

select date
from tbemp
order by convert(datetime, date, 103) ASC

style 103 = dd/MM/yyyy (msdn)

How to call external url in jquery?

JQuery and PHP

In PHP file "contenido.php":

<?php
$mURL = $_GET['url'];

echo file_get_contents($mURL);
?>

In html:

<script type="text/javascript" src="js/jquery/jquery.min.js"></script>
<script type="text/javascript">
    function getContent(pUrl, pDivDestino){
        var mDivDestino = $('#'+pDivDestino);

        $.ajax({
            type : 'GET',
            url : 'contenido.php',
            dataType : 'html',
            data: {
                url : pUrl
            },
            success : function(data){                                               
                mDivDestino.html(data);
            }   
        });
    }
</script>

<a href="#" onclick="javascript:getContent('http://www.google.com/', 'contenido')">Get Google</a>
<div id="contenido"></div>

Fastest way to tell if two files have the same contents in Unix/Linux?

For files that are not different, any method will require having read both files entirely, even if the read was in the past.

There is no alternative. So creating hashes or checksums at some point in time requires reading the whole file. Big files take time.

File metadata retrieval is much faster than reading a large file.

So, is there any file metadata you can use to establish that the files are different? File size ? or even results of the file command which does just read a small portion of the file?

File size example code fragment:

  ls -l $1 $2 | 
  awk 'NR==1{a=$5} NR==2{b=$5} 
       END{val=(a==b)?0 :1; exit( val) }'

[ $? -eq 0 ] && echo 'same' || echo 'different'  

If the files are the same size then you are stuck with full file reads.

How to change line-ending settings

Line ending format used in OS

  • Windows: CR (Carriage Return \r) and LF (LineFeed \n) pair
  • OSX,Linux: LF (LineFeed \n)

We can configure git to auto-correct line ending formats for each OS in two ways.

  1. Git Global configuration
  2. Use .gitattributes file

Global Configuration

In Linux/OSX
git config --global core.autocrlf input

This will fix any CRLF to LF when you commit.

In Windows
git config --global core.autocrlf true

This will make sure when you checkout in windows, all LF will convert to CRLF

.gitattributes File

It is a good idea to keep a .gitattributes file as we don't want to expect everyone in our team set their config. This file should keep in repo's root path and if exist one, git will respect it.

* text=auto

This will treat all files as text files and convert to OS's line ending on checkout and back to LF on commit automatically. If wanted to tell explicitly, then use

* text eol=crlf
* text eol=lf

First one is for checkout and second one is for commit.

*.jpg binary

Treat all .jpg images as binary files, regardless of path. So no conversion needed.

Or you can add path qualifiers:

my_path/**/*.jpg binary

Is it possible to use pip to install a package from a private GitHub repository?

You can also install a private repository dependency via git+https://github.com/... URL by providing login credentials (login and password, or deploy token) for curl with the .netrc file:

echo "machine github.com login ei-grad password mypasswordshouldbehere" > ~/.netrc
pip install "git+https://github.com/ei-grad/my_private_repo.git#egg=my_private_repo"

How to check permissions of a specific directory?

Here is the short answer:

$ ls -ld directory

Here's what it does:

-d, --directory
    list directory entries instead of contents, and do not dereference symbolic links

You might be interested in manpages. That's where all people in here get their nice answers from.

refer to online man pages

How to make an alert dialog fill 90% of screen size?

If you use dialog fragment you can do it on onResume method. It's code for Xamarin Android, but I think it so easy to understand it

public override void OnResume() 
{
    base.OnResume();
    var metrics = Resources.DisplayMetrics;

    double width = metrics.WidthPixels * 0.9;
    double height = metrics.HeightPixels * 0.6;

    this.Dialog.Window.SetLayout((int)width, (int)height);
    this.Dialog.Window.SetGravity(Android.Views.GravityFlags.Center);
}

Git error when trying to push -- pre-receive hook declined

Specifying a node.js version can solve the problem like

{
  "name": "myapp",
  "description": "a really cool app",
  "version": "1.0.0",
  "engines": {
    "node": "10.3.0"
  }
}

How to enable CORS in ASP.NET Core

You have to configure in Startup.cs class

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

did you specify the right host or port? error on Kubernetes

try run with sudo permission mode
example sudo kubectl....

PHP and MySQL Select a Single Value

It is quite evident that there is only a single id corresponding to a single username because username is unique.

But the actual problem lies in the query itself-

$sql = "SELECT 'id' FROM Users WHERE username='$name'";

O/P

+----+
| id |
+----+
| id |
+----+

i.e. 'id' actually is treated as a string not as the id attribute.

Correct synatx:

$sql = "SELECT `id` FROM Users WHERE username='$name'";

i.e. use grave accent(`) instead of single quote(').

or

$sql = "SELECT id FROM Users WHERE username='$name'";

Complete code

session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;

What's the best way to check if a String represents an integer in Java?

Find this may helpful:

public static boolean isInteger(String self) {
    try {
        Integer.valueOf(self.trim());
        return true;
    } catch (NumberFormatException nfe) {
        return false;
    }
}

Responsive image map

For responsive image maps you will need to use a plugin:

https://github.com/stowball/jQuery-rwdImageMaps (No longer maintained)

Or

https://github.com/davidjbradshaw/imagemap-resizer


No major browsers understand percentage coordinates correctly, and all interpret percentage coordinates as pixel coordinates.

http://www.howtocreate.co.uk/tutorials/html/imagemaps

And also this page for testing whether browsers implement

http://home.comcast.net/~urbanjost/IMG/resizeimg3.html

Iterate Multi-Dimensional Array with Nested Foreach Statement

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

The output of this example is:

9 99 3 33 5 55

References


In Java, multidimensional arrays are array of arrays, so the following works:

    int[][] table = {
            { 1, 2, 3 },
            { 4, 5, 6 },
    };
    for (int[] row : table) {
        for (int el : row) {
            System.out.println(el);
        }
    }

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

Bash tool to get nth line from a file

According to my tests, in terms of performance and readability my recommendation is:

tail -n+N | head -1

N is the line number that you want. For example, tail -n+7 input.txt | head -1 will print the 7th line of the file.

tail -n+N will print everything starting from line N, and head -1 will make it stop after one line.


The alternative head -N | tail -1 is perhaps slightly more readable. For example, this will print the 7th line:

head -7 input.txt | tail -1

When it comes to performance, there is not much difference for smaller sizes, but it will be outperformed by the tail | head (from above) when the files become huge.

The top-voted sed 'NUMq;d' is interesting to know, but I would argue that it will be understood by fewer people out of the box than the head/tail solution and it is also slower than tail/head.

In my tests, both tails/heads versions outperformed sed 'NUMq;d' consistently. That is in line with the other benchmarks that were posted. It is hard to find a case where tails/heads was really bad. It is also not surprising, as these are operations that you would expect to be heavily optimized in a modern Unix system.

To get an idea about the performance differences, these are the number that I get for a huge file (9.3G):

  • tail -n+N | head -1: 3.7 sec
  • head -N | tail -1: 4.6 sec
  • sed Nq;d: 18.8 sec

Results may differ, but the performance head | tail and tail | head is, in general, comparable for smaller inputs, and sed is always slower by a significant factor (around 5x or so).

To reproduce my benchmark, you can try the following, but be warned that it will create a 9.3G file in the current working directory:

#!/bin/bash
readonly file=tmp-input.txt
readonly size=1000000000
readonly pos=500000000
readonly retries=3

seq 1 $size > $file
echo "*** head -N | tail -1 ***"
for i in $(seq 1 $retries) ; do
    time head "-$pos" $file | tail -1
done
echo "-------------------------"
echo
echo "*** tail -n+N | head -1 ***"
echo

seq 1 $size > $file
ls -alhg $file
for i in $(seq 1 $retries) ; do
    time tail -n+$pos $file | head -1
done
echo "-------------------------"
echo
echo "*** sed Nq;d ***"
echo

seq 1 $size > $file
ls -alhg $file
for i in $(seq 1 $retries) ; do
    time sed $pos'q;d' $file
done
/bin/rm $file

Here is the output of a run on my machine (ThinkPad X1 Carbon with an SSD and 16G of memory). I assume in the final run everything will come from the cache, not from disk:

*** head -N | tail -1 ***
500000000

real    0m9,800s
user    0m7,328s
sys     0m4,081s
500000000

real    0m4,231s
user    0m5,415s
sys     0m2,789s
500000000

real    0m4,636s
user    0m5,935s
sys     0m2,684s
-------------------------

*** tail -n+N | head -1 ***

-rw-r--r-- 1 phil 9,3G Jan 19 19:49 tmp-input.txt
500000000

real    0m6,452s
user    0m3,367s
sys     0m1,498s
500000000

real    0m3,890s
user    0m2,921s
sys     0m0,952s
500000000

real    0m3,763s
user    0m3,004s
sys     0m0,760s
-------------------------

*** sed Nq;d ***

-rw-r--r-- 1 phil 9,3G Jan 19 19:50 tmp-input.txt
500000000

real    0m23,675s
user    0m21,557s
sys     0m1,523s
500000000

real    0m20,328s
user    0m18,971s
sys     0m1,308s
500000000

real    0m19,835s
user    0m18,830s
sys     0m1,004s

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

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

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

how to insert datetime into the SQL Database table?

You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:

INSERT INTO MyTable (MyDate) Values (GetDate())

If it is not today's date then you should be able to use a string and specify the date format:

INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982

You do not always need to convert the string either, often you can just do something like:

INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

And SQL Server will figure it out for you.

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

Clean up a fork and restart it from the upstream

Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.

remote: error: GH003: Sorry, force-pushing to master is not allowed.

If you get an error message like this one please try the following steps.

To effectively reset your fork you need to follow these steps :

git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin

Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :

git checkout master
git push --force origin

Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :

git push origin --delete tmp_master
git branch -D tmp_master

Other answers warning about lossing your change still apply, be carreful.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

There is one rather sneaky trick not mentioned here so far. We assume that you have no extra way to store data, but that is not strictly true.

One way around your problem is to do the following horrible thing, which should not be attempted by anyone under any circumstances: Use the network traffic to store data. And no, I don't mean NAS.

You can sort the numbers with only a few bytes of RAM in the following way:

  • First take 2 variables: COUNTER and VALUE.
  • First set all registers to 0;
  • Every time you receive an integer I, increment COUNTER and set VALUE to max(VALUE, I);
  • Then send an ICMP echo request packet with data set to I to the router. Erase I and repeat.
  • Every time you receive the returned ICMP packet, you simply extract the integer and send it back out again in another echo request. This produces a huge number of ICMP requests scuttling backward and forward containing the integers.

Once COUNTER reaches 1000000, you have all of the values stored in the incessant stream of ICMP requests, and VALUE now contains the maximum integer. Pick some threshold T >> 1000000. Set COUNTER to zero. Every time you receive an ICMP packet, increment COUNTER and send the contained integer I back out in another echo request, unless I=VALUE, in which case transmit it to the destination for the sorted integers. Once COUNTER=T, decrement VALUE by 1, reset COUNTER to zero and repeat. Once VALUE reaches zero you should have transmitted all integers in order from largest to smallest to the destination, and have only used about 47 bits of RAM for the two persistent variables (and whatever small amount you need for the temporary values).

I know this is horrible, and I know there can be all sorts of practical issues, but I thought it might give some of you a laugh or at least horrify you.

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

Thanks to Alex Mckay I had a resolve for dynamic setting a props:

  for(let prop in filter)
      (state.filter as Record<string, any>)[prop] = filter[prop];

SQL distinct for 2 fields in a database

If you still want to group only by one column (as I wanted) you can nest the query:

select c1, count(*) from (select distinct c1, c2 from t) group by c1

How to fix docker: Got permission denied issue

In Linux environment, after installing docker and docker-compose reboot is required for work docker better.

$ reboot

OR restart the docker

$ sudo systemctl restart docker

Server cannot set status after HTTP headers have been sent IIS7.5

The HTTP server doesn't send the response header back to the client until you either specify an error or else you start sending data. If you start sending data back to the client, then the server has to send the response head (which contains the status code) first. Once the header has been sent, you can no longer put a status code in the header, obviously.

Here's the usual problem. You start up the page, and send some initial tags (i.e. <head>). The server then sends those tags to the client, after first sending the HTTP response header with an assumed SUCCESS status. Now you start working on the meat of the page and discover a problem. You can not send an error at this point because the response header, which would contain the error status, has already been sent.

The solution is this: Before you generate any content at all, check if there are going to be any errors. Only then, when you have assured that there will be no problems, can you then start sending content, like the tag.

In your case, it seems like you have a login page that processes a POST request from a form. You probably throw out some initial HTML, then check if the username and password are valid. Instead, you should authenticate the user/password first, before you generate any HTML at all.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

Just add AsEnumerable() andToList() , so it looks like this

db.Favorites
    .Where(x => x.userId == userId)
    .Join(db.Person, x => x.personId, y => y.personId, (x, y).ToList().AsEnumerable()

ToList().AsEnumerable()

A potentially dangerous Request.Path value was detected from the client (*)

When dealing with Uniform Resource Locator(URL) s there are certain syntax standards, in this particular situation we are dealing with Reserved Characters.

As up to RFC 3986, Reserved Characters may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm; And asterisk(*) is a Reserved Character.

The best practice is to use Unreserved Characters in URLs or you can try encoding it.

Keep digging :

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

`IF` statement with 3 possible answers each based on 3 different ranges

This is what I did:

Very simply put:

=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))

The first IF Statement, if true will input Profit, and if false will lead on to the next IF statement and so forth :)

I only have basic formula knowledge but it's working so I will accept I am right!

Run parallel multiple commands at once in the same terminal

To run multiple commands just add && between two commands like this: command1 && command2

And if you want to run them in two different terminals then you do it like this:

gnome-terminal -e "command1" && gnome-terminal -e "command2"

This will open 2 terminals with command1 and command2 executing in them.

Hope this helps you.

bootstrap 3 wrap text content within div for horizontal alignment

Add the following style to your h3 elements:

word-wrap: break-word;

This will cause the long URLs in them to wrap. The default setting for word-wrap is normal, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.

TSQL Default Minimum DateTime

Unless you are doing a DB to track historical times more than a century ago, using

Modified datetime DEFAULT ((0)) 

is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL.

However, since first Modified datetime is the time at which the record was inserted, you can use:

Modified datetime NOT NULL DEFAULT (GETUTCDATE())

which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)

With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE().

How to set the text color of TextView in code?

Kotlin Extension Solution

Add these to make changing text color simpler

For setting ColorInt

myView.textColor = Color.BLACK // or Color.parseColor("#000000"), etc.

var TextView.textColor: Int
get() = currentTextColor
set(@ColorInt color) {
    setTextColor(color)
}

For setting ColorRes

myView.setTextColorRes(R.color.my_color)

fun TextView.setTextColorRes(@ColorRes colorRes: Int) {
    val color = ContextCompat.getColor(context, colorRes)
    setTextColor(color)
}

HashMap with multiple values under the same key

HashMap<Integer,ArrayList<String>> map = new    HashMap<Integer,ArrayList<String>>();

ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);

jquery's append not working with svg element?

 var svg; // if you have variable declared and not assigned value.
 // then you make a mistake by appending elements to that before creating element    
 svg.appendChild(document.createElement("g"));
 // at some point you assign to svg
 svg = document.createElementNS('http://www.w3.org/2000/svg', "svg")
 // then you put it in DOM
 document.getElementById("myDiv").appendChild(svg)
 // it wont render unless you manually change myDiv DOM with DevTools

// to fix assign before you append
var svg = createElement("svg", [
    ["version", "1.2"],
    ["xmlns:xlink", "http://www.w3.org/1999/xlink"],
    ["aria-labelledby", "title"],
    ["role", "img"],
    ["class", "graph"]
]);
function createElement(tag, attributeArr) {
      // .createElementNS  NS is must! Does not draw without
      let elem = document.createElementNS('http://www.w3.org/2000/svg', tag);             
      attributeArr.forEach(element => elem.setAttribute(element[0], element[1]));
      return elem;
}
// extra: <circle> for example requires attributes to render. Check if missing.