Programs & Examples On #Subapplication

Embedding JavaScript engine into .NET

Anybody just tuning in check out Jurassic as well:

http://jurassic.codeplex.com/

edit: this has moved to github (and seems active at first glance)

https://github.com/paulbartrum/jurassic

Select a Column in SQL not in Group By

You can use as below,

Select X.a, X.b, Y.c from (
                Select X.a as a, sum (b) as sum_b from name_table X
                group by X.a)X
left join from name_table Y on Y.a = X.a

Example;

CREATE TABLE #products (
    product_name VARCHAR(MAX),
    code varchar(3),
    list_price [numeric](8, 2) NOT NULL
);

INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('Dinding', 'ADE', 2000)
INSERT INTO #products VALUES ('Kaca', 'AKB', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)

--SELECT * FROM #products 
SELECT distinct x.code, x.SUM_PRICE, product_name FROM (SELECT code, SUM(list_price) as SUM_PRICE From #products 
               group by code)x
left join #products y on y.code=x.code

DROP TABLE #products

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

Argument of type 'X' is not assignable to parameter of type 'X'

In my case, it was that I had a custom interface called Item, but I imported accidentally because of the auto-completion, the angular Item class. Be sure that you're importing from the right package.

matplotlib savefig in jpeg format

I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig.

To upgrade to matplotlib 1.1.0 with pip, use this command:

pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'

EDIT (to respond to comment):

pylab is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.

On my system, pylab is just this:

from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__

You can see that pylab is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab or with matplotlib.pyplot.

If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.

pandas unique values multiple columns

In [5]: set(df.Col1).union(set(df.Col2))
Out[5]: {'Bill', 'Bob', 'Joe', 'Mary', 'Steve'}

Or:

set(df.Col1) | set(df.Col2)

HttpClient - A task was cancelled?

I ran into this issue because my Main() method wasn't waiting for the task to complete before returning, so the Task<HttpResponseMessage> myTask was being cancelled when my console program exited.

The solution was to call myTask.GetAwaiter().GetResult() in Main() (from this answer).

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)

  • Run SQL*Plus and login as SYSTEM. You should know what password you’ve used during the installation of Oracle DB XE.
  • Run the command alter system set processes=150 scope=spfile; in SQL*Plus
  • VERY IMPORTANT: Restart the database.

From here:

http://www.atpeaz.com/index.php/2010/fixing-the-ora-12519-tnsno-appropriate-service-handler-found-error/

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
Out[2]:
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

Oracle sqlldr TRAILING NULLCOLS required, but why?

Try giving 5 ',' in every line, similar to line number 4.

Can't concatenate 2 arrays in PHP

you may use operator . $array3 = $array1.$array2;

Check if value exists in column in VBA

The find method of a range is faster than using a for loop to loop through all the cells manually.

here is an example of using the find method in vba

Sub Find_First()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
    With Sheets("Sheet1").Range("A:A") 'searches all of column A
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            Application.Goto Rng, True 'value found
        Else
            MsgBox "Nothing found" 'value not found
        End If
    End With
End If
End Sub

How to add many functions in ONE ng-click?

Follow the below

ng-click="anyFunction()"

anyFunction() {
   // call another function here
   anotherFunction();
}

Call removeView() on the child's parent first

In onCreate with activity or in onCreateView with fragment.

 if (view != null) {
    ViewGroup parent = (ViewGroup) view.getParent();
    if (parent != null) {
        parent.removeView(view);
    }
}
try {
    view = inflater.inflate(R.layout.fragment_main, container, false);
} catch (InflateException e) {

}

JavaScript get clipboard data on paste event (Cross browser)

This one does not use any setTimeout().

I have used this great article to achieve cross browser support.

$(document).on("focus", "input[type=text],textarea", function (e) {
    var t = e.target;
    if (!$(t).data("EventListenerSet")) {
        //get length of field before paste
        var keyup = function () {
            $(this).data("lastLength", $(this).val().length);
        };
        $(t).data("lastLength", $(t).val().length);
        //catch paste event
        var paste = function () {
            $(this).data("paste", 1);//Opera 11.11+
        };
        //process modified data, if paste occured
        var func = function () {
            if ($(this).data("paste")) {
                alert(this.value.substr($(this).data("lastLength")));
                $(this).data("paste", 0);
                this.value = this.value.substr(0, $(this).data("lastLength"));
                $(t).data("lastLength", $(t).val().length);
            }
        };
        if (window.addEventListener) {
            t.addEventListener('keyup', keyup, false);
            t.addEventListener('paste', paste, false);
            t.addEventListener('input', func, false);
        }
        else {//IE
            t.attachEvent('onkeyup', function () {
                keyup.call(t);
            });
            t.attachEvent('onpaste', function () {
                paste.call(t);
            });
            t.attachEvent('onpropertychange', function () {
                func.call(t);
            });
        }
        $(t).data("EventListenerSet", 1);
    }
}); 

This code is extended with selection handle before paste: demo

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

Include the port number with the IP address.

For example:

http://19.18.20.101:5566

where 5566 is the port number.

How to store values from foreach loop into an array?

Just to save you too much typos:

foreach($group_membership as $username){
        $username->items = array(additional array to add);
    }
    print_r($group_membership);

How to print Two-Dimensional Array like table

I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.

From the initial question, as has been adequately explained by @djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:

System.out.println();

However, printing that immediately after the first print statement gives erroneous results. What gives?

1 
2 
...
n 

This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!

Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.

for(i=0;i<7;i++){
    for(j=0;j<5;j++) {
        System.out.print(twoDm[i][j]+" ");  
    }
    System.out.println();
}

And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.

Giving graphs a subtitle in matplotlib

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different fontsize arguments). Hope that helps!

What is move semantics?

In easy (practical) terms:

Copying an object means copying its "static" members and calling the new operator for its dynamic objects. Right?

class A
{
   int i, *p;

public:
   A(const A& a) : i(a.i), p(new int(*a.p)) {}
   ~A() { delete p; }
};

However, to move an object (I repeat, in a practical point of view) implies only to copy the pointers of dynamic objects, and not to create new ones.

But, is that not dangerous? Of course, you could destruct a dynamic object twice (segmentation fault). So, to avoid that, you should "invalidate" the source pointers to avoid destructing them twice:

class A
{
   int i, *p;

public:
   // Movement of an object inside a copy constructor.
   A(const A& a) : i(a.i), p(a.p)
   {
     a.p = nullptr; // pointer invalidated.
   }

   ~A() { delete p; }
   // Deleting NULL, 0 or nullptr (address 0x0) is safe. 
};

Ok, but if I move an object, the source object becomes useless, no? Of course, but in certain situations that's very useful. The most evident one is when I call a function with an anonymous object (temporal, rvalue object, ..., you can call it with different names):

void heavyFunction(HeavyType());

In that situation, an anonymous object is created, next copied to the function parameter, and afterwards deleted. So, here it is better to move the object, because you don't need the anonymous object and you can save time and memory.

This leads to the concept of an "rvalue" reference. They exist in C++11 only to detect if the received object is anonymous or not. I think you do already know that an "lvalue" is an assignable entity (the left part of the = operator), so you need a named reference to an object to be capable to act as an lvalue. A rvalue is exactly the opposite, an object with no named references. Because of that, anonymous object and rvalue are synonyms. So:

class A
{
   int i, *p;

public:
   // Copy
   A(const A& a) : i(a.i), p(new int(*a.p)) {}

   // Movement (&& means "rvalue reference to")
   A(A&& a) : i(a.i), p(a.p)
   {
      a.p = nullptr;
   }

   ~A() { delete p; }
};

In this case, when an object of type A should be "copied", the compiler creates a lvalue reference or a rvalue reference according to if the passed object is named or not. When not, your move-constructor is called and you know the object is temporal and you can move its dynamic objects instead of copying them, saving space and memory.

It is important to remember that "static" objects are always copied. There's no ways to "move" a static object (object in stack and not on heap). So, the distinction "move"/ "copy" when an object has no dynamic members (directly or indirectly) is irrelevant.

If your object is complex and the destructor has other secondary effects, like calling to a library's function, calling to other global functions or whatever it is, perhaps is better to signal a movement with a flag:

class Heavy
{
   bool b_moved;
   // staff

public:
   A(const A& a) { /* definition */ }
   A(A&& a) : // initialization list
   {
      a.b_moved = true;
   }

   ~A() { if (!b_moved) /* destruct object */ }
};

