Programs & Examples On #Slidedown

An effect of showing element with a sliding motion.

Slidedown and slideup layout with animation

This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.

How to Use slideDown (or show) function on a table row?

I'm a bit behind the times on answering this, but I found a way to do it :)

function eventinfo(id) {
    tr = document.getElementById("ei"+id);
    div = document.getElementById("d"+id);
    if (tr.style.display == "none") {
        tr.style.display="table-row";
        $(div).slideDown('fast');
    } else {
        $(div).slideUp('fast');
        setTimeout(function(){tr.style.display="none";}, 200);
    }
}

I just put a div element inside the table data tags. when it is set visible, as the div expands, the whole row comes down. then tell it to fade back up (then timeout so you see the effect) before hiding the table row again :)

Hope this helps someone!

How to determine MIME type of file in android?

its works for me and flexible both for content and file

public static String getMimeType(Context context, Uri uri) {
    String extension;

    //Check uri format to avoid null
    if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        //If scheme is a content
        final MimeTypeMap mime = MimeTypeMap.getSingleton();
        extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
    } else {
        //If scheme is a File
        //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
        extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());

    }

    return extension;
}

How to find all combinations of coins when given some dollar value

Lots of variations here but couldn't find a PHP solution for the number of combinations anywhere so I'll add one in.

/**
 * @param int $money The total value
 * @param array $coins The coin denominations
 * @param int $sum The countable sum
 * @return int
 */
function getTotalCombinations($money, $coins, &$sum = 0){
  if ($money == 0){
    return $sum++;
  } else if (empty($coins) || $money < 0){
    return $sum;
  } else {
      $firstCoin = array_pop(array_reverse($coins));
      getTotalCombinations($money - $firstCoin, $coins, $sum) + getTotalCombinations($money, array_diff($coins, [$firstCoin]), $sum);
  }
  return $sum;
}


$totalCombinations = getTotalCombinations($money, $coins);

Open directory dialog

For those who don't want to create a custom dialog but still prefer a 100% WPF way and don't want to use separate DDLs, additional dependencies or outdated APIs, I came up with a very simple hack using the Save As dialog.

No using directive needed, you may simply copy-paste the code below !

It should still be very user-friendly and most people will never notice.

The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

It is a big hack for sure, but maybe it will do the job just fine for your usage...

In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

The only issues with this hack are :

  • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
  • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
  • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

How do you redirect HTTPS to HTTP?

For those that are using a .conf file.

<VirtualHost *:443>
    ServerName domain.com
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/domain.crt
    SSLCertificateKeyFile /etc/apache2/ssl/domain.key
    SSLCACertificateFile /etc/apache2/ssl/domain.crt

</VirtualHost>

Wavy shape with css

My implementation uses the svg element in html and I also made a generator for making the wave you want:

https://smooth.ie/blogs/news/svg-wavey-transitions-between-sections

<div style="height: 150px; overflow: hidden;">
  <svg viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;">
    <path d="M0.00,92.27 C216.83,192.92 304.30,8.39 500.00,109.03 L500.00,0.00 L0.00,0.00 Z" style="stroke: none;fill: #e1efe3;"></path>
  </svg>
</div>

https://jsfiddle.net/1b8L7nax/5/

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

Text Progress Bar in the Console

Write a \r to the console. That is a "carriage return" which causes all text after it to be echoed at the beginning of the line. Something like:

def update_progress(progress):
    print '\r[{0}] {1}%'.format('#'*(progress/10), progress)

which will give you something like: [ ########## ] 100%

How to post data in PHP using file_get_contents?

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

shared global variables in C

If you're sharing code between C and C++, remember to add the following to the shared.hfile:

#ifdef __cplusplus
extern "C" {
#endif

extern int my_global;
/* other extern declarations ... */

#ifdef __cplusplus
}
#endif

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

Change hash without reload in jQuery

You can set your hash directly to URL too.

window.location.hash = "YourHash";

The result : http://url#YourHash

What's with the dollar sign ($"string")

It's the new feature in C# 6 called Interpolated Strings.

The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.

For more details about this, please take a look at MSDN.

Now, think a little bit more about it. Why this feature is great?

For example, you have class Point:

public class Point
{
    public int X { get; set; }

    public int Y { get; set; }
}

Create 2 instances:

var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };

Now, you want to output it to the screen. The 2 ways that you usually use:

Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");

As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:

Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));

This creates a new problem:

  1. You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.

For those reasons, we should use new feature:

Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");

The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

For the full post, please read this blog.

Difference between Math.Floor() and Math.Truncate()

Some examples:

Round(1.5) = 2
Round(2.5) = 2
Round(1.5, MidpointRounding.AwayFromZero) = 2
Round(2.5, MidpointRounding.AwayFromZero) = 3
Round(1.55, 1) = 1.6
Round(1.65, 1) = 1.6
Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6
Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7

Truncate(2.10) = 2
Truncate(2.00) = 2
Truncate(1.90) = 1
Truncate(1.80) = 1

Twitter Bootstrap - add top space between rows

Editing or overriding the row in Twitter bootstrap is a bad idea, because this is a core part of the page scaffolding and you will need rows without a top margin.

To solve this, instead create a new class "top-buffer" that adds the standard margin that you need.

.top-buffer { margin-top:20px; }

And then use it on the row divs where you need a top margin.

<div class="row top-buffer"> ...

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

What does \d+ mean in regular expression terms?

\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.

Syntax behind sorted(key=lambda: ...)

Since the usage of lambda was asked in the context of sorted(), take a look at this as well https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions

Split comma-separated values

.NET 2.0 does not support LINQ - SO thread;
But you can create a 3.5 project in VS2005 - MSDN thread

Without lambda support, you'll need to do something like this:

string s = "a,b, b, c";
string[] values = s.Split(',');
for(int i = 0; i < values.Length; i++)
{
   values[i] = values[i].Trim();
}

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

VB.net: Date without time

Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").

Failed to load resource under Chrome

I updated my Chrome browser to the latest version and the issue was fixed.

How to check if two arrays are equal with JavaScript?

[2021 changelog: bugfix for option4: no total ordering on js objects (even excluding NaN!=NaN and '5'==5 ('5'===5, '2'<3, etc.)), so cannot use .sort on Map.keys() (though you can on Object.keys(obj), since even 'numerical' keys are strings)]

Option 1

Easiest option, works in almost all cases, except that null!==undefined but they both are converted to JSON representation null and considered equal:

function arraysEqual(a1,a2) {
    /* WARNING: arrays must not contain {objects} or behavior may be undefined */
    return JSON.stringify(a1)==JSON.stringify(a2);
}

