Programs & Examples On #Adornerdecorator

"unary operator expected" error in Bash if condition

Try assigning a value to $aug1 before use it in if[] statements; the error message will disappear afterwards.

Get number days in a specified month using JavaScript?

// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number 
// so it returns the correct amount of days
function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}

// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29

Create two threads, one display odd & other even numbers

package javaapplication45;

public class JavaApplication45 extends Thread {

    public static void main(String[] args) {
        //even numbers
        Thread t1 = new Thread() {
            public void run() {
                for (int i = 1; i <= 20; i++) {
                    if (i % 2 == 0) {
                        System.out.println("even thread " + i);
                    }
                }
            }
        };
        t1.start();
        //odd numbers
        Thread t2 = new Thread() {
            public void run() {
                for (int i = 1; i <= 20; i++) {
                    if (i % 2 != 0) {
                        System.out.println("odd thread " + i);
                    }
                }
            }
        };
        t2.start();

    }

}

Good tutorial for using HTML5 History API (Pushstate?)

You could try Davis.js, it gives you routing in your JavaScript using pushState when available and without JavaScript it allows your server side code to handle the requests.

Mailto links do nothing in Chrome but work in Firefox?

Another solution is to implement your own custom popup/form/user control that will be universally interpreted across all browsers.

Granted this will not leverage the "mailto" out of the box capabilities. It all depends on what availability adherence you are working against. Unfortunately for myself - the mailto needed to be available to everyone by default without "inconveniencing the client".

Your decision ultimately.

how to change a selections options based on another select option selected?

as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well. put the following below your body tag

<script>
$('#mainCat').on('change', function() {
    let selected = $(this).val();
    $("#expertCat option").each(function(){
        let element =  $(this) ;
        if (element.data("tag") != selected){
            element.removeClass('visible');
            element.addClass('hidden');
            element.hide() ;
        }else{
            element.removeClass('hidden');
            element.addClass('visible');
            element.show();
        }
    });
    let expertCat = $('#expertCat');
    expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

There are some processes left in the background on that port, several reasons can cause this problem, but you can solve easily if you end process which is related to 8080 or Spring.

If you are using Linux there is steps how to end process:

  1. Open terminal and type command "htop"
  2. press key F3(it will allow you to search)
  3. Type "8080" if there was no result on 8080 after that try "spring"
  4. Then Press F9(KILL) And press "9"(SIGKILL)

this will kill process which is left on 8080 port and let you run application.

View more than one project/solution in Visual Studio

Two ways come to mind...

  1. Open another visual studio window and open the second solution in it.

  2. It would be preferable to add your existing projects to one solution, just right click and add existing project and navigate to the project file(csproj). .... e.g. C:\Users\User\Documents\Visual Studio 2012\Projects\MySqlWindowsFormsApplication1\MySql Windows Forms Project1\MySql Windows Forms Project1.csproj ....In this second way you might want to setup multiple start up projects i.e. for people with client-server apps or apps with dependencies. ....To do this Select the solution then GoTo: Project>>Properties>>Startup Project>> Select Multiple Startup projects and set actions to Start. When you debug, the selected as start will run.

  3. For interest sake you could open another multiple solution windows to view different projects at the same time. http://www.schwammysays.net/visual-studio-2012-tip-multiple-solution-explorers/

How to append in a json file in Python?

You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

How to terminate a window in tmux?

<Prefix> & for killing a window

<Prefix> x for killing a pane

If there is only one pane (i.e. the window is not split into multiple panes, <Prefix> x would kill the window)

As always iterated, <Prefix> is generally CTRL+b. (I think for beginner questions, we can just say CTRL+b all the time, and not talk about prefix at all, but anyway :) )

How to convert an array to object in PHP?

In the simplest case, it's probably sufficient to "cast" the array as an object:

$object = (object) $array;

Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:

$object = new stdClass();
foreach ($array as $key => $value)
{
    $object->$key = $value;
}

As Edson Medina pointed out, a really clean solution is to use the built-in json_ functions:

$object = json_decode(json_encode($array), FALSE);

This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.

Warning! (thanks to Ultra for the comment):

json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL

How can I select an element in a component template?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor:

constructor(private myElement: ElementRef) { ... }

Docs: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html

Adding elements to an xml file in C#

You're close, but you want name to be an XAttribute rather than XElement:

 XDocument doc = XDocument.Load(spath); 
 XElement root = new XElement("Snippet"); 
 root.Add(new XAttribute("name", "name goes here")); 
 root.Add(new XElement("SnippetCode", "SnippetCode")); 
 doc.Element("Snippets").Add(root); 
 doc.Save(spath); 

Can two Java methods have same name with different return types?

The java documentation states:

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

See: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

How to remove "Server name" items from history of SQL Server Management Studio

File SqlStudio.bin actually contains binary serialized data of type "Microsoft.SqlServer.Management.UserSettings.SqlStudio".

Using BinaryFormatter class you can write simple .NET application in order to edit file content.

What is the Linux equivalent to DOS pause?

This function works in both bash and zsh, and ensures I/O to the terminal:

# Prompt for a keypress to continue. Customise prompt with $*
function pause {
  >/dev/tty printf '%s' "${*:-Press any key to continue... }"
  [[ $ZSH_VERSION ]] && read -krs  # Use -u0 to read from STDIN
  [[ $BASH_VERSION ]] && </dev/tty read -rsn1
  printf '\n'
}
export_function pause

Put it in your .{ba,z}shrc for Great Justice!

Use async await with Array.map

If you map to an array of Promises, you can then resolve them all to an array of numbers. See Promise.all.

Writing Unicode text to a text file?

The file opened by codecs.open is a file that takes unicode data, encodes it in iso-8859-1 and writes it to the file. However, what you try to write isn't unicode; you take unicode and encode it in iso-8859-1 yourself. That's what the unicode.encode method does, and the result of encoding a unicode string is a bytestring (a str type.)

You should either use normal open() and encode the unicode yourself, or (usually a better idea) use codecs.open() and not encode the data yourself.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Avoid using Xcode to rename files in a folder reference. If you rename a file using Xcode, it will be marked for commit. If you later delete it before the commit, you will end up with this error.

Adding Table rows Dynamically in Android

You shouldn't be using an item defined in the Layout XML in order to create more instances of it. You should either create it in a separate XML and inflate it or create the TableRow programmaticaly. If creating them programmaticaly, should be something like this:

    public void init(){
    TableLayout ll = (TableLayout) findViewById(R.id.displayLinear);


    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        checkBox = new CheckBox(this);
        tv = new TextView(this);
        addBtn = new ImageButton(this);
        addBtn.setImageResource(R.drawable.add);
        minusBtn = new ImageButton(this);
        minusBtn.setImageResource(R.drawable.minus);
        qty = new TextView(this);
        checkBox.setText("hello");
        qty.setText("10");
        row.addView(checkBox);
        row.addView(minusBtn);
        row.addView(qty);
        row.addView(addBtn);
        ll.addView(row,i);
    }
}

PHP How to find the time elapsed since a date time?

Wrote my own

function getElapsedTime($eventTime)
{
    $totaldelay = time() - strtotime($eventTime);
    if($totaldelay <= 0)
    {
        return '';
    }
    else
    {
        if($days=floor($totaldelay/86400))
        {
            $totaldelay = $totaldelay % 86400;
            return $days.' days ago.';
        }
        if($hours=floor($totaldelay/3600))
        {
            $totaldelay = $totaldelay % 3600;
            return $hours.' hours ago.';
        }
        if($minutes=floor($totaldelay/60))
        {
            $totaldelay = $totaldelay % 60;
            return $minutes.' minutes ago.';
        }
        if($seconds=floor($totaldelay/1))
        {
            $totaldelay = $totaldelay % 1;
            return $seconds.' seconds ago.';
        }
    }
}

Expression must be a modifiable lvalue

The assignment operator has lower precedence than &&, so your condition is equivalent to:

if ((match == 0 && k) = m)

But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the sub­expression match == 0 && k, so you cannot assign to it.

By contrast, comparison has higher precedence, so match == 0 && k == m is equivalent to:

if ((match == 0) && (k == m))

How do I get the last four characters from a string in C#?

mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;

How to call javascript from a href?

JavaScript code is usually called from the onclick event of a link. For example, you could instead do:

In Head Section of HTML Document

<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>

In Body of HTML Document

<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>

Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery.

For example:

In Head Section of HTML Document

<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>

In Body of HTML Document

<a href="#" id="mylink">Call JavaScript </a>

ThreeJS: Remove object from scene

You can use this

function removeEntity(object) {
    var scene = document.querySelectorAll("scene");                               //clear the objects from the scene
    for (var i = 0; i < scene.length; i++) {                                    //loop through to get all object in the scene
    var scene =document.getElementById("scene");                                  
    scene.removeChild(scene.childNodes[0]);                                        //remove all specified objects
  }   

Random number c++ in some range

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}

How to set value to variable using 'execute' in t-sql?

The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised

You'll have to use a temp table/table variable outside of the dynamic SQL:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)

INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')  

select * FROM @siteId

Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

Recently I came across the same issue. I was able to ssh to my pi on my network, but not from outside my home network.

I had already:

  • installed and tested ssh on my home network.
  • Set a static IP for my pi.
  • Set up a Dynamic DNS service and installed the software on my pi. I referenced these instructions for setting up the static ip, and there are many more instructional resources out there.

Also, I set up port forward on my router for hosting a web site and I had even port forward port 22 to my pi's static IP for ssh, but I left the field blank where you specify the application you are performing the port forwarding for on the router. Anyway, I added 'ssh' into this field and, VOILA! A working ssh connection from anywhere to my pi.

I'll write out my router's port forwarding settings.

(ApplicationTextField)_ssh     (external port)_22     (Internal Port)_22     (Protocal)_Both     (To IP Address)_192.168.1.###     (Enabled)_checkBox

Port forwarding settings can be different for different routers though, so look up directions for your router.

Now, when I am outside of my home network I connect to my pi by typing:

ssh pi@[hostname]

Then I am able to input my password and connect.

Dealing with "Xerces hell" in Java/Maven?

There are 2.11.0 JARs (and source JARs!) of Xerces in Maven Central since 20th February 2013! See Xerces in Maven Central. I wonder why they haven't resolved https://issues.apache.org/jira/browse/XERCESJ-1454...

I've used:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>

and all dependencies have resolved fine - even proper xml-apis-1.4.01!

And what's most important (and what wasn't obvious in the past) - the JAR in Maven Central is the same JAR as in the official Xerces-J-bin.2.11.0.zip distribution.