So, your code is shorter (you don't need to do a nullptr assignment for each dynamic member) and more general.

Other typical question: what is the difference between A&& and const A&&? Of course, in the first case, you can modify the object and in the second not, but, practical meaning? In the second case, you can't modify it, so you have no ways to invalidate the object (except with a mutable flag or something like that), and there is no practical difference to a copy constructor.

And what is perfect forwarding? It is important to know that a "rvalue reference" is a reference to a named object in the "caller's scope". But in the actual scope, a rvalue reference is a name to an object, so, it acts as a named object. If you pass an rvalue reference to another function, you are passing a named object, so, the object isn't received like a temporal object.

void some_function(A&& a)
{
   other_function(a);
}

The object a would be copied to the actual parameter of other_function. If you want the object a continues being treated as a temporary object, you should use the std::move function:

other_function(std::move(a));

With this line, std::move will cast a to an rvalue and other_function will receive the object as a unnamed object. Of course, if other_function has not specific overloading to work with unnamed objects, this distinction is not important.

Is that perfect forwarding? Not, but we are very close. Perfect forwarding is only useful to work with templates, with the purpose to say: if I need to pass an object to another function, I need that if I receive a named object, the object is passed as a named object, and when not, I want to pass it like a unnamed object:

template<typename T>
void some_function(T&& a)
{
   other_function(std::forward<T>(a));
}

That's the signature of a prototypical function that uses perfect forwarding, implemented in C++11 by means of std::forward. This function exploits some rules of template instantiation:

 `A& && == A&`
 `A&& && == A&&`

So, if T is a lvalue reference to A (T = A&), a also (A& && => A&). If T is a rvalue reference to A, a also (A&& && => A&&). In both cases, a is a named object in the actual scope, but T contains the information of its "reference type" from the caller scope's point of view. This information (T) is passed as template parameter to forward and 'a' is moved or not according to the type of T.

Html5 Full screen video

    if (vi_video[0].exitFullScreen) vi_video[0].exitFullScreen();
    else if (vi_video[0].webkitExitFullScreen) vi_video[0].webkitExitFullScreen();
    else if (vi_video[0].mozExitFullScreen) vi_video[0].mozExitFullScreen();
    else if (vi_video[0].oExitFullScreen) vi_video[0].oExitFullScreen();
    else if (vi_video[0].msExitFullScreen) vi_video[0].msExitFullScreen();
    else { vi_video.parent().append(vi_video.remove()); }

Convert Unix timestamp into human readable date using MySQL

You can use the DATE_FORMAT function. Here's a page with examples, and the patterns you can use to select different date components.

How does Django's Meta class work?

Answers that claim Django model's Meta and metaclasses are "completely different" are misleading answers.

The construction of Django model class objects, that is to say the object that stands for the class definition itself (yes, classes are also objects), are indeed controlled by a metaclass called ModelBase, and you can see that code here.

And one of the things that ModelBase does is to create the _meta attribute on every Django model which contains validation machinery, field details, save logic and so forth. During this operation, the stuff that is specified in the model's inner Meta class is read and used within that process.

So, while yes, in a sense Meta and metaclasses are different 'things', within the mechanics of Django model construction they are intimately related; understanding how they work together will deepen your insight into both at once.

This might be a helpful source of information to better understand how Django models employ metaclasses.

https://code.djangoproject.com/wiki/DevModelCreation

And this might help too if you want to better understand how objects work in general.

https://docs.python.org/3/reference/datamodel.html

How can we generate getters and setters in Visual Studio?

If you're using ReSharper, go into the ReSharper menu → CodeGenerate...

(Or hit Alt + Ins inside the surrounding class), and you'll get all the options for generating getters and/or setters you can think of :-)

LINQ Inner-Join vs Left-Join

If you actually have a database, this is the most-simple way:

var lsPetOwners = ( from person in context.People
                    from pets in context.Pets
                        .Where(mypet => mypet.Owner == person.ID) 
                        .DefaultIfEmpty()
                     select new { OwnerName = person.Name, Pet = pets.Name }
                   ).ToList();

Explicit Return Type of Lambda

You can have more than one statement when still return:

[]() -> your_type {return (
        your_statement,
        even_more_statement = just_add_comma,
        return_value);}

http://www.cplusplus.com/doc/tutorial/operators/#comma

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.

How to select only 1 row from oracle sql?

More flexible than select max() is:

select distinct first_row(column_x) over (order by column_y,column_z,...) from Table_A

Styling HTML5 input type number

<input type="number" name="numericInput" size="2" min="0" maxlength="2" value="0" />

How to show particular image as thumbnail while implementing share on Facebook?

From Facebook's spec, use a code like this:

<meta property="og:image" content="http://siim.lepisk.com/wp-content/uploads/2011/01/siim-blog-fb.png" />

Source: Facebook Share

How to vertically align text with icon font?

In this scenario, since you are working with inline-level elements, you could add vertical-align: middle to the span elements for vertical centering:

.nav-text {
  vertical-align: middle;
}

Alternatively, you could set the display of the parent element to flex and set align-items to center for vertical centering:

.menu {
  display: flex;
  align-items: center;
}

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

Generating random number between 1 and 10 in Bash Shell Script

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

Why doesn't importing java.util.* include Arrays and Lists?

Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.

Update


It gives that warning because your the line should actually be

List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();

You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.

How do I configure PyCharm to run py.test tests?

I'm using 2018.2

I do Run -> Edit Configurations... Then click the + in the upper left of the modal dialog. Select "python tests" -> py.test Then I give it a name like "All test with py.test"

I select Target: module name and put in the module where my tests are (that is 'tests' for me) or the module where all my code is if my tests are mixed in with my code. This was tripping me up.

I set the Python interpreter.

I set the working directory to the project directory.

What does the restrict keyword mean in C++?

This is the original proposal to add this keyword. As dirkgently pointed out though, this is a C99 feature; it has nothing to do with C++.

How to sort Map values by key in Java?

Using the TreeMap you can sort the map.

Map<String, String> map = new HashMap<>();        
Map<String, String> treeMap = new TreeMap<>(map);
for (String str : treeMap.keySet()) {
    System.out.println(str);
}

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

java.io.NotSerializableException can occur when you serialize an inner class instance because:

serializing such an inner class instance will result in serialization of its associated outer class instance as well

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

Ref: The Serializable Interface

Variable length (Dynamic) Arrays in Java

I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:

ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Convert wchar_t to char

assert is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug.

Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char version.

Overlaying histograms with ggplot2 in R

While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.

The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.

Single histogram:

plot_histogram <- function(df, feature) {
    plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
    geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
    geom_density(alpha=0.3, fill="red") +
    geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
    labs(x=feature, y = "Density")
    print(plt)
}

Multiple histogram:

plot_multi_histogram <- function(df, feature, label_column) {
    plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
    geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
    geom_density(alpha=0.7) +
    geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
    labs(x=feature, y = "Density")
    plt + guides(fill=guide_legend(title=label_column))
}

Usage:

Simply pass your data frame into the above functions along with desired arguments:

plot_histogram(iris, 'Sepal.Width')

enter image description here

plot_multi_histogram(iris, 'Sepal.Width', 'Species')

enter image description here

The extra parameter in plot_multi_histogram is the name of the column containing the category labels.

We can see this more dramatically by creating a dataframe with many different distribution means:

a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))

Passing data frame in as before (and widening chart using options):

options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')

enter image description here

How to change the port of Tomcat from 8080 to 80?

On Ubuntu and Debian systems, there are several steps needed:

  1. In server.xml, change the line <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> to have port="80".

  2. Install the recommended (not required) authbind package, with a command like:

    sudo apt-get install authbind

  3. Enable authbind in the server.xml file (in either /etc/tomcat6 or /etc/tomcat7) by uncommenting and setting the line like:

    AUTHBIND=yes

All three steps are needed.

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Javascript: formatting a rounded number to N decimals

There's always a better way for doing things.

var number = 51.93999999999761;

I would like to get four digits precision: 51.94

just do:

number.toPrecision(4);

the result will be: 51.94

Running a shell script through Cygwin on Windows

If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).

To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
#!/bin/bash echo '$0 = ' $0 echo '$1 = ' $1 filepath=$1 3. On Windows with Cygwin, you type "test1.sh" to run
4. On a Unix, you also type "test1.sh" to run


Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.

Note: Using this method, you do not need to prepend your script file name with bash to run

How to implement a FSM - Finite State Machine in Java

You can implement Finite State Machine in two different ways.

Option 1:

Finite State machine with a pre-defined workflow : Recommended if you know all states in advance and state machine is almost fixed without any changes in future

  1. Identify all possible states in your application

  2. Identify all the events in your application

  3. Identify all the conditions in your application, which may lead state transition

  4. Occurrence of an event may cause transitions of state

  5. Build a finite state machine by deciding a workflow of states & transitions.

    e.g If an event 1 occurs at State 1, the state will be updated and machine state may still be in state 1.

    If an event 2 occurs at State 1, on some condition evaluation, the system will move from State 1 to State 2

This design is based on State and Context patterns.

Have a look at Finite State Machine prototype classes.

Option 2:

Behavioural trees: Recommended if there are frequent changes to state machine workflow. You can dynamically add new behaviour without breaking the tree.

enter image description here

The base Task class provides a interface for all these tasks, the leaf tasks are the ones just mentioned, and the parent tasks are the interior nodes that decide which task to execute next.

The Tasks have only the logic they need to actually do what is required of them, all the decision logic of whether a task has started or not, if it needs to update, if it has finished with success, etc. is grouped in the TaskController class, and added by composition.

The decorators are tasks that “decorate” another class by wrapping over it and giving it additional logic.

Finally, the Blackboard class is a class owned by the parent AI that every task has a reference to. It works as a knowledge database for all the leaf tasks

Have a look at this article by Jaime Barrachina Verdia for more details

How can I apply styles to multiple classes at once?

.abc, .xyz { margin-left: 20px; }

is what you are looking for.

How to create a file name with the current date & time in Python?

This prints in an easy to read format -

import datetime

time_now  = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S') 

print(time_now)

Output: 02_03_2021_22_44_50

How to update a plot in matplotlib?

All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx! Good luck!

Load a Bootstrap popover content with AJAX. Is this possible?

If the content in the popover isn't likely to change, it would make sense to retrieve it only once. Also, some of the solutions here have the issue that if you move over multiple "previews" fast, you get multiple open popups. This solution addresses both those things.

$('body').on('mouseover', '.preview', function() 
{
    var e = $(this);
    if (e.data('title') == undefined)
    {
        // set the title, so we don't get here again.
        e.data('title', e.text());

        // set a loader image, so the user knows we're doing something
        e.data('content', '<img src="/images/ajax-loader.gif" />');
        e.popover({ html : true, trigger : 'hover'}).popover('show');

        // retrieve the real content for this popover, from location set in data-href
        $.get(e.data('href'), function(response)
        {
            // set the ajax-content as content for the popover
            e.data('content', response.html);

            // replace the popover
            e.popover('destroy').popover({ html : true, trigger : 'hover'});

            // check that we're still hovering over the preview, and if so show the popover
            if (e.is(':hover'))
            {
                e.popover('show');
            }
        });
    }
});

Python os.path.join() on a list

This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.

import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]

reduce is builtin in Python 2.x. In Python 3.x it has been moved to itertools However the accepted the answer is better.

This has been answered below but answering if you have a list of items that needs to be joined.

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

Javascript window.open pass values using POST

thanks php-b-grader !

below the generic function for window.open pass values using POST:

function windowOpenInPost(actionUrl,windowName, windowFeatures, keyParams, valueParams) 
{
    var mapForm = document.createElement("form");
    var milliseconds = new Date().getTime();
    windowName = windowName+milliseconds;
    mapForm.target = windowName;
    mapForm.method = "POST";
    mapForm.action = actionUrl;
    if (keyParams && valueParams && (keyParams.length == valueParams.length)){
        for (var i = 0; i < keyParams.length; i++){
        var mapInput = document.createElement("input");
            mapInput.type = "hidden";
            mapInput.name = keyParams[i];
            mapInput.value = valueParams[i];
            mapForm.appendChild(mapInput);

        }
        document.body.appendChild(mapForm);
    }


    map = window.open('', windowName, windowFeatures);
if (map) {
    mapForm.submit();
} else {
    alert('You must allow popups for this map to work.');
}}

Remove last item from array

Using the spread operator:

_x000D_
_x000D_
const a = [1,2,3]
const [, ...rest] = a.reverse();
const withoutLast = rest.reverse();
console.log(withoutLast)
_x000D_
_x000D_
_x000D_

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

Exit code 137 (128+9) indicates that your program exited due to receiving signal 9, which is SIGKILL. This also explains the killed message. The question is, why did you receive that signal?

The most likely reason is probably that your process crossed some limit in the amount of system resources that you are allowed to use. Depending on your OS and configuration, this could mean you had too many open files, used too much filesytem space or something else. The most likely is that your program was using too much memory. Rather than risking things breaking when memory allocations started failing, the system sent a kill signal to the process that was using too much memory.

As I commented earlier, one reason you might hit a memory limit after printing finished counting is that your call to counter.items() in your final loop allocates a list that contains all the keys and values from your dictionary. If your dictionary had a lot of data, this might be a very big list. A possible solution would be to use counter.iteritems() which is a generator. Rather than returning all the items in a list, it lets you iterate over them with much less memory usage.

So, I'd suggest trying this, as your final loop:

for key, value in counter.iteritems():
    writer.writerow([key, value])

Note that in Python 3, items returns a "dictionary view" object which does not have the same overhead as Python 2's version. It replaces iteritems, so if you later upgrade Python versions, you'll end up changing the loop back to the way it was.

How to reset settings in Visual Studio Code?

If you want to start afresh, deleting the settings.json file from your user's profile will do the trick.

But if you don't want to reset everything, it is still possible through settings menu.

settings menu

You can search for the setting that you want to revert back using search box.

You will see some settings with the left blue line, it means you've modified that one.

search setting

If you take your cursor to that setting, a gear button will appear. You can click this to restore that setting.

gear button

You can also use the drop-down below that setting and change it to default.

setting drop down

Targeting only Firefox with CSS

Using -engine specific rules ensures effective browser targeting.

<style type="text/css">

    //Other browsers
    color : black;


    //Webkit (Chrome, Safari)
    @media screen and (-webkit-min-device-pixel-ratio:0) { 
        color:green;
    }

    //Firefox
    @media screen and (-moz-images-in-menus:0) {
        color:orange;
    }
</style>

//Internet Explorer
<!--[if IE]>
     <style type='text/css'>
        color:blue;
    </style>
<![endif]-->

How do I use Comparator to define a custom sort order?

I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

public enum PaintColors {
    SILVER, BLUE, MAGENTA, RED
}

and

 static class ColorComparator implements Comparator<CarSort>
 {
     public int compare(CarSort c1, CarSort c2)
     {
         return c1.getColor().compareTo(c2.getColor());
     }
 }

You change the String to PaintColor and then in main your car list becomes:

carList.add(new CarSort("Ford Figo",PaintColor.SILVER));

...

Collections.sort(carList, new ColorComparator());

Exclude property from type

If you prefer to use a library, use ts-essentials.

import { Omit } from "ts-essentials";

type ComplexObject = {
  simple: number;
  nested: {
    a: string;
    array: [{ bar: number }];
  };
};

type SimplifiedComplexObject = Omit<ComplexObject, "nested">;

// Result:
// {
//  simple: number
// }

// if you want to Omit multiple properties just use union type:
type SimplifiedComplexObject = Omit<ComplexObject, "nested" | "simple">;

// Result:
// { } (empty type)

PS: You will find lots of other useful stuff there ;)

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

To get rid of the default dropdown arrow use:

-moz-appearance: window; 

Flutter : Vertically center column

For me the problem was there was was Expanded inside the column which I had to remove and it worked.

Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded( // remove this
              flex: 2,
              child: Text("content here"),
            ),
          ],
        )

Difference between File.separator and slash in paths

Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a / with a : just like the windows jvm replaces it with a \).

However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.

Is floating point math broken?

It's actually pretty simple. When you have a base 10 system (like ours), it can only express fractions that use a prime factor of the base. The prime factors of 10 are 2 and 5. So 1/2, 1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the denominators all use prime factors of 10. In contrast, 1/3, 1/6, and 1/7 are all repeating decimals because their denominators use a prime factor of 3 or 7. In binary (or base 2), the only prime factor is 2. So you can only express fractions cleanly which only contain 2 as a prime factor. In binary, 1/2, 1/4, 1/8 would all be expressed cleanly as decimals. While, 1/5 or 1/10 would be repeating decimals. So 0.1 and 0.2 (1/10 and 1/5) while clean decimals in a base 10 system, are repeating decimals in the base 2 system the computer is operating in. When you do math on these repeating decimals, you end up with leftovers which carry over when you convert the computer's base 2 (binary) number into a more human readable base 10 number.

From https://0.30000000000000004.com/

How can I suppress all output from a command using Bash?

The following sends standard output to the null device (bit bucket).

scriptname >/dev/null

And if you also want error messages to be sent there, use one of (the first may not work in all shells):

scriptname &>/dev/null
scriptname >/dev/null 2>&1
scriptname >/dev/null 2>/dev/null

And, if you want to record the messages, but not see them, replace /dev/null with an actual file, such as:

scriptname &>scriptname.out

For completeness, under Windows cmd.exe (where "nul" is the equivalent of "/dev/null"), it is:

scriptname >nul 2>nul

Call apply-like function on each row of dataframe with multiple arguments from each row

If data.frame columns are different types, apply() has a problem. A subtlety about row iteration is how apply(a.data.frame, 1, ...) does implicit type conversion to character types when columns are different types; eg. a factor and numeric column. Here's an example, using a factor in one column to modify a numeric column:

mean.height = list(BOY=69.5, GIRL=64.0)

subjects = data.frame(gender = factor(c("BOY", "GIRL", "GIRL", "BOY"))
         , height = c(71.0, 59.3, 62.1, 62.1))

apply(height, 1, function(x) x[2] - mean.height[[x[1]]])

The subtraction fails because the columns are converted to character types.

One fix is to back-convert the second column to a number:

apply(subjects, 1, function(x) as.numeric(x[2]) - mean.height[[x[1]]])

But the conversions can be avoided by keeping the columns separate and using mapply():

mapply(function(x,y) y - mean.height[[x]], subjects$gender, subjects$height)

mapply() is needed because [[ ]] does not accept a vector argument. So the column iteration could be done before the subtraction by passing a vector to [], by a bit more ugly code:

subjects$height - unlist(mean.height[subjects$gender])

Linux command to list all available commands and aliases

You can always to the following:

1. Hold the $PATH environment variable value.
2. Split by ":"
3. For earch entry: 
    ls * $entry 
4. grep your command in that output.

The shell will execute command only if they are listed in the path env var anyway.

VB.Net: Dynamically Select Image from My.Resources

Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.

PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name") 

How can I take a screenshot/image of a website using Python?

I created a library called pywebcapture that wraps selenium that will do just that:

pip install pywebcapture

Once you install with pip, you can do the following to easily get full size screenshots:

# import modules
from pywebcapture import loader, driver

# load csv with urls
csv_file = loader.CSVLoader("csv_file_with_urls.csv", has_header_bool, url_column, optional_filename_column)
uri_dict = csv_file.get_uri_dict()

# create instance of the driver and run
d = driver.Driver("path/to/webdriver/", output_filepath, delay, uri_dict)
d.run()

Enjoy!

https://pypi.org/project/pywebcapture/

Is it possible to apply CSS to half of a character?

Limited CSS and jQuery Solution

I am not sure how elegant this solution is, but it cuts everything exactly in half: http://jsfiddle.net/9wxfY/11/

Otherwise, I have created a nice solution for you... All you need to do is have this for your HTML:

Take a look at this most recent, and accurate, edit as of 6/13/2016 : http://jsfiddle.net/9wxfY/43/

As for the CSS, it is very limited... You only need to apply it to :nth-child(even)

_x000D_
_x000D_
$(function(){_x000D_
  var $hc = $('.half-color');_x000D_
  var str = $hc.text();_x000D_
  $hc.html("");_x000D_
_x000D_
  var i = 0;_x000D_
  var chars;_x000D_
  var dupText;_x000D_
_x000D_
  while(i < str.length){_x000D_
    chars = str[i];_x000D_
    if(chars == " ") chars = "&nbsp;";_x000D_
    dupText = "<span>" + chars + "</span>";_x000D_
_x000D_
    var firstHalf = $(dupText);_x000D_
    var secondHalf = $(dupText);_x000D_
_x000D_
    $hc.append(firstHalf)_x000D_
    $hc.append(secondHalf)_x000D_
_x000D_
    var width = firstHalf.width()/2;_x000D_
_x000D_
    firstHalf.width(width);_x000D_
    secondHalf.css('text-indent', -width);_x000D_
_x000D_
    i++;_x000D_
  }_x000D_
});
_x000D_
.half-color span{_x000D_
  font-size: 2em;_x000D_
  display: inline-block;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.half-color span:nth-child(even){_x000D_
  color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="half-color">This is a sentence</div>
_x000D_
_x000D_
_x000D_

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

How do I make a dotted/dashed line in Android?

I have created dashed dotted line for EditText. Here you go. Create your new xml. e.g dashed_border.xml Code here:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:bottom="1dp"
    android:left="-2dp"
    android:right="-2dp"
    android:top="-2dp">
    <shape android:shape="rectangle">
        <stroke
            android:width="2dp"
            android:color="#000000"
            android:dashGap="3dp"
            android:dashWidth="1dp" />

        <solid android:color="#00FFFFFF" />

        <padding
            android:bottom="10dp"
            android:left="10dp"
            android:right="10dp"
            android:top="10dp" />
    </shape>
</item></layer-list>

And use your new xml file in your EditText for example:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/dashed_border"/>

Cheers! :)

SQL Server - Return value after INSERT

* Parameter order in the connection string is sometimes important. * The Provider parameter's location can break the recordset cursor after adding a row. We saw this behavior with the SQLOLEDB provider.

After a row is added, the row fields are not available, UNLESS the Provider is specified as the first parameter in the connection string. When the provider is anywhere in the connection string except as the first parameter, the newly inserted row fields are not available. When we moved the the Provider to the first parameter, the row fields magically appeared.

How to use a RELATIVE path with AuthUserFile in htaccess?

I know this is an old question, but I just searched for the same thing and probably there are many others searching for a quick, mobile solution. Here is what I finally come up with:

# We set production environment by default
SetEnv PROD_ENV 1

<IfDefine DEV_ENV>
  # If 'DEV_ENV' has been defined, then unset the PROD_ENV
  UnsetEnv PROD_ENV

  AuthType Basic
  AuthName "Protected Area"
  AuthUserFile /var/www/foo.local/.htpasswd
  Require valid-user
</IfDefine>

<IfDefine PROD_ENV>
  AuthType Basic
  AuthName "Protected Area"
  AuthUserFile /home/foo/public_html/.htpasswd
  Require valid-user
</IfDefine>

Bootstrap 4 Change Hamburger Toggler Color

One simplest way to encounter this is to use font awesome for example

 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
       <span><i class="fas fa-bars"></i></span>
</button>

Then u can change the i element like you change any other ielement.

Authentication failed to bitbucket

The issue was solved for me after changing the repository password, using no special characters (!"§$%&&).

Obviously, win-credential-store and git and bitbucket's web interface use different character encodings.

complete procedure:

D:\shared\Project> cd /path/to/your/project
D:\shared\Project> git init
D:\shared\Project> git remote add origin https://bitbucket.org/USERNAME/project.git
D:\shared\Project> git-credential-winstore.exe

then

D:\shared\Project> git push
Failed to erase credential: Element not found
fatal: Authentication failed for 'https://bitbucket.org/USERNAME/project.git/'

After changing the passphrase:

D:\shared\Project> git push
Counting objects: 102, done.
Delta compression using up to 8 threads.
... etc. ...

Settings in Windows tresory:

address: git:bitbucket.org (remeber the preceding "git:")
user: USERNAME
pass: old incl!"§§$%&, new without!"§$%%&/( (your passphrase!)

How to send objects through bundle

Figuring out what path to take requires answering not only CommonsWare's key question of "why" but also the question of "to what?" are you passing it.

The reality is that the only thing that can go through bundles is plain data - everything else is based on interpretations of what that data means or points to. You can't literally pass an object, but what you can do is one of three things:

1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles.

2) You can pass an opaque handle. If you are passing it within the same context (though one might ask why bother) that will be a handle you can invoke or dereference. But if you pass it through Binder to a different context it's literal value will be an arbitrary number (in fact, these arbitrary numbers count sequentially from startup). You can't do anything but keep track of it, until you pass it back to the original context which will cause Binder to transform it back into the original handle, making it useful again.

3) You can pass a magic handle, such as a file descriptor or reference to certain os/platform objects, and if you set the right flags Binder will create a clone pointing to the same resource for the recipient, which can actually be used on the other end. But this only works for a very few types of objects.

Most likely, you are either passing your class just so the other end can keep track of it and give it back to you later, or you are passing it to a context where a clone can be created from serialized constituent data... or else you are trying to do something that just isn't going to work and you need to rethink the whole approach.

The EntityManager is closed

I faced the same problem. After looking at several places here is how I dealt with it.

//function in some model/utility
function someFunction($em){
    try{
        //code which may throw exception and lead to closing of entity manager
    }
    catch(Exception $e){
        //handle exception
        return false;
    }
    return true;
}

//in controller assuming entity manager is in $this->em 
$result = someFunction($this->em);
if(!$result){
    $this->getDoctrine()->resetEntityManager();
    $this->em = $this->getDoctrine()->getManager();
}

Hope this helps someone!

Fragments within Fragments

I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.

I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.

I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.

I hope this helps you out.

How can I encode a string to Base64 in Swift?

Swift 4.0.3

import UIKit

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data as Data, encoding: String.Encoding.utf8)
}

func toBase64() -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }

    return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
}

Adding attribute in jQuery

$('#someid').attr('disabled', 'true');

Is there an operator to calculate percentage in Python?

use of %

def percent(expression):
    if "%" in expression:
        expression = expression.replace("%","/100")
    return eval(expression)

>>> percent("1500*20%")
300.0

Somthing simple

>>> p = lambda x: x/100
>>> p(20)
0.2
>>> 100*p(20)
20.0
>>>

Return JsonResult from web api without its properties

I had a similar problem (differences being I wanted to return an object that was already converted to a json string and my controller get returns a IHttpActionResult)