(This might not work if your array contains objects. Whether this still works with objects depends on whether the JSON implementation sorts keys. For example, the JSON of {1:2,3:4} may or may not be equal to {3:4,1:2}; this depends on the implementation, and the spec makes no guarantee whatsoever. [2017 update: Actually the ES6 specification now guarantees object keys will be iterated in order of 1) integer properties, 2) properties in the order they were defined, then 3) symbol properties in the order they were defined. Thus IF the JSON.stringify implementation follows this, equal objects (in the === sense but NOT NECESSARILY in the == sense) will stringify to equal values. More research needed. So I guess you could make an evil clone of an object with properties in the reverse order, but I cannot imagine it ever happening by accident...] At least on Chrome, the JSON.stringify function tends to return keys in the order they were defined (at least that I've noticed), but this behavior is very much subject to change at any point and should not be relied upon. If you choose not to use objects in your lists, this should work fine. If you do have objects in your list that all have a unique id, you can do a1.map(function(x)}{return {id:x.uniqueId}}). If you have arbitrary objects in your list, you can read on for option #2.)

This works for nested arrays as well.

It is, however, slightly inefficient because of the overhead of creating these strings and garbage-collecting them.


Option 2

More "proper" option, which you can override to deal with special cases (like regular objects and null/undefined and custom objects, if you so desire):

// generally useful functions
function type(x) { // does not work in general, but works on JSONable objects we care about... modify as you see fit
    // e.g.  type(/asdf/g) --> "[object RegExp]"
    return Object.prototype.toString.call(x);
}
function zip(arrays) {
    // e.g. zip([[1,2,3],[4,5,6]]) --> [[1,4],[2,5],[3,6]]
    return arrays[0].map(function(_,i){
        return arrays.map(function(array){return array[i]})
    });
}

 

// helper functions
function allCompareEqual(array) {
    // e.g.  allCompareEqual([2,2,2,2]) --> true
    // does not work with nested arrays or objects
    return array.every(function(x){return x==array[0]});
}

function isArray(x){ return type(x)==type([]) }
function getLength(x){ return x.length }
function allTrue(array){ return array.reduce(function(a,b){return a&&b},true) }
    // e.g. allTrue([true,true,true,true]) --> true
    // or just array.every(function(x){return x});

 

function allDeepEqual(things) {
    // works with nested arrays
    if( things.every(isArray) )
        return allCompareEqual(things.map(getLength))     // all arrays of same length
               && allTrue(zip(things).map(allDeepEqual)); // elements recursively equal

    //else if( this.every(isObject) )
    //  return {all have exactly same keys, and for 
    //          each key k, allDeepEqual([o1[k],o2[k],...])}
    //  e.g. ... && allTrue(objectZip(objects).map(allDeepEqual)) 

    //else if( ... )
    //  extend some more

    else
        return allCompareEqual(things);
}

Demo:

allDeepEqual([ [], [], [] ])
true
allDeepEqual([ [1], [1], [1] ])
true
allDeepEqual([ [1,2], [1,2] ])
true
allDeepEqual([ [[1,2],[3]], [[1,2],[3]] ])
true

allDeepEqual([ [1,2,3], [1,2,3,4] ])
false
allDeepEqual([ [[1,2],[3]], [[1,2],[],3] ])
false
allDeepEqual([ [[1,2],[3]], [[1],[2,3]] ])
false
allDeepEqual([ [[1,2],3], [1,[2,3]] ])
false

To use this like a regular function, do:

function allDeepEqual2() {
    return allDeepEqual([].slice.call(arguments));
}

Demo:

allDeepEqual2([[1,2],3], [[1,2],3])
true

Options 3

edit: It's 2016 and my previous overcomplicated answer was bugging me. This recursive, imperative "recursive programming 101" implementation keeps the code really simple, and furthermore fails at the earliest possible point (giving us efficiency). It also doesn't generate superfluous ephemeral datastructures (not that there's anything wrong with functional programming in general, but just keeping it clean here).

If we wanted to apply this to a non-empty arrays of arrays, we could do seriesOfArrays.reduce(arraysEqual).

This is its own function, as opposed to using Object.defineProperties to attach to Array.prototype, since that would fail with a key error if we passed in an undefined value (that is however a fine design decision if you want to do so).

This only answers OPs original question.

function arraysEqual(a,b) {
    /*
        Array-aware equality checker:
        Returns whether arguments a and b are == to each other;
        however if they are equal-lengthed arrays, returns whether their 
        elements are pairwise == to each other recursively under this
        definition.
    */
    if (a instanceof Array && b instanceof Array) {
        if (a.length!=b.length)  // assert same length
            return false;
        for(var i=0; i<a.length; i++)  // assert each element equal
            if (!arraysEqual(a[i],b[i]))
                return false;
        return true;
    } else {
        return a==b;  // if not both arrays, should be the same
    }
}

Examples:

arraysEqual([[1,2],3], [[1,2],3])
true
arraysEqual([1,2,3], [1,2,3,4])
false
arraysEqual([[1,2],[3]], [[1,2],[],3])
false
arraysEqual([[1,2],[3]], [[1],[2,3]])
false
arraysEqual([[1,2],3], undefined)
false
arraysEqual(undefined, undefined)
true
arraysEqual(1, 2)
false
arraysEqual(null, null)
true
arraysEqual(1, 1)
true
arraysEqual([], 1)
false
arraysEqual([], undefined)
false
arraysEqual([], [])
true

If you wanted to apply this to JSON-like data structures with js Objects, you could do so. Fortunately we're guaranteed that all objects keys are unique, so iterate over the objects OwnProperties and sort them by key, then assert that both the sorted key-array is equal and the value-array are equal, and just recurse. We can extend this to include Maps as well (where the keys are also unique). (However if we extend this to Sets, we run into the tree isomorphism problem http://logic.pdmi.ras.ru/~smal/files/smal_jass08_slides.pdf - fortunately it's not as hard as general graph isomorphism; there is in fact an O(#vertices) algorithm to solve it, but it can get very complicated to do it efficiently. The pathological case is if you have a set made up of lots of seemingly-indistinguishable objects, but upon further inspection some of those objects may differ as you delve deeper into them. You can also work around this by using hashing to reject almost all cases.)


Option 4: (continuation of 2016 edit)

This should work with most objects:

const STRICT_EQUALITY = (a,b)=> a===b;
function deepEquals(a,b, areEqual=STRICT_EQUALITY) {
    /* compares objects hierarchically using the provided 
       notion of equality (defaulting to ===);
       supports Arrays, Objects, Maps, ArrayBuffers */
    if (a instanceof Array && b instanceof Array)
        return arraysEqual(a,b, areEqual);
    if (Object.getPrototypeOf(a)===Object.prototype && Object.getPrototypeOf(b)===Object.prototype)
        return objectsEqual(a,b, areEqual);
    if (a instanceof Map && b instanceof Map)
        return mapsEqual(a,b, areEqual);        
    if (a instanceof Set && b instanceof Set) {
        if (areEquals===STRICT_EQUALITY)
            return setsEqual(a,b);
        else
            throw "Error: set equality by hashing not implemented because cannot guarantee custom notion of equality is transitive without programmer intervention."
    }
    if ((a instanceof ArrayBuffer || ArrayBuffer.isView(a)) && (b instanceof ArrayBuffer || ArrayBuffer.isView(b)))
        return typedArraysEqual(a,b);
    return areEqual(a,b);  // see note[1] -- IMPORTANT
}

function arraysEqual(a,b, areEqual) {
    if (a.length!=b.length)
        return false;
    for(var i=0; i<a.length; i++)
        if (!deepEquals(a[i],b[i], areEqual))
            return false;
    return true;
}
function objectsEqual(a,b, areEqual) {
    var aKeys = Object.getOwnPropertyNames(a);
    var bKeys = Object.getOwnPropertyNames(b);
    if (aKeys.length!=bKeys.length)
        return false;
    aKeys.sort();
    bKeys.sort();
    for(var i=0; i<aKeys.length; i++)
        if (!areEqual(aKeys[i],bKeys[i])) // keys must be strings
            return false;
    return deepEquals(aKeys.map(k=>a[k]), aKeys.map(k=>b[k]), areEqual);
}
function mapsEqual(a,b, areEqual) { // assumes Map's keys use the '===' notion of equality, which is also the assumption of .has and .get methods in the spec; however, Map's values use our notion of the areEqual parameter
    if (a.size!=b.size)
        return false;
    return [...a.keys()].every(k=> 
        b.has(k) && deepEquals(a.get(k), b.get(k), areEqual)
    );
}
function setsEqual(a,b) {
    // see discussion in below rest of StackOverflow answer
    return a.size==b.size && [...a.keys()].every(k=> 
        b.has(k)
    );
}
function typedArraysEqual(a,b) {
    // we use the obvious notion of equality for binary data
    a = new Uint8Array(a);
    b = new Uint8Array(b);
    if (a.length != b.length)
        return false;
    for(var i=0; i<a.length; i++)
        if (a[i]!=b[i])
            return false;
    return true;
}

Demo (not extensively tested):

var nineTen = new Float32Array(2);
nineTen[0]=9; nineTen[1]=10;

> deepEquals(
    [[1,[2,3]], 4, {a:5,'111':6}, new Map([['c',7],['d',8]]), nineTen],
    [[1,[2,3]], 4, {111:6,a:5}, new Map([['d',8],['c',7]]), nineTen]
)
true

> deepEquals(
    [[1,[2,3]], 4, {a:'5','111':6}, new Map([['c',7],['d',8]]), nineTen],
    [[1,[2,3]], 4, {111:6,a:5}, new Map([['d',8],['c',7]]), nineTen],
    (a,b)=>a==b
)
true

Note that if one is using the == notion of equality, then know that falsey values and coercion means that == equality is NOT TRANSITIVE. For example ''==0 and 0=='0' but ''!='0'. This is relevant for Sets: I do not think one can override the notion of Set equality in a meaningful way. If one is using the built-in notion of Set equality (that is, ===), then the above should work. However if one uses a non-transitive notion of equality like ==, you open a can of worms: Even if you forced the user to define a hash function on the domain (hash(a)!=hash(b) implies a!=b) I'm not sure that would help... Certainly one could do the O(N^2) performance thing and remove pairs of == items one by one like a bubble sort, and then do a second O(N^2) pass to confirm things in equivalence classes are actually == to each other, and also != to everything not thus paired, but you'd STILL have to throw a runtime error if you have some coercion going on... You'd also maybe get weird (but potentially not that weird) edge cases with https://developer.mozilla.org/en-US/docs/Glossary/Falsy and Truthy values (with the exception that NaN==NaN... but just for Sets!). This is not an issue usually with most Sets of homogenous datatype.

(sidenote: Maps are es6 dictionaries. I can't tell if they have O(1) or O(log(N)) lookup performance, but in any case they are 'ordered' in the sense that they keep track of the order in which key-value pairs were inserted into them. However, the semantic of whether two Maps should be equal if elements were inserted in a different order into them is ambiguous. I give a sample implementation below of a deepEquals that considers two maps equal even if elements were inserted into them in a different order.)

(note [1]: IMPORTANT: NOTION OF EQUALITY: You may want to override the noted line with a custom notion of equality, which you'll also have to change in the other functions anywhere it appears. For example, do you or don't you want NaN==NaN? By default this is not the case. There are even more weird things like 0=='0'. Do you consider two objects to be the same if and only if they are the same object in memory? See https://stackoverflow.com/a/5447170/711085 . You should document the notion of equality you use. )

You should be able to extend the above to WeakMaps, WeakSets. Not sure if it makes sense to extend to DataViews. Should also be able to extend to RegExps probably, etc.

As you extend it, you realize you do lots of unnecessary comparisons. This is where the type function that I defined way earlier (solution #2) can come in handy; then you can dispatch instantly. Whether that is worth the overhead of (possibly? not sure how it works under the hood) string representing the type is up to you. You can just then rewrite the dispatcher, i.e. the function deepEquals, to be something like:

var dispatchTypeEquals = {
    number: function(a,b) {...a==b...},
    array: function(a,b) {...deepEquals(x,y)...},
    ...
}
function deepEquals(a,b) {
    var typeA = extractType(a);
    var typeB = extractType(a);
    return typeA==typeB && dispatchTypeEquals[typeA](a,b);
}

Delete all local git branches

I had a similar kind of situation and recently found the following command useful.

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep>/) printf "%s", $0 }'`

If you want to keep multiple branches, then

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep1>|<Branch_You_Want_to_Keep2>/) printf "%s", $0 }'`

hope this helps someone.

Why shouldn't I use mysql_* functions in PHP?

I find the above answers really lengthy, so to summarize:

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface
  • Support for Prepared Statements
  • Support for Multiple Statements
  • Support for Transactions
  • Enhanced debugging capabilities
  • Embedded server support

Source: MySQLi overview


As explained in the above answers, the alternatives to mysql are mysqli and PDO (PHP Data Objects).

  • API supports server-side Prepared Statements: Supported by MYSQLi and PDO
  • API supports client-side Prepared Statements: Supported only by PDO
  • API supports Stored Procedures: Both MySQLi and PDO
  • API supports Multiple Statements and all MySQL 4.1+ functionality - Supported by MySQLi and mostly also by PDO

Both MySQLi and PDO were introduced in PHP 5.0, whereas MySQL was introduced prior to PHP 3.0. A point to note is that MySQL is included in PHP5.x though deprecated in later versions.

How to check if internet connection is present in Java?

public boolean checkInternetConnection()
{
     boolean status = false;
     Socket sock = new Socket();
     InetSocketAddress address = new InetSocketAddress("www.google.com", 80);

     try
     {
        sock.connect(address, 3000);
        if(sock.isConnected()) status = true;
     }
     catch(Exception e)
     {
         status = false;       
     }
     finally
     {
        try
         {
            sock.close();
         }
         catch(Exception e){}
     }

     return status;
}

Installing Tomcat 7 as Service on Windows Server 2008

There are a lot of answers here, but many overlook a few points. I ran into the same issue and it was likely due to a combination of being a complete neophyte when it comes to tomcat. Even more I am rather new to web servers in general. I consider myself somewhat proficient user of windows, but I guess not proficient enough. In particular I don't work with services too much.

I did not have a startup.bat or any bat files. I only downloaded the 32-bit/64-bit Windows Service Installer. The bin that is created for that download is small - only 4 files. My colleagues were surprised that I did not have a catalina.bat etc... and I was too. Only the below four files in the bin. And no %CATALINA_HOME% or %TOMCAT_HOME% etc...

bootstrap.jar
tomcat-juli.jar
Tomcat7.exe
Tomcat7w.exe

With this setup I had some frustrations as setting parameters is done via the gui widget - very helpful I might add.

So nearly all the answers I have perused were not immediately applicable as many said, "go to bin and issue the startup.bat file" I am a neophyte but not so much to not be able to look into the bin and start such a file it is existed!

For my simple purposes (again remember that I am a neophyte at tomcat and even web servers) all I wanted to do was to be able to startup and shutdown the tomcat server from a cmd prompt window. Nothing too heavy duty. I am embarrassed to say how simple it is. It is probably evident to anyone with a shred of experience with services and such.

To Start server: <Tomcat Root>/bin>Tomcat7.exe start
To Stop server: <Tomcat Root>/bin>Tomcat7.exe stop

Found here - http://crunchify.com/how-to-start-stop-apache-tomcat-server-via-command-line-setup-as-windows-service/

I did not realize there was a separate download the 64-bit Windows zip file that has a tomcat server and all the standard array of cmd line tomcat management tools. This zip file has all the common startup/shutdown scripts, batch files for windows, including catalina.bat/.sh etc... Then all the above answers make sense and are rather trivial.

Remember I am a neophyte when it comes to tomcat and web servers. It appears these two downloads are somewhat mutually exclusive in the sense that if I download and install the 32-bit/64-bit Windows Service Installer version and the 64-bit Windows zip file the startup.bat file in the 64-bit Windows zip file version will not run or interact with the 32-bit/64-bit Windows Service Installer tomcat instance. But I am not sure about this point.

Sql Server return the value of identity column after insert statement

SELECT SCOPE_IDENTITY()

after the insert statement

Please refer the following links

http://msdn.microsoft.com/en-us/library/ms190315.aspx

How to add a response header on nginx when using proxy_pass?

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.

Iterate through a C++ Vector using a 'for' loop

If you use

std::vector<std::reference_wrapper<std::string>> names{ };

Do not forget, when you use auto in the for loop, to use also get, like this:

for (auto element in : names)
{
    element.get()//do something
}

Different ways of adding to Dictionary

The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net

This is the This indexer:

public TValue this[TKey key]
{
    get
    {
        int index = this.FindEntry(key);
        if (index >= 0)
        {
            return this.entries[index].value;
        }
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }
    set
    {
        this.Insert(key, value, false);
    }
}

And this is the Add method:

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}

I won't post the entire Insert method as it's rather long, however the method declaration is this:

private void Insert(TKey key, TValue value, bool add)

And further down in the function, this happens:

if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
    if (add)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }

Which checks if the key already exists, and if it does and the parameter add is true, it throws the exception.

So for all purposes and intents the performance is the same.

Like a few other mentions, it's all about whether you need the check, for attempts at adding the same key twice.

Sorry for the lengthy post, I hope it's okay.

How do you unit test private methods?

For JAVA language

Here, you can over-ride a particular method of the testing class with mock behavior.

For the below code:

public class ClassToTest 
{
    public void methodToTest()
    {
        Integer integerInstance = new Integer(0);
        boolean returnValue= methodToMock(integerInstance);
        if(returnValue)
        {
            System.out.println("methodToMock returned true");
        }
        else
        {
            System.out.println("methodToMock returned true");
        }
        System.out.println();
    }
    private boolean methodToMock(int value)
    {
        return true;
    }
}

Test class would be:

public class ClassToTestTest{