I couldn't however find xml-schema-1.1-beta version - it can't be a Maven classifier-ed version because of additional dependencies.

Is recursion ever faster than looping?

is recursion ever faster than a loop?

No, Iteration will always be faster than Recursion. (in a Von Neumann Architecture)

Explanation:

If you build the minimum operations of a generic computer from scratch, "Iteration" comes first as a building block and is less resource intensive than "recursion", ergo is faster.

Building a pseudo-computing-machine from scratch:

Question yourself: What do you need to compute a value, i.e. to follow an algorithm and reach a result?

We will establish a hierarchy of concepts, starting from scratch and defining in first place the basic, core concepts, then build second level concepts with those, and so on.

  1. First Concept: Memory cells, storage, State. To do something you need places to store final and intermediate result values. Let’s assume we have an infinite array of "integer" cells, called Memory, M[0..Infinite].

  2. Instructions: do something - transform a cell, change its value. alter state. Every interesting instruction performs a transformation. Basic instructions are:

    a) Set & move memory cells

    • store a value into memory, e.g.: store 5 m[4]
    • copy a value to another position: e.g.: store m[4] m[8]

    b) Logic and arithmetic

    • and, or, xor, not
    • add, sub, mul, div. e.g. add m[7] m[8]
  3. An Executing Agent: a core in a modern CPU. An "agent" is something that can execute instructions. An Agent can also be a person following the algorithm on paper.

  4. Order of steps: a sequence of instructions: i.e.: do this first, do this after, etc. An imperative sequence of instructions. Even one line expressions are "an imperative sequence of instructions". If you have an expression with a specific "order of evaluation" then you have steps. It means than even a single composed expression has implicit “steps” and also has an implicit local variable (let’s call it “result”). e.g.:

    4 + 3 * 2 - 5
    (- (+ (* 3 2) 4 ) 5)
    (sub (add (mul 3 2) 4 ) 5)  
    

    The expression above implies 3 steps with an implicit "result" variable.

    // pseudocode
    
           1. result = (mul 3 2)
           2. result = (add 4 result)
           3. result = (sub result 5)
    

    So even infix expressions, since you have a specific order of evaluation, are an imperative sequence of instructions. The expression implies a sequence of operations to be made in a specific order, and because there are steps, there is also an implicit "result" intermediate variable.

  5. Instruction Pointer: If you have a sequence of steps, you have also an implicit "instruction pointer". The instruction pointer marks the next instruction, and advances after the instruction is read but before the instruction is executed.

    In this pseudo-computing-machine, the Instruction Pointer is part of Memory. (Note: Normally the Instruction Pointer will be a “special register” in a CPU core, but here we will simplify the concepts and assume all data (registers included) are part of “Memory”)

  6. Jump - Once you have an ordered number of steps and an Instruction Pointer, you can apply the "store" instruction to alter the value of the Instruction Pointer itself. We will call this specific use of the store instruction with a new name: Jump. We use a new name because is easier to think about it as a new concept. By altering the instruction pointer we're instructing the agent to “go to step x“.

  7. Infinite Iteration: By jumping back, now you can make the agent "repeat" a certain number of steps. At this point we have infinite Iteration.

                       1. mov 1000 m[30]
                       2. sub m[30] 1
                       3. jmp-to 2  // infinite loop
    
  8. Conditional - Conditional execution of instructions. With the "conditional" clause, you can conditionally execute one of several instructions based on the current state (which can be set with a previous instruction).

  9. Proper Iteration: Now with the conditional clause, we can escape the infinite loop of the jump back instruction. We have now a conditional loop and then proper Iteration

    1. mov 1000 m[30]
    2. sub m[30] 1
    3. (if not-zero) jump 2  // jump only if the previous 
                            // sub instruction did not result in 0
    
    // this loop will be repeated 1000 times
    // here we have proper ***iteration***, a conditional loop.
    
  10. Naming: giving names to a specific memory location holding data or holding a step. This is just a "convenience" to have. We do not add any new instructions by having the capacity to define “names” for memory locations. “Naming” is not a instruction for the agent, it’s just a convenience to us. Naming makes code (at this point) easier to read and easier to change.

       #define counter m[30]   // name a memory location
       mov 1000 counter
    loop:                      // name a instruction pointer location
        sub counter 1
        (if not-zero) jmp-to loop  
    
  11. One-level subroutine: Suppose there’s a series of steps you need to execute frequently. You can store the steps in a named position in memory and then jump to that position when you need to execute them (call). At the end of the sequence you'll need to return to the point of calling to continue execution. With this mechanism, you’re creating new instructions (subroutines) by composing core instructions.

    Implementation: (no new concepts required)

    • Store the current Instruction Pointer in a predefined memory position
    • jump to the subroutine
    • at the end of the subroutine, you retrieve the Instruction Pointer from the predefined memory location, effectively jumping back to the following instruction of the original call

    Problem with the one-level implementation: You cannot call another subroutine from a subroutine. If you do, you'll overwrite the returning address (global variable), so you cannot nest calls.

    To have a better Implementation for subroutines: You need a STACK

  12. Stack: You define a memory space to work as a "stack", you can “push” values on the stack, and also “pop” the last “pushed” value. To implement a stack you'll need a Stack Pointer (similar to the Instruction Pointer) which points to the actual “head” of the stack. When you “push” a value, the stack pointer decrements and you store the value. When you “pop”, you get the value at the actual Stack Pointer and then the Stack Pointer is incremented.

  13. Subroutines Now that we have a stack we can implement proper subroutines allowing nested calls. The implementation is similar, but instead of storing the Instruction Pointer in a predefined memory position, we "push" the value of the IP in the stack. At the end of the subroutine, we just “pop” the value from the stack, effectively jumping back to the instruction after the original call. This implementation, having a “stack” allows calling a subroutine from another subroutine. With this implementation we can create several levels of abstraction when defining new instructions as subroutines, by using core instructions or other subroutines as building blocks.

  14. Recursion: What happens when a subroutine calls itself?. This is called "recursion".

    Problem: Overwriting the local intermediate results a subroutine can be storing in memory. Since you are calling/reusing the same steps, if the intermediate result are stored in predefined memory locations (global variables) they will be overwritten on the nested calls.

    Solution: To allow recursion, subroutines should store local intermediate results in the stack, therefore, on each recursive call (direct or indirect) the intermediate results are stored in different memory locations.

...

having reached recursion we stop here.

Conclusion:

In a Von Neumann Architecture, clearly "Iteration" is a simpler/basic concept than “Recursion". We have a form of "Iteration" at level 7, while "Recursion" is at level 14 of the concepts hierarchy.

Iteration will always be faster in machine code because it implies less instructions therefore less CPU cycles.

Which one is "better"?

  • You should use "iteration" when you are processing simple, sequential data structures, and everywhere a “simple loop” will do.

  • You should use "recursion" when you need to process a recursive data structure (I like to call them “Fractal Data Structures”), or when the recursive solution is clearly more “elegant”.

Advice: use the best tool for the job, but understand the inner workings of each tool in order to choose wisely.

Finally, note that you have plenty of opportunities to use recursion. You have Recursive Data Structures everywhere, you’re looking at one now: parts of the DOM supporting what you are reading are a RDS, a JSON expression is a RDS, the hierarchical file system in your computer is a RDS, i.e: you have a root directory, containing files and directories, every directory containing files and directories, every one of those directories containing files and directories...

TypeError: 'builtin_function_or_method' object is not subscriptable

Mad a similar error, easy to fix:

    TypeError Traceback (most recent call last) <ipython-input-2-1eb12bfdc7db> in <module>
  3 mylist = [10,20,30] ----> 4 arr = np.array[(10,20,30)] 5 d = {'a':10, 'b':20, 'c':30} TypeError: 'builtin_function_or_method' object is not subscriptable

but I should have written it as:

arr = np.array([10,20,30])

Very fixable, rookie/dumb mistake.

How to declare an array inside MS SQL Server Stored Procedure?

Great question and great idea, but in SQL you'll need to do this:

For data type datetime, something like this-

declare @BeginDate    datetime = '1/1/2016',
        @EndDate      datetime = '12/1/2016'
create table #months (dates datetime)
declare @var datetime = @BeginDate
   while @var < dateadd(MONTH, +1, @EndDate)
   Begin
          insert into #months Values(@var)
          set @var = Dateadd(MONTH, +1, @var)
   end

If all you really want is numbers, do this-

create table #numbas (digit int)
declare @var int = 1        --your starting digit
    while @var <= 12        --your ending digit
    begin
        insert into #numbas Values(@var)
        set @var = @var +1
    end

Django URL Redirect

In Django 1.8, this is how I did mine.

from django.views.generic.base import RedirectView

url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))

Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.

Nested Git repositories?

I would use one repository per project. That way, the history becomes easier to browse through.

I would also check the version of the third party library I'm using, into the repository of the project using it.

Checking if a string array contains a value, and if so, getting its position

you can try like this...you can use Array.IndexOf() , if you want to know the position also

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

Why boolean in Java takes only true or false? Why not 1 or 0 also?

In c and C++ there is no data type called BOOLEAN Thats why it uses 1 and 0 as true false value. and in JAVA 1 and 0 are count as an INTEGER type so it produces error in java. And java have its own boolean values true and false with boolean data type.

happy programming..

mysql datetime comparison

But this is obviously performing a 'string' comparison

No. The string will be automatically cast into a DATETIME value.

See 11.2. Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

Test class with a new() call in it with Mockito

I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.

Here is how:

class TestedClass extends AARRGGHH {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

Now, PowerMockRunner failed to initialize TestedClass because it extends AARRGGHH, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.

I found a nice hack with minimal refactoring of TestedClass: I created a small method

LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
    new lc = new LoginContext(login, callbackHandler);
}

The scope of this method is necessarily package.

Then your test stub will look like:

LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
    .when(testClass)
    .initLoginContext("login", callbackHandler)

and the trick is done...

How to convert a string of bytes into an int?

In python 3 you can easily convert a byte string into a list of integers (0..255) by

>>> list(b'y\xcc\xa6\xbb')
[121, 204, 166, 187]

REST, HTTP DELETE and parameters

It's an old question, but here are some comments...

  1. In SQL, the DELETE command accepts a parameter "CASCADE", which allows you to specify that dependent objects should also be deleted. This is an example of a DELETE parameter that makes sense, but 'man rm' could provide others. How would these cases possibly be implemented in REST/HTTP without a parameter?
  2. @Jan, it seems to be a well-established convention that the path part of the URL identifies a resource, whereas the querystring does not (at least not necessarily). Examples abound: getting the same resource but in a different format, getting specific fields of a resource, etc. If we consider the querystring as part of the resource identifier, it is impossible to have a concept of "different views of the same resource" without turning to non-RESTful mechanisms such as HTTP content negotiation (which can be undesirable for many reasons).