Here is how I solved it. First I declared a utility class

public class RawJsonActionResult : IHttpActionResult
{
    private readonly string _jsonString;

    public RawJsonActionResult(string jsonString)
    {
        _jsonString = jsonString;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = new StringContent(_jsonString);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
        return Task.FromResult(response);
    }
}

This class can then be used in your controller. Here is a simple example

public IHttpActionResult Get()
{
    var jsonString = "{\"id\":1,\"name\":\"a small object\" }";
    return new RawJsonActionResult(jsonString);
}

How to rsync only a specific list of files?

$ date
  Wed 24 Apr 2019 09:54:53 AM PDT
$ rsync --version
  rsync  version 3.1.3  protocol version 31
  ...

Syntax: rsync <file_/_folder_list> <source> <target>

Folder names (here, WITH a trailing /; e.g. Cancer - Evolution/) are in a folder list file (e.g.: cm_folder_list_test):

# /mnt/Vancouver/projects/ie/claws/data/cm_folder_list_test
# test file: 2019-04-24
Cancer/
Cancer - Evolution/
Cancer - Genomic Variants/
Cancer - Metastasis (EMT Transition ...)/
Cancer Pathways, Networks/
Catabolism - Autophagy; Phagosomes; Mitophagy/
Catabolism - Lysosomes/

If you don't include those trailing /, the rsync'd target folders are created, but are empty.

Those folder names are appended to the rest of their path (/home/victoria/Mail/2_RESEARCH - NEWS), thus providing the complete folder path to rsync; e.g.: /home/victoria/Mail/2_RESEARCH - NEWS/Cancer - Evolution/.

Note that you also need to use --files-from= ..., NOT --include-from= ...

rsync -aqP --delete --files-from=/mnt/Vancouver/projects/ie/claws/data/cm_folder_list_test "/home/victoria/Mail/2_RESEARCH - NEWS" $IN/

(In my BASH script, I defined variable $IN as follows.)

BASEDIR="/mnt/Vancouver/projects/ie/claws"
IN=$BASEDIR/data/test/input

rsync options used:

 -a  :   archive: equals -rlptgoD (no -H,-A,-X)
    -r  :   recursive
    -l  :   copy symlinks as symlinks
    -p  :   preserve permissions
    -t  :   preserve modification times 
    -g  :   preserve group 
    -o  :   preserve owner (super-user only) 
    -D  :   same as --devices --specials 
  -q  :   quiet (https://serverfault.com/questions/547106/run-totally-silent-rsync)

  --delete
    This  tells  rsync to delete extraneous files from the RECEIVING SIDE (ones
    that AREN’T ON THE SENDING SIDE), but only for the directories that are
    being synchronized.  You must have asked rsync to send the whole directory
    (e.g.  "dir" or "dir/") without using a wildcard for the directory’s contents
    (e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus
    gets a request to transfer individual files, not the files’ parent directory.
    Files  that  are  excluded  from  the transfer are also excluded from being
    deleted unless you use the --delete-excluded option or mark the rules as
    only matching on the sending side (see the include/exclude modifiers in the
    FILTER RULES section).  ...

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Locate Git installation folder on Mac OS X

Mostly in /usr/local/git (there are also /etc/paths.d/git and /etc/manpaths.d/git items).

What is a wrapper class?

A wrapper class is a class that serves the sole purpose of holding something and adding some functionality to it. In Java since the primitives (like ints,floats,chars...) are not objects so if you want to treat them like one then you have to use a wrapper class. Suppose you want to create a Vector of ints, the problem is a Vector only holds Objects not primitives. So what you will do is put all the ints in an Integer wrapper and use that. Example:

int number = 5;
Integer numberWrapped = new Integer(number);
//now you have the int in an object.
//and this is how to access the int value that is being wrapped.
int again = numberWrapped.intValue();

Embedding DLLs in a compiled executable

The excerpt by Jeffrey Richter is very good. In short, add the library's as embedded resources and add a callback before anything else. Here is a version of the code (found in the comments of his page) that I put at the start of Main method for a console app (just make sure that any calls that use the library's are in a different method to Main).

AppDomain.CurrentDomain.AssemblyResolve += (sender, bargs) =>
        {
            String dllName = new AssemblyName(bargs.Name).Name + ".dll";
            var assem = Assembly.GetExecutingAssembly();
            String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));
            if (resourceName == null) return null; // Not found, maybe another handler will find it
            using (var stream = assem.GetManifestResourceStream(resourceName))
            {
                Byte[] assemblyData = new Byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
        };

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

No, no, NO!

In single threated tasks you don't need to use Iterator, moreover, CopyOnWriteArrayList (due to performance hit).

Solution is much simpler: try to use canonical for loop instead of for-each loop.

According to Java copyright owners (some years ago Sun, now Oracle) for-each loop guide, it uses iterator to walk through collection and just hides it to make code looks better. But, unfortunately as we can see, it produced more problems than profits, otherwise this topic would not arise.

For example, this code will lead to java.util.ConcurrentModificationException when entering next iteration on modified ArrayList:

        // process collection
        for (SomeClass currElement: testList) {

            SomeClass founDuplicate = findDuplicates(currElement);
            if (founDuplicate != null) {
                uniqueTestList.add(founDuplicate);
                testList.remove(testList.indexOf(currElement));
            }
        }

But following code works just fine:

    // process collection
    for (int i = 0; i < testList.size(); i++) {
        SomeClass currElement = testList.get(i);

        SomeClass founDuplicate = findDuplicates(currElement);
        if (founDuplicate != null) {
            uniqueTestList.add(founDuplicate);
            testList.remove(testList.indexOf(currElement));
            i--; //to avoid skipping of shifted element
        }
    }

So, try to use indexing approach for iterating over collections and avoid for-each loop, as they are not equivalent! For-each loop uses some internal iterators, which check collection modification and throw ConcurrentModificationException exception. To confirm this, take a closer look at the printed stack trace when using first example that I've posted:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at TestFail.main(TestFail.java:43)

For multithreading use corresponding multitask approaches (like synchronized keyword).

Convert string to List<string> in one line?

List<string> result = names.Split(new char[] { ',' }).ToList();

Or even cleaner by Dan's suggestion:

List<string> result = names.Split(',').ToList();

Entity Framework - Code First - Can't Store List<String>

I Know this is a old question, and Pawel has given the correct answer, I just wanted to show a code example of how to do some string processing, and avoid an extra class for the list of a primitive type.

public class Test
{
    public Test()
    {
        _strings = new List<string>
        {
            "test",
            "test2",
            "test3",
            "test4"
        };
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    private List<String> _strings { get; set; }

    public List<string> Strings
    {
        get { return _strings; }
        set { _strings = value; }
    }

    [Required]
    public string StringsAsString
    {
        get { return String.Join(',', _strings); }
        set { _strings = value.Split(',').ToList(); }
    }
}

adding to window.onload event?

There are basically two ways

  1. store the previous value of window.onload so your code can call a previous handler if present before or after your code executes

  2. using the addEventListener approach (that of course Microsoft doesn't like and requires you to use another different name).

The second method will give you a bit more safety if another script wants to use window.onload and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.

Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

Pass arguments to Constructor in VBA

I use one Factory module that contains one (or more) constructor per class which calls the Init member of each class.

For example a Point class:

Class Point
Private X, Y
Sub Init(X, Y)
  Me.X = X
  Me.Y = Y
End Sub

A Line class

Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
  If P1 Is Nothing Then
    Set Me.P1 = NewPoint(X1, Y1)
    Set Me.P2 = NewPoint(X2, Y2)
  Else
    Set Me.P1 = P1
    Set Me.P2 = P2
  End If
End Sub

And a Factory module:

Module Factory
Function NewPoint(X, Y)
  Set NewPoint = New Point
  NewPoint.Init X, Y
End Function

Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
  Set NewLine = New Line
  NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function

Function NewLinePt(P1, P2)
  Set NewLinePt = New Line
  NewLinePt.Init P1:=P1, P2:=P2
End Function

Function NewLineXY(X1, Y1, X2, Y2)
  Set NewLineXY = New Line
  NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function

One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:

D = Distance(NewPoint(10, 10), NewPoint(20, 20)

or:

D = NewPoint(10, 10).Distance(NewPoint(20, 20))

It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init call on each creator.

And it's fairly object oriented: the Init functions are defined inside the objects.

EDIT

I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):

NewLine.DeleteAllLinesShorterThan 10

Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The basic concept we have to be clear while approaching this question is to understand the difference between is and ==.

"is" is will compare the memory location. if id(a)==id(b), then a is b returns true else it returns false.

so, we can say that is is used for comparing memory locations. Whereas,

== is used for equality testing which means that it just compares only the resultant values. The below shown code may acts as an example to the above given theory.

code

Click here for the code

In the case of string literals(strings without getting assigned to variables), the memory address will be same as shown in the picture. so, id(a)==id(b). remaining this is self-explanatory.

Detect URLs in text with JavaScript

Here is what I ended up using as my regex:

var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

This doesn't include trailing punctuation in the URL. Crescent's function works like a charm :) so:

function linkify(text) {
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    });
}

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

How to convert a char array back to a string?

 //Given Character Array 
  char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};


    //Converting Character Array to String using String funtion     
    System.out.println(String.valueOf(a));
    //OUTPUT : hello world

Converting any given Array type to String using Java 8 Stream function

String stringValue = 
Arrays.stream(new char[][]{a}).map(String::valueOf).collect(Collectors.joining());

Python object deleting itself

I am trying the same thing. I have a RPG battle system in which my Death(self) function has to kill the own object of the Fighter class. But it appeared it`s not possible. Maybe my class Game in which I collect all participants in the combat should delete units form the "fictional" map???

   def Death(self):
    if self.stats["HP"] <= 0:
        print("%s wounds were too much... Dead!"%(self.player["Name"]))
        del self
    else:
        return True

def Damage(self, enemy):
    todamage = self.stats["ATK"] + randint(1,6)
    todamage -= enemy.stats["DEF"]
    if todamage >=0:
        enemy.stats["HP"] -= todamage
        print("%s took %d damage from your attack!"%(enemy.player["Name"], todamage))
        enemy.Death()
        return True
    else:
        print("Ineffective...")
        return True
def Attack(self, enemy):
    tohit = self.stats["DEX"] + randint(1,6)
    if tohit > enemy.stats["EVA"]:
        print("You landed a successful attack on %s "%(enemy.player["Name"]))
        self.Damage(enemy)
        return True
    else:
        print("Miss!")
        return True
def Action(self, enemylist):
    for i in range(0, len(enemylist)):
        print("No.%d, %r"%(i, enemylist[i]))
    print("It`s your turn, %s. Take action!"%(self.player["Name"]))
    choice = input("\n(A)ttack\n(D)efend\n(S)kill\n(I)tem\n(H)elp\n>")
    if choice == 'a'or choice == 'A':
        who = int(input("Who? "))
        self.Attack(enemylist[who])
        return True
    else:
        return self.Action()

Class not registered Error

I had this problem and I solved it when I understood that it was looking for the Windows Registry specified in the brackets.

Since the error was happening only in one computer, what I had to do was export the registry from the computer that it was working and install it on the computer that was missing it.

Using arrays or std::vectors in C++, what's the performance gap?

Assuming a fixed-length array (e.g. int* v = new int[1000]; vs std::vector<int> v(1000);, with the size of v being kept fixed at 1000), the only performance consideration that really matters (or at least mattered to me when I was in a similar dilemma) is the speed of access to an element. I looked up the STL's vector code, and here is what I found:

const_reference
operator[](size_type __n) const
{ return *(this->_M_impl._M_start + __n); }

This function will most certainly be inlined by the compiler. So, as long as the only thing that you plan to do with v is access its elements with operator[], it seems like there shouldn't really be any difference in performance.