    @Test
    public void testMethodToTest(){

        new Mockup<ClassToTest>(){
            @Mock
            private boolean methodToMock(int value){
                return true;
            }
        };

        ....    

    }
}

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How can I format DateTime to web UTC format?

Some people have pointed out that ‘ToUniversalTime’ is somewhat unsafe in that it can cause unintended incorrect time dispalys. Expanding on that I’m providing a more detailed example of a solution. The sample here creates an extension to the DateTime object that safely returns a UTC DateTime where you can use ToString as desired….

class Program
{
    static void Main(string[] args)
    {
        DateTime dUtc = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Utc);
        DateTime dUnspecified = new DateTime(2016, 6, 1, 3, 17, 0, 0, DateTimeKind.Unspecified);

        //Sample of an unintended mangle:
        //Prints "2016-06-01 10:17:00Z"
        Console.WriteLine(dUnspecified.ToUniversalTime().ToString("u"));

        //Prints "2016 - 06 - 01 03:17:00Z"
        Console.WriteLine(dUtc.SafeUniversal().ToString("u"));

        //Prints "2016 - 06 - 01 03:17:00Z"
        Console.WriteLine(dUnspecified.SafeUniversal().ToString("u"));
    }
}

public static class ConvertExtensions
{
    public static DateTime SafeUniversal(this DateTime inTime)
    {
        return (DateTimeKind.Unspecified == inTime.Kind)
            ? new DateTime(inTime.Ticks, DateTimeKind.Utc)
            : inTime.ToUniversalTime();
    }
}

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

A package called styled-components can solve this problem in an ELEGANT way.

Reference

  1. Glen Maddern - Styling React Apps with Styled Components

Example

_x000D_
_x000D_
const styled = styled.default_x000D_
const Square = styled.div`_x000D_
  height: 120px;_x000D_
  width: 200px;_x000D_
  margin: 100px;_x000D_
  background-color: green;_x000D_
  cursor: pointer;_x000D_
  position: relative;_x000D_
  &:hover {_x000D_
    background-color: red;_x000D_
  };_x000D_
`_x000D_
class Application extends React.Component {_x000D_
  render() {_x000D_
    return (_x000D_
      <Square>_x000D_
      </Square>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Render the above component into the div#app_x000D_
 */_x000D_
ReactDOM.render(<Application />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>_x000D_
<div id='app'></div>
_x000D_
_x000D_
_x000D_

Using PUT method in HTML form

To set methods PUT and DELETE I perform as following:

<form
  method="PUT"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="hidden" name="put_id" value="1" />
  <input type="text" name="put_name" value="content_or_not" />
  <div>
    <button name="update_data">Save changes</button>
    <button name="remove_data">Remove</button>
  </div>
</form>
<hr>
<form
  method="DELETE"
  action="domain/route/param?query=value"
>
  <input type="hidden" name="delete_id" value="1" />
  <input type="text" name="delete_name" value="content_or_not" />
  <button name="delete_data">Remove item</button>
</form>

Then JS acts to perform the desired methods:

<script>
   var putMethod = ( event ) => {
     // Prevent redirection of Form Click
     event.preventDefault();
     var target = event.target;
     while ( target.tagName != "FORM" ) {
       target = target.parentElement;
     } // While the target is not te FORM tag, it looks for the parent element
     // The action attribute provides the request URL
     var url = target.getAttribute( "action" );

     // Collect Form Data by prefix "put_" on name attribute
     var bodyForm = target.querySelectorAll( "[name^=put_]");
     var body = {};
     bodyForm.forEach( element => {
       // I used split to separate prefix from worth name attribute
       var nameArray = element.getAttribute( "name" ).split( "_" );
       var name = nameArray[ nameArray.length - 1 ];
       if ( element.tagName != "TEXTAREA" ) {
         var value = element.getAttribute( "value" );
       } else {
       // if element is textarea, value attribute may return null or undefined
         var value = element.innerHTML;
       }
       // all elements with name="put_*" has value registered in body object
       body[ name ] = value;
     } );
     var xhr = new XMLHttpRequest();
     xhr.open( "PUT", url );
     xhr.setRequestHeader( "Content-Type", "application/json" );
     xhr.onload = () => {
       if ( xhr.status === 200 ) {
       // reload() uses cache, reload( true ) force no-cache. I reload the page to make "redirects normal effect" of HTML form when submit. You can manipulate DOM instead.
         location.reload( true );
       } else {
         console.log( xhr.status, xhr.responseText );
       }
     }
     xhr.send( body );
   }

   var deleteMethod = ( event ) => {
     event.preventDefault();
     var confirm = window.confirm( "Certeza em deletar este conteúdo?" );
     if ( confirm ) {
       var target = event.target;
       while ( target.tagName != "FORM" ) {
         target = target.parentElement;
       }
       var url = target.getAttribute( "action" );
       var xhr = new XMLHttpRequest();
       xhr.open( "DELETE", url );
       xhr.setRequestHeader( "Content-Type", "application/json" );
       xhr.onload = () => {
         if ( xhr.status === 200 ) {
           location.reload( true );
           console.log( xhr.responseText );
         } else {
           console.log( xhr.status, xhr.responseText );
         }
       }
       xhr.send();
     }
   }
</script>

With these functions defined, I add a event listener to the buttons which make the form method request:

<script>
  document.querySelectorAll( "[name=update_data], [name=delete_data]" ).forEach( element => {
    var button = element;
    var form = element;
    while ( form.tagName != "FORM" ) {
      form = form.parentElement;
    }
    var method = form.getAttribute( "method" );
    if ( method == "PUT" ) {
      button.addEventListener( "click", putMethod );
    }
    if ( method == "DELETE" ) {
      button.addEventListener( "click", deleteMethod );
    }
  } );
</script>

And for the remove button on the PUT form:

<script>
  document.querySelectorAll( "[name=remove_data]" ).forEach( element => {
    var button = element;
    button.addEventListener( "click", deleteMethod );
</script>

_ - - - - - - - - - - -

This article https://blog.garstasio.com/you-dont-need-jquery/ajax/ helps me a lot!

Beyond this, you can set postMethod function and getMethod to handle POST and GET submit methods as you like instead browser default behavior. You can do whatever you want instead use location.reload(), like show message of successful changes or successful deletion.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

JSFiddle: https://jsfiddle.net/enriquerene/d6jvw52t/53/

Work with a time span in Javascript

If you're not too worried in accuracy after days, you can simply do the maths

function timeSince(when) { // this ignores months
    var obj = {};
    obj._milliseconds = (new Date()).valueOf() - when.valueOf();
    obj.milliseconds = obj._milliseconds % 1000;
    obj._seconds = (obj._milliseconds - obj.milliseconds) / 1000;
    obj.seconds = obj._seconds % 60;
    obj._minutes = (obj._seconds - obj.seconds) / 60;
    obj.minutes = obj._minutes % 60;
    obj._hours = (obj._minutes - obj.minutes) / 60;
    obj.hours = obj._hours % 24;
    obj._days = (obj._hours - obj.hours) / 24;
    obj.days = obj._days % 365;
    // finally
    obj.years = (obj._days - obj.days) / 365;
    return obj;
}

then timeSince(pastDate); and use the properties as you like.

Otherwise you can use .getUTC* to calculate it, but note it may be slightly slower to calculate

function timeSince(then) {
    var now = new Date(), obj = {};
    obj.milliseconds = now.getUTCMilliseconds() - then.getUTCMilliseconds();
    obj.seconds = now.getUTCSeconds() - then.getUTCSeconds();
    obj.minutes = now.getUTCMinutes() - then.getUTCMinutes();
    obj.hours = now.getUTCHours() - then.getUTCHours();
    obj.days = now.getUTCDate() - then.getUTCDate();
    obj.months = now.getUTCMonth() - then.getUTCMonth();
    obj.years = now.getUTCFullYear() - then.getUTCFullYear();
    // fix negatives
    if (obj.milliseconds < 0) --obj.seconds, obj.milliseconds = (obj.milliseconds + 1000) % 1000;
    if (obj.seconds < 0) --obj.minutes, obj.seconds = (obj.seconds + 60) % 60;
    if (obj.minutes < 0) --obj.hours, obj.minutes = (obj.minutes + 60) % 60;
    if (obj.hours < 0) --obj.days, obj.hours = (obj.hours + 24) % 24;
    if (obj.days < 0) { // months have different lengths
        --obj.months;
        now.setUTCMonth(now.getUTCMonth() + 1);
        now.setUTCDate(0);
        obj.days = (obj.days + now.getUTCDate()) % now.getUTCDate();
    }
    if (obj.months < 0)  --obj.years, obj.months = (obj.months + 12) % 12;
    return obj;
}

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

What is the difference between precision and scale?

Precision 4, scale 2: 99.99

Precision 10, scale 0: 9999999999

Precision 8, scale 3: 99999.999

Precision 5, scale -3: 99999000

How do I concatenate a string with a variable?

Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.

To identify the first case or determine the cause of the second case, add these as the first lines inside the function:

alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));

That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.

The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:

<head>
<title>My Web Page</title>
<script>
    function AddBorder(id) {
        ...
    }
    AddBorder(42);    // Won't work; the page hasn't completely loaded yet!
</script>
</head>

To fix this, put all the code that uses AddBorder inside an onload event handler:

// Can only have one of these per page
window.onload = function() {
    ...
    AddBorder(42);
    ...
} 

// Or can have any number of these on a page
function doWhatever() {
   ...
   AddBorder(42);
   ...
}

if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.

Could not find an implementation of the query pattern

You may need to add a using statement to the file. The default Silverlight class template doesn't include it:

using System.Linq;

How to get a dependency tree for an artifact?

If your artifact is not a dependency of a given project, your best bet is to use a repository search engine. Many of them describes the dependencies of a given artifact.

Angular 2: Passing Data to Routes?

1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

How can I get the length of text entered in a textbox using jQuery?

CODE

$('#montant-total-prevu').on("change", function() {

var taille = $('#montant-total-prevu').val().length;

    if (taille > 9) {

//TODO

}

});

Access Google's Traffic Data through a Web Service

Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/

The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.

Get access to parent control from user control - C#

((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControl at frmMain

cast a List to a Collection

Casting never needs a new:

Collection<T> collection = myList;

You don't even make the cast explicit, because Collection is a super-type of List, so it will work just like this.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Some additional advice for Windows(10) users:

  1. If you are using Anaconda Prompt/PowerShell for the first time, type "Anaconda" in the search field of your Windows task bar and you will see the suggested software.
  2. Make sure to open the Anaconda prompt as administrator.
  3. Always navigate to your user directory or the directory with your Jupyter Notebook files first before running the command. Otherwise you might end up somewhere in your system files and be confused by an unfamiliar file tree.

The correct way to open Jupyter notebook with new data limit from the Anaconda Prompt on my own Windows 10 PC is:

(base) C:\Users\mobarget\Google Drive\Jupyter Notebook>jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

By changing

compile 'com.google.android.gms:play-services:8.1.0'

to only needed files, the problem can be solved This Issue is generated because of exceeding files in th build.gradle file.

Convert object string to JSON

Your best and safest bet would be JSON5 – JSON for Humans. It is created specifically for that use case.

_x000D_
_x000D_
const result = JSON5.parse("{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }");_x000D_
_x000D_
console.log(JSON.stringify(result));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/json5/0.5.1/json5.min.js"></script>
_x000D_
_x000D_
_x000D_

Byte[] to InputStream or OutputStream

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - The setBinaryStream method is really a getter. Go figure.

How to add a new object (key-value pair) to an array in javascript?

If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :

var postData = $('#yourform').serializeArray();

// postData (array with objects) : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]

...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :

postData.push({"name": "phone", "value": "1234-123456"});

Result:

// postData : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]

When should I use mmap for file access?

mmap is great if you have multiple processes accessing data in a read only fashion from the same file, which is common in the kind of server systems I write. mmap allows all those processes to share the same physical memory pages, saving a lot of memory.

mmap also allows the operating system to optimize paging operations. For example, consider two programs; program A which reads in a 1MB file into a buffer creating with malloc, and program B which mmaps the 1MB file into memory. If the operating system has to swap part of A's memory out, it must write the contents of the buffer to swap before it can reuse the memory. In B's case any unmodified mmap'd pages can be reused immediately because the OS knows how to restore them from the existing file they were mmap'd from. (The OS can detect which pages are unmodified by initially marking writable mmap'd pages as read only and catching seg faults, similar to Copy on Write strategy).

mmap is also useful for inter process communication. You can mmap a file as read / write in the processes that need to communicate and then use synchronization primitives in the mmap'd region (this is what the MAP_HASSEMAPHORE flag is for).

One place mmap can be awkward is if you need to work with very large files on a 32 bit machine. This is because mmap has to find a contiguous block of addresses in your process's address space that is large enough to fit the entire range of the file being mapped. This can become a problem if your address space becomes fragmented, where you might have 2 GB of address space free, but no individual range of it can fit a 1 GB file mapping. In this case you may have to map the file in smaller chunks than you would like to make it fit.

Another potential awkwardness with mmap as a replacement for read / write is that you have to start your mapping on offsets of the page size. If you just want to get some data at offset X you will need to fixup that offset so it's compatible with mmap.

And finally, read / write are the only way you can work with some types of files. mmap can't be used on things like pipes and ttys.

What is the best way to implement a "timer"?

Reference ServiceBase to your class and put the below code in the OnStartevent:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

StartSendingMails = function name you want to run in the application.

 protected override void OnStart(string[] args)
        {
            // It tells in what interval the service will run each time.
            Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
            base.OnStart(args);
            TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
            serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
        }

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

Multiple contexts with the same path error running web service in Eclipse using Tomcat

  1. In your project's Properties, choose "Web Project Settings".
  2. Change "Context root".
  3. Clean your server
  4. now you can restart your server

Iptables setting multiple multiports in one rule

enable_boxi_poorten

}

enable_boxi_poorten() {
SRV="boxi_poorten"
boxi_ports="427 5666 6001 6002 6003 6004 6005 6400 6410 8080 9321 15191 16447 17284 17723 17736 21306 25146 26632 27657 27683 28925 41583 45637 47648 49633 52551 53166 56392 56599 56911 59115 59898 60163 63512 6352 25834"


case "$1" in
  "LOCAL")
         for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s $LOC_SUB --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     # multiports gaat maar tot 15 maximaal :((
     # daarom maar for loop maken
     # $IPT -A tcp_inbound -p TCP -s $LOC_SUB -m state --state NEW -m multiport --dports $MULTIPORTS -j ACCEPT -m comment --comment "boxi specifieke poorten"
     echo "${GREEN}Allowing $SRV for local hosts.....${NORMAL}"
    ;;
  "WEB")
     for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s 0/0 --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     echo "${RED}Allowing $SRV for all hosts.....${NORMAL}"
    ;;
  *)
     for port in $boxi_ports; do $IPT -A tcp_inbound -p TCP -s $LOC_SUB --dport $port -j ACCEPT -m comment --comment "boxi specifieke poorten";done
     echo "${GREEN}Allowing $SRV for local hosts.....${NORMAL}"
    ;;
 esac

}

jQuery ID starts with

try:

$("td[id^=" + value + "]")

Simulate a specific CURL in PostMan

A simpler approach would be:

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!
  5. Click Send to post the command

Hope this helps!

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

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

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

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

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

This might help someone.

I've created new test project with Core Data called "CoreData". Shortly I've got "Use of undeclared type" for NSManagedObjectContext and other Core Data classes. After several attempts of importing, adding to Build phases, etc. I've deleted project and started new one called "TestingCoreData" and it all worked well.

Don't name (test) Projects like name of the Classes

Get week day name from a given month, day and year individually in SQL Server

If you have SQL Server 2012:

If your date parts are integers then you can use DATEFROMPARTS function.

SELECT DATENAME( dw, DATEFROMPARTS( @Year, @Month, @Day ) )

If your date parts are strings, then you can use the CONCAT function.

SELECT DATENAME( dw, CONVERT( date, CONCAT( @Day, '/' , @Month, '/', @Year ), 103 ) )

Image, saved to sdcard, doesn't appear in Android's Gallery app

this work with me

File file = ..... // Save file

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

How about

if (length ($name || '')) {
  # do something with $name
}

This isn't quite equivalent to your original version, as it will also return false if $name is the numeric value 0 or the string '0', but will behave the same in all other cases.

In perl 5.10 (or later), the appropriate approach would be to use the defined-or operator instead:

use feature ':5.10';
if (length ($name // '')) {
  # do something with $name
}

This will decide what to get the length of based on whether $name is defined, rather than whether it's true, so 0/'0' will handle those cases correctly, but it requires a more recent version of perl than many people have available.

Getting error "The package appears to be corrupt" while installing apk file

This is weird. I don't know why this was happening with me while generating signed apk but below steps worked for me.

  1. Go to file and select invalidate caches/restarts
  2. After that go to build select clean project
  3. And then select Rebuild project

That's it.

How to make blinking/flashing text with CSS 3

@-webkit-keyframes blinker {  
  0% { opacity: 1.0; }
  50% { opacity: 0.0; }
  100% { opacity: 1.0; }
}

_x000D_
_x000D_
@-webkit-keyframes blinker {  _x000D_
  0% { opacity: 1.0; }_x000D_
  50% { opacity: 0.0; }_x000D_
  100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
.blink {_x000D_
  width: 10px;_x000D_
  height: 10px;_x000D_
  border-radius: 10px;_x000D_
  animation: blinker 2s linear infinite;_x000D_
  background-color: red;_x000D_
  margin-right: 5px;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}
_x000D_
<div class="content">_x000D_
  <i class="blink"></i>_x000D_
  LIVE_x000D_
</div>
_x000D_
_x000D_
_x000D_

What evaluates to True/False in R?

If you think about it, comparing numbers to logical statements doesn't make much sense. However, since 0 is often associated with "Off" or "False" and 1 with "On" or "True", R has decided to allow 1 == TRUE and 0 == FALSE to both be true. Any other numeric-to-boolean comparison should yield false, unless it's something like 3 - 2 == TRUE.

Launch an app from within another (iPhone)

I also tried this a while ago (Launch iPhone Application with Identifier), but there definitely is no DOCUMENTED way to do this. :)

How many parameters are too many?

For me , when the list crosses one line on my IDE, then it's one parameter too many. I want to see all the parameters in one line without breaking eye contact. But that's just my personal preference.

Sorting a list with stream.sorted() in Java

This is not like Collections.sort() where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

You've just missed to assign the result

How to sort a collection by date in MongoDB?

This worked for me:

collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... });

Using Node.js, Express.js, and Monk

What is the difference between Numpy's array() and asarray() functions?

The difference can be demonstrated by this example:

  1. generate a matrix

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. use numpy.array to modify A. Doesn't work because you are modifying a copy

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. use numpy.asarray to modify A. It worked because you are modifying A itself

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    

Hope this helps!

Are complex expressions possible in ng-hide / ng-show?

Use a controller method if you need to run arbitrary JavaScript code, or you could define a filter that returned true or false.

I just tested (should have done that first), and something like ng-show="!a && b" worked as expected.

How to convert an ArrayList containing Integers to primitive int array?

Java 8:

int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();

pandas dataframe columns scaling with sklearn

Like this?

dfTest = 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']
         })