How to remove leading whitespace from each line in a file

For this specific problem, something like this would work:

$ sed 's/^ *//g' < input.txt > output.txt

It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:

$ sed 's/^[ \t]+//g' < input.txt > output.txt

The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.

Finally, instead of < input.txt > output.txt you can use the -i option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.

C#: what is the easiest way to subtract time?

Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.

AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.

AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.

AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.

AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.

AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.

AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.

How to split a string and assign it to variables

There's are multiple ways to split a string :

  1. If you want to make it temporary then split like this:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. Split based on struct :

    • Create a struct and split like this

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Host and ServerDetail.Port

If you don't want to split specific string do it like this:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

Maximize a window programmatically and prevent the user from changing the windows state

To programmatically maximize the windowstate you can use:

 this.WindowState = FormWindowState.Maximized;
 this.MaximizeBox = false;

Show current assembly instruction in GDB

You can do

display/i $pc

and every time GDB stops, it will display the disassembly of the next instruction.

GDB-7.0 also supports set disassemble-next-line on, which will disassemble the entire next line, and give you more of the disassembly context.

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

  • You can also use the file extension to check for the filetype.
  • More simpler way would be to do something as given below inside add :

    add : function (e,data){
       var extension = data.originalFiles[0].name.substr( 
       (data.originalFiles[0].name.lastIndexOf('.') +1) );
                switch(extension){
                    case 'csv':
                    case 'xls':
                    case 'xlsx':
                        data.url = <Your URL>; 
                        data.submit();
                    break;
                    default:
                        alert("File type not accepted");
                    break;
                }
      }
    

Find a class somewhere inside dozens of JAR files?

I know this is an old question but...
I had the same issue, so If someone is looking for a very simple solution for windows - there is a software named Locate32 Just put jar as file extension
And containing the class name
It finds the file within seconds.

Locate32 in action

why are there two different kinds of for loops in java?

Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator. Some lists like LinkedList will iterate faster with an Iterator versus get(i). This is because because link list's iterator keeps track of the current pointer. Whereas each get in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator because it will be using Collections iterator, which in theory is optimized for the collection type.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I experienced the same problem on my repository. I'm the master of the repository, but I had such an error.

I've unprotected my project and then re-protected again, and the error is gone.

We had upgraded the gitlab version between my previous push and the problematic one. I suppose that this upgrade has created the bug.

get basic SQL Server table structure information

Instead of using count(*) you can SELECT * and you will return all of the details that you want including data_type:

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'

MSDN Docs on INFORMATION_SCHEMA.COLUMNS

Android: How to set password property in an edit text?

Here's a new way of putting dots in password

<EditText
    android:id="@+id/loginPassword"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:hint="@string/pwprompt" /

add android:inputType = "textPassword"

StringUtils.isBlank() vs String.isEmpty()

The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,

StringUtils.isBlank()

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

StringUtils.isEmpty

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.

If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.

  • To show the wait_timeout value:

SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+

| Variable_name | Value |

+---------------+-------+

| wait_timeout | 28800 |

+---------------+-------+

the value is in second, it means that non-interactive connection still up to 8 hours.

  • To change the value of "wait_timeout" variable:

SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)

After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.

Vibrate and Sound defaults on notification

// set notification audio

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);

When should I use cross apply over inner join?

cross apply sometimes enables you to do things that you cannot do with inner join.

Example (a syntax error):

select F.* from sys.objects O  
inner join dbo.myTableFun(O.name) F   
on F.schema_id= O.schema_id

This is a syntax error, because, when used with inner join, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)

However:

select F.* from sys.objects O  
cross apply ( select * from dbo.myTableFun(O.name) ) F  
where F.schema_id= O.schema_id

This is legal.

Edit: Or alternatively, shorter syntax: (by ErikE)

select F.* from sys.objects O  
cross apply dbo.myTableFun(O.name) F
where F.schema_id= O.schema_id

Edit:

Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

//BEWARE
//This works ONLY if the server returns 401 first
//The client DOES NOT send credentials on first request
//ONLY after a 401
client.Credentials = new NetworkCredential(userName, passWord); //doesnt work

//So use THIS instead to send credentials RIGHT AWAY
string credentials = Convert.ToBase64String(
    Encoding.ASCII.GetBytes(userName + ":" + password));
client.Headers[HttpRequestHeader.Authorization] = string.Format(
    "Basic {0}", credentials);

docker entrypoint running bash script gets "permission denied"

If you still get Permission denied errors when you try to run your script in the docker's entrypoint, just try DO NOT use the shell form of the entrypoint:

Instead of: ENTRYPOINT ./bin/watcher write ENTRYPOINT ["./bin/watcher"]:

https://docs.docker.com/engine/reference/builder/#entrypoint

enter image description here

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

Finding non-numeric rows in dataframe in pandas?

In case you are working with a column with string values, you can use THE VERY USEFUL function series.str.isnumeric() like:

a = pd.Series(['hi','hola','2.31','288','312','1312', '0,21', '0.23'])

What i do is to copy that column to new column, and do a str.replace('.','') and str.replace(',','') then i select the numeric values. and:

a = a.str.replace('.','')
a = a.str.replace(',','') 
a.str.isnumeric()

Out[15]: 0 False 1 False 2 True 3 True 4 True 5 True 6 True 7 True dtype: bool

Good luck all!

Pandas DataFrame to List of Lists

Maybe something changed but this gave back a list of ndarrays which did what I needed.

list(df.values)

Assert equals between 2 Lists in Junit

Don't transform to string and compare. This is not good for perfomance. In the junit, inside Corematchers, there's a matcher for this => hasItems

List<Integer> yourList = Arrays.asList(1,2,3,4)    
assertThat(yourList, CoreMatchers.hasItems(1,2,3,4,5));

This is the better way that I know of to check elements in a list.

Simple two column html layout without using tables

I know this is an old post, but figured I'd add my two penneth. How about the seldom used and oft' forgot Description list? With a simple bit of css you can get a really clean markup.

<dl>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
</dl>

take a look at this example http://codepen.io/butlerps/pen/wGmXPL

Shell script - remove first and last quote (") from a variable

Update

A simple and elegant answer from Stripping single and double quotes in a string using bash / standard Linux commands only:

BAR=$(eval echo $BAR) strips quotes from BAR.

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

Based on hueybois's answer, I came up with this function after much trial and error:

function stripStartAndEndQuotes {
    cmd="temp=\${$1%\\\"}"
    eval echo $cmd
    temp="${temp#\"}"
    eval echo "$1=$temp"
}

If you don't want anything printed out, you can pipe the evals to /dev/null 2>&1.

Usage:

$ BAR="FOO BAR"
$ echo BAR
"FOO BAR"
$ stripStartAndEndQuotes "BAR"
$ echo BAR
FOO BAR

How can I initialize C++ object member variables in the constructor?

Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):

The note is a bit large, so I will demonstrate it here with some sample code.

When you chose to hold the members as I mentioned, you have to keep in mind also these two things:

  1. For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass or MyClass in the original examples and MyClass in the code below), in case there are several (see InnerClass1 in the example below). Meaning, you can "comment out" the m_innerClass1(a) and m_innerClass1(15) only if you enable the InnerClass1 default constructor.

  2. For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2 in the example below).

See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++ version 7.3.0):

#include <iostream>

using namespace std;

class InnerClass1
{
    public:
        InnerClass1(int a) : m_a(a)
        {
            cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;
        }

        /* No default constructor
        InnerClass1() : m_a(15)
        {
            cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;
        }
        */

        ~InnerClass1()
        {
            cout << "InnerClass1::~InnerClass1" << endl;
        }

    private:
        int m_a;
};

class InnerClass2
{
    public:
        InnerClass2(int a) : m_a(a)
        {
            cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;
        }

        InnerClass2() : m_a(15)
        {
            cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;
        }

        ~InnerClass2()
        {
            cout << "InnerClass2::~InnerClass2" << endl;
        }

    private:
        int m_a;
};

class MyClass
{
    public:
        MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
        {
            cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;
        }

         MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
        {
            cout << "MyClass::MyClass() - m_b:" << m_b << endl;
        }

        ~MyClass()
        {
            cout << "MyClass::~MyClass" << endl;
        }

    private:
        InnerClass1 m_innerClass1;
        InnerClass2 m_innerClass2;
        int m_b;
};

int main(int argc, char** argv)
{
    cout << "main - start" << endl;

    MyClass obj;

    cout << "main - end" << endl;
    return 0;
}

Reset auto increment counter in postgres

To get sequence id use

SELECT pg_get_serial_sequence('tableName', 'ColumnName');

This will gives you sequesce id as tableName_ColumnName_seq

To Get Last seed number use

select currval(pg_get_serial_sequence('tableName', 'ColumnName'));

or if you know sequence id already use it directly.

select currval(tableName_ColumnName_seq);

It will gives you last seed number

To Reset seed number use

ALTER SEQUENCE tableName_ColumnName_seq RESTART WITH 45

Maximum number of rows in an MS Access database engine table?

Some comments:

  1. Jet/ACE files are organized in data pages, which means there is a certain amount of slack space when your record boundaries are not aligned with your data pages.

  2. Row-level locking will greatly reduce the number of possible records, since it forces one record per data page.

  3. In Jet 4, the data page size was increased to 4KBs (from 2KBs in Jet 3.x). As Jet 4 was the first Jet version to support Unicode, this meant that you could store 1GB of double-byte data (i.e., 1,000,000,000 double-byte characters), and with Unicode compression turned on, 2GBs of data. So, the number of records is going to be affected by whether or not you have Unicode compression on.

  4. Since we don't know how much room in a Jet/ACE file is taken up by headers and other metadata, nor precisely how much room index storage takes, the theoretical calculation is always going to be under what is practical.

  5. To get the most efficient possible storage, you'd want to use code to create your database rather than the Access UI, because Access creates certain properties that pure Jet does not need. This is not to say there are a lot of these, as properties set to the Access defaults are usually not set at all (the property is created only when you change it from the default value -- this can be seen by cycling through a field's properties collection, i.e., many of the properties listed for a field in the Access table designer are not there in the properties collection because they haven't been set), but you might want to limit yourself to Jet-specific data types (hyperlink fields are Access-only, for instance).