Adding maven nexus repo to my pom.xml

From maven setting reference, you can not put your username/password in a pom.xml

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

You can first add a repository in your pom and then add the username/password in the $MAVEN_HOME/conf/settings.xml:

  <servers>
    <server>
        <id>my-internal-site</id>
        <username>yourUsername</username>
        <password>yourPassword</password>
    </server>
  </servers>

Django Template Variables and Javascript

I use this way in Django 2.1 and work for me and this way is secure (reference):

Django side:

def age(request):
    mydata = {'age':12}
    return render(request, 'test.html', context={"mydata_json": json.dumps(mydata)})

Html side:

<script type='text/javascript'>
     const  mydata = {{ mydata_json|safe }};
console.log(mydata)
 </script>

Where in memory are my variables stored in C?

pointers(ex:char *arr,int *arr) -------> heap

Nope, they can be on the stack or in the data segment. They can point anywhere.

Applying an ellipsis to multiline text

If you also have multiple elements and you want a link with read more button after ellipsis, take a look on https://stackoverflow.com/a/51418807/10104342

If you want something like this:

Every month first 10 TB are are not charged. All other traffic... Read more

How to reverse a singly linked list using only two pointers?

curr = head;
prev = NULL;

while (curr != NULL) {
    next = curr->next; // store current's next, since it will be overwritten
    curr->next = prev;
    prev = curr;
    curr = next;
}

head = prev; // update head

Soft keyboard open and close listener in an activity in Android

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/addresses_confirm_root_view"
android:orientation="vertical">

<---In the xml root use the id--->

final LinearLayout activityRootView = view.findViewById(R.id.addresses_confirm_root_view); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect r = new Rect(); //r will be populated with the coordinates of your view that area still visible. activityRootView.getWindowVisibleDisplayFrame(r);

            int heightDiff = activityRootView.getRootView().getHeight() - r.height();
            if (heightDiff > 0.25 * activityRootView.getRootView().getHeight()) {
                // if more than 25% of the screen, its probably a keyboard...
                onkeyboard();

            } else {
                //Keyboard not visible
                offkeyboard();
            }
        }
    });

Logging best practices