dfTest[['A','B']] = dfTest[['A','B']].apply(
                           lambda x: MinMaxScaler().fit_transform(x))
dfTest

    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

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

How to install the current version of Go in Ubuntu Precise

I like to use GVM for managing my Go versions in my Ubuntu box. Pretty simple to use, and if you're familiar with RVM, it's a nobrainer. It allows you to have multiple versions of Go installed in your system and switch between whichever version you want at any point in time.

Install GVM with:

sudo apt-get install bison mercurial
bash < <(curl -LSs 'https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer')
. "$HOME/.gvm/scripts/gvm"

and then it's as easy as doing this:

gvm install go1.1.1
gvm use go1.1.1 --default

The default flag at the end of the second command will set go1.1.1 to be your default Go version whenever you start a new terminal session.

Can I add extension methods to an existing static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.

 public static class ConfigurationManagerWrapper
 {
      public static ConfigurationSection GetSection( string name )
      {
         return ConfigurationManager.GetSection( name );
      }

      .....

      public static ConfigurationSection GetWidgetSection()
      {
          return GetSection( "widgets" );
      }
 }

How to change JAVA.HOME for Eclipse/ANT

Simply, to enforce JAVA version to Ant in Eclipse:

Use RunAs option on Ant file then select External Tool Configuration in JRE tab define your JDK/JRE version you want to use.

SQLAlchemy create_all() does not create tables

This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

def get_db():
  if 'db' not in g:
    g.db = SQLAlchemy(current_app)
  return g.db

I also have a separate cli command that also does the create_all:

# tasks/db.py
from lib.db import get_db

@current_app.cli.command('init-db')
def init_db():
  db = get_db()
  db.create_all()

I also am using a application factory.

When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).

The fix that I came around to was to make sure that the db was a single global reference:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

db = None
def get_db():
  global db
  if not db:
    db = SQLAlchemy(current_app)
  return db

I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.

How to create a MySQL hierarchical recursive query?

The best approach I've come up with is

  1. Use lineage to store\sort\trace trees. That's more than enough, and works thousands times faster for reading than any other approach. It also allows to stay on that pattern even if DB will change(as ANY db will allow that pattern to be used)
  2. Use function that determines lineage for specific ID.
  3. Use it as you wish (in selects, or on CUD operations, or even by jobs).

Lineage approach descr. can be found wherever, for example Here or here. As of function - that is what enspired me.

In the end - got more-or-less simple, relatively fast, and SIMPLE solution.

Function's body

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `get_lineage`(the_id INT) RETURNS text CHARSET utf8
    READS SQL DATA
BEGIN

 DECLARE v_rec INT DEFAULT 0;

 DECLARE done INT DEFAULT FALSE;
 DECLARE v_res text DEFAULT '';
 DECLARE v_papa int;
 DECLARE v_papa_papa int DEFAULT -1;
 DECLARE csr CURSOR FOR 
  select _id,parent_id -- @n:=@n+1 as rownum,T1.* 
  from 
    (SELECT @r AS _id,
        (SELECT @r := table_parent_id FROM table WHERE table_id = _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := the_id, @l := 0,@n:=0) vars,
        table m
    WHERE @r <> 0
    ) T1
    where T1.parent_id is not null
 ORDER BY T1.lvl DESC;
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    open csr;
    read_loop: LOOP
    fetch csr into v_papa,v_papa_papa;
        SET v_rec = v_rec+1;
        IF done THEN
            LEAVE read_loop;
        END IF;
        -- add first
        IF v_rec = 1 THEN
            SET v_res = v_papa_papa;
        END IF;
        SET v_res = CONCAT(v_res,'-',v_papa);
    END LOOP;
    close csr;
    return v_res;
END

And then you just

select get_lineage(the_id)

Hope it helps somebody :)

How to remove focus from single editText

Just include this line

android:selectAllOnFocus="false"

in the XML segment corresponding to the EditText layout.

Why does intellisense and code suggestion stop working when Visual Studio is open?

I spent a lot of time researching the same problem. Some solutions related this bug with some referenced assemblies. Others said that Microsoft.Windows.Design.Extension.dll and .Interactivity.dll should be in the references of the project. But none of these solutions worked for me.

I think it is a bug in Visual Studio 2012, Microsoft has to fix it.

What's the difference between struct and class in .NET?

Besides the basic difference of access specifier, and few mentioned above I would like to add some of the major differences including few of the mentioned above with a code sample with output, which will give a more clear idea of the reference and value

Structs:

  • Are value types and do not require heap allocation.
  • Memory allocation is different and is stored in stack
  • Useful for small data structures
  • Affect performance, when we pass value to method, we pass the entire data structure and all is passed to the stack.
  • Constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
  • The variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
  • Do not support user-specified inheritance, and they implicitly inherit from type object

Class:

  • Reference Type value
  • Stored in Heap
  • Store a reference to a dynamically allocated object
  • Constructors are invoked with the new operator, but that does not allocate memory on the heap
  • Multiple variables may have a reference to the same object
  • It is possible for operations on one variable to affect the object referenced by the other variable