I just wasted an hour mucking around with this using Rnd() to populate 4 fields defined as type byte, with composite PK on the four fields, and it took forever to append enough records to get up to any significant portion of 2GBs. At over 2 million records, the file was under 80MBs. I finally quit after reaching just 700K 7 MILLION records and the file compacted to 184MBs. The amount of time it would take to get up near 2GBs is just more than I'm willing to invest!

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

My biggest concern with not checking folder node_modules into Git is that 10 years down the road, when your production application is still in use, npm may not be around. Or npm might become corrupted; or the maintainers might decide to remove the library that you rely on from their repository; or the version you use might be trimmed out.

This can be mitigated with repository managers like Maven, because you can always use your own local Nexus (Sonatype) or Artifactory to maintain a mirror with the packages that you use. As far as I understand, such a system doesn't exist for npm. The same goes for client-side library managers like Bower and Jam.js.

If you've committed the files to your own Git repository, then you can update them when you like, and you have the comfort of repeatable builds and the knowledge that your application won't break because of some third-party action.

How to recover a dropped stash in Git?

Once you know the hash of the stash commit you dropped, you can apply it as a stash:

git stash apply $stash_hash

Or, you can create a separate branch for it with

git branch recovered $stash_hash

After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.

Finding the hash

If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda).

Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:

git fsck --no-reflog | awk '/dangling commit/ {print $3}'

...or using Powershell for Windows:

git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] }

This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.

The easiest way to find the stash commit you want is probably to pass that list to gitk:

gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

...or see the answer from emragins if using Powershell for Windows.

This will launch a repository browser showing you every single commit in the repository ever, regardless of whether it is reachable or not.

You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app.

To spot stash commits, look for commit messages of this form:

        WIP on somebranch: commithash Some old commit message

Note: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash.

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

how to insert value into DataGridView Cell?

int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";

hope this help! :)

is python capable of running on multiple cores?

As stated in prior answers - it depends on the answer to "cpu or i/o bound?",
but also to the answer to "threaded or multi-processing?":

Examples run on Raspberry Pi 3B 1.2GHz 4-core with Python3.7.3
--( With other processes running including htop )

  • For this test - multiprocessing and threading had similar results for i/o bound,
    but multi-processing was more efficient than threading for cpu-bound.

Using threads:

Typical Result:
. Starting 4000 cycles of io-bound threading
. Sequential run time: 39.15 seconds
. 4 threads Parallel run time: 18.19 seconds
. 2 threads Parallel - twice run time: 20.61 seconds

Typical Result:
. Starting 1000000 cycles of cpu-only threading
. Sequential run time: 9.39 seconds
. 4 threads Parallel run time: 10.19 seconds
. 2 threads Parallel twice - run time: 9.58 seconds

Using multiprocessing:

Typical Result:
. Starting 4000 cycles of io-bound processing
. Sequential - run time: 39.74 seconds
. 4 procs Parallel - run time: 17.68 seconds
. 2 procs Parallel twice - run time: 20.68 seconds

Typical Result:
. Starting 1000000 cycles of cpu-only processing
. Sequential run time: 9.24 seconds
. 4 procs Parallel - run time: 2.59 seconds
. 2 procs Parallel twice - run time: 4.76 seconds

compare_io_multiproc.py:
#!/usr/bin/env python3

# Compare single proc vs multiple procs execution for io bound operation

"""
Typical Result:
  Starting 4000 cycles of io-bound processing
  Sequential - run time: 39.74 seconds
  4 procs Parallel - run time: 17.68 seconds
  2 procs Parallel twice - run time: 20.68 seconds
"""
import time
import multiprocessing as mp

# one thousand
cycles = 1 * 1000

def t():
        with open('/dev/urandom', 'rb') as f:
                for x in range(cycles):
                        f.read(4 * 65535)

if __name__ == '__main__':
    print("  Starting {} cycles of io-bound processing".format(cycles*4))
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("  Sequential - run time: %.2f seconds" % (time.time() - start_time))

    # four procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p1.start()
    p2.start()
    p3.start()
    p4.start()
    p1.join()
    p2.join()
    p3.join()
    p4.join()
    print("  4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))

    # two procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p3.start()
    p4.start()
    p3.join()
    p4.join()
    print("  2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))

compare_cpu_multiproc.py
#!/usr/bin/env python3

# Compare single proc vs multiple procs execution for cpu bound operation

"""
Typical Result:
  Starting 1000000 cycles of cpu-only processing
  Sequential run time: 9.24 seconds
  4 procs Parallel - run time: 2.59 seconds
  2 procs Parallel twice - run time: 4.76 seconds
"""
import time
import multiprocessing as mp

# one million
cycles = 1000 * 1000

def t():
    for x in range(cycles):
        fdivision = cycles / 2.0
        fcomparison = (x > fdivision)
        faddition = fdivision + 1.0
        fsubtract = fdivision - 2.0
        fmultiply = fdivision * 2.0

if __name__ == '__main__':
    print("  Starting {} cycles of cpu-only processing".format(cycles))
    start_time = time.time()
    t()
    t()
    t()
    t()
    print("  Sequential run time: %.2f seconds" % (time.time() - start_time))

    # four procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p1.start()
    p2.start()
    p3.start()
    p4.start()
    p1.join()
    p2.join()
    p3.join()
    p4.join()
    print("  4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))

    # two procs
    start_time = time.time()
    p1 = mp.Process(target=t)
    p2 = mp.Process(target=t)
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    p3 = mp.Process(target=t)
    p4 = mp.Process(target=t)
    p3.start()
    p4.start()
    p3.join()
    p4.join()
    print("  2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))


Enable/Disable a dropdownbox in jquery

this is to disable dropdown2 , dropdown 3 if you select the option from dropdown1 that has the value 15

$("#dropdown1").change(function(){
            if ( $(this).val()!= "15" ) {
                $("#dropdown2").attr("disabled",true);
                $("#dropdown13").attr("disabled",true);

            }

Styling Google Maps InfoWindow

Use the InfoBox plugin from the Google Maps Utility Library. It makes styling/managing map pop-ups much easier.

Note that you'll need to make sure it loads after the google maps API:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap" async defer></script>
<script src="/js/infobox_packed.js" async defer></script>

Bootstrap fullscreen layout with 100% height

All you have to do is have a height of 100vh on your main container/wrapper, and then set height 100% or 50% for child elements.. depending on what you're trying to achieve. I tried to copy your mock up in a basic sense.

In case you want to center stuff within, look into flexbox. I put in an example for you.

You can view it on full screen, and resize the browser and see how it works. The layout stays the same.

_x000D_
_x000D_
.left {_x000D_
  background: grey;  _x000D_
}_x000D_
_x000D_
.right {_x000D_
  background: black;  _x000D_
}_x000D_
_x000D_
.main-wrapper {_x000D_
  height: 100vh;  _x000D_
}_x000D_
_x000D_
.section {_x000D_
  height: 100%;  _x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.half {_x000D_
  background: #f9f9f9;_x000D_
  height: 50%;  _x000D_
  width: 100%;_x000D_
  margin: 15px 0;_x000D_
}_x000D_
_x000D_
h4 {_x000D_
  color: white;  _x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<div class="main-wrapper">_x000D_
  <div class="section left col-xs-3">_x000D_
    <div class="half"><h4>Top left</h4></div>_x000D_
    <div class="half"><h4>Bottom left</h4></div>_x000D_
  </div>_x000D_
  <div class="section right col-xs-9">_x000D_
    <h4>Extra step: center stuff here</h4>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to watch for form changes in Angular

Expanding on Mark's suggestions...

Method 3

Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.

export class App implements DoCheck {
  person = { first: "Sally", last: "Jones" };
  oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning

  ngDoCheck() {
    // Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
    for (let prop in this.person) {
      if (this.oldPerson[prop] !==  this.person[prop]) {
        console.log(`person.${prop} changed: ${this.person[prop]}`);
        this.oldPerson[prop] = this.person[prop];
      }
    }
  }

Try in Plunker

Creating a daemon in Linux

By calling fork() you've created a child process. If the fork is successful (fork returned a non-zero PID) execution will continue from this point from within the child process. In this case we want to gracefully exit the parent process and then continue our work in the child process.

Maybe this will help: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html

How to get VM arguments from inside of Java application?

I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.

Here's the SSCCE:

import java.util.*;
import java.lang.management.ManagementFactory;

class main {
  public static void main(final String[] args) {
    System.out.println(fullVMArguments());
  }

  static String fullVMArguments() {
    String name = javaVmName();
    return (contains(name, "Server") ? "-server "
      : contains(name, "Client") ? "-client " : "")
      + joinWithSpace(vmArguments());
  }

  static List<String> vmArguments() {
    return ManagementFactory.getRuntimeMXBean().getInputArguments();
  }

  static boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static String javaVmName() {
    return System.getProperty("java.vm.name");
  }

  static String joinWithSpace(Collection<String> c) {
    return join(" ", c);
  }

  public static String join(String glue, Iterable<String> strings) {
    if (strings == null) return "";
    StringBuilder buf = new StringBuilder();
    Iterator<String> i = strings.iterator();
    if (i.hasNext()) {
      buf.append(i.next());
      while (i.hasNext())
        buf.append(glue).append(i.next());
    }
    return buf.toString();
  }
}

Could be made shorter if you want the arguments in a List<String>.

Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.

How to prevent favicon.ico requests?

Personally I used this in my HTML head tag:

<link rel="shortcut icon" href="#" />

surface plots in matplotlib

This is not a general solution but might help many of those who just typed "matplotlib surface plot" in Google and landed here.

Suppose you have data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)], then you can get three 1-d lists using x, y, z = zip(*data). Now you can of course create 3d scatterplot using three 1-d lists.

But, why can't in general this data be used to create surface plot? To understand that consider an empty 3-d plot :

Now, suppose for each possible value of (x, y) on a "discrete" regular grid, you have a z value, then there's no issue & you can in fact get a surface plot:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

x = np.linspace(0, 10, 6)  # [0, 2,..,10] : 6 distinct values
y = np.linspace(0, 20, 5)  # [0, 5,..,20] : 5 distinct values
z = np.linspace(0, 100, 30)  # 6 * 5 = 30 values, 1 for each possible combination of (x,y)

X, Y = np.meshgrid(x, y)
Z = np.reshape(z, X.shape)  # Z.shape must be equal to X.shape = Y.shape

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

What's happens when you haven't got z for all possible combinations of (x, y)? Then at the point (at intersection of two black lines on x-y plane on blank plot above), we don't know what is the value of z. It could be anything, we don't know how 'high' or 'low' our surface should be at that point (although it can be approximated using other functions, surface_plot requires that you supply it arguments where X.shape = Y.shape = Z.shape).

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

How to make Regular expression into non-greedy?

You are right that greediness is an issue:

--A--Z--A--Z--
  ^^^^^^^^^^
     A.*Z

If you want to match both A--Z, you'd have to use A.*?Z (the ? makes the * "reluctant", or lazy).

There are sometimes better ways to do this, though, e.g.

A[^Z]*+Z

This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.

In your case, the regex would be:

/(\[[^\]]++\])/

Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:

/(\[[^\]]+\])/

See also


Quick summary

*   Zero or more, greedy
*?  Zero or more, reluctant
*+  Zero or more, possessive

+   One or more, greedy
+?  One or more, reluctant
++  One or more, possessive

?   Zero or one, greedy
??  Zero or one, reluctant
?+  Zero or one, possessive

Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m} constructs.

Examples in Java:

System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!"));  // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"

System.out.println("xxxxxx".replaceAll("x{3,5}", "Y"));  // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"

Custom sort function in ng-repeat

The following link explains filters in Angular extremely well. It shows how it is possible to define custom sort logic within an ng-repeat. http://toddmotto.com/everything-about-custom-filters-in-angular-js

For sorting object with properties, this is the code I have used: (Note that this sort is the standard JavaScript sort method and not specific to angular) Column Name is the name of the property on which sorting is to be performed.

self.myArray.sort(function(itemA, itemB) {
    if (self.sortOrder === "ASC") {
        return itemA[columnName] > itemB[columnName];
    } else {
        return itemA[columnName] < itemB[columnName];
    }
});

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

how to set textbox value in jquery

I would like to point out to you that .val() also works with selects to select the current selected value.

Angular: date filter adds timezone, how to output UTC?

The date filter always formats the dates using the local timezone. You'll have to write your own filter, based on the getUTCXxx() methods of Date, or on a library like moment.js.

Import MySQL database into a MS SQL Server

you can use sqlie application for converting from mysql to sqlserver you can watch this video https://www.youtube.com/watch?v=iTVEqys_vTQ&t=108s

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

CSS: Auto resize div to fit container width

You can overflow:hidden to your #content. Write like this:

#content
{
    min-width:700px;
    margin-left:10px;
    overflow:hidden;
    background-color:AppWorkspace;
}

Check this http://jsfiddle.net/Zvt2j/1/

How to unmount a busy device

Someone has mentioned that if you are using terminal and your current directory is inside the path which you want to unmount, you will get the error.
As a complementary, in this case, your lsof | grep path-to-be-unmounted must have below output:

bash ... path-to-be-unmounted

Javascript Iframe innerHTML

Don't forget that you can not cross domains because of security.

So if this is the case, you should use JSON.

How to calculate the bounding box for a given lat/lng location?

I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).

My implementation follows (It's written in Python; I have not tested it):

# degrees to radians
def deg2rad(degrees):
    return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
    return 180.0*radians/math.pi

# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0  # Major semiaxis [m]
WGS84_b = 6356752.3  # Minor semiaxis [m]

# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
    # http://en.wikipedia.org/wiki/Earth_radius
    An = WGS84_a*WGS84_a * math.cos(lat)
    Bn = WGS84_b*WGS84_b * math.sin(lat)
    Ad = WGS84_a * math.cos(lat)
    Bd = WGS84_b * math.sin(lat)
    return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )

# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
    lat = deg2rad(latitudeInDegrees)
    lon = deg2rad(longitudeInDegrees)
    halfSide = 1000*halfSideInKm

    # Radius of Earth at given latitude
    radius = WGS84EarthRadius(lat)
    # Radius of the parallel at given latitude
    pradius = radius*math.cos(lat)

    latMin = lat - halfSide/radius
    latMax = lat + halfSide/radius
    lonMin = lon - halfSide/pradius
    lonMax = lon + halfSide/pradius

    return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))

EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):