Update: For extensions to System.Diagnostics, providing some of the missing listeners you might want, see Essential.Diagnostics on CodePlex (http://essentialdiagnostics.codeplex.com/)


Frameworks

Q: What frameworks do you use?

A: System.Diagnostics.TraceSource, built in to .NET 2.0.

It provides powerful, flexible, high performance logging for applications, however many developers are not aware of its capabilities and do not make full use of them.

There are some areas where additional functionality is useful, or sometimes the functionality exists but is not well documented, however this does not mean that the entire logging framework (which is designed to be extensible) should be thrown away and completely replaced like some popular alternatives (NLog, log4net, Common.Logging, and even EntLib Logging).

Rather than change the way you add logging statements to your application and re-inventing the wheel, just extended the System.Diagnostics framework in the few places you need it.

It seems to me the other frameworks, even EntLib, simply suffer from Not Invented Here Syndrome, and I think they have wasted time re-inventing the basics that already work perfectly well in System.Diagnostics (such as how you write log statements), rather than filling in the few gaps that exist. In short, don't use them -- they aren't needed.

Features you may not have known:

  • Using the TraceEvent overloads that take a format string and args can help performance as parameters are kept as separate references until after Filter.ShouldTrace() has succeeded. This means no expensive calls to ToString() on parameter values until after the system has confirmed message will actually be logged.
  • The Trace.CorrelationManager allows you to correlate log statements about the same logical operation (see below).
  • VisualBasic.Logging.FileLogTraceListener is good for writing to log files and supports file rotation. Although in the VisualBasic namespace, it can be just as easily used in a C# (or other language) project simply by including the DLL.
  • When using EventLogTraceListener if you call TraceEvent with multiple arguments and with empty or null format string, then the args are passed directly to the EventLog.WriteEntry() if you are using localized message resources.
  • The Service Trace Viewer tool (from WCF) is useful for viewing graphs of activity correlated log files (even if you aren't using WCF). This can really help debug complex issues where multiple threads/activites are involved.
  • Avoid overhead by clearing all listeners (or removing Default); otherwise Default will pass everything to the trace system (and incur all those ToString() overheads).

Areas you might want to look at extending (if needed):

  • Database trace listener
  • Colored console trace listener
  • MSMQ / Email / WMI trace listeners (if needed)
  • Implement a FileSystemWatcher to call Trace.Refresh for dynamic configuration changes

Other Recommendations:

Use structed event id's, and keep a reference list (e.g. document them in an enum).

Having unique event id's for each (significant) event in your system is very useful for correlating and finding specific issues. It is easy to track back to the specific code that logs/uses the event ids, and can make it easy to provide guidance for common errors, e.g. error 5178 means your database connection string is wrong, etc.

Event id's should follow some kind of structure (similar to the Theory of Reply Codes used in email and HTTP), which allows you to treat them by category without knowing specific codes.

e.g. The first digit can detail the general class: 1xxx can be used for 'Start' operations, 2xxx for normal behaviour, 3xxx for activity tracing, 4xxx for warnings, 5xxx for errors, 8xxx for 'Stop' operations, 9xxx for fatal errors, etc.

The second digit can detail the area, e.g. 21xx for database information (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warnings, etc), 23xx for another module, etc.

Assigned, structured event id's also allow you use them in filters.

Q: If you use tracing, do you make use of Trace.Correlation.StartLogicalOperation?

A: Trace.CorrelationManager is very useful for correlating log statements in any sort of multi-threaded environment (which is pretty much anything these days).

You need at least to set the ActivityId once for each logical operation in order to correlate.

Start/Stop and the LogicalOperationStack can then be used for simple stack-based context. For more complex contexts (e.g. asynchronous operations), using TraceTransfer to the new ActivityId (before changing it), allows correlation.

The Service Trace Viewer tool can be useful for viewing activity graphs (even if you aren't using WCF).

Q: Do you write this code manually, or do you use some form of aspect oriented programming to do it? Care to share a code snippet?

A: You may want to create a scope class, e.g. LogicalOperationScope, that (a) sets up the context when created and (b) resets the context when disposed.

This allows you to write code such as the following to automatically wrap operations:

  using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
  {
    // .. do work here
  }

On creation the scope could first set ActivityId if needed, call StartLogicalOperation and then log a TraceEventType.Start message. On Dispose it could log a Stop message, and then call StopLogicalOperation.

Q: Do you provide any form of granularity over trace sources? E.g., WPF TraceSources allow you to configure them at various levels.

A: Yes, multiple Trace Sources are useful / important as systems get larger.

Whilst you probably want to consistently log all Warning & above, or all Information & above messages, for any reasonably sized system the volume of Activity Tracing (Start, Stop, etc) and Verbose logging simply becomes too much.

Rather than having only one switch that turns it all either on or off, it is useful to be able to turn on this information for one section of your system at a time.

This way, you can locate significant problems from the usually logging (all warnings, errors, etc), and then "zoom in" on the sections you want and set them to Activity Tracing or even Debug levels.

The number of trace sources you need depends on your application, e.g. you may want one trace source per assembly or per major section of your application.

If you need even more fine tuned control, add individual boolean switches to turn on/off specific high volume tracing, e.g. raw message dumps. (Or a separate trace source could be used, similar to WCF/WPF).

You might also want to consider separate trace sources for Activity Tracing vs general (other) logging, as it can make it a bit easier to configure filters exactly how you want them.

Note that messages can still be correlated via ActivityId even if different sources are used, so use as many as you need.


Listeners

Q: What log outputs do you use?

This can depend on what type of application you are writing, and what things are being logged. Usually different things go in different places (i.e. multiple outputs).

I generally classify outputs into three groups:

(1) Events - Windows Event Log (and trace files)

e.g. If writing a server/service, then best practice on Windows is to use the Windows Event Log (you don't have a UI to report to).

In this case all Fatal, Error, Warning and (service-level) Information events should go to the Windows Event Log. The Information level should be reserved for these type of high level events, the ones that you want to go in the event log, e.g. "Service Started", "Service Stopped", "Connected to Xyz", and maybe even "Schedule Initiated", "User Logged On", etc.

In some cases you may want to make writing to the event log a built-in part of your application and not via the trace system (i.e. write Event Log entries directly). This means it can't accidentally be turned off. (Note you still also want to note the same event in your trace system so you can correlate).

In contrast, a Windows GUI application would generally report these to the user (although they may also log to the Windows Event Log).

Events may also have related performance counters (e.g. number of errors/sec), and it can be important to co-ordinate any direct writing to the Event Log, performance counters, writing to the trace system and reporting to the user so they occur at the same time.

i.e. If a user sees an error message at a particular time, you should be able to find the same error message in the Windows Event Log, and then the same event with the same timestamp in the trace log (along with other trace details).

(2) Activities - Application Log files or database table (and trace files)

This is the regular activity that a system does, e.g. web page served, stock market trade lodged, order taken, calculation performed, etc.

Activity Tracing (start, stop, etc) is useful here (at the right granuality).

Also, it is very common to use a specific Application Log (sometimes called an Audit Log). Usually this is a database table or an application log file and contains structured data (i.e. a set of fields).

Things can get a bit blurred here depending on your application. A good example might be a web server which writes each request to a web log; similar examples might be a messaging system or calculation system where each operation is logged along with application-specific details.

A not so good example is stock market trades or a sales ordering system. In these systems you are probably already logging the activity as they have important business value, however the principal of correlating them to other actions is still important.

As well as custom application logs, activities also often have related peformance counters, e.g. number of transactions per second.

In generally you should co-ordinate logging of activities across different systems, i.e. write to your application log at the same time as you increase your performance counter and log to your trace system. If you do all at the same time (or straight after each other in the code), then debugging problems is easier (than if they all occur at diffent times/locations in the code).

(3) Debug Trace - Text file, or maybe XML or database.

This is information at Verbose level and lower (e.g. custom boolean switches to turn on/off raw data dumps). This provides the guts or details of what a system is doing at a sub-activity level.

This is the level you want to be able to turn on/off for individual sections of your application (hence the multiple sources). You don't want this stuff cluttering up the Windows Event Log. Sometimes a database is used, but more likely are rolling log files that are purged after a certain time.

A big difference between this information and an Application Log file is that it is unstructured. Whilst an Application Log may have fields for To, From, Amount, etc., Verbose debug traces may be whatever a programmer puts in, e.g. "checking values X={value}, Y=false", or random comments/markers like "Done it, trying again".

One important practice is to make sure things you put in application log files or the Windows Event Log also get logged to the trace system with the same details (e.g. timestamp). This allows you to then correlate the different logs when investigating.

If you are planning to use a particular log viewer because you have complex correlation, e.g. the Service Trace Viewer, then you need to use an appropriate format i.e. XML. Otherwise, a simple text file is usually good enough -- at the lower levels the information is largely unstructured, so you might find dumps of arrays, stack dumps, etc. Provided you can correlated back to more structured logs at higher levels, things should be okay.

Q: If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?

A: For files, generally you want rolling log files from a manageability point of view (with System.Diagnostics simply use VisualBasic.Logging.FileLogTraceListener).

Availability again depends on the system. If you are only talking about files then for a server/service, rolling files can just be accessed when necessary. (Windows Event Log or Database Application Logs would have their own access mechanisms).

If you don't have easy access to the file system, then debug tracing to a database may be easier. [i.e. implement a database TraceListener].

One interesting solution I saw for a Windows GUI application was that it logged very detailed tracing information to a "flight recorder" whilst running and then when you shut it down if it had no problems then it simply deleted the file.

If, however it crashed or encountered a problem then the file was not deleted. Either if it catches the error, or the next time it runs it will notice the file, and then it can take action, e.g. compress it (e.g. 7zip) and email it or otherwise make available.

Many systems these days incorporate automated reporting of failures to a central server (after checking with users, e.g. for privacy reasons).


Viewing

Q: What tools to you use for viewing the logs?

A: If you have multiple logs for different reasons then you will use multiple viewers.

Notepad/vi/Notepad++ or any other text editor is the basic for plain text logs.

If you have complex operations, e.g. activities with transfers, then you would, obviously, use a specialized tool like the Service Trace Viewer. (But if you don't need it, then a text editor is easier).

As I generally log high level information to the Windows Event Log, then it provides a quick way to get an overview, in a structured manner (look for the pretty error/warning icons). You only need to start hunting through text files if there is not enough in the log, although at least the log gives you a starting point. (At this point, making sure your logs have co-ordinated entires becomes useful).

Generally the Windows Event Log also makes these significant events available to monitoring tools like MOM or OpenView.

Others --

If you log to a Database it can be easy to filter and sort informatio (e.g. zoom in on a particular activity id. (With text files you can use Grep/PowerShell or similar to filter on the partiular GUID you want)

MS Excel (or another spreadsheet program). This can be useful for analysing structured or semi-structured information if you can import it with the right delimiters so that different values go in different columns.

When running a service in debug/test I usually host it in a console application for simplicity I find a colored console logger useful (e.g. red for errors, yellow for warnings, etc). You need to implement a custom trace listener.

Note that the framework does not include a colored console logger or a database logger so, right now, you would need to write these if you need them (it's not too hard).

It really annoys me that several frameworks (log4net, EntLib, etc) have wasted time re-inventing the wheel and re-implemented basic logging, filtering, and logging to text files, the Windows Event Log, and XML files, each in their own different way (log statements are different in each); each has then implemented their own version of, for example, a database logger, when most of that already existed and all that was needed was a couple more trace listeners for System.Diagnostics. Talk about a big waste of duplicate effort.

Q: If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?

These things can be turned on/off as needed. I find Trace.axd quite useful for debugging how a server responds to certain things, but it's not generally useful in a heavily used environment or for long term tracing.

Q: What about custom performance counters?

For a professional application, especially a server/service, I expect to see it fully instrumented with both Performance Monitor counters and logging to the Windows Event Log. These are the standard tools in Windows and should be used.

You need to make sure you include installers for the performance counters and event logs that you use; these should be created at installation time (when installing as administrator). When your application is running normally it should not need have administration privileges (and so won't be able to create missing logs).

This is a good reason to practice developing as a non-administrator (have a separate admin account for when you need to install services, etc). If writing to the Event Log, .NET will automatically create a missing log the first time you write to it; if you develop as a non-admin you will catch this early and avoid a nasty surprise when a customer installs your system and then can't use it because they aren't running as administrator.

What does O(log n) mean exactly?

Algorithms in the Divide and Conquer paradigm are of complexity O(logn). One example here, calculate your own power function,

int power(int x, unsigned int y)
{
    int temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
}

from http://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/

How to get xdebug var_dump to show full object/array

Or you can use an alternative:

https://github.com/kint-php/kint

It works with zero set up and has much more features than Xdebug's var_dump anyway. To bypass the nested limit on the fly with Kint, just use

 +d( $variable ); // append `+` to the dump call

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening. The problem resolved for me by stopping IIS by running the command "iisreset -stop"

How to detect a mobile device with JavaScript?

You would detect the requesting browsers user agent string, and then decide based on what it is if it's coming from a mobile browser or not. This device is not perfect, and never will be due to the fact that user agents aren't standardized for mobile devices (at least not to my knowledge).

This site will help you create the code: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm

Example:

You could get the user agent in javascript by doing this:

var uagent = navigator.userAgent.toLowerCase();

And then do the check's in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)

function DetectIphone()
{
   if (uagent.search("iphone") > -1)
      alert('true');
   else
      alert('false');
}

Edit

You'd create a simple HTML page like so:

<html>
    <head>
        <title>Mobile Detection</title>
    </head>
    <body>
        <input type="button" OnClick="DetectIphone()" value="Am I an Iphone?" />
    </body>
</html>
<script>
    function DetectIphone()
    {
       var uagent = navigator.userAgent.toLowerCase();
       if (uagent.search("iphone") > -1)
          alert('true');
       else
          alert('false');
    }
</script>

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

Change jsp on button click

If you wanna do with a button click and not the other way. You can do it by adding location.href to your button. Here is how I'm using

<button class="btn btn-lg btn-primary" id="submit" onclick="location.href ='/dashboard'" >Go To Dashboard</button>

The button above uses bootstrap classes for styling. Without styling, the simplest code would be

<button onclick="location.href ='/dashboard'" >Go To Dashboard</button>

The /dashboard is my JSP page, If you are using extension too then used /dashboard.jsp

How to get just the date part of getdate()?

try this:

select convert (date ,getdate())

or

select CAST (getdate() as DATE)

or

select convert(varchar(10), getdate(),121)

Incorrect syntax near ''

I got this error because I pasted alias columns into a DECLARE statement.

DECLARE @userdata TABLE(
f.TABLE_CATALOG nvarchar(100),
f.TABLE_NAME nvarchar(100),
f.COLUMN_NAME nvarchar(100),
p.COLUMN_NAME nvarchar(100)
)
SELECT * FROM @userdata 

ERROR: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '.'.

DECLARE @userdata TABLE(
f_TABLE_CATALOG nvarchar(100),
f_TABLE_NAME nvarchar(100),
f_COLUMN_NAME nvarchar(100),
p_COLUMN_NAME nvarchar(100)
)
SELECT * FROM @userdata

NO ERROR

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

npm install --global windows-build-tools

just run this command via powershell (right click and run as administrator!)

worked for me..

What do the terms "CPU bound" and "I/O bound" mean?

I/O Bound process:- If most part of the lifetime of a process is spent in i/o state, then the process is a i/o bound process.example:-calculator,internet explorer

CPU Bound process:- If most part of the process life is spent in cpu,then it is cpu bound process.

Is JavaScript a pass-by-reference or pass-by-value language?

Passing arguments to a function in JavaScript is analogous to passing parameters by pointer value in C:

/*
The following C program demonstrates how arguments
to JavaScript functions are passed in a way analogous
to pass-by-pointer-value in C. The original JavaScript
test case by @Shog9 follows with the translation of
the code into C. This should make things clear to
those transitioning from C to JavaScript.

function changeStuff(num, obj1, obj2)
{
    num = num * 10;
    obj1.item = "changed";
    obj2 = {item: "changed"};
}

var num = 10;
var obj1 = {item: "unchanged"};
var obj2 = {item: "unchanged"};
changeStuff(num, obj1, obj2);
console.log(num);
console.log(obj1.item);    
console.log(obj2.item);

This produces the output:

10
changed
unchanged
*/

#include <stdio.h>
#include <stdlib.h>

struct obj {
    char *item;
};

void changeStuff(int *num, struct obj *obj1, struct obj *obj2)
{
    // make pointer point to a new memory location
    // holding the new integer value
    int *old_num = num;
    num = malloc(sizeof(int));
    *num = *old_num * 10;
    // make property of structure pointed to by pointer
    // point to the new value
    obj1->item = "changed";
    // make pointer point to a new memory location
    // holding the new structure value
    obj2 = malloc(sizeof(struct obj));
    obj2->item = "changed";
    free(num); // end of scope
    free(obj2); // end of scope
}

int num = 10;
struct obj obj1 = { "unchanged" };
struct obj obj2 = { "unchanged" };

int main()
{
    // pass pointers by value: the pointers
    // will be copied into the argument list
    // of the called function and the copied
    // pointers will point to the same values
    // as the original pointers
    changeStuff(&num, &obj1, &obj2);
    printf("%d\n", num);
    puts(obj1.item);
    puts(obj2.item);
    return 0;
}

equivalent of vbCrLf in c#

try this:

AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.None);

or

AccountList.Split(new String[]{"\r\n"},System.StringSplitOptions.RemoveEmptyEntries);

How do I set the default font size in Vim?

The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):

set guifont=default
if has('windows')
    "get dpi, strip out utf-16 garbage and new lines
    "system() converts 0x00 to 0x01 for 'platform independence'
    "should return something like 'PixelsPerXLogicalInch=192'
    "get the part from the = to the end of the line (eg '=192') and strip
    "the first character
    "and convert to a number
    let dpi = str2nr(strpart(matchstr(substitute(
        \system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
        \'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
        \'=.*$'), 1))
    if dpi > 100
        set guifont=high_dpi_font
    endif
endif

How do I test a private function or a class that has private methods, fields or inner classes?

Here is my generic function to test private fields:

protected <F> F getPrivateField(String fieldName, Object obj)
    throws NoSuchFieldException, IllegalAccessException {
    Field field =
        obj.getClass().getDeclaredField(fieldName);

    field.setAccessible(true);
    return (F)field.get(obj);
}

Equivalent of Math.Min & Math.Max for Dates?

How about a DateTime extension method?

public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
    return instance > dateTime ? instance : dateTime;
}

Usage:

var maxDate = date1.MaxOf(date2);

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

.NET / C# - Convert char[] to string

char[] characters;
...
string s = new string(characters);

Draw radius around a point in Google map

In spherical geometry shapes are defined by points, lines and angles between those lines. You have only those rudimentary values to work with.

Therefore a circle (in terms of a a shape projected onto a sphere) is something that must be approximated using points. The more points, the more it'll look like a circle.

Having said that, realize that google maps is projecting the earth onto a flat surface (think "unrolling" the earth and stretching+flattening until it looks "square"). And if you have a flat coordinate system you can draw 2D objects on it all you want.

In other words you can draw a scaled vector circle on a google map. The catch is, google maps doesn't give it to you out of the box (they want to stay as close to GIS values as is pragmatically possible). They only give you GPolygon which they want you to use to approximate a circle. However, this guy did it using vml for IE and svg for other browsers (see "SCALED CIRCLES" section).

Now, going back to your question about Google Latitude using a scaled circle image (and this is probably the most useful to you): if you know the radius of your circle will never change (eg it's always 10 miles around some point), then the easiest solution would be to use a GGroundOverlay, which is just an image url + the GLatLngBounds the image represents. The only work you need to do then is cacluate the GLatLngBounds representing your 10 mile radius. Once you have that, the google maps api handles scaling your image as the user zooms in and out.

How to know whether refresh button or browser back button is clicked in Firefox

Use for on refresh event

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload

And

$(window).unload(function() {
      alert('Handler for .unload() called.');
});

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

In your case here is a implementation using directions service.

function displayRoute() {

    var start = new google.maps.LatLng(28.694004, 77.110291);
    var end = new google.maps.LatLng(28.72082, 77.107241);

    var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
    directionsDisplay.setMap(map); // map should be already initialized.

    var request = {
        origin : start,
        destination : end,
        travelMode : google.maps.TravelMode.DRIVING
    };
    var directionsService = new google.maps.DirectionsService(); 
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

Disable Transaction Log

You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.

You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.

ALTER DATABASE MyDB SET RECOVERY SIMPLE;

can't access mysql from command line mac

I've tried all the solutions from the answers but couldn't get mysql command to work from the terminal, always getting the message

bash: command not found

The solution is to change the .bash_profile, and add the mysql path to .bash_profile

To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using

nano .bash_profile

3. Add the following command to add the mysql path

PATH="/usr/local/mysql/bin:${PATH}"
export PATH

4. Press Ctrl+X, then press y and press enter.

The following is how my .bash_profile looks like enter image description here

How to know/change current directory in Python shell?

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

How to dynamically create CSS class in JavaScript and apply?

YUI has by far the best stylesheet utility I have seen out there. I encourage you to check it out, but here's a taste:

// style element or locally sourced link element
var sheet = YAHOO.util.StyleSheet(YAHOO.util.Selector.query('style',null,true));

sheet = YAHOO.util.StyleSheet(YAHOO.util.Dom.get('local'));


// OR the id of a style element or locally sourced link element
sheet = YAHOO.util.StyleSheet('local');


// OR string of css text
var css = ".moduleX .alert { background: #fcc; font-weight: bold; } " +
          ".moduleX .warn  { background: #eec; } " +
          ".hide_messages .moduleX .alert, " +
          ".hide_messages .moduleX .warn { display: none; }";

sheet = new YAHOO.util.StyleSheet(css);

There are obviously other much simpler ways of changing styles on the fly such as those suggested here. If they make sense for your problem, they might be best, but there are definitely reasons why modifying css is a better solution. The most obvious case is when you need to modify a large number of elements. The other major case is if you need your style changes to involve the cascade. Using the dom to modify an element will always have a higher priority. Its the sledgehammer approach and is equivalent to using the style attribute directly on the html element. That is not always the desired effect.

What is the difference between int, Int16, Int32 and Int64?

According to Jeffrey Richter(one of the contributors of .NET framework development)'s book 'CLR via C#':

int is a primitive type allowed by the C# compiler, whereas Int32 is the Framework Class Library type (available across languages that abide by CLS). In fact, int translates to Int32 during compilation.

Also,

In C#, long maps to System.Int64, but in a different programming language, long could map to Int16 or Int32. In fact, C++/CLI does treat long as Int32.

In fact, most (.NET) languages won't even treat long as a keyword and won't compile code that uses it.

I have seen this author, and many standard literature on .NET preferring FCL types(i.e., Int32) to the language-specific primitive types(i.e., int), mainly on such interoperability concerns.

How to extract numbers from a string in Python?

This is more than a bit late, but you can extend the regex expression to account for scientific notation too.

import re

# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

Gives all good!

Additionally, you can look at the AWS Glue built-in regex

What are all the differences between src and data-src attributes?

data-src attribute is part of the data-* attributes collection introduced in HTML5. data-src allow us to store extra data that have no meaning to the browser but that can be use by Javascript Code or CSS rules.

WebView link click open default browser

you can use Intent for this:

Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

CSS, Images, JS not loading in IIS

I had this same problem. For me, it was due to Cache-Control header being set at the server level in IIS to no-cache, no-store. So for my application I had to add in the below to my web.config:

<httpProtocol>
    <customHeaders>
        <remove name="Cache-Control" />
    </customHeaders>
</httpProtocol>

"Correct" way to specifiy optional arguments in R functions

To be honest I like the OP's first way of actually starting it with a NULL value and then checking it with is.null (primarily because it is very simply and easy to understand). It maybe depends on the way people are used to coding but the Hadley seems to support the is.null way too:

From Hadley's book "Advanced-R" Chapter 6, Functions, p.84 (for the online version check here):

You can determine if an argument was supplied or not with the missing() function.

i <- function(a, b) {
  c(missing(a), missing(b))
}
i()
#> [1] TRUE TRUE
i(a = 1)
#> [1] FALSE  TRUE
i(b = 2)
#> [1]  TRUE FALSE
i(1, 2)
#> [1] FALSE FALSE

Sometimes you want to add a non-trivial default value, which might take several lines of code to compute. Instead of inserting that code in the function definition, you could use missing() to conditionally compute it if needed. However, this makes it hard to know which arguments are required and which are optional without carefully reading the documentation. Instead, I usually set the default value to NULL and use is.null() to check if the argument was supplied.

mysqldump data only

Try to dump to a delimited file.

mysqldump -u [username] -p -t -T/path/to/directory [database] --fields-enclosed-by=\" --fields-terminated-by=,

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

How to avoid 'undefined index' errors?

You can use isset() without losing the concatenation:

//snip
$str = 'something'
 . ( isset($output['alternate_title']) ? $output['alternate_title'] : '' )
 . ( isset($output['access_info']) ? $output['access_info'] : '' )
 . //etc.

You could also write a function to return the string if it is set - this probably isn't very efficient:

function getIfSet(& $var) {
    if (isset($var)) {
        return $var;
    }
    return null;
}

$str = getIfSet($output['alternate_title']) . getIfSet($output['access_info']) //etc

You won't get a notice because the variable is passed by reference.

JavaScript closures vs. anonymous functions

According to the closure definition:

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

You are using closure if you define a function which use a variable which is defined outside of the function. (we call the variable a free variable).
They all use closure(even in the 1st example).

css ellipsis on second line

If anyone is trying to get line-clamp to work in flexbox, it's slightly trickier - especially once you are torture testing with really long words. The only real differences in this code snippet are min-width: 0; in the flex item containing truncated text, and word-wrap: break-word;. A hat-tip to https://css-tricks.com/flexbox-truncated-text/ for the insight. Disclaimer: this is still webkit only as far as I know.

_x000D_
_x000D_
.flex-parent {
  display: flex;
}

.short-and-fixed {
  width: 30px;
  height: 30px;
  background: lightgreen;
}

.long-and-truncated {
  margin: 0 20px;
  flex: 1;
  min-width: 0;/* Important for long words! */
}

.long-and-truncated span {
  display: inline;
  -webkit-line-clamp: 3;
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  word-wrap: break-word;/* Important for long words! */
}
_x000D_
<div class="flex-parent">
  <div class="flex-child short-and-fixed">
  </div>
  <div class="flex-child long-and-truncated">
    <span>asdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasd</span>
  </div>
  <div class="flex-child short-and-fixed">
  </div>
</div>
_x000D_
_x000D_
_x000D_

http://codepen.io/AlgeoMA/pen/JNvJdx (codepen version)

Java executors: how to be notified, without blocking, when a task completes?

Simple code to implement Callback mechanism using ExecutorService

import java.util.concurrent.*;
import java.util.*;

public class CallBackDemo{
    public CallBackDemo(){
        System.out.println("creating service");
        ExecutorService service = Executors.newFixedThreadPool(5);

        try{
            for ( int i=0; i<5; i++){
                Callback callback = new Callback(i+1);
                MyCallable myCallable = new MyCallable((long)i+1,callback);
                Future<Long> future = service.submit(myCallable);
                //System.out.println("future status:"+future.get()+":"+future.isDone());
            }
        }catch(Exception err){
            err.printStackTrace();
        }
        service.shutdown();
    }
    public static void main(String args[]){
        CallBackDemo demo = new CallBackDemo();
    }
}
class MyCallable implements Callable<Long>{
    Long id = 0L;
    Callback callback;
    public MyCallable(Long val,Callback obj){
        this.id = val;
        this.callback = obj;
    }
    public Long call(){
        //Add your business logic
        System.out.println("Callable:"+id+":"+Thread.currentThread().getName());
        callback.callbackMethod();
        return id;
    }
}
class Callback {
    private int i;
    public Callback(int i){
        this.i = i;
    }
    public void callbackMethod(){
        System.out.println("Call back:"+i);
        // Add your business logic
    }
}

output:

creating service
Callable:1:pool-1-thread-1
Call back:1
Callable:3:pool-1-thread-3
Callable:2:pool-1-thread-2
Call back:2
Callable:5:pool-1-thread-5
Call back:5
Call back:3
Callable:4:pool-1-thread-4
Call back:4

Key notes:

  1. If you want process tasks in sequence in FIFO order, replace newFixedThreadPool(5) with newFixedThreadPool(1)
  2. If you want to process next task after analysing the result from callback of previous task,just un-comment below line

    //System.out.println("future status:"+future.get()+":"+future.isDone());
    
  3. You can replace newFixedThreadPool() with one of

    Executors.newCachedThreadPool()
    Executors.newWorkStealingPool()
    ThreadPoolExecutor
    

    depending on your use case.

  4. If you want to handle callback method asynchronously

    a. Pass a shared ExecutorService or ThreadPoolExecutor to Callable task

    b. Convert your Callable method to Callable/Runnable task

    c. Push callback task to ExecutorService or ThreadPoolExecutor

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I have Visual Studio Team System 2008 Development Edition, and had to remove all updates and Hotfixes:

  • Update KB972221
  • Hotfix KB973674
  • Hotfix KB971091

Reboot, then the following Hotfix appeared, which I then removed as per @riaraos' answer:

  • Hotfix KB952241

Before the Change/Remove would work!

Hope that helps someone else.

nginx upload client_max_body_size issue

Does your upload die at the very end? 99% before crashing? Client body and buffers are key because nginx must buffer incoming data. The body configs (data of the request body) specify how nginx handles the bulk flow of binary data from multi-part-form clients into your app's logic.

The clean setting frees up memory and consumption limits by instructing nginx to store incoming buffer in a file and then clean this file later from disk by deleting it.

Set body_in_file_only to clean and adjust buffers for the client_max_body_size. The original question's config already had sendfile on, increase timeouts too. I use the settings below to fix this, appropriate across your local config, server, & http contexts.

client_body_in_file_only clean;
client_body_buffer_size 32K;

client_max_body_size 300M;

sendfile on;
send_timeout 300s;

Combine Date and Time columns using python pandas

Use the combine function:

datetime.datetime.combine(date, time)

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

Formula to determine brightness of RGB color

The HSV colorspace should do the trick, see the wikipedia article depending on the language you're working in you may get a library conversion .

H is hue which is a numerical value for the color (i.e. red, green...)

S is the saturation of the color, i.e. how 'intense' it is

V is the 'brightness' of the color.

Declaring a python function with an array parameters and passing an array argument to the function call?

Maybe you want unpack elements of array, I don't know if I got it, but below a example:

def my_func(*args):
    for a in args:
        print a

my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)

How do I write a Windows batch script to copy the newest file from a directory?

To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:

FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY "%%I" <<NewDir>> & GOTO :END
:END

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

.NET HttpClient. How to POST string value?

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

Sorting A ListView By Column

If you are starting out with a ListView, do yourself a huge favour and use an ObjectListView instead. ObjectListView is an open source wrapper around .NET WinForms ListView, which makes the ListView much easier to use and solves lots of common problems for you. Sorting by column click is one of the many things it handles for you automatically.

Seriously, you will never regret using an ObjectListView instead of a normal ListView.

How to draw a filled triangle in android canvas?

you can also use vertice :

private static final int verticesColors[] = {
    Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0xFF000000, 0xFF000000, 0xFF000000
};
float verts[] = {
    point1.x, point1.y, point2.x, point2.y, point3.x, point3.y
};
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, verts.length, verts, 0, null, 0, verticesColors,   0, null, 0, 0, new Paint());

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

We could call startActivityForResult() directly from Fragment So You should call this.startActivityForResult(i, 1); instead of getActivity().startActivityForResult(i, 1);

Intent i = new Intent(getActivity(), SecondActivity.class);
i.putExtra("helloString", helloString);
this.startActivityForResult(i, 1);

Activity will send the Activity Result to your Fragment.

How do I get the full path to a Perl script that is executing?

Are you looking for this?:

my $thisfile = $1 if $0 =~
/\\([^\\]*)$|\/([^\/]*)$/;

print "You are running $thisfile
now.\n";

The output will look like this:

You are running MyFileName.pl now.

It works on both Windows and Unix.

How do you enable auto-complete functionality in Visual Studio C++ express edition?

Start writing, then just press CTRL+SPACE and there you go ...

Oracle Differences between NVL and Coalesce

Though this one is obvious, and even mentioned in a way put up by Tom who asked this question. But lets put up again.

NVL can have only 2 arguments. Coalesce may have more than 2.

select nvl('','',1) from dual; //Result: ORA-00909: invalid number of arguments
select coalesce('','','1') from dual; //Output: returns 1

How do I send a POST request as a JSON?

Here is an example of how to use urllib.request object from Python standard library.

import urllib.request
import json
from pprint import pprint

url = "https://app.close.com/hackwithus/3d63efa04a08a9e0/"

values = {
    "first_name": "Vlad",
    "last_name": "Bezden",
    "urls": [
        "https://twitter.com/VladBezden",
        "https://github.com/vlad-bezden",
    ],
}


headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
}

data = json.dumps(values).encode("utf-8")
pprint(data)

try:
    req = urllib.request.Request(url, data, headers)
    with urllib.request.urlopen(req) as f:
        res = f.read()
    pprint(res.decode())
except Exception as e:
    pprint(e)

Actionbar notification count icon (badge) like Google has

I don't like ActionView based solutions, my idea is:

  1. create a layout with TextView, that TextView will be populated by application
  2. when you need to draw a MenuItem:

    2.1. inflate layout

    2.2. call measure() & layout() (otherwise view will be 0px x 0px, it's too small for most use cases)

    2.3. set the TextView's text

    2.4. make "screenshot" of the view

    2.6. set MenuItem's icon based on bitmap created on 2.4

  3. profit!

so, result should be something like enter image description here

  1. create layout here is a simple example
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/counterPanel"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:background="@drawable/ic_menu_gallery">
    <RelativeLayout
        android:id="@+id/counterValuePanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/counterBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/unread_background" />

        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:textSize="8sp"
            android:layout_centerInParent="true"
            android:textColor="#FFFFFF" />
    </RelativeLayout>
</FrameLayout>

@drawable/unread_background is that green TextView's background, @drawable/ic_menu_gallery is not really required here, it's just to preview layout's result in IDE.

  1. add code into onCreateOptionsMenu/onPrepareOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
    
        MenuItem menuItem = menu.findItem(R.id.testAction);
        menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
    
        return true;
    }
    
  2. Implement build-the-icon method:

    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
        view.setBackgroundResource(backgroundImageId);
    
        if (count == 0) {
            View counterTextPanel = view.findViewById(R.id.counterValuePanel);
            counterTextPanel.setVisibility(View.GONE);
        } else {
            TextView textView = (TextView) view.findViewById(R.id.count);
            textView.setText("" + count);
        }
    
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
    
        return new BitmapDrawable(getResources(), bitmap);
    }
    

The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter

MongoDB: How to update multiple documents with a single command?

Thanks for sharing this, I used with 2.6.7 and following query just worked,

for all docs:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})

for single doc:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})