Code Sample

    static void Main(string[] args)
    {
        //Struct
        myStruct objStruct = new myStruct();
        objStruct.x = 10;
        Console.WriteLine("Initial value of Struct Object is: " + objStruct.x);
        Console.WriteLine();
        methodStruct(objStruct);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Struct Object is: " + objStruct.x);
        Console.WriteLine();

        //Class
        myClass objClass = new myClass(10);
        Console.WriteLine("Initial value of Class Object is: " + objClass.x);
        Console.WriteLine();
        methodClass(objClass);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Class Object is: " + objClass.x);
        Console.Read();
    }
    static void methodStruct(myStruct newStruct)
    {
        newStruct.x = 20;
        Console.WriteLine("Inside Struct Method");
        Console.WriteLine("Inside Method value of Struct Object is: " + newStruct.x);
    }
    static void methodClass(myClass newClass)
    {
        newClass.x = 20;
        Console.WriteLine("Inside Class Method");
        Console.WriteLine("Inside Method value of Class Object is: " + newClass.x);
    }
    public struct myStruct
    {
        public int x;
        public myStruct(int xCons)
        {
            this.x = xCons;
        }
    }
    public class myClass
    {
        public int x;
        public myClass(int xCons)
        {
            this.x = xCons;
        }
    }

Output

Initial value of Struct Object is: 10

Inside Struct Method Inside Method value of Struct Object is: 20

After Method call value of Struct Object is: 10

Initial value of Class Object is: 10

Inside Class Method Inside Method value of Class Object is: 20

After Method call value of Class Object is: 20

Here you can clearly see the difference between call by value and call by reference.

C# string reference type?

"A picture is worth a thousand words".

I have a simple example here, it's similar to your case.

string s1 = "abc";
string s2 = s1;
s1 = "def";
Console.WriteLine(s2);
// Output: abc

This is what happened:

enter image description here

  • Line 1 and 2: s1 and s2 variables reference to the same "abc" string object.
  • Line 3: Because strings are immutable, so the "abc" string object do not modify itself (to "def"), but a new "def" string object is created instead, and then s1 references to it.
  • Line 4: s2 still references to "abc" string object, so that's the output.

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

jquery 3.0 url.indexOf error

Update all your code that calls load function like,

$(window).load(function() { ... });

To

$(window).on('load', function() { ... });

jquery.js:9612 Uncaught TypeError: url.indexOf is not a function

This error message comes from jQuery.fn.load function.

I've come across the same issue on my application. After some digging, I found this statement in jQuery blog,

.load, .unload, and .error, deprecated since jQuery 1.8, are no more. Use .on() to register listeners.

I simply just change how my jQuery objects call the load function like above. And everything works as expected.

How to capture a list of specific type with mockito

There is an open issue in Mockito's GitHub about this exact problem.

I have found a simple workaround that does not force you to use annotations in your tests:

import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;

public final class MockitoCaptorExtensions {

    public static <T> ArgumentCaptor<T> captorFor(final CaptorTypeReference<T> argumentTypeReference) {
        return new CaptorContainer<T>().captor;
    }

    public static <T> ArgumentCaptor<T> captorFor(final Class<T> argumentClass) {
        return ArgumentCaptor.forClass(argumentClass);
    }

    public interface CaptorTypeReference<T> {

        static <T> CaptorTypeReference<T> genericType() {
            return new CaptorTypeReference<T>() {
            };
        }

        default T nullOfGenericType() {
            return null;
        }

    }

    private static final class CaptorContainer<T> {

        @Captor
        private ArgumentCaptor<T> captor;

        private CaptorContainer() {
            MockitoAnnotations.initMocks(this);
        }

    }

}

What happens here is that we create a new class with the @Captor annotation and inject the captor into it. Then we just extract the captor and return it from our static method.

In your test you can use it like so:

ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(genericType());

Or with syntax that resembles Jackson's TypeReference:

ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(
    new CaptorTypeReference<Supplier<Set<List<Object>>>>() {
    }
);

It works, because Mockito doesn't actually need any type information (unlike serializers, for example).

Reload nginx configuration

Maybe you're not doing it as root?

Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx.

How to serve an image using nodejs

This may be a bit off-topic, since you are asking about static file serving via Node.js specifically (where fs.createReadStream('./image/demo.jpg').pipe(res) is actually a good idea), but in production you may want to have your Node app handle tasks, that cannot be tackled otherwise, and off-load static serving to e.g Nginx.

This means less coding inside your app, and better efficiency since reverse proxies are by design ideal for this.

grep from tar.gz without extracting [faster one]

Am trying to grep pattern from dozen files .tar.gz but its very slow

tar -ztf file.tar.gz | while read FILENAME
do
        if tar -zxf file.tar.gz "$FILENAME" -O | grep "string" > /dev/null
        then
                echo "$FILENAME contains string"
        fi
done

That's actually very easy with ugrep option -z:

-z, --decompress
        Decompress files to search, when compressed.  Archives (.cpio,
        .pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
        .tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
        matching pathnames of files in archives are output in braces.  If
        -g, -O, -M, or -t is specified, searches files within archives
        whose name matches globs, matches file name extensions, matches
        file signature magic bytes, or matches file types, respectively.
        Supported compression formats: gzip (.gz), compress (.Z), zip,
        bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
        lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).

Which requires just one command to search file.tar.gz as follows:

ugrep -z "string" file.tar.gz

This greps each of the archived files to display matches. Archived filenames are shown in braces to distinguish them from ordinary filenames. For example:

$ ugrep -z "Hello" archive.tgz
{Hello.bat}:echo "Hello World!"
Binary file archive.tgz{Hello.class} matches
{Hello.java}:public class Hello // prints a Hello World! greeting
{Hello.java}:  { System.out.println("Hello World!");
{Hello.pdf}:(Hello)
{Hello.sh}:echo "Hello World!"
{Hello.txt}:Hello

If you just want the file names, use option -l (--files-with-matches) and customize the filename output with option --format="%z%~" to get rid of the braces:

$ ugrep -z Hello -l --format="%z%~" archive.tgz
Hello.bat
Hello.class
Hello.java
Hello.pdf
Hello.sh
Hello.txt

What is a good pattern for using a Global Mutex in C#?

A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.

Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8

private Mutex mutex;
private bool mutexCreated;

public App()
{
    string mutexId = $"Global\\{GetType().GUID}";
    mutex = new Mutex(true, mutexId, out mutexCreated);
}

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    if (!mutexCreated)
    {
        MessageBox.Show("Already started!");
        Shutdown();
    }
}

Because Mutex implements IDisposable it is released automatically but for completeness call dispose:

protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    mutex.Dispose();
}

Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).

public class SingleApplication : Application
{
    private Mutex mutex;
    private bool mutexCreated;

    public SingleApplication()
    {
        string mutexId = $"Global\\{GetType().GUID}";

        MutexAccessRule allowEveryoneRule = new MutexAccessRule(
            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
            MutexRights.FullControl, 
            AccessControlType.Allow);
        MutexSecurity securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);

        // initiallyOwned: true == false + mutex.WaitOne()
        mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);        
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        if (mutexCreated)
        {
            try
            {
                mutex.ReleaseMutex();
            }
            catch (ApplicationException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        mutex.Dispose();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        if (!mutexCreated)
        {
            MessageBox.Show("Already started!");
            Shutdown();
        }
    }
}

How do I check to see if my array includes an object?

Why not do it simply by picking eight different numbers from 0 to Horse.count and use that to get your horses?

offsets = (0...Horse.count).to_a.sample(8)
@suggested_horses = offsets.map{|i| Horse.first(:offset => i) }

This has the added advantage that it won't cause an infinite loop if you happen to have less than 8 horses in your database.

Note: Array#sample is new to 1.9 (and coming in 1.8.8), so either upgrade your Ruby, require 'backports' or use something like shuffle.first(n).

Change User Agent in UIWebView

To just add a custom content to the current UserAgent value, do the following:

1 - Get the user agent value from a NEW WEBVIEW

2 - Append the custom content to it

3 - Save the new value in a dictionary with the key UserAgent

4 - Save the dictionary in standardUserDefaults.

See the exemple below:

NSString *userAgentP1 = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *userAgentP2 = @"My_custom_value";
NSString *userAgent = [NSString stringWithFormat:@"%@ %@", userAgentP1, userAgentP2];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How to read a large file line by line?

foreach (new SplFileObject(__FILE__) as $line) {
    echo $line;
}

Check table exist or not before create it in Oracle

As Rene also commented, it's quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

declare
nCount NUMBER;
v_sql LONG;

begin
SELECT count(*) into nCount FROM dba_tables where table_name = 'EMPLOYEE';
IF(nCount <= 0)
THEN
v_sql:='
create table EMPLOYEE
(
ID NUMBER(3),
NAME VARCHAR2(30) NOT NULL
)';
execute immediate v_sql;

END IF;
end;

But I'd rather go catch on the Exception, saves you some unnecessary lines of code:

declare
v_sql LONG;
begin

v_sql:='create table EMPLOYEE
  (
  ID NUMBER(3),
  NAME VARCHAR2(30) NOT NULL
  )';
execute immediate v_sql;

EXCEPTION
    WHEN OTHERS THEN
      IF SQLCODE = -955 THEN
        NULL; -- suppresses ORA-00955 exception
      ELSE
         RAISE;
      END IF;
END; 
/

Domain Account keeping locking out with correct password every few minutes

I have seen this problem when the user had set up a scheduled task to run under his account. He forgot to update the password on the task after he changed his account password. The scheduled task was trying to logon with the old password and kept locking out his account.

Splitting a dataframe string column into multiple different columns

The way via unlist and matrix seems a bit convoluted, and requires you to hard-code the number of elements (this is actually a pretty big no-go. Of course you could circumvent hard-coding that number and determine it at run-time)

I would go a different route, and construct a data frame directly from the list that strsplit returns. For me, this is conceptually simpler. There are essentially two ways of doing this:

  1. as.data.frame – but since the list is exactly the wrong way round (we have a list of rows rather than a list of columns) we have to transpose the result. We also clear the rownames since they are ugly by default (but that’s strictly unnecessary!):

    `rownames<-`(t(as.data.frame(strsplit(text, '\\.'))), NULL)
    
  2. Alternatively, use rbind to construct a data frame from the list of rows. We use do.call to call rbind with all the rows as separate arguments:

    do.call(rbind, strsplit(text, '\\.'))
    

Both ways yield the same result:

     [,1] [,2] [,3]  [,4]
[1,] "F"  "US" "CLE" "V13"
[2,] "F"  "US" "CA6" "U13"
[3,] "F"  "US" "CA6" "U13"
[4,] "F"  "US" "CA6" "U13"
[5,] "F"  "US" "CA6" "U13"
[6,] "F"  "US" "CA6" "U13"
…

Clearly, the second way is much simpler than the first.

How set background drawable programmatically in Android

You can also set the background of any Image:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

How to set width of mat-table column in angular?

As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"

for example :

<mat-table #table [dataSource]="dataSource" matSortDisableClear>
    <ng-container matColumnDef="productId">
        <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="productName">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let product">
            <button (click)="view(product)">
                <mat-icon>visibility</mat-icon>
            </button>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

here matColumnDef is productId, productName and action

now we apply width by matColumnDef

styling

.mat-column-productId {
    flex: 0 0 10%;
}
.mat-column-productName {
    flex: 0 0 50%;
}

and remaining width is equally allocated to other columns

svn: E155004: ..(path of resource).. is already locked

  1. Downlaod and copy sqlite.exe to .svn's parent directory
  2. Open shell in this directory
  3. Query to find locks in corresponding tables => in wc_lock* table (the table name is something like this)
  4. Delete the locked items in above table by sqlite query

just this steps helped me to resolve:

svn: E155004: Working copy 'resourceAddress' locked

Getter and Setter declaration in .NET

With this, you can perform some code in the get or set scope.

private string _myProperty;
public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

You also can use automatic properties:

public string myProperty
{
    get;
    set;
}

And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.

You also can control the visibility of these scopes, for sample:

public string myProperty
{
    get;
    private set;
}

public string myProperty2
{
    get;
    protected set;
}

public string myProperty3
{
    get; 
}

Update

Now in C# you can initialize the value of a property. For sample:

public int Property { get; set; } = 1;

If also can define it and make it readonly, without a set.

public int Property { get; } = 1;

And finally, you can define an arrow function.

public int Property => GetValue();

PDF to byte array and vice versa