def dps2deg(degrees, primes, seconds):
    return degrees + primes/60.0 + seconds/3600.0

def deg2dps(degrees):
    intdeg = math.floor(degrees)
    primes = (degrees - intdeg)*60.0
    intpri = math.floor(primes)
    seconds = (primes - intpri)*60.0
    intsec = round(seconds)
    return (int(intdeg), int(intpri), int(intsec))

Add and remove a class on click using jQuery?

You can do this:-

$('#about-link').addClass('current');
$('#menu li a').on('click', function(e){
    e.preventDefault();
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});

Demo: Fiddle

Do you get charged for a 'stopped' instance on EC2?

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

Git "error: The branch 'x' is not fully merged"

As Drew Taylor pointed out, branch deletion with -d only considers the current HEAD in determining if the branch is "fully merged". It will complain even if the branch is merged with some other branch. The error message could definitely be clearer in this regard... You can either checkout the merged branch before deleting, or just use git branch -D. The capital -D will override the check entirely.

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

How to upgrade scikit-learn package in anaconda

Updating a Specific Library - scikit-learn:

Anaconda (conda):

conda install scikit-learn

Pip Installs Packages (pip):

pip install --upgrade scikit-learn

Verify Update:

conda list scikit-learn

It should now display the current (and desired) version of the scikit-learn library.

For me personally, I tried using the conda command to update the scikit-learn library and it acted as if it were installing the latest version to then later discover (with an execution of the conda list scikit-learn command) that it was the same version as previously and never updated (or recognized the update?). When I used the pip command, it worked like a charm and correctly updated the scikit-learn library to the latest version!

Hope this helps!

More in-depth details of latest version can be found here (be mindful this applies to the scikit-learn library version of 0.22):

How to display my application's errors in JSF?

You also have to include the FormID in your call to addMessage().

 FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));

This should do the trick.

Regards.

Compare two objects' properties to find differences?

Compare NET Objects can help you!

CompareLogic logic = new CompareLogic();
var compare = logic.Compare(obj1, obj2);
comparacao.Differences.ForEach(diff => Debug.Write(diff.PropertyName));
// Or formatted summary
Debug.Write(comparacao.DifferencesString);

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Write to CSV file and export it?

Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.

Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.

You can add the following to the (I believe this is correct) Load event:

string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");

var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
  sb.AppendLine(TransformDataLineIntoCsv(line));

HttpContext.Current.Response.Write(sb.ToString());

writing to the response stream code ganked from here.

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

Select value from list of tuples where condition

One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]

If else embedding inside html

 <?php if (date("H") < "12" && date("H")>"6") { ?>
   src="<?php bloginfo('template_url'); ?>/images/img/morning.gif" 
 <?php } elseif (date("H") > "12" && date("H")<"17") { ?>
 src="<?php bloginfo('template_url'); ?>/images/img/noon.gif" 
  <?php } elseif (date("H") > "17" && date("H")<"21") { ?>
   src="<?php bloginfo('template_url'); ?>/images/img/evening.gif" 
  <?php } elseif (date("H") > "21" && date("H")<"24") { ?>
  src="<?php bloginfo('template_url'); ?>/images/img/night.gif" 
  <?php }else { ?>
  src="<?php bloginfo('template_url'); ?>/images/img/mid_night.gif" 
  <?php } ?>

PowerShell to remove text from a string

Another way to do this is with operator -replace.

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

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

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

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

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

Random number from a range in a Bash Script

You can do this

cat /dev/urandom|od -N2 -An -i|awk -v f=2000 -v r=65000 '{printf "%i\n", f + r * $1 / 65536}'

If you need more details see Shell Script Random Number Generator.

javascript set cookie with expire time

Here's a function I wrote another application. Feel free to reuse:

function writeCookie (key, value, days) {
    var date = new Date();

    // Default at 365 days.
    days = days || 365;

    // Get unix milliseconds at current time plus number of days
    date.setTime(+ date + (days * 86400000)); //24 * 60 * 60 * 1000

    window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";

    return value;
};

How to get current timestamp in milliseconds since 1970 just the way Java gets

If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}

How to ignore user's time zone and force Date() use specific time zone

You could use setUTCMilliseconds()

var _date = new Date();
_date.setUTCMilliseconds(1270544790922);

Example use of "continue" statement in Python?

It is not absolutely necessary since it can be done with IFs but it's more readable and also less expensive in run time.

I use it in order to skip an iteration in a loop if the data does not meet some requirements:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

Output:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

As you can see, the wrong value did not make it after the continue statement.

Frame Buster Buster ... buster code needed

If you look at the values returned by setInterval() they are usually single digits, so you can usually disable all such interrupts with a single line of code:

for (var j = 0 ; j < 256 ; ++j) clearInterval(j)

Sometimes adding a WCF Service Reference generates an empty reference.cs

As @dblood points out, the main pain is in the DataContractSerializer, that doens't correctly re-use the types. There are already some answers here so I'll start by adding some pro's and cons about these:

  • The 'IsReference' flag causes a lot of trouble, but removing it isn't always the answer (specifically: in situations with recursion).
  • The underlying issue is that the data contract is somehow not the same as the type names, even though they sometimes are (huh? Yes, you read that right!). Apparently the serializer is quite picky and it's very hard to find the real issue.
  • Removing the 'references checks' from the 'Configure service reference' works, but leaves you with a multiple implementations. However, I often reuse SOAP interfaces across DLL's. Also, in most mature SOA's that I know, multiple services interfaces implement and extend the same interface classes. Removing 'use referenced types' checks results in a situation where you cannot simply pass objects around anymore.

Fortunately, if you are in control of your service, there is a simple solution that solves all these issues. This means you can still re-use service interfaces across DLL's - which is IMO a must-have for a proper solution. This is how the solution works:

  1. Create a separate interface DLL. In that DLL, include all DataContract and ServiceContract's; put ServiceContract's on your interfaces.
  2. Derive the server implementation from the interface.
  3. Use the same DLL to construct the client using your favorite method. For example (IMyInterface is the service contract interface):

    var httpBinding = new BasicHttpBinding();
    var identity = new DnsEndpointIdentity("");
    var address = new EndpointAddress(url, identity, new AddressHeaderCollection());
    var channel = new ChannelFactory<IMyInterface>(httpBinding, address);
    return channel.CreateChannel();
    

In other words: Don't use the 'add service reference' functionality, but force WCF to use the (correct) service types by bypassing the proxy generation. After all, you already have these classes.

Pro's:

  1. You bypass the svcutil.exe process, which means you don't have any IsReference issues
  2. DataContract types and names are correct by definition; after all, both server and client use the very same definition.
  3. If you extend the API or use types from another DLL, (1) and (2) still hold, so you won't run in any trouble there.