How to clone ArrayList and also clone its contents?

Basically there are three ways without iterating manually,

1 Using constructor

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);

2 Using addAll(Collection<? extends E> c)

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(dogs);

3 Using addAll(int index, Collection<? extends E> c) method with int parameter

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(0, dogs);

NB : The behavior of these operations will be undefined if the specified collection is modified while the operation is in progress.

How to use font-awesome icons from node-modules

With expressjs, public it:

app.use('/stylesheets/fontawesome', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/'));

And you can see it at: yourdomain.com/stylesheets/fontawesome/css/all.min.css

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';

Include this on your api's header, it may vary depending on how you are displaying json data,

if your using ajax, to retrieve and display data your header would look like this,

$.ajax({
   url: '',
   headers: {  'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
   data: data,
   type: 'dataType',
   /* etc */
   success: function(jsondata){

   }
})

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

How can I create my own comparator for a map?

Since C++11, you can also use a lambda expression instead of defining a comparator struct:

auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);

my_map["1"]      = "a";
my_map["three"]  = "b";
my_map["two"]    = "c";
my_map["fouuur"] = "d";

for(auto const &kv : my_map)
    cout << kv.first << endl;

Output:

1
two
three
fouuur

I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.

Code on Ideone

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

How to update (append to) an href in jquery?

$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

Difference between array_map, array_walk and array_filter

The following revision seeks to more clearly delineate PHP's array_filer(), array_map(), and array_walk(), all of which originate from functional programming:

array_filter() filters out data, producing as a result a new array holding only the desired items of the former array, as follows:

<?php
$array = array(1, "apples",2, "oranges",3, "plums");

$filtered = array_filter( $array, "ctype_alpha");
var_dump($filtered);
?>

live code here

All numeric values are filtered out of $array, leaving $filtered with only types of fruit.

array_map() also creates a new array but unlike array_filter() the resulting array contains every element of the input $filtered but with altered values, owing to applying a callback to each element, as follows:

<?php

$nu = array_map( "strtoupper", $filtered);
var_dump($nu);
?>

live code here

The code in this case applies a callback using the built-in strtoupper() but a user-defined function is another viable option, too. The callback applies to every item of $filtered and thereby engenders $nu whose elements contain uppercase values.

In the next snippet, array walk() traverses $nu and makes changes to each element vis a vis the reference operator '&'. The changes occur without creating an additional array. Every element's value changes in place into a more informative string specifying its key, category and value.

<?php

$f = function(&$item,$key,$prefix) {
    $item = "$key: $prefix: $item";
}; 
array_walk($nu, $f,"fruit");
var_dump($nu);    
?>    

See demo

Note: the callback function with respect to array_walk() takes two parameters which will automatically acquire an element's value and its key and in that order, too when invoked by array_walk(). (See more here).

How to fire a button click event from JavaScript in ASP.NET

$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");

Force GUI update from UI Thread

If you only need to update a couple controls, .update() is sufficient.

btnMyButton.BackColor=Color.Green; // it eventually turned green, after a delay
btnMyButton.Update(); // after I added this, it turned green quickly

Dynamically converting java object of Object class to a given class when class name is known

You don't have to convert the object to a MyClass object because it already is. Wnat you really want to do is to cast it, but since the class name is not known at compile time, you can't do that, since you can't declare a variable of that class. My guess is that you want/need something like "duck typing", i.e. you don't know the class name but you know the method name at compile time. Interfaces, as proposed by Gregory, are your best bet to do that.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Actually you don't have to deal with the static metamodel if you had your annotations right.

With the following entities :

@Entity
public class Pet {
  @Id
  protected Long id;
  protected String name;
  protected String color;
  @ManyToOne
  protected Set<Owner> owners;
}

@Entity
public class Owner {
  @Id
  protected Long id;
  protected String name;
}

You can use this :

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> petMetaModel = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(petMetaModel.getSet("owners", Owner.class));

How to copy a file to multiple directories using the gnu cp command

If you need to be specific on into which folders to copy the file you can combine find with one or more greps. For example to replace any occurences of favicon.ico in any subfolder you can use:

find . | grep favicon\.ico | xargs -n 1 cp -f /root/favicon.ico

How do I post form data with fetch api?

To add on the good answers above you can also avoid setting explicitly the action in HTML and use an event handler in javascript, using "this" as the form to create the "FormData" object

Html form :

<form id="mainForm" class="" novalidate>
<!--Whatever here...-->
</form>

In your JS :

$("#mainForm").submit(function( event ) {
  event.preventDefault();
  const formData = new URLSearchParams(new FormData(this));
  fetch("http://localhost:8080/your/server",
    {   method: 'POST',
        mode : 'same-origin',
        credentials: 'same-origin' ,
        body : formData
    })
    .then(function(response) {
      return response.text()
    }).then(function(text) {
        //text is the server's response
    });
});

jquery ajax function not working

I was having this issue and none of these answers were able to help me with the issue. For anyone else who happens to have the same problem, here is a possible solution that worked for me. Simply reformat the code to be the following:

$("#postcontent").submit(function(e) {
  $.ajax({
    type:"POST",
    url:"add_new_post.php",
    data:$("#postcontent").serialize(),
    beforeSend:function(){
      $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
    },
    success (response) {   
      //alert(response);
      $("#return_update_msg").html(response); 
      $(".post_submitting").fadeOut(1000);                
    },
    error (data) {
      // handle the error
    }
  });
});

The difference in the code is that this code has an error handler. You can choose to handle the error however you wish but it is best practice to have the error handler in case of an exception. Also, the formatting of the success and error functions within the ajax function are different. This is the only format for success/error that would work for me. Hope it helps!

How to set password for Redis?

To set the password, edit your redis.conf file, find this line

# requirepass foobared

Then uncomment it and change foobared to your password. Make sure you choose something pretty long, 32 characters or so would probably be good, it's easy for an outside user to guess upwards of 150k passwords a second, as the notes in the config file mention.

To authenticate with your new password using predis, the syntax you have shown is correct. Just add password as one of the connection parameters.

To shut down redis... check in your config file for the pidfile setting, it will probably be

pidfile /var/run/redis.pid

From the command line, run:

cat /var/run/redis.pid

That will give you the process id of the running server, then just kill the process using that pid:

kill 3832

Update

I also wanted to add, you could also make the /etc/init.d/redis-server stop you're used to work on your live server. All those files in /etc/init.d/ are just shell scripts, take the redis-server script off your local server, and copy it to the live server in the same location, and then just look what it does with vi or whatever you like to use, you may need to modify some paths and such, but it should be pretty simple.

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
        if(bitmap!=null){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }

How to force JS to do math instead of putting two strings together

You can add + behind the variable and it will force it to be an integer

var dots = 5
    function increase(){
        dots = +dots + 5;
    }

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

fast way to copy formatting in excel

Does:

Set Sheets("Output").Range("$A$1:$A$500") =  Sheets(sheet_).Range("$A$1:$A$500")

...work? (I don't have Excel in front of me, so can't test.)

How do I use a Boolean in Python?

Yes, there is a bool data type (which inherits from int and has only two values: True and False).

But also Python has the boolean-able concept for every object, which is used when function bool([x]) is called.

See more: object.nonzero and boolean-value-of-objects-in-python.

What to do with "Unexpected indent" in python?

This error can also occur when pasting something into the Python interpreter (terminal/console).

Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like

def my_function():
    x = 3

    y = 7

the interpreter will interpret the empty line before y = 7 as the end of the expression, i.e. that you're done defining your function, and the next line - y = 7 will have incorrect indentation because it is a new expression.

Why use def main()?

Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.

How can I group by date time column without taking time into consideration

Here is the example works fine in oracle

select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

How to get the first element of the List or Set?

You can use the get(index) method to access an element from a List.

Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.

How can I select the row with the highest ID in MySQL?

SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;

This would return all rows with highest id, in case id column is not constrained to be unique.

Spark DataFrame groupBy and sort in the descending order (pyspark)

Use orderBy:

df.orderBy('column_name', ascending=False)

Complete answer:

group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)

http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html

Why is it important to override GetHashCode when Equals method is overridden?

It's actually very hard to implement GetHashCode() correctly because, in addition to the rules Marc already mentioned, the hash code should not change during the lifetime of an object. Therefore the fields which are used to calculate the hash code must be immutable.

I finally found a solution to this problem when I was working with NHibernate. My approach is to calculate the hash code from the ID of the object. The ID can only be set though the constructor so if you want to change the ID, which is very unlikely, you have to create a new object which has a new ID and therefore a new hash code. This approach works best with GUIDs because you can provide a parameterless constructor which randomly generates an ID.

Changing Vim indentation behavior by file type

Use ftplugins or autocommands to set options.

ftplugin

In ~/.vim/ftplugin/python.vim:

setlocal shiftwidth=2 softtabstop=2 expandtab

And don't forget to turn them on in ~/.vimrc:

filetype plugin indent on

(:h ftplugin for more information)

autocommand

In ~/.vimrc:

autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab

You can replace any of the long commands or settings with their short versions:
autocmd: au
setlocal: setl
shiftwidth: sw
tabstop: ts
softtabstop: sts
expandtab: et

I would also suggest learning the difference between tabstop and softtabstop. A lot of people don't know about softtabstop.

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.