This worked for me. I haven't used any third-party libraries. Just the ones that are shipped with Java.

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PDFUtility {

public static void main(String[] args) throws IOException {
    /**
     * Converts byte stream into PDF.
     */
    PDFUtility pdfUtility = new PDFUtility();
    byte[] byteStreamPDF = pdfUtility.convertPDFtoByteStream();
    FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\aseem\\Desktop\\BlaFolder\\BlaFolder2\\aseempdf.pdf");
    fileOutputStream.write(byteStreamPDF);
    fileOutputStream.close();
    System.out.println("File written successfully");
}

/**
 * Creates PDF to Byte Stream
 *
 * @return
 * @throws IOException
 */
protected byte[] convertPDFtoByteStream() throws IOException {
    Path path = Paths.get("C:\\Users\\aseem\\aaa.pdf");
    return Files.readAllBytes(path);
}

}

How to switch a user per task or set of tasks?

In Ansible >1.4 you can actually specify a remote user at the task level which should allow you to login as that user and execute that command without resorting to sudo. If you can't login as that user then the sudo_user solution will work too.

---
- hosts: webservers
  remote_user: root
  tasks:
    - name: test connection
      ping:
      remote_user: yourname

See http://docs.ansible.com/playbooks_intro.html#hosts-and-users

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How to use XPath preceding-sibling correctly

You don't need to go level up and use .. since all buttons are on the same level:

//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']

symbol(s) not found for architecture i386