Cons:

  1. A-sync methods are a pain, since you don't generate an a-sync proxy. As a result, I wouldn't recommend doing this in Silverlight applications.

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

Maven skip tests

I have another approach for Intellij users, and it is working very fine for me:

  1. Click on the "Skip Test" button

enter image description here

  1. Hold the "CTRL" button
  2. Select "clean" and "install"

enter image description here

  1. Click on the "Run" button in the maven pannel

enter image description here

Prevent PDF file from downloading and printing

That is not possible. Reading is downloading. When a user is reading a file, browser is downloading that file to temp. So even if you disable the download button, the user can click "File -> Save As" or copy that file from temp folder.

There are a few things you can do:

Method 1

The following code will embed a PDF without any toolbars and hide the print/download icons

<embed src="{URL_TO_PDF.PDF}#toolbar=0&navpanes=0&scrollbar=0" width="425" height="425">

Method 02

Using Google Drive

Right click on pdf and goto Share(below image)

enter image description here

Then go to Advanced option in left bottom

enter image description here

Tick Both check boxes. After copy embed link and paste it to your src. No download and Save drive option is not allowed

Bad Request, Your browser sent a request that this server could not understand

Make sure you url encode all of the query params in your url.

In my case there was a space ' ' in my url, and I was making an API call using curl, and my api server was giving this error.

Means the following url http://somedomain.com?key=some value with space

should be http://somedomain.com/?key=some%20value%20with%20space

How to calculate the inverse of the normal cumulative distribution function in python?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the inverse cumulative distribution function (inv_cdf - inverse of the cdf), also known as the quantile function or the percent-point function for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=10, sigma=2).inv_cdf(0.95)
# 13.289707253902943

Which can be simplified for the standard normal distribution (mu = 0 and sigma = 1):

NormalDist().inv_cdf(0.95)
# 1.6448536269514715

How to simulate a touch event in Android?

Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:

view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);

For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?

Hide Button After Click (With Existing Form on Page)

Here is another solution using Jquery I find it a little easier and neater than inline JS sometimes.

    <html>
    <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>

        /* if you prefer to functionize and use onclick= rather then the .on bind
        function hide_show(){
            $(this).hide();
            $("#hidden-div").show();
        }
        */

        $(function(){
            $("#chkbtn").on('click',function() {
                $(this).hide();
                $("#hidden-div").show();
            }); 
        });
    </script>
    <style>
    .hidden-div {
        display:none
    }
    </style>
    </head>
    <body>
    <div class="reform">
        <form id="reform" action="action.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="" />
            <fieldset>
                content here...
            </fieldset>

                <div class="hidden-div" id="hidden-div">

            <fieldset>
                more content here that is hidden until the button below is clicked...
            </fieldset>
        </form>
                </div>
                <span style="display:block; padding-left:640px; margin-top:10px;"><button id="chkbtn">Check Availability</button></span>
    </div>
    </body>
    </html>

Get table column names in MySQL?

Look into:

mysql_query('DESCRIBE '.$table);

What is "loose coupling?" Please provide examples

Consider a simple shopping cart application that uses a CartContents class to keep track of the items in the shopping cart and an Order class for processing a purchase. The Order needs to determine the total value of the contents in the cart, it might do that like so:

Tightly Coupled Example:

public class CartEntry
{
    public float Price;
    public int Quantity;
}

public class CartContents
{
    public CartEntry[] items;
}

public class Order
{
    private CartContents cart;
    private float salesTax;

    public Order(CartContents cart, float salesTax)
    {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float OrderTotal()
    {
        float cartTotal = 0;
        for (int i = 0; i < cart.items.Length; i++)
        {
            cartTotal += cart.items[i].Price * cart.items[i].Quantity;
        }
        cartTotal += cartTotal*salesTax;
        return cartTotal;
    }
}

Notice how the OrderTotal method (and thus the Order class) depends on the implementation details of the CartContents and the CartEntry classes. If we were to try to change this logic to allow for discounts, we'd likely have to change all 3 classes. Also, if we change to using a List collection to keep track of the items we'd have to change the Order class as well.

Now here's a slightly better way to do the same thing:

Less Coupled Example:

public class CartEntry
{
    public float Price;
    public int Quantity;

    public float GetLineItemTotal()
    {
        return Price * Quantity;
    }
}

public class CartContents
{
    public CartEntry[] items;

    public float GetCartItemsTotal()
    {
        float cartTotal = 0;
        foreach (CartEntry item in items)
        {
            cartTotal += item.GetLineItemTotal();
        }
        return cartTotal;
    }
}

public class Order
{
    private CartContents cart;
    private float salesTax;

    public Order(CartContents cart, float salesTax)
    {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float OrderTotal()
    {
        return cart.GetCartItemsTotal() * (1.0f + salesTax);
    }
}

The logic that is specific to the implementation of the cart line item or the cart collection or the order is restricted to just that class. So we could change the implementation of any of these classes without having to change the other classes. We could take this decoupling yet further by improving the design, introducing interfaces, etc, but I think you see the point.

Changing image on hover with CSS/HTML

_x000D_
_x000D_
.hover_image:hover {text-decoration: none} /* Optional (avoid undesired underscore if a is used as wrapper) */_x000D_
.hide {display:none}_x000D_
/* Do the shift: */_x000D_
.hover_image:hover img:first-child{display:none}_x000D_
.hover_image:hover img:last-child{display:inline-block}
_x000D_
<body> _x000D_
    <a class="hover_image" href="#">_x000D_
        <!-- path/to/first/visible/image: -->_x000D_
        <img src="http://farmacias.dariopm.com/cc2/_cc3/images/f1_silverstone_2016.jpg" />_x000D_
        <!-- path/to/hover/visible/image: -->_x000D_
        <img src="http://farmacias.dariopm.com/cc2/_cc3/images/f1_malasia_2016.jpg" class="hide" />_x000D_
    </a>_x000D_
</body>
_x000D_
_x000D_
_x000D_

To try to improve this Rashid's good answer I'm adding some comments:

The trick is done over the wrapper of the image to be swapped (an 'a' tag this time but maybe another) so the 'hover_image' class has been put there.

Advantages:

  • Keeping both images url together in the same place helps if they need to be changed.

  • Seems to work with old navigators too (CSS2 standard).

  • It's self explanatory.

  • The hover image is preloaded (no delay after hovering).

How to source virtualenv activate in a Bash script

When I was learning venv I created a script to remind me how to activate it.

#!/bin/sh
# init_venv.sh
if [ -d "./bin" ];then
  echo "[info] Ctrl+d to deactivate"
  bash -c ". bin/activate; exec /usr/bin/env bash --rcfile <(echo 'PS1=\"(venv)\${PS1}\"') -i"
fi

This has the advantage that it changes the prompt.

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

foreach loop in angularjs

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

Java 8 Lambda Stream forEach with multiple statements

You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()):

entryList.forEach(e->e.setTempId(tempId));

List<Entry> updatedEntries = entryList.stream()
  .map(e->entityManager.update(entry, entry.getId()))
  .collect(toList());

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
            <ul>
                <li>Menu1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
            </ul> 
        </div>
    </div>



body{
    margin-top:50px;}
.menuBar{
    width:100%;
    height:50px;
    display:block;
    position:absolute;
    top:0;
    left:0;
    }
.logo{
    float:left;
    }
.nav{
    float:right;
    margin-right:10px;}
.nav ul li{
    list-style:none;
    float:left;
    }

Googlemaps API Key for Localhost

You have to check the specific error within the javascript console (e.g. Ctrl + Shift + K in Firefox for Windows).

According to Steven Gliebe (2016), there are four common cases for this problem. If I may summarize it, as this:

  1. MissingKeyMapError >> Get Google Maps API Key (but also consider alternative no.2)
  2. RefererNotAllowedMapError >> Register your localhost:port in your google developer dashboard.
  3. ApiNotActivatedMapError >> Enabling the Google Maps API in Google API Library page
  4. InvalidKeyMapError >> Add your key to your scripts/ codes properly

After doing some code modification, please clear your browser cache as necessary.

In case there are other errors, you can check Google Maps API Error Codes Documentation page.

Removing u in list

[u'{email:[email protected],gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test1,gem:0}']

'u' denotes unicode characters. We can easily remove this with map function on the final list element

map(str, test)

Another way is when you are appending it to the list

test.append(str(a))

How to sign an android apk file

The manual is clear enough. Please specify what part you get stuck with after you work through it, I'd suggest:

https://developer.android.com/studio/publish/app-signing.html

Okay, a small overview without reference or eclipse around, so leave some space for errors, but it works like this

  • Open your project in eclipse
  • Press right-mouse - > tools (android tools?) - > export signed application (apk?)
  • Go through the wizard:
  • Make a new key-store. remember that password
  • Sign your app
  • Save it etc.

Also, from the link:

Compile and sign with Eclipse ADT

If you are using Eclipse with the ADT plugin, you can use the Export Wizard to export a signed .apk (and even create a new keystore, if necessary). The Export Wizard performs all the interaction with the Keytool and Jarsigner for you, which allows you to sign the package using a GUI instead of performing the manual procedures to compile, sign, and align, as discussed above. Once the wizard has compiled and signed your package, it will also perform package alignment with zip align. Because the Export Wizard uses both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described above in the Basic Setup for Signing.

To create a signed and aligned .apk in Eclipse:

  1. Select the project in the Package Explorer and select File > Export.
  2. Open the Android folder, select Export Android Application, and click Next.

    The Export Android Application wizard now starts, which will guide you through the process of signing your application, including steps for selecting the private key with which to sign the .apk (or creating a new keystore and private key).

  3. Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for distribution.

HTML text input field with currency symbol

Put the '$' in front of the text input field, instead of inside it. It makes validation for numeric data a lot easier because you don't have to parse out the '$' after submit.

You can, with JQuery.validate() (or other), add some client-side validation rules that handle currency. That would allow you to have the '$' inside the input field. But you still have to do server-side validation for security and that puts you back in the position of having to remove the '$'.

Convert JSON to Map

Using the GSON library:

import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;

Use the following code:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);

Android Google Maps API V2 Zoom to Current Location

Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin

locationClient.lastLocation.addOnSuccessListener { location: Location? ->
            location?.let {
                val position = CameraPosition.Builder()
                        .target(LatLng(it.latitude, it.longitude))
                        .zoom(15.0f)
                        .build()
                map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
            }
        }

Get Application Name/ Label via ADB Shell or Terminal

If you know the app id of the package (like org.mozilla.firefox), it is easy. First to get the path of actual package file of the appId,