Thought to add my solution for this, after spending a few hours on the same error :(

The guys above were correct that the first thing you should check is whether you had missed adding any frameworks, see the steps provided by Pruthvid above.

My problem, it turned out, was a compile class missing after I deleted it, and later added it back in again.

Check your "Compile Sources" as shown for the reported error classes. Add in any missing classes that you created.

How to view data saved in android database(SQLite)?

If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.

What is the best IDE for PHP?

The best IDE for PHP in my opinion is Zend Studio (which itself is based on Eclipse PDT). Note that in this case "best" does not necessarily mean "good." It is slow and a bit buggy, but even so, it's still the best option for PHP programmers. I've tried a ton of PHP editors over the years and I haven't yet found one that works great.

Komodo IDE would be my second choice. My only problem with Komodo is that the autocomplete is not as good. With properly structured apps where you use phpDoc to document return types etc., it should be alright. But I work on a project that doesn't really do that and Komodo can't read across files to know that $user is a User object for example.

Pythonic way to check if a list is sorted or not

Definitely works in Python 3 and above for integers or strings:

def tail(t):
    return t[:]

letters = ['a', 'b', 'c', 'd', 'e']
rest = tail(letters)
rest.sort()
if letters == rest:
    print ('Given list is SORTED.')
else:
    print ('List NOT Sorted.')

=====================================================================

Another way of finding if the given list is sorted or not

trees1 = list ([1, 4, 5, 3, 2])
trees2 = list (trees1)
trees2.sort()
if trees1 == trees2:
    print ('trees1 is SORTED')
else:
    print ('Not sorted')

Today`s date in an excel macro

Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

adding line break

\n in c3 working correctly

using System; namespace testing2

public class Test { 
    public static void Main(string[] args) {
        Console.WriteLine("Enter your name");
        String s = Console.ReadLine();
        Console.WriteLine("Your name is " + s + "\n" + "Thank You");
    }
}

Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

Here is a function I made based on the answer above

def getDateToEpoch(myDateTime):
    res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
    return res

You can wrap the returned value like this : str(int(res)) To return it without a decimal value to be used as string or just int (without the str)

What does 'foo' really mean?

Among my colleagues, the meaning (or perhaps more accurately - the use) of the term "foo" has been to serve as a placeholder to represent an example for a name. Examples include, but not limited to, yourVariableName, yourObjectName, or yourColumnName.

Today, I avoid using "foo" and prefer using this type of named substitution for a couple of reasons.

  • In my earlier days, I originally found the use of "foo" as a placement in any example to represent something as f'd-up to be confusing. I wanted a working example, not something that was foobar.
  • Your results may vary, but I always, 100%, everytime, never-failed, got more follow-up questions about the meaning of the actual variable where "foo" was used.

Adjusting the Xcode iPhone simulator scale and size

You can't have 1:1 ratio.

However you can scale it from the iOS Simulator > Window > Scale menu.

Better way to set distance between flexbox items

There is indeed a nice, tidy, CSS-only way to do this (that one may consider "better").

Of all the answers posted here, I only found one that uses calc() successfully (by Dariusz Sikorski). But when posed with: "but it fails if there are only 2 items in the last row" there was no solution expanded.

This solution addresses the OP's question with an alternative to negative margins and addresses the problem posed to Dariusz.

notes:

  • This example only demonstrates a 3-column layout
  • It uses calc() to let the browser do math the way it wants -- 100%/3 (although 33.3333% should work just as well), and (1em/3)*2 (although .66em should also work well).
  • It uses ::after to pad the last row if there are fewer elements than columns

_x000D_
_x000D_
.flex-container {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
.flex-container:after {_x000D_
  content: "";_x000D_
}_x000D_
.flex-container > div,_x000D_
.flex-container:after {_x000D_
  box-sizing: border-box;_x000D_
  width: calc((100%/3) - ((1em/3)*2));_x000D_
}_x000D_
.flex-container > :nth-child(n + 4) {_x000D_
  margin-top: 1em;_x000D_
}_x000D_
_x000D_
/* the following is just to visualize the items */_x000D_
.flex-container > div,_x000D_
.flex-container:after {_x000D_
  font-size: 2em;_x000D_
}_x000D_
.flex-container {_x000D_
  margin-bottom:4em;_x000D_
}_x000D_
.flex-container > div {_x000D_
  text-align: center;_x000D_
  background-color: #aaa;_x000D_
  padding: 1em;_x000D_
}_x000D_
.flex-container:after {_x000D_
  border: 1px dashed red;_x000D_
}
_x000D_
<h2>Example 1 (2 elements)</h2>_x000D_
<div class="flex-container">_x000D_
  <div>1</div>_x000D_
  <div>2</div>_x000D_
</div>_x000D_
_x000D_
<h2>Example 2 (3 elements)</h2>_x000D_
<div class="flex-container">_x000D_
  <div>1</div>_x000D_
  <div>2</div>_x000D_
  <div>3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also at https://codepen.io/anon/pen/rqWagE

Python Database connection Close

You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.

import pyodbc

class MS_DB():
    """ Collection of helper methods to query the MS SQL Server database.
    """

    def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
        self.username = username
        self._password = password
        self.host = host
        self.port = str(port)
        self.db = initial_db
        conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
                    self.host + ';PORT='+ self.port +';DATABASE='+ \
                    self.db +';UID='+ self.username +';PWD='+ \ 
                    self._password +';'
        print('Connected to DB:', conn_str)
        self._connection = pyodbc.connect(conn_str)        
        pyodbc.pooling = False

    def __repr__(self):
        return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"

    def __str__(self):
        return f"MS-SQLServer Module for STP on {self.host}"

    def __del__(self):
        self._connection.close()
        print("Connection closed.")

    @contextmanager
    def cursor(self, commit: bool = False):
        """
        A context manager style of using a DB cursor for database operations. 
        This function should be used for any database queries or operations that 
        need to be done. 

        :param commit:
        A boolean value that says whether to commit any database changes to the database. Defaults to False.
        :type commit: bool
        """
        cursor = self._connection.cursor()
        try:
            yield cursor
        except pyodbc.DatabaseError as err:
            print("DatabaseError {} ".format(err))
            cursor.rollback()
            raise err
        else:
            if commit:
                cursor.commit()
        finally:
            cursor.close()

ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
        cursor.execute("SELECT @@version;")
        print(cur.fetchall())

Windows 10 SSH keys

If you have Windows 10 with the OpenSSH client you may be able to generate the key, but you will have trouble copying it to the target Linux box as the ssh-copy-id command is not part of the client toolset.

Having has this problem I wrote a small PowerShell function to address this, that you add to your profile.

function ssh-copy-id([string]$userAtMachine, [string]$port = 22) {   
    # Get the generated public key
    $key = "$ENV:USERPROFILE" + "/.ssh/id_rsa.pub"
    # Verify that it exists
    if (!(Test-Path "$key")) {
        # Alert user
        Write-Error "ERROR: '$key' does not exist!"            
    }
    else {  
        # Copy the public key across
        & cat "$key" | ssh $userAtMachine -p $port "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys || exit 1"      
    }
}

You can get the gist here

I have a brief write up about it here

How can I convert an RGB image into grayscale in Python?

The fastest and current way is to use Pillow, installed via pip install Pillow.

The code is then:

from PIL import Image
img = Image.open('input_file.jpg').convert('L')
img.save('output_file.jpg')

SSRS chart does not show all labels on Horizontal axis

Really late reply for me, but I just suffered the pain of this problem as well.

What fixed it for me (after trying the Axis label settings and intervals from those screens, none of which worked!) was select the Horizontal Axis, then when you can see all the properties find Labels, and change LabelInterval to 1.

For some reason when I set this from the pop up properties screens it either never 'stuck' or it changes a slightly different value that didn't fix my issue.

fastest way to export blobs from table into individual files

I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:

declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1; 
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources

You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):

sp_configure 'show advanced options', 1;  
GO  
RECONFIGURE;  
GO  
sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

Read/write to file using jQuery

Yes it is possible.

The technique is described below

http://jquery.tiddlywiki.org/twFile.html

Publish to IIS, setting Environment Variable

To get the details about the error I had to add ASPNETCORE_ENVIRONMENT environment variable for the corresponding Application Pool system.applicationHost/applicationPools.

Note: the web application in my case was ASP.NET Core 2 web application hosted on IIS 10. It can be done via Configuration Editor in IIS Manager (see Editing Collections with Configuration Editor to figure out where to find this editor in IIS Manager).

Are there any style options for the HTML5 Date picker?

FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color, fill, etc.

I did eventually figure out that some filter properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:

_x000D_
_x000D_
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
  background: transparent;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
 <input type="date" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

Hopefully this helps some people as for the most part chrome even directly says this is impossible.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

The free Tamper Data Firefox extension is pretty good. Allows you to view, filter and modify all requests.

Rownum in postgresql

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

Recommended date format for REST GET API

REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).

If not having ugly URI is a concern (e.g. not including the url encoded version of :, -, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g. http://example.com/start/1331162374). The URL looks a little cleaner, but you certainly lose readability.

The /2012/03/07 is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.

Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I struggled with this for a long time. I am using Angular 6 and I found that

let headers = new HttpHeaders();
headers = headers.append('key', 'value');

did not work. But what did work was

let headers = new HttpHeaders().append('key', 'value');

did, which makes sense when you realize they are immutable. So having created a header you can't add to it. I haven't tried it, but I suspect

let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');

would work too.

.attr("disabled", "disabled") issue

Thank you all for your contribution! I found the problem:

ITS A FIREBUG BUG !!!

My code works. I have asked the PHP Dev to change the input types hidden in to input type text. The disabled feature works. But the firebug console does not update this status!

you can test out this firebug bug by your self here http://jsbin.com/uneti3/3#. Thx to aSeptik for the example page.

update: 2. June 2012: Firebug in FF11 still has this bug.

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

Also check your triggers.

Encountered this with a history table trigger which tried to insert the main table id into the history table id instead of the correct hist-table.source_id column.

The update statement did not touch the id column at all so took some time to find:

UPDATE source_table SET status = 0;

The trigger tried to do something similar to this:

FOR EACH ROW
BEGIN
    INSERT INTO `history_table` (`action`,`id`,`status`,`time_created`)
    VALUES('update', NEW.id, NEW.status, NEW.time_created);
END;

Was corrected to something like this:

FOR EACH ROW
BEGIN
    INSERT INTO `history_table` (`action`,`source_id`,`status`,`time_created`)
    VALUES('update', NEW.id, NEW.status, NEW.time_created);
END;

How to find out the server IP address (using JavaScript) that the browser is connected to?

I think you may use the callback from a JSONP request or maybe just the pure JSON data using an external service but based on the output of javascript location.host that way:

$.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
    console.warn('Fetching JSON data...');
    // Log output to console
    console.info(JSON.stringify(data, null, 2));
});

I'll use this code for my personal needs, as first I was coming on this site for the same reason.

You may use another external service instead the one I'm using for my needs. A very nice list exist and contains tests done here https://stackoverflow.com/a/35123097/5778582

Spring Boot application.properties value not populating

follow these steps. 1:- create your configuration class like below you can see

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

@Configuration
public class YourConfiguration{

    // passing the key which you set in application.properties
    @Value("${some.pro}")
    private String somePro;

   // getting the value from that key which you set in application.properties
    @Bean
    public String getsomePro() {
        return somePro;
    }
}

2:- when you have a configuration class then inject in the variable from a configuration where you need.

@Component
public class YourService {

    @Autowired
    private String getsomePro;

    // now you have a value in getsomePro variable automatically.
}

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

In my case the problem was the bind addresses in /etc/mysql/my.cnf, then:

nano /etc/mysql/my.cnf

search bind addresses and remove the specific with the host ip (not the 127.0.0.1)

How to read large text file on windows?

Definitely EditPad Lite !

It's extremely fast not just while opening files, but also functions like "Replace All", trimming of leading/trailing whitespaces or converting content to lowercase are very fast.

And it is also very similar to Notepad++ ;)

The type WebMvcConfigurerAdapter is deprecated

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

  • we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory
  • we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

XML Configuration

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.

spring.mvc.static-path-pattern=/resources/static/**

How to present UIActionSheet iOS Swift?

Action Sheet in iOS10 with Swift3.0. Follow this link.

 @IBAction func ShowActionSheet(_ sender: UIButton) {
    // Create An UIAlertController with Action Sheet

    let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)

    // Create UIAlertAction for UIAlertController

    let addAction = UIAlertAction(title: "Add", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File has been Add")
    })
    let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File has been Edit")
    })

    let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        print("File has been Delete")
    })
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
        print("Cancel")
    })

    // Add UIAlertAction in UIAlertController

    optionMenuController.addAction(addAction)
    optionMenuController.addAction(saveAction)
    optionMenuController.addAction(deleteAction)
    optionMenuController.addAction(cancelAction)

    // Present UIAlertController with Action Sheet

    self.present(optionMenuController, animated: true, completion: nil)

}

How can you detect the version of a browser?

Here are several prominent libraries that handle browser detection as of May 2019.

Bowser by lancedikson - 3,761?s - Last updated May 26, 2019 - 4.8KB

_x000D_
_x000D_
var result = bowser.getParser(window.navigator.userAgent);_x000D_
console.log(result);_x000D_
document.write("You are using " + result.parsedResult.browser.name +_x000D_
               " v" + result.parsedResult.browser.version + _x000D_
               " on " + result.parsedResult.os.name);
_x000D_
<script src="https://unpkg.com/[email protected]/es5.js"></script>
_x000D_
_x000D_
_x000D_

*supports Edge based on Chromium


Platform.js by bestiejs - 2,250?s - Last updated Oct 30, 2018 - 5.9KB

_x000D_
_x000D_
console.log(platform);_x000D_
document.write("You are using " + platform.name +_x000D_
               " v" + platform.version + _x000D_
               " on " + platform.os);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery Browser by gabceb - 504?s - Last updated Nov 23, 2015 - 1.3KB

_x000D_
_x000D_
console.log($.browser)_x000D_
document.write("You are using " + $.browser.name +_x000D_
               " v" + $.browser.versionNumber + _x000D_
               " on " + $.browser.platform);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
_x000D_
_x000D_
_x000D_

Detect.js (Archived) by darcyclarke - 522?s - Last updated Oct 26, 2015 - 2.9KB

_x000D_
_x000D_
var result = detect.parse(navigator.userAgent);_x000D_
console.log(result);_x000D_
document.write("You are using " + result.browser.family +_x000D_
               " v" + result.browser.version + _x000D_
               " on " + result.os.family);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
_x000D_
_x000D_
_x000D_

Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B

_x000D_
_x000D_
console.log(BrowserDetect)_x000D_
document.write("You are using " + BrowserDetect.browser +_x000D_
               " v" + BrowserDetect.version + _x000D_
               " on " + BrowserDetect.OS);
_x000D_
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
_x000D_
_x000D_
_x000D_


Notable Mentions:

  • WhichBrowser - 1,355?s - Last updated Oct 2, 2018
  • Modernizr - 23,397?s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.

Further Reading

DataTable: Hide the Show Entries dropdown but keep the Search box

You can find more information directly on this link: http://datatables.net/examples/basic_init/filter_only.html

$(document).ready(function() {
$('#example').dataTable({
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": true,
    "bInfo": false,
    "bAutoWidth": false });
});

Hope that helps !

EDIT : If you are lazy, "bLengthChange": false, is the one you need to change :)

notifyDataSetChanged example

I recently wrote on this topic, though this post it old, I thought it will be helpful to someone who wants to know how to implement BaseAdapter.notifyDataSetChanged() step by step and in a correct way.

Please follow How to correctly implement BaseAdapter.notifyDataSetChanged() in Android or the newer blog BaseAdapter.notifyDataSetChanged().

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

Truncating all tables in a Postgres database

In this case it would probably be better to just have an empty database that you use as a template and when you need to refresh, drop the existing database and create a new one from the template.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Laravel use same form for create and edit

Pretty easy in your controller you do:

public function create()
{
    $user = new User;

    $action = URL::route('user.store');

    return View::('viewname')->with(compact('user', 'action'));
}

public function edit($id)
{
    $user = User::find($id);

    $action = URL::route('user.update', ['id' => $id]);

    return View::('viewname')->with(compact('user', 'action'));
}

And you just have to use this way:

{{ Form::model($user, ['action' => $action]) }}

   {{ Form::input('email') }}
   {{ Form::input('first_name') }}

{{ Form::close() }}

Executing command line programs from within python

If you're concerned about server performance then look at capping the number of running sox processes. If the cap has been hit you can always cache the request and inform the user when it's finished in whichever way suits your application.

Alternatively, have the n worker scripts on other machines that pull requests from the db and call sox, and then push the resulting output file to where it needs to be.

Can I call a base class's virtual function if I'm overriding it?

The C++ syntax is like this:

class Bar : public Foo {
  // ...

  void printStuff() {
    Foo::printStuff(); // calls base class' function
  }
};

Using Java generics for JPA findAll() query with WHERE clause

you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with

entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Convert and format a Date in JSP

In JSP, you'd normally like to use JSTL <fmt:formatDate> for this. You can of course also throw in a scriptlet with SimpleDateFormat, but scriptlets are strongly discouraged since 2003.

Assuming that ${bean.date} returns java.util.Date, here's how you can use it:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />

If you're actually using a java.util.Calendar, then you can invoke its getTime() method to get a java.util.Date out of it that <fmt:formatDate> accepts:

<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />

Or, if you're actually holding the date in a java.lang.String (this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date instead of as java.lang.String!), here's how you can convert from one date string format e.g. MM/dd/yyyy to another date string format e.g. yyyy-MM-dd with help of JSTL <fmt:parseDate>.

<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Getting only response header from HTTP POST using curl

For long response bodies (and various other similar situations), the solution I use is always to pipe to less, so

curl -i https://api.github.com/users | less

or

curl -s -D - https://api.github.com/users | less

will do the job.

Import Android volley to Android Studio

Way too complicated guys. Just include it in your gradle dependencies:

dependencies {
    ...
    compile 'com.mcxiaoke.volley:library:1.0.17'
}

How to configure nginx to enable kinda 'file browser' mode?

You should try HttpAutoindexModule.

Set autoindex option to on. It is off by default.

Your example configuration should be ok

location /{ 
   root /home/yozloy/html/; 
   index index.html; 
   autoindex on;
}

Without autoindex option you should be getting Error 403 for requests that end with / on directories that do not have an index.html file. With this option you should be getting a simple listing:

<html>
<head><title>Index of /</title></head>
<body bgcolor="white">
<h1>Index of /test/</h1><hr><pre><a href="../">../</a>
<a href="test.txt">test.txt</a>                 19-May-2012 10:43            0
</pre><hr></body>
</html>

Edit: Updated the listing to delete any references to test

How to get package name from anywhere?

You can use undocumented method android.app.ActivityThread.currentPackageName() :

Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method  = clazz.getDeclaredMethod("currentPackageName", null);
String appPackageName = (String) method.invoke(clazz, null);

Caveat: This must be done on the main thread of the application.

Thanks to this blog post for the idea: http://blog.javia.org/static-the-android-application-package/ .

Angular: Cannot find a differ supporting object '[object Object]'

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

New to unit testing, how to write great tests?

For unit testing, I found both Test Driven (tests first, code second) and code first, test second to be extremely useful.

Instead of writing code, then writing test. Write code then look at what you THINK the code should be doing. Think about all the intended uses of it and then write a test for each. I find writing tests to be faster but more involved than the coding itself. The tests should test the intention. Also thinking about the intentions you wind up finding corner cases in the test writing phase. And of course while writing tests you might find one of the few uses causes a bug (something I often find, and I am very glad this bug did not corrupt data and go unchecked).

Yet testing is almost like coding twice. In fact I had applications where there was more test code (quantity) than application code. One example was a very complex state machine. I had to make sure that after adding more logic to it, the entire thing always worked on all previous use cases. And since those cases were quite hard to follow by looking at the code, I wound up having such a good test suite for this machine that I was confident that it would not break even after making changes, and the tests saved my ass a few times. And as users or testers were finding bugs with the flow or corner cases unaccounted for, guess what, added to tests and never happened again. This really gave users confidence in my work in addition to making the whole thing super stable. And when it had to be re-written for performance reasons, guess what, it worked as expected on all inputs thanks to the tests.

All the simple examples like function square(number) is great and all, and are probably bad candidates to spend lots of time testing. The ones that do important business logic, thats where the testing is important. Test the requirements. Don't just test the plumbing. If the requirements change then guess what, the tests must too.

Testing should not be literally testing that function foo invoked function bar 3 times. That is wrong. Check if the result and side-effects are correct, not the inner mechanics.

Is it .yaml or .yml?

EDIT:

So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?

This question could be:

  1. A request for advice; or

  2. A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.

People differ in their predilection for following:

  1. Official advice; or

  2. The preponderance of practice.

Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!

In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.

By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.

Whatever your personal inclination, be it to follow one path or the other, I do not object.

(End of edit.)

The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).

As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.

As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.

Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."

Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."

As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.

The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.

Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!

Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?

Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).

Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.

Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.

Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.

Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".

The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.

".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.

How do I flush the PRINT buffer in TSQL?

Use the RAISERROR function:

RAISERROR( 'This message will show up right away...',0,1) WITH NOWAIT

You shouldn't completely replace all your prints with raiserror. If you have a loop or large cursor somewhere just do it once or twice per iteration or even just every several iterations.

Also: I first learned about RAISERROR at this link, which I now consider the definitive source on SQL Server Error handling and definitely worth a read:
http://www.sommarskog.se/error-handling-I.html

Tokenizing strings in C

Do it like this:

char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
    printf("token: %s\n", token);
    token = strtok(NULL, " ");
}

Note: strtok modifies the string its tokenising, so it cannot be a const char*.

Automatically pass $event with ng-click?

As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).

The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:

<clickable>
  <h1>Hello World!</h1>
</clickable>

Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):

app.directive('clickable', function() {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div ng-transclude ng-click="handleClick($event)"></div>'
    };
});

Finally in my controller I have the click event ready to go:

$scope.handleClick = function($event) {
    var i = 0;
};

Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.

Hope that helps!

SQL Query to find the last day of the month

Declare @GivenDate datetime 
Declare @ResultDate datetime 
DEclare @EOMDate datetime 
Declare @Day int 
set @GivenDate=getdate() 
set @GivenDate= (dateadd(mm,1,@GivenDate)) 
set @Day =day(@GivenDate) 
set @ResultDate=dateadd(dd,-@Day+1,@GivenDate) 
select @EOMDate =dateadd(dd,-1 ,@ResultDate) 
select @EOMDate 

What is a 'Closure'?

A simple example in Groovy for your reference:

def outer() {
    def x = 1
    return { -> println(x)} // inner
}
def innerObj = outer()
innerObj() // prints 1

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Declare type which its key is string and value can be any then declare the object with this type and the lint won't show up

type MyType = {[key: string]: any};

So your code will be

type ISomeType = {[key: string]: any};

    let someObject: ISomeType = {
        firstKey:   'firstValue',
        secondKey:  'secondValue',
        thirdKey:   'thirdValue'
    };

    let key: string = 'secondKey';

    let secondValue: string = someObject[key];

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Insert line after first match using sed

I had a similar task, and was not able to get the above perl solution to work.

Here is my solution:

perl -i -pe "BEGIN{undef $/;} s/^\[mysqld\]$/[mysqld]\n\ncollation-server = utf8_unicode_ci\n/sgm" /etc/mysql/my.cnf

Explanation:

Uses a regular expression to search for a line in my /etc/mysql/my.cnf file that contained only [mysqld] and replaced it with

[mysqld] collation-server = utf8_unicode_ci

effectively adding the collation-server = utf8_unicode_ci line after the line containing [mysqld].

MVC 5 Access Claims Identity User Data

You can also do this:

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;

Update

To provide further explanation as per comments.

If you are creating users within your system as follows:

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

You should automatically have some Claims populated relating to you Identity.

To add customized claims after a user authenticates you can do this as follows:

var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));

The claims can be read back out as Darin has answered above or as I have.

The claims are persisted when you call below passing the identity in:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);

Print a list of all installed node.js modules

Why not grab them from dependencies in package.json?

Of course, this will only give you the ones you actually saved, but you should be doing that anyway.

console.log(Object.keys(require('./package.json').dependencies));

Print JSON parsed object?

The following code will display complete json data in alert box

var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

json = JSON.parse(data);
window.alert(JSON.stringify(json));

How to compare only date components from DateTime in EF?

//Note for Linq Users/Coders

This should give you the exact comparison for checking if a date falls within range when working with input from a user - date picker for example:

((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
        ((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date

where startdate and enddate are values from a date picker.

How do I read configuration settings from Symfony2 config.yml?

In order to be able to expose some configuration parameters for your bundle you should consult the documentation for doing so. It's fairly easy to do :)

Here's the link: How to expose a Semantic Configuration for a Bundle

Git - how delete file from remote repository

If you have deleted lot of files and folders, just do this

git commit -a -m .
git push

Paging with Oracle

Ask Tom on pagination and very, very useful analytic functions.

This is excerpt from that page:

select * from (
    select /*+ first_rows(25) */
     object_id,object_name,
     row_number() over
    (order by object_id) rn
    from all_objects
)
where rn between :n and :m
order by rn;

Return index of highest value in an array

<?php

$array = array(11 => 14,
               10 => 9,
               12 => 7,
               13 => 7,
               14 => 4,
               15 => 6);

echo array_search(max($array), $array);

?>

array_search() return values:

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

Selecting a Record With MAX Value

The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)

select * 
from (
    select PEAA.PresupuestoEtapaActividadId,
        PEAH.PresupuestoEtapaActividadHistoricoId,             
        sum(PEAA.ValorTotalDesperdicioBase) as Base,
        sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
    from hgc.PresupuestoActividadAnalisis as PEAA
    inner join hgc.PresupuestoEtapaActividad as PEA
        on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
    inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
        on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId                                                         
    group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId    
) as t
where exists (
    select 1 
    from (
        select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId                                                                     
        from hgc.PresupuestoEtapaActividadHistorico as PEAH                       
        group by PEAH.PresupuestoEtapaActividadId  
    ) as ti
    where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId 
)

How to resize datagridview control when form resizes

If you want to show the complete headers text

this will auto resize the columns so that the headers will show complete header text.

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

For Dock Mode

If you want to show the Dock Mode in your panel or form.

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

Adding custom HTTP headers using JavaScript

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

npm install error - unable to get local issuer certificate

Well this is not a right answer but can be consider as a quick workaround. Right answer is turn off Strict SSL.

I am having the same error

PhantomJS not found on PATH
Downloading https://github.com/Medium/phantomjs/releases/download/v2.1.1/phantomjs-2.1.1-windows.zip
Saving to C:\Users\Sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip
Receiving...

Error making request.
Error: unable to get local issuer certificate
at TLSSocket. (_tls_wrap.js:1105:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:639:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38)

So the after reading the error.

Just downloaded the file manually and placed it on the required path. i.e

C:\Users\Sam\AppData\Local\Temp\phantomjs\

This solved my problem.

    PhantomJS not found on PATH                                                                                                
Download already available at C:\Users\sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip                    
Verified checksum of previously downloaded file                                                                            
Extracting zip contents                                    

SyntaxError: non-default argument follows default argument

You can't have a non-keyword argument after a keyword argument.

Make sure you re-arrange your function arguments like so:

def a(len1,til,hgt=len1,col=0):
    system('mode con cols='+len1,'lines='+hgt)
    system('title',til)
    system('color',col)

a(64,"hi",25,"0b")

How to use "Share image using" sharing Intent to share images in android?

I found the easiest way to do this is by using the MediaStore to temporarily store the image that you want to share:

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

From: Sharing Content With Intents

How to use Python to login to a webpage and retrieve cookies for later usage?

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

Display an image into windows forms

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

Failing to run jar file from command line: “no main manifest attribute”

You can select the "Runnable JAR File" after you click on "Export".

You can specify your main driver in "Launch Configuration"

enter image description here enter image description here

Check if page gets reloaded or refreshed in JavaScript

Store a cookie the first time someone visits the page. On refresh check if your cookie exists and if it does, alert.

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // cookie doesn't exist, create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // not first visit, so alert
    alert('You refreshed!');
  }
}

and in your body tag:

<body onload="checkFirstVisit()">

Switch php versions on commandline ubuntu 16.04

type this in your command line, should work for all ubuntu between 16.04, 18.04 and 20.04.

$ sudo update-alternatives --config php

and this is what you will get

There are 4 choices for the alternative php (providing /usr/bin/php).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php7.2   72        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.0   70        manual mode
  3            /usr/bin/php7.1   71        manual mode
  4            /usr/bin/php7.2   72        manual mode
Press <enter> to keep the current choice[*], or type selection number:

Choose the appropriate version

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • Regex doesn't work in String.matches()

    String.matches returns whether the whole string matches the regex, not just any substring.

    Return Result from Select Query in stored procedure to a List

    Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

    private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.DataSource = "it.hurts.when.IP";
                builder.UserID = "someDBUser";
                builder.Password = "someDBPassword";
                builder.InitialCatalog = "someDB";
                return new SqlConnection(builder.ConnectionString);
            }
    
            public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
            {
                try
                {
                    DataTable dataTable = new DataTable();
    
                    using (SqlConnection Connection = getConnectionString())
                    {
                        // Open connection
                        Connection.Open();
    
                        // Create command from params / SP
                        SqlCommand cmd = new SqlCommand(SPName, Connection);
    
                        // Add parameters
                        cmd.Parameters.AddRange(Params.ToArray());
                        cmd.CommandType = CommandType.StoredProcedure;
    
                        // Make datatable for conversion
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(dataTable);
                        da.Dispose();
    
                        // Close connection
                        Connection.Close();
                    }
    
                    // Convert to list of T
                    var retVal = ConvertToList<T>(dataTable);
                    return retVal;
                }
                catch (SqlException e)
                {
                    Console.WriteLine("ConvertToList Exception: " + e.ToString());
                    return new List<T>();
                }
            }
    
            /// <summary>
            /// Converts datatable to List<someType> if possible.
            /// </summary>
            public static List<T> ConvertToList<T>(DataTable dt)
            {
                try // Necesarry unfotunately.
                {
                    var columnNames = dt.Columns.Cast<DataColumn>()
                        .Select(c => c.ColumnName)
                        .ToList();
    
                    var properties = typeof(T).GetProperties();
    
                    return dt.AsEnumerable().Select(row =>
                        {
                            var objT = Activator.CreateInstance<T>();
    
                            foreach (var pro in properties)
                            {
                                if (columnNames.Contains(pro.Name))
                                {
                                    if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                    else pro.SetValue(objT, row[pro.Name], null);
                                }
                            }
    
                            return objT;
                        }).ToList();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                    Console.WriteLine("ConvertToList Exception: " + e.ToString());
                    return new List<T>();
                }
            }
    

    Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

    Removing MySQL 5.7 Completely

    You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

    sudo apt-get remove --purge mysql-server mysql-client mysql-common

    sudo rm -rf /var/lib/mysql

    I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

    Generating random strings with T-SQL

    When generating random data, specially for test, it is very useful to make the data random, but reproducible. The secret is to use explicit seeds for the random function, so that when the test is run again with the same seed, it produces again exactly the same strings. Here is a simplified example of a function that generates object names in a reproducible manner:

    alter procedure usp_generateIdentifier
        @minLen int = 1
        , @maxLen int = 256
        , @seed int output
        , @string varchar(8000) output
    as
    begin
        set nocount on;
        declare @length int;
        declare @alpha varchar(8000)
            , @digit varchar(8000)
            , @specials varchar(8000)
            , @first varchar(8000)
        declare @step bigint = rand(@seed) * 2147483647;
    
        select @alpha = 'qwertyuiopasdfghjklzxcvbnm'
            , @digit = '1234567890'
            , @specials = '_@# '
        select @first = @alpha + '_@';
    
        set  @seed = (rand((@seed+@step)%2147483647)*2147483647);
    
        select @length = @minLen + rand(@seed) * (@maxLen-@minLen)
            , @seed = (rand((@seed+@step)%2147483647)*2147483647);
    
        declare @dice int;
        select @dice = rand(@seed) * len(@first),
            @seed = (rand((@seed+@step)%2147483647)*2147483647);
        select @string = substring(@first, @dice, 1);
    
        while 0 < @length 
        begin
            select @dice = rand(@seed) * 100
                , @seed = (rand((@seed+@step)%2147483647)*2147483647);
            if (@dice < 10) -- 10% special chars
            begin
                select @dice = rand(@seed) * len(@specials)+1
                    , @seed = (rand((@seed+@step)%2147483647)*2147483647);
                select @string = @string + substring(@specials, @dice, 1);
            end
            else if (@dice < 10+10) -- 10% digits
            begin
                select @dice = rand(@seed) * len(@digit)+1
                    , @seed = (rand((@seed+@step)%2147483647)*2147483647);
                select @string = @string + substring(@digit, @dice, 1);
            end
            else -- rest 80% alpha
            begin
                declare @preseed int = @seed;
                select @dice = rand(@seed) * len(@alpha)+1
                    , @seed = (rand((@seed+@step)%2147483647)*2147483647);
    
                select @string = @string + substring(@alpha, @dice, 1);
            end
    
            select @length = @length - 1;   
        end
    end
    go
    

    When running the tests the caller generates a random seed it associates with the test run (saves it in the results table), then passed along the seed, similar to this:

    declare @seed int;
    declare @string varchar(256);
    
    select @seed = 1234; -- saved start seed
    
    exec usp_generateIdentifier 
        @seed = @seed output
        , @string = @string output;
    print @string;  
    exec usp_generateIdentifier 
        @seed = @seed output
        , @string = @string output;
    print @string;  
    exec usp_generateIdentifier 
        @seed = @seed output
        , @string = @string output;
    print @string;  
    

    Update 2016-02-17: See the comments bellow, the original procedure had an issue in the way it advanced the random seed. I updated the code, and also fixed the mentioned off-by-one issue.

    Python print statement “Syntax Error: invalid syntax”

    In Python 3, print is a function, you need to call it like print("hello world").

    Binary search (bisection) in Python

    Binary Search :

    // List - values inside list
    // searchItem - Item to search
    // size - Size of list
    // upperBound - higher index of list
    // lowerBound - lower index of list
    def binarySearch(list, searchItem, size, upperBound, lowerBound):
            print(list)
            print(upperBound)
            print(lowerBound)
            mid = ((upperBound + lowerBound)) // 2
            print(mid)
            if int(list[int(mid)]) == value:
                   return "value exist"
            elif int(list[int(mid)]) < value:
                 return searchItem(list, value, size, upperBound, mid + 1)
            elif int(list[int(mid)]) > value:
                   return searchItem(list, value, size, mid - 1, lowerBound)
    

    // To call above function use :

    list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    searchItem = 1        
    print(searchItem(list[0], item, len(list[0]) -1, len(list[0]) - 1, 0))