$  adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox

Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk

After that aapt tool comes in handy :

$  adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...

Again some grep magic to get the Label.

How to convert datetime to integer in python

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

def to_integer(dt_time):
    return 10000*dt_time.year + 100*dt_time.month + dt_time.day

E.g.

In [1]: import datetime

In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
:    return 10000*dt_time.year + 100*dt_time.month + dt_time.day
:    # Or take the appropriate chars from a string date representation.
:--

In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

Merging Cells in Excel using C#

You can use Microsoft.Office.Interop.Excel:

worksheet.Range[worksheet.Cells[rowNum, columnNum], worksheet.Cells[rowNum, columnNum]].Merge();

You can also use NPOI:

var cellsTomerge = new NPOI.SS.Util.CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
_sheet.AddMergedRegion(cellsTomerge);

LINQ query on a DataTable

var query = from p in dt.AsEnumerable()
                    where p.Field<string>("code") == this.txtCat.Text
                    select new
                    {
                        name = p.Field<string>("name"),
                        age= p.Field<int>("age")                         
                    };

the name and age fields are now part of the query object and can be accessed like so: Console.WriteLine(query.name);

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

Python: Remove division decimal

You could probably do like below

# p and q are the numbers to be divided
if p//q==p/q:
    print(p//q)
else:
    print(p/q)

Find an object in array?

For Swift 3,

let index = array.index(where: {$0.name == "foo"})

How to remove all characters after a specific character in python?

import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)

Output: "This is a test"

What is the meaning of Bus: error 10 in C

str2 is pointing to a statically allocated constant character array. You can't write to it/over it. You need to dynamically allocate space via the *alloc family of functions.

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.

How to properly upgrade node using nvm

You can more simply run one of the following commands:

Latest version:
nvm install node --reinstall-packages-from=node
Stable (LTS) version:
nvm install lts/* --reinstall-packages-from=node

This will install the appropriate version and reinstall all packages from the currently used node version. This saves you from manually handling the specific versions.

Edit - added command for installing LTS version according to @m4js7er comment.

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

How to run a maven created jar file using just the command line

Use this command.

mvn package

to make the package jar file. Then, run this command.

java -cp target/artifactId-version-SNAPSHOT.jar package.Java-Main-File-Name

after mvn package command. Target folder with classes, test classes, jar file and other resources folder and files will be created.

type your own artifactId, version and package and java main file.

Notepad++ - How can I replace blank lines

This should get your sorted:

  • Highlight from the end of the first line, to the very beginning of the third line.
  • Use the Ctrl + H to bring up the 'Find and Replace' window.
  • The highlighed region will already be plased in the 'Find' textbox.
  • Replace with: \r\n
  • 'Replace All' will then remove all the additional line spaces not required.

Here's how it should look: enter image description here

Remove empty elements from an array in Javascript

I'm simply adding my voice to the above “call ES5's Array..filter() with a global constructor” golf-hack, but I suggest using Object instead of String, Boolean, or Number as suggested above.

Specifically, ES5's filter() already doesn't trigger for undefined elements within the array; so a function that universally returns true, which returns all elements filter() hits, will necessarily only return non-undefined elements:

> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]

However, writing out ...(function(){return true;}) is longer than writing ...(Object); and the return-value of the Object constructor will be, under any circumstances, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting, Object is a short-hand for function(){return true}.

> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

Regex empty string or email

If you are using it within rails - activerecord validation you can set allow_blank: true

As:

validates :email, allow_blank: true, format: { with: EMAIL_REGEX }

Javascript event handler with parameters

It is an old question but a common one. So let me add this one here.

With arrow function syntax you can achieve it more succinct way since it is lexically binded and can be chained.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

const event_handler = (event, arg) => console.log(event, arg);
el.addEventListener('click', (event) => event_handler(event, 'An argument'));

If you need to clean up the event listener:

// Let's use use good old function sytax
function event_handler(event, arg) {
  console.log(event, arg);
}

// Assign the listener callback to a variable
var doClick = (event) => event_handler(event, 'An argument'); 

el.addEventListener('click', doClick);

// Do some work...

// Then later in the code, clean up
el.removeEventListener('click', doClick);

Here is crazy one-liner:

// You can replace console.log with some other callback function
el.addEventListener('click', (event) => ((arg) => console.log(event, arg))('An argument'));

More docile version: More appropriate for any sane work.

el.addEventListener('click', (event) => ((arg) => {
  console.log(event, arg);
})('An argument'));

How to validate a form with multiple checkboxes to have atleast one checked

This script below should put you on the right track perhaps?

You can keep this html the same (though I changed the method to POST):

<form method="POST" id="subscribeForm">
    <fieldset id="cbgroup">
        <div><input name="list" id="list0" type="checkbox"  value="newsletter0" >zero</div>
        <div><input name="list" id="list1" type="checkbox"  value="newsletter1" >one</div>
        <div><input name="list" id="list2" type="checkbox"  value="newsletter2" >two</div>
    </fieldset>
    <input name="submit" type="submit"  value="submit">
</form>

and this javascript validates

function onSubmit() 
{ 
    var fields = $("input[name='list']").serializeArray(); 
    if (fields.length === 0) 
    { 
        alert('nothing selected'); 
        // cancel submit
        return false;
    } 
    else 
    { 
        alert(fields.length + " items selected"); 
    }
}

// register event on form, not submit button
$('#subscribeForm').submit(onSubmit)

and you can find a working example of it here

UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.

UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)

UPDATE (June 2016)
Changes == to ===

Best way to use PHP to encrypt and decrypt passwords?

Security Warning: This class is not secure. It's using Rijndael256-ECB, which is not semantically secure. Just because "it works" doesn't mean "it's secure". Also, it strips tailing spaces afterwards due to not using proper padding.

Found this class recently, it works like a dream!

class Encryption {
    var $skey = "yourSecretKey"; // you can change it

    public  function safe_b64encode($string) {
        $data = base64_encode($string);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

    public function safe_b64decode($string) {
        $data = str_replace(array('-','_'),array('+','/'),$string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }

    public  function encode($value){ 
        if(!$value){return false;}
        $text = $value;
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
        return trim($this->safe_b64encode($crypttext)); 
    }

    public function decode($value){
        if(!$value){return false;}
        $crypttext = $this->safe_b64decode($value); 
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
        return trim($decrypttext);
    }
}

And to call it:

$str = "My secret String";

$converter = new Encryption;
$encoded = $converter->encode($str );
$decoded = $converter->decode($encoded);    

echo "$encoded<p>$decoded";

How do I check for vowels in JavaScript?

function isVowel(char)
{
  if (char.length == 1)
  {
    var vowels = "aeiou";
    var isVowel = vowels.indexOf(char) >= 0 ? true : false;

    return isVowel;
  }
}

Basically it checks for the index of the character in the string of vowels. If it is a consonant, and not in the string, indexOf will return -1.

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag prevents git merge from executing a "fast-forward" if it detects that your current HEAD is an ancestor of the commit you're trying to merge. A fast-forward is when, instead of constructing a merge commit, git just moves your branch pointer to point at the incoming commit. This commonly occurs when doing a git pull without any local changes.

However, occasionally you want to prevent this behavior from happening, typically because you want to maintain a specific branch topology (e.g. you're merging in a topic branch and you want to ensure it looks that way when reading history). In order to do that, you can pass the --no-ff flag and git merge will always construct a merge instead of fast-forwarding.

Similarly, if you want to execute a git pull or use git merge in order to explicitly fast-forward, and you want to bail out if it can't fast-forward, then you can use the --ff-only flag. This way you can regularly do something like git pull --ff-only without thinking, and then if it errors out you can go back and decide if you want to merge or rebase.

Table with fixed header and fixed column on pure css

This is no easy feat.

The following link is to a working demo:

Link Updated according to lanoxx's comment

http://jsfiddle.net/C8Dtf/366/

Just remember to add these:

<script type="text/javascript" charset="utf-8" src="http://datatables.net/release-datatables/media/js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="http://datatables.net/release-datatables/extras/FixedColumns/media/js/FixedColumns.js"></script>

i don't see any other way of achieving this. Especially not by using css only.

This is a lot to go through. Hope this helps :)

Compare a date string to datetime in SQL Server?

In sqlserver

DECLARE @p_date DATE

SELECT * 
FROM table1
WHERE column_dateTime=@p_date

In C# Pass the short string of date value using ToShortDateString() function. sample: DateVariable.ToShortDateString();

What does ||= (or-equals) mean in Ruby?

This is the default assignment notation

for example: x ||= 1
this will check to see if x is nil or not. If x is indeed nil it will then assign it that new value (1 in our example)

more explicit:
if x == nil
x = 1
end

SQL Server® 2016, 2017 and 2019 Express full download

When you can't apply Juki's answer then after selecting the desired version of media you can use Fiddler to determine where the files are located.

SQL Server 2019 Express Edition (English):

SQL Server 2017 Express Edition (English):

SQL Server 2016 with SP2 Express Edition (English):

SQL Server 2016 with SP1 Express Edition (English):

And here is how to use Fiddler.

Google Authenticator available as a public service?

For C# user, run this simple Console App to understand how to verify the one time token code. Note that we need to install library Otp.Net from Nuget package first.

static string secretKey = "JBSWY3DPEHPK3PXP"; //add this key to your Google Authenticator app  

private static void Main(string[] args)
{
        var bytes = Base32Encoding.ToBytes(secretKey);

        var totp = new Totp(bytes);

        while (true)
        {
            Console.Write("Enter your code from Google Authenticator app: ");
            string userCode = Console.ReadLine();

            //Generate one time token code
            string tokenInApp = totp.ComputeTotp();
            int remainingSeconds = totp.RemainingSeconds();

            if (userCode.Equals(tokenInApp)
                && remainingSeconds > 0)
            {
                Console.WriteLine("Success!");
            }
            else
            {
                Console.WriteLine("Failed. Try again!");
            }
        }
}

How to avoid pressing Enter with getchar() for reading a single character only?

You could include the 'ncurses' library, and use getch() instead of getchar().

Python integer incrementing with ++

Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.

Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().

How to load a xib file in a UIView

You could try:

UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];

Php multiple delimiters in explode

How about this?

/**
 * Like explode with multiple delimiters. 
 * Default delimiters are: \ | / and ,
 *
 * @param string $string String that thould be converted to an array.
 * @param mixed $delimiters Every single char will be interpreted as an delimiter. If a delimiter with multiple chars is needed, use an Array.
 * @return array. If $string is empty OR not a string, return false
 */
public static function multiExplode($string, $delimiters = '\\|/,') 
{
  $delimiterArray = is_array($delimiters)?$delimiters:str_split($delimiters);
  $newRegex = implode('|', array_map (function($delimiter) {return preg_quote($delimiter, '/');}, $delimiterArray));
  return is_string($string) && !empty($string) ? array_map('trim', preg_split('/('.$newRegex.')/', $string, -1, PREG_SPLIT_NO_EMPTY)) : false;
}

In your case you should use an Array for the $delimiters param. Then it is possible to use multiple chars as one delimiter.

If you don't care about trailing spaces in your results, you can remove the array_map('trim', [...] ) part in the return row. (But don't be a quibbler in this case. Keep the preg_split in it.)

Required PHP Version: 5.3.0 or higher.

You can test it here

How to read the post request parameters using JavaScript

One option is to set a cookie in PHP.

For example: a cookie named invalid with the value of $invalid expiring in 1 day:

setcookie('invalid', $invalid, time() + 60 * 60 * 24);

Then read it back out in JS (using the JS Cookie plugin):

var invalid = Cookies.get('invalid');

if(invalid !== undefined) {
    Cookies.remove('invalid');
}

You can now access the value from the invalid variable in JavaScript.

Changing website favicon dynamically

Why not?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

What is the purpose of using -pedantic in GCC/G++ compiler?

I use it all the time in my coding.

The -ansi flag is equivalent to -std=c89. As noted, it turns off some extensions of GCC. Adding -pedantic turns off more extensions and generates more warnings. For example, if you have a string literal longer than 509 characters, then -pedantic warns about that because it exceeds the minimum limit required by the C89 standard. That is, every C89 compiler must accept strings of length 509; they are permitted to accept longer, but if you are being pedantic, it is not portable to use longer strings, even though a compiler is permitted to accept longer strings and, without the pedantic warnings, GCC will accept them too.

How to toggle a boolean?

I was searching after a toggling method that does the same, except for an inital value of null or undefined, where it should become false.

Here it is:

booly = !(booly != false)

val() doesn't trigger change() in jQuery

From redsquare's excellent suggestion, this works nicely:

$.fn.changeVal = function (v) {
    return this.val(v).trigger("change");
}

$("#my-input").changeVal("Tyrannosaurus Rex");

How to get class object's name as a string in Javascript?

Some time ago, I used this.

Perhaps you could try:

+function(){
    var my_var = function get_this_name(){
        alert("I " + this.init());
    };
    my_var.prototype.init = function(){
        return my_var.name;
    }
    new my_var();
}();

Pop an Alert: "I get_this_name".

HTML checkbox - allow to check only one checkbox

The unique name identifier applies to radio buttons:

<input type="radio" />

change your checkboxes to radio and everything should be working

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

Test if characters are in a string

Also, can be done using "stringr" library:

> library(stringr)
> chars <- "test"
> value <- "es"
> str_detect(chars, value)
[1] TRUE

### For multiple value case:
> value <- c("es", "l", "est", "a", "test")
> str_detect(chars, value)
[1]  TRUE FALSE  TRUE FALSE  TRUE

Pandas: Convert Timestamp to datetime.date

Assume time column is in timestamp integer msec format

1 day = 86400000 ms

Here you go:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 
  theme_bw()

enter image description here

Second line in li starts under the bullet after CSS-reset

The li tag has a property called list-style-position. This makes your bullets inside or outside the list. On default, it’s set to inside. That makes your text wrap around it. If you set it to outside, the text of your li tags will be aligned.

The downside of that is that your bullets won't be aligned with the text outside the ul. If you want to align it with the other text you can use a margin.

ul li {
    /*
     * We want the bullets outside of the list,
     * so the text is aligned. Now the actual bullet
     * is outside of the list’s container
     */
    list-style-position: outside;

    /*
     * Because the bullet is outside of the list’s
     * container, indent the list entirely
     */
    margin-left: 1em;
}

Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement

  • Changed the code block to provide just the solution
  • Changed the indentation unit to em’s
  • Each property is applied to the ul element
  • Good comments :)

npm install from Git in a specific version

My example comment to @qubyte above got chopped, so here's something that's easier to read...

The method @surjikal described above works for branch commits, but it didn't work for a tree commit I was trying include.


The archive mode also works for commits. For example, fetch @ a2fbf83

npm:

npm install  https://github.com/github/fetch/archive/a2fbf834773b8dc20eef83bb53d081863d3fc87f.tar.gz

yarn:

yarn add  https://github.com/github/fetch/archive/a2fbf834773b8dc20eef83bb53d081863d3fc87f.tar.gz

format:

 https://github.com/<owner>/<repo>/archive/<commit-id>.tar.gz


Here's the tree commit that required the /archive/ mode:

yarn add  https://github.com/vuejs/vuex/archive/c3626f779b8ea902789dd1c4417cb7d7ef09b557.tar.gz

for the related vuex commit

Using Jquery Datatable with AngularJs

After many hours of experimenting with using jQueryDataTables with Angular, I found what I needed was available with a native Angular directive called ng-table. It provides sorting, pagination, and ajax reloads (sort of lazy loading capable with a few tweaks).

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

If you are using Developer Edition of SQL Server change ".\SQLEXPRESS" to your computer name in connection string.

Before:

Data Source=.\SQLEXPRESS;Initial Catalog=SchoolDB-EF6CodeFirst;Integrated Security=True;MultipleActiveResultSets=True

After:

Data Source=DESKTOP-DKV41G2;Initial Catalog=SchoolDB-EF6CodeFirst;Integrated Security=True;MultipleActiveResultSets=True

String formatting in Python 3

Here are the docs about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

"({0.goals} goals, ${0.penalties})".format(self)

Explaining:

  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.

There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:

"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'

Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

Difference between StringBuilder and StringBuffer

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

because of this it does not allow two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes . String Buffer can be converted to the string by using toString() method.

StringBuffer demo1 = new StringBuffer(“Hello”) ;
// The above object stored in heap and its value can be changed .

demo1=new StringBuffer(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. StringBuilder is fast as it is not thread safe .

StringBuilder demo2= new StringBuilder(“Hello”);
// The above object too is stored in the heap and its value can be modified

demo2=new StringBuilder(“Bye”);
// Above statement is right as it modifies the value which is allowed in the StringBuilder

enter image description here

Resource: String Vs StringBuffer Vs StringBuilder

How to dismiss notification after action has been clicked

You will need to run the following code after your intent is fired to remove the notification.

NotificationManagerCompat.from(this).cancel(null, notificationId);

NB: notificationId is the same id passed to run your notification

Python xml ElementTree from a string source?

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

ng-model for `<input type="file"/>` (with directive DEMO)

function filesModelDirective(){
  return {
    controller: function($parse, $element, $attrs, $scope){
      var exp = $parse($attrs.filesModel);
      $element.on('change', function(){
        exp.assign($scope, this.files[0]);
        $scope.$apply();
      });
    }
  };
}
app.directive('filesModel', filesModelDirective);

Clear form after submission with jQuery

Just add this to your Action file in some div or td, so that it comes with incoming XML object

    <script type="text/javascript">
    $("#formname").resetForm();
    </script>

Where "formname" is the id of form you want to edit

Git keeps asking me for my ssh key passphrase

This has been happening to me after restarts since upgrading from OS X El Capitan (10.11) to macOS Sierra (10.12). The ssh-add solution worked temporarily but would not persist across another restart.

The permanent solution was to edit (or create) ~/.ssh/config and enable the UseKeychain option.

Host *
    UseKeychain yes

Related: macOS keeps asking my ssh passphrase since I updated to Sierra

Maximum on http header values?

As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).

It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:

pagesize.c:

#include <unistd.h>
#include <stdio.h>

int main() {
    int pageSize = getpagesize();
    printf("Page size on your system = %i bytes\n", pageSize);
    return 0;
}

Compile with gcc -o pagesize pagesize.c then run ./pagesize. My ubuntu server from Linode dutifully informs me the answer is 4k.

How do we change the URL of a working GitLab install?

There are detailed notes on this that helped me completely, located here.

Jonathon Reinhart has already answered with the key bit, to edit /etc/gitlab/gitlab.rb, alter the external_url and then run sudo gitlab-ctl reconfigure; sudo gitlab-ctl restart

However I needed to go a bit further and docs I linked above explained it. So what I ended up with looks like:

external_url 'https://gitlab.toilethumor.com'
nginx['ssl_certificate'] = "/www/ssl/star_toilethumor.com-chained.crt"
nginx['ssl_certificate_key'] = "/www/ssl/star_toilethumor.com.key"
nginx['proxy_set_headers'] = {
 "X-Forwarded-Proto" => "http",
 "CUSTOM_HEADER" => "VALUE"
}

Above, I've explicitly declared where my SSL goodies are on this server. And that's of course followed by

sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart

Also, when you switch the omnibus package to https, the bundled nginx will only serve on port 443. Since all my stuff is reached via reverse proxy, this part was potentially significant.

As I went through this, I screwed something up and it helpful to find the actual nginx logs, this lead me there:

sudo gitlab-ctl tail nginx

Program to find largest and smallest among 5 numbers without using array

For example 5 consecutive numbers

int largestNumber;
int smallestNumber;
int number;
std::cin>>number;
largestNumber = number;
smallestNumber = number;
for (i=0 ; i<5; i++)
{
   std::cin>>number;
   if (number > largestNumber) 
   {
     largest = number;
   }
   if (numbers < smallestNumber) 
   {
     smallestNumber= number;
   }
}

Recommended way to insert elements into map

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. operator[] needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

How do I create a message box with "Yes", "No" choices and a DialogResult?

dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);

if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
    enter code here
}
else 
{
    enter code here
}

Check more detail from here

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

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

JavaScript is always pass-by-value; everything is of value type.

Objects are values, and member functions of objects are values themselves (remember that functions are first-class objects in JavaScript). Also, regarding the concept that everything in JavaScript is an object; this is wrong. Strings, symbols, numbers, booleans, nulls, and undefineds are primitives.

On occasion they can leverage some member functions and properties inherited from their base prototypes, but this is only for convenience. It does not mean that they are objects themselves. Try the following for reference:

x = "test";
alert(x.foo);
x.foo = 12;
alert(x.foo);

In both alerts you will find the value to be undefined.

Vue-router redirect on page not found (404)

@mani's Original answer is all you want, but if you'd also like to read it in official way, here's

Reference to Vue's official page:

https://router.vuejs.org/guide/essentials/history-mode.html#caveat