Programs & Examples On #Packet capture

is for questions about capturing packets of various protocols that are transmitted over a network.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

Rather than using a DisplayFilter you could use a very simple CaptureFilter like

port 53

See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

iPhone and WireShark

The easiest way of doing this will be to use wifi of course. You will need to determine if your wifi base acts as a hub or a switch. If it acts as a hub then just connect your windows pc to it and wireshark should be able to see all the traffic from the iPhone. If it is a switch then your easiest bet will be to buy a cheap hub and connect the wan side of your wifi base to the hub and then connect your windows pc running wireshark to the hub as well. At that point wireshark will be able to see all the traffic as it passes over the hub.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

Wireshark localhost traffic capture

You can view loopback traffic live in Wireshark by having it read RawCap's output instantly. cmaynard describes this ingenious approach at the Wireshark forums. I will cite it here:

[...] if you want to view live traffic in Wireshark, you can still do it by running RawCap from one command-line and running Wireshark from another. Assuming you have cygwin's tail available, this could be accomplished using something like so:

cmd1: RawCap.exe -f 127.0.0.1 dumpfile.pcap

cmd2: tail -c +0 -f dumpfile.pcap | Wireshark.exe -k -i -

It requires cygwin's tail, and I could not find a way to do this with Windows' out-of-the-box tools. His approach works very fine for me and allows me to use all of Wiresharks filter capabilities on captured loopback traffic live.

How to reload a page using JavaScript

location.reload();

See this MDN page for more information.

If you are refreshing after an onclick then you'll need to return false directly after

location.reload();
return false;

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

The ScriptManager must appear before any controls that need it

It simply wants the ASP control on your ASPX page. I usually place mine right under the tag, or inside first Content area in the master's body (if your using a master page)

<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
        <div>
            [Content]
        </div>
    </form>
</body>

SQL Left Join first match only

Turns out I was doing it wrong, I needed to perform a nested select first of just the important columns, and do a distinct select off that to prevent trash columns of 'unique' data from corrupting my good data. The following appears to have resolved the issue... but I will try on the full dataset later.

SELECT DISTINCT P2.*
FROM (
  SELECT
      IDNo
    , FirstName
    , LastName
  FROM people P
) P2

Here is some play data as requested: http://sqlfiddle.com/#!3/050e0d/3

CREATE TABLE people
(
       [entry] int
     , [IDNo] varchar(3)
     , [FirstName] varchar(5)
     , [LastName] varchar(7)
);

INSERT INTO people
    (entry,[IDNo], [FirstName], [LastName])
VALUES
    (1,'uqx', 'bob', 'smith'),
    (2,'abc', 'john', 'willis'),
    (3,'ABC', 'john', 'willis'),
    (4,'aBc', 'john', 'willis'),
    (5,'WTF', 'jeff', 'bridges'),
    (6,'Sss', 'bill', 'doe'),
    (7,'sSs', 'bill', 'doe'),
    (8,'ssS', 'bill', 'doe'),
    (9,'ere', 'sally', 'abby'),
    (10,'wtf', 'jeff', 'bridges')
;

Remove all padding and margin table HTML and CSS

Tables are odd elements. Unlike divs they have special rules. Add cellspacing and cellpadding attributes, set to 0, and it should fix the problem.

<table id="page" width="100%" border="0" cellspacing="0" cellpadding="0">

Can media queries resize based on a div element instead of the screen?

You can use the ResizeObserver API. It's still in it's early days so it's not supported by all browsers yet (but there several polyfills that can help you with that).

Basically this API allow you to attach an event listener to the resize of a DOM element.

Demo 1 - Demo 2

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):

path =   'C:\Users\myUserName\project\subfolder'
path   # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path)              # gives windows error
path =   'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path)              # gives expected behavior

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

What are all the common ways to read a file in Ruby?

file_content = File.read('filename with extension');
puts file_content;

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

{apache_dir}/conf.d/ssl.conf

This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

path.join vs path.resolve with __dirname

Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.

path.join returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.

For instance:

path.join('app/libs/oauth', '/../ssl')

resolves to app/libs/ssl

path.resolve, on the other hand, will resolve to an absolute path.

For instance, when you run:

path.resolve('bar', '/foo');

The path returned will be /foo since that is the first absolute path that can be constructed.

However, if you run:

path.resolve('/bar/bae', '/foo', 'test');

The path returned will be /foo/test again because that is the first absolute path that can be formed from right to left.

If you don't provide a path that specifies the root directory then the paths given to the resolve function are appended to the current working directory. So if your working directory was /home/mark/project/:

path.resolve('test', 'directory', '../back');

resolves to

/home/mark/project/test/back

Using __dirname is the absolute path to the directory containing the source file. When you use path.resolve or path.join they will return the same result if you give the same path following __dirname. In such cases it's really just a matter of preference.

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

Get single listView SelectedItem

If its just a natty little app with one or two ListViews I normally just create a little helper property:

private ListViewItem SelectedItem { get { return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null); } }

If I have loads, then move it out to a helper class:

internal static class ListViewEx
{
    internal static ListViewItem GetSelectedItem(this ListView listView1)
    {
        return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null);
    }
}

so:

ListViewItem item = lstFixtures.GetSelectedItem();

The ListView interface is a bit rubbish so I normally find the helper class grows quite quickly.

Creating default object from empty value in PHP?

This is a warning which I faced in PHP 7, the easy fix to this is by initializing the variable before using it

$myObj=new \stdClass();

Once you have intialized it then you can use it for objects

 $myObj->mesg ="Welcome back - ".$c_user;

Rotating a view in Android

One line in XML


<View
    android:rotation="45"
    ... />

Understanding implicit in Scala

A very basic example of Implicits in scala.

Implicit parameters:

val value = 10
implicit val multiplier = 3
def multiply(implicit by: Int) = value * by
val result = multiply // implicit parameter wiil be passed here
println(result) // It will print 30 as a result

Note: Here multiplier will be implicitly passed into the function multiply. Missing parameters to the function call are looked up by type in the current scope meaning that code will not compile if there is no implicit variable of type Int in the scope.

Implicit conversions:

implicit def convert(a: Double): Int = a.toInt
val res = multiply(2.0) // Type conversions with implicit functions
println(res)  // It will print 20 as a result

Note: When we call multiply function passing a double value, the compiler will try to find the conversion implicit function in the current scope, which converts Int to Double (As function multiply accept Int parameter). If there is no implicit convert function then the compiler will not compile the code.

handle textview link click in my android app

Just to share an alternative solution using a library I created. With Textoo, this can be achieved like:

TextView locNotFound = Textoo
    .config((TextView) findViewById(R.id.view_location_disabled))
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            if ("internal://settings/location".equals(url)) {
                Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(locSettings);
                return true;
            } else {
                return false;
            }
        }
    })
    .apply();

Or with dynamic HTML source:

String htmlSource = "Links: <a href='http://www.google.com'>Google</a>";
Spanned linksLoggingText = Textoo
    .config(htmlSource)
    .parseHtml()
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            Log.i("MyActivity", "Linking to google...");
            return false; // event not handled.  Continue default processing i.e. link to google
        }
    })
    .apply();
textView.setText(linksLoggingText);

How to unpackage and repackage a WAR file

Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:

sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/templates/fragments/header.html
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh

Add params to given URL in Python

Based on this answer, one-liner for simple cases (Python 3 code):

from urllib.parse import urlparse, urlencode


url = "https://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}

url += ('&' if urlparse(url).query else '?') + urlencode(params)

or:

url += ('&', '?')[urlparse(url).query == ''] + urlencode(params)

Compiling C++11 with g++

Your Ubuntu definitely has a sufficiently recent version of g++. The flag to use is -std=c++0x.

Entity Framework : How do you refresh the model when the db changes?

I just had to update an .edmx model. The model/Run Custom Tool option was not refreshing the fields for me, but once I had the graphical designer open, I was able to manually rename the fields.

Download File Using jQuery

  • Using jQuery function

        var valFileDownloadPath = 'http//:'+'your url';
    
       window.open(valFileDownloadPath , '_blank');
    

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...

UICollectionView Self Sizing Cells with Auto Layout

To whomever it may help,

I had that nasty crash if estimatedItemSize was set. Even if I returned 0 in numberOfItemsInSection. Therefore, the cells themselves and their auto-layout were not the cause of the crash... The collectionView just crashed, even when empty, just because estimatedItemSize was set for self-sizing.

In my case I reorganized my project, from a controller containing a collectionView to a collectionViewController, and it worked.

Go figure.

Abstract class in Java

An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract. Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.

Angular 2: How to style host element of the component?

I have found a solution how to style just the component element. I have not found any documentation how it works, but you can put attributes values into the component directive, under the 'host' property like this:

@Component({
    ...
    styles: [`
      :host {
        'style': 'display: table; height: 100%',
        'class': 'myClass'
      }`
})
export class MyComponent
{
    constructor() {}

    // Also you can use @HostBinding decorator
    @HostBinding('style.background-color') public color: string = 'lime';
    @HostBinding('class.highlighted') public highlighted: boolean = true;
}

UPDATE: As Günter Zöchbauer mentioned, there was a bug, and now you can style the host element even in css file, like this:

:host{ ... }

Calling Javascript from a html form

There are a few things to change in your edited version:

  1. You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].

  2. There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>

  3. Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).

  4. Because of #3, get rid of everything not the alert statement in your handler.

The code should now look like:

function handleClick()
      {
        alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
      }
    </script>
  </head>
<body>
    <form name="aye">
      <input name="Submit"  type="submit" value="Update" onclick="handleClick();return false"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>

Why doesn't Python have a sign function?

It just doesn't.

The best way to fix this is:

sign = lambda x: bool(x > 0) - bool(x < 0)

Why is jquery's .ajax() method not sending my session cookie?

Adding my scenario and solution in case it helps someone else. I encountered similar case when using RESTful APIs. My Web server hosting HTML/Script/CSS files and Application Server exposing APIs were hosted on same domain. However the path was different.

web server - mydomain/webpages/abc.html

used abc.js which set cookie named mycookie

app server - mydomain/webapis/servicename.

to which api calls were made

I was expecting the cookie in mydomain/webapis/servicename and tried reading it but it was not being sent. After reading comment from the answer, I checked in browser's development tool that mycookie's path was set to "/webpages" and hence not available in service call to

mydomain/webapis/servicename

So While setting cookie from jquery, this is what I did -

$.cookie("mycookie","mayvalue",{**path:'/'**});

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

docker command not found even though installed with apt-get

IMPORTANT - on ubuntu package docker is something entirely different ( avoid it ) :

issue following to view what if any packages you have mentioning docker

dpkg -l|grep docker

if only match is following then you do NOT have docker installed below is an unrelated package

docker - System tray for KDE3/GNOME2 docklet applications

if you see something similar to following then you have docker installed

 dpkg -l|grep docker

ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

NOTE - ubuntu package docker.io is not getting updates ( obsolete do NOT use )


Instead do this : install the latest version of docker on linux by executing the following:

  sudo curl -sSL https://get.docker.com/ | sh
# sudo curl -sSL https://test.docker.com | sh  # get dev pipeline version
  

here is a typical output ( ubuntu 16.04 )

apparmor is enabled in the kernel and apparmor utils were already installed
+ sudo -E sh -c apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
Executing: /tmp/tmp.rAAGu0P85R/gpg.1.sh --keyserver
hkp://ha.pool.sks-keyservers.net:80
--recv-keys
58118E89F3A912897C070ADBF76221572C52609D
gpg: requesting key 2C52609D from hkp server ha.pool.sks-keyservers.net
gpg: key 2C52609D: "Docker Release Tool (releasedocker) <[email protected]>" 1 new signature
gpg: Total number processed: 1
gpg:         new signatures: 1
+ break
+ sudo -E sh -c apt-key adv -k 58118E89F3A912897C070ADBF76221572C52609D >/dev/null
+ sudo -E sh -c mkdir -p /etc/apt/sources.list.d
+ dpkg --print-architecture
+ sudo -E sh -c echo deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main > /etc/apt/sources.list.d/docker.list
+ sudo -E sh -c sleep 3; apt-get update; apt-get install -y -q docker-engine
Hit:1 http://repo.steampowered.com/steam precise InRelease
Hit:2 http://download.virtualbox.org/virtualbox/debian xenial InRelease                                                           
Ign:3 http://dl.google.com/linux/chrome/deb stable InRelease                                                                      
Hit:4 http://dl.google.com/linux/chrome/deb stable Release                                                                        
Hit:5 http://archive.canonical.com/ubuntu xenial InRelease                                                                        
Hit:6 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial InRelease                                                     
Hit:7 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-updates InRelease                                             
Hit:8 http://ppa.launchpad.net/me-davidsansome/clementine/ubuntu xenial InRelease                                                 
Ign:9 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 InRelease                                                         
Hit:10 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-backports InRelease                                          
Hit:11 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 Release                                                          
Hit:12 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial-security InRelease                                           
Hit:14 http://ppa.launchpad.net/numix/ppa/ubuntu xenial InRelease                                                                 
Ign:15 http://linux.dropbox.com/ubuntu wily InRelease                                                                             
Ign:16 http://repo.vivaldi.com/stable/deb stable InRelease                                                                        
Hit:17 http://repo.vivaldi.com/stable/deb stable Release                                                                          
Get:18 http://linux.dropbox.com/ubuntu wily Release [6,596 B]            
Get:19 https://apt.dockerproject.org/repo ubuntu-xenial InRelease [20.6 kB]    
Ign:20 http://packages.amplify.nginx.com/ubuntu xenial InRelease                      
Hit:22 http://packages.amplify.nginx.com/ubuntu xenial Release
Hit:23 https://deb.opera.com/opera-beta stable InRelease
Hit:26 https://deb.opera.com/opera-developer stable InRelease
Get:28 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 Packages [1,719 B]
Hit:29 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Fetched 28.9 kB in 1s (17.2 kB/s)
Reading package lists... Done
W: http://repo.mongodb.org/apt/debian/dists/wheezy/mongodb-org/3.2/Release.gpg: Signature by key 42F3E95A2C4F08279C4960ADD68FA50FEA312927 uses weak digest algorithm (SHA1)
Reading package lists...
Building dependency tree...
Reading state information...
The following additional packages will be installed:
  aufs-tools cgroupfs-mount
The following NEW packages will be installed:
  aufs-tools cgroupfs-mount docker-engine
0 upgraded, 3 newly installed, 0 to remove and 17 not upgraded.
Need to get 14.6 MB of archives.
After this operation, 73.7 MB of additional disk space will be used.
Get:1 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 aufs-tools amd64 1:3.2+20130722-1.1ubuntu1 [92.9 kB]
Get:2 http://mirror.cc.columbia.edu/pub/linux/ubuntu/archive xenial/universe amd64 cgroupfs-mount all 1.2 [4,970 B]
Get:3 https://apt.dockerproject.org/repo ubuntu-xenial/main amd64 docker-engine amd64 1.11.2-0~xenial [14.5 MB]
Fetched 14.6 MB in 7s (2,047 kB/s)
Selecting previously unselected package aufs-tools.
(Reading database ... 427978 files and directories currently installed.)
Preparing to unpack .../aufs-tools_1%3a3.2+20130722-1.1ubuntu1_amd64.deb ...
Unpacking aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Selecting previously unselected package cgroupfs-mount.
Preparing to unpack .../cgroupfs-mount_1.2_all.deb ...
Unpacking cgroupfs-mount (1.2) ...
Selecting previously unselected package docker-engine.
Preparing to unpack .../docker-engine_1.11.2-0~xenial_amd64.deb ...
Unpacking docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for systemd (229-4ubuntu6) ...
Setting up aufs-tools (1:3.2+20130722-1.1ubuntu1) ...
Setting up cgroupfs-mount (1.2) ...
Setting up docker-engine (1.11.2-0~xenial) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu6) ...
Processing triggers for ureadahead (0.100.0-19) ...
+ sudo -E sh -c docker version
Client:
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

Server:
 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   b9f10c9
 Built:        Wed Jun  1 22:00:43 2016
 OS/Arch:      linux/amd64

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker stens

Remember that you will have to log out and back in for this to take effect!

Here is the underlying detailed install instructions which as you can see comes bundled into above technique ... Above one liner gives you same as :

https://docs.docker.com/engine/installation/linux/ubuntulinux/

Once installed you can see what docker packages were installed by issuing

dpkg -l|grep docker
ii  docker-ce                                  5:19.03.13~3-0~ubuntu-focal         amd64        Docker: the open-source application container engine
ii  docker-ce-cli                              5:19.03.13~3-0~ubuntu-focal         amd64        Docker CLI: the open-source application container engine

now Docker updates will get installed going forward when you issue

sudo apt-get update
sudo apt-get upgrade

take a look at

 ls -latr /etc/apt/sources.list.d/*docker*
-rw-r--r-- 1 root root 202 Jun 23 10:01 /etc/apt/sources.list.d/docker.list.save
-rw-r--r-- 1 root root  71 Jul  4 11:32 /etc/apt/sources.list.d/docker.list


cat /etc/apt/sources.list.d/docker.list

deb [arch=amd64] https://apt.dockerproject.org/repo ubuntu-xenial main

or more generally

cd /etc/apt
grep -r docker *
sources.list.d/docker.list:deb [arch=amd64] https://download.docker.com/linux/ubuntu focal test

Iterator invalidation rules

C++17 (All references are from the final working draft of CPP17 - n4659)


Insertion

Sequence Containers

  • vector: The functions insert, emplace_back, emplace, push_back cause reallocation if the new size is greater than the old capacity. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. If no reallocation happens, all the iterators and references before the insertion point remain valid. [26.3.11.5/1]
    With respect to the reserve function, reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity(). [26.3.11.3/6]

  • deque: An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque. [26.3.8.4/1]

  • list: Does not affect the validity of iterators and references. If an exception is thrown there are no effects. [26.3.10.4/1].
    The insert, emplace_front, emplace_back, emplace, push_front, push_back functions are covered under this rule.

  • forward_list: None of the overloads of insert_after shall affect the validity of iterators and references [26.3.9.5/1]

  • array: As a rule, iterators to an array are never invalidated throughout the lifetime of the array. One should take note, however, that during swap, the iterator will continue to point to the same array element, and will thus change its value.

Associative Containers

  • All Associative Containers: The insert and emplace members shall not affect the validity of iterators and references to the container [26.2.6/9]

Unordered Associative Containers

  • All Unordered Associative Containers: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. [26.2.7/9]
    The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. [26.2.7/14]
    The insert and emplace members shall not affect the validity of iterators if (N+n) <= z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor. [26.2.7/15]

  • All Unordered Associative Containers: In case of a merge operation (e.g., a.merge(a2)), iterators referring to the transferred elements and all iterators referring to a will be invalidated, but iterators to elements remaining in a2 will remain valid. (Table 91 — Unordered associative container requirements)

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

Erasure

Sequence Containers

  • vector: The functions erase and pop_back invalidate iterators and references at or after the point of the erase. [26.3.11.5/3]

  • deque: An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only iterators and references to the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque. [ Note: pop_front and pop_back are erase operations. —end note ] [26.3.8.4/4]

  • list: Invalidates only the iterators and references to the erased elements. [26.3.10.4/3]. This applies to erase, pop_front, pop_back, clear functions.
    remove and remove_if member functions: Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value, pred(*i) != false. Invalidates only the iterators and references to the erased elements [26.3.10.5/15].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version of unique with no arguments) or pred(*i, *(i - 1)) (for the version of unique with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.10.5/19]

  • forward_list: erase_after shall invalidate only iterators and references to the erased elements. [26.3.9.5/1].
    remove and remove_if member functions - Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements. [26.3.9.6/12].
    unique member function - Erases all but the first element from every consecutive group of equal elements referred to by the iterator i in the range [first + 1, last) for which *i == *(i-1) (for the version with no arguments) or pred(*i, *(i - 1)) (for the version with a predicate argument) holds. Invalidates only the iterators and references to the erased elements. [26.3.9.6/16]

  • All Sequence Containers: clear invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator (Table 87 — Sequence container requirements). But for forward_list, clear does not invalidate past-the-end iterators. [26.3.9.5/32]

  • All Sequence Containers: assign invalidates all references, pointers and iterators referring to the elements of the container. For vector and deque, also invalidates the past-the-end iterator. (Table 87 — Sequence container requirements)

Associative Containers

  • All Associative Containers: The erase members shall invalidate only iterators and references to the erased elements [26.2.6/9]

  • All Associative Containers: The extract members invalidate only iterators to the removed element; pointers and references to the removed element remain valid [26.2.6/10]

Container Adaptors

  • stack: inherited from underlying container
  • queue: inherited from underlying container
  • priority_queue: inherited from underlying container

General container requirements relating to iterator invalidation:

  • Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [26.2.1/12]

  • no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [26.2.1/(11.6)]

As examples of the above requirements:

  • transform algorithm: The op and binary_op functions shall not invalidate iterators or subranges, or modify elements in the ranges [28.6.4/1]

  • accumulate algorithm: In the range [first, last], binary_op shall neither modify elements nor invalidate iterators or subranges [29.8.2/1]

  • reduce algorithm: binary_op shall neither invalidate iterators or subranges, nor modify elements in the range [first, last]. [29.8.3/5]

and so on...

Error inflating class android.support.design.widget.NavigationView

I was also having this same issue, after looking nearly 3 hours I find out that the problem was in my drawable_menu.xml file, it was wrongly written :D

How to drop columns using Rails migration

There are two good ways to do this:

remove_column

You can simply use remove_column, like so:

remove_column :users, :first_name

This is fine if you only need to make a single change to your schema.

change_table block

You can also do this using a change_table block, like so:

change_table :users do |t|
  t.remove :first_name
end

I prefer this as I find it more legible, and you can make several changes at once.

Here's the full list of supported change_table methods:

http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_table

Eclipse CDT: Symbol 'cout' could not be resolved

If all else fails, like it did in my case, then just disable annotations. I started a c++11 project with own makefile but couldn't fix all the problems. Even if you disable annotations, eclipse will still be able to help you do some autocompletion. Most importantly, the debugger still works!

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

How can I reuse a navigation bar on multiple pages?

I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.

First, create a page with all the navigation bar's HTML content.

Next, use jQuery's $.get method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html and added a placeholder tag (Like <div id="nav-placeholder">) in your index.html, then you would use the following code:

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
    $("#nav-placeholder").replaceWith(data);
});
</script>

How can I create a Java method that accepts a variable number of arguments?

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

Passing references to pointers in C++

The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is const.

So you can do one of either the following:

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}


void myfunc2(string* const& val)
{
    // Do stuff to the string pointer
}

int main()
// sometime later 
{
    // ...
    string s;
    string* ps = &s;

    myfunc( ps);   // OK because ps is not a temporary
    myfunc2( &s);  // OK because the parameter is a const&
    // ...

    return 0;
}

SQL is null and = null

It's important to note, that NULL doesn't equal NULL.

NULL is not a value, and therefore cannot be compared to another value.

where x is null checks whether x is a null value.

where x = null is checking whether x equals NULL, which will never be true

Best way to "push" into C# array

This is acceptable as assigning to an array. But if you are asking for pushing, I am pretty sure its not possible in array. Rather it can be achieved by using Stack, Queue or any other data structure. Real arrays doesn't have such functions. But derived classes such as ArrayList have it.

How to handle ListView click in Android

In Kotlin, add a listener to your listView as simple as java

your_listview.setOnItemClickListener { parent, view, position, id ->   

    Toast.makeText(this, position, Toast.LENGTH_SHORT).show()

 }

What is the Git equivalent for revision number?

The SHA1 hash of the commit is the equivalent to a Subversion revision number.

How do I compare two strings in python?

open both of the files then compare them by splitting its word contents;

log_file_A='file_A.txt'

log_file_B='file_B.txt'

read_A=open(log_file_A,'r')
read_A=read_A.read()
print read_A

read_B=open(log_file_B,'r')
read_B=read_B.read()
print read_B

File_A_set = set(read_A.split(' '))
File_A_set = set(read_B.split(' '))
print File_A_set == File_B_set

ElasticSearch - Return Unique Values

You can use the terms aggregation.

{
"size": 0,
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  "size" : 500 }
    }
}}

The size parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.

A search will return something like:

{
"took" : 16,
"timed_out" : false,
"_shards" : {
  "total" : 2,
  "successful" : 2,
  "failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
  "langs" : {
    "buckets" : [ {
      "key" : "10",
      "doc_count" : 244812
    }, {
      "key" : "11",
      "doc_count" : 136794
 
    }, {
      "key" : "12",
      "doc_count" : 32312
       } ]
    }
  }
}

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

  1. Make a jar file from your applet class and META-INF/MANIFEST.MF file.
  2. Sign your jar file with your certificate.
  3. Configure your local site permissions as > file:///C:/ or http: //localhost:8080
  4. Then run your html document on Intenet Explorer on Windows.(Not Google Chrome !)

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

How to prevent IFRAME from redirecting top-level window

Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.

Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

In HTML5 you can use sandbox property. Please see Pankrat's answer below. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

Python dictionary: Get list of values for list of keys

Or just mydict.keys() That's a builtin method call for dictionaries. Also explore mydict.values() and mydict.items().

//Ah, OP post confused me.

size of struct in C

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

Change select box option background color

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

SQL Server Group By Month

Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

If you have a date (not a datetime) value, then you can zero it directly:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )

If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )

Maven compile: package does not exist

You have to add the following dependency to your build:

<dependency>
    <groupId>org.openrdf.sesame</groupId>
    <artifactId>sesame-rio-api</artifactId>
    <version>2.7.2</version>
</dependency>

Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

Oracle: How to filter by date and time in a where clause

Put it this way

where ("R"."TIME_STAMP">=TO_DATE ('03-02-2013 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
   AND "R"."TIME_STAMP"<=TO_DATE ('09-02-2013 23:59:59', 'DD-MM-YYYY HH24:MI:SS')) 

Where R is table name.
TIME_STAMP is FieldName in Table R.

How do I export a project in the Android studio?

Follow the below steps to sign the application in the android studio:-

  1. First Go to Build->Generate Signed APK

    First screenshot

  2. Then Once you click on the Generate Signed APK then there is info dialog message appear.

    Second screenshot

  3. Click on the Create New button if you don't have any keystore file. If you have click on the Choose Existing.

    This screenshot

  4. Once you click on the Create New button then now dialog box appear where you need to enter the keystore file info, other signing authority details.

    Fourth screenshot

  5. Once you fill complete details then click on the Ok button then it redirect to this dialog.

    Fifth screenshot

  6. Click on the Next button then check mark on the Run ProGuard and click on the finish. It generate the signed APK.

    Sixth screenshot

    Seventh screenshot

Error CS2001: Source file '.cs' could not be found

In my case, I add file as Link from another project and then rename file in source project that cause problem in destination project. I delete linked file in destination and add again with new name.

Android Transparent TextView?

try to set the transparency with the android-studio designer in activity_main.xml. If you want it to be transparent, write it for example like this for white: White: #FFFFFF, with 50% transparency: #80FFFFFF This is for Kotlin tho, not sure if that will work the same way for basic android (java).

List names of all tables in a SQL Server 2012 schema

SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'schema_name';

SpringMVC RequestMapping for GET parameters

You can add @RequestMapping like so:

@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
   @RequestParam("_search") String search,
   @RequestParam String nd,
   @RequestParam int rows,
   @RequestParam int page,
   @RequestParam String sidx) 
   @RequestParam String sord) {

Steps to send a https request to a rest service in Node js

Using the request module solved the issue.

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = "vinod"; 
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(   
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }  
},
 function (error, response, body) {
 console.log(body); }  );         

Convert special characters to HTML in Javascript

From Mozilla ...

Note that charCodeAt will always return a value that is less than 65,536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. Because of this, in order to examine or reproduce the full character for individual characters of value 65,536 and above, for such characters, it is necessary to retrieve not only charCodeAt(i), but also charCodeAt(i+1) (as if examining/reproducing a string with two >letters).

The Best Solution

/**
 * (c) 2012 Steven Levithan <http://slevithan.com/>
 * MIT license
 */
if (!String.prototype.codePointAt) {
    String.prototype.codePointAt = function (pos) {
        pos = isNaN(pos) ? 0 : pos;
        var str = String(this),
            code = str.charCodeAt(pos),
            next = str.charCodeAt(pos + 1);
        // If a surrogate pair
        if (0xD800 <= code && code <= 0xDBFF && 0xDC00 <= next && next <= 0xDFFF) {
            return ((code - 0xD800) * 0x400) + (next - 0xDC00) + 0x10000;
        }
        return code;
    };
}

/**
 * Encodes special html characters
 * @param string
 * @return {*}
 */
function html_encode(string) {
    var ret_val = '';
    for (var i = 0; i < string.length; i++) { 
        if (string.codePointAt(i) > 127) {
            ret_val += '&#' + string.codePointAt(i) + ';';
        } else {
            ret_val += string.charAt(i);
        }
    }
    return ret_val;
}

Usage example:

html_encode("?");

What is the point of the diamond operator (<>) in Java 7?

Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.

Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.

Using List<String> list = new LinkedList() will get you rawtype warnings.

How to SUM two fields within an SQL query

SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

Consider this example,

ID  VALUE1  VALUE2
===================
1   1       2
1   2       2
2   3       4
2   4       5

 

SELECT  ID, SUM(VALUE1), SUM(VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1), SUM(VALUE2)
1   3           4
2   7           9

 

SELECT  ID, VALUE1 + VALUE2
FROM    TableName

will result

ID, VALUE1 + VALUE2
1   3
1   4
2   7
2   9

 

SELECT  ID, SUM(VALUE1 + VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1 + VALUE2)
1   7
2   16

Creating a new directory in C

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.

Daemon Threads Explanation

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. Sleep for a little while.

When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

Changing image on hover with CSS/HTML

My jquery solution.

function changeOverImage(element) {
        var url = $(element).prop('src'),
            url_over = $(element).data('change-over')
        ;

        $(element)
            .prop('src', url_over)
            .data('change-over', url)
        ;
    }
    $(document).delegate('img[data-change-over]', 'mouseover', function () {
        changeOverImage(this);
    });
    $(document).delegate('img[data-change-over]', 'mouseout', function () {
        changeOverImage(this);
    });

and html

<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=%3Cimg%20original%20/%3E&w=342&h=300" data-change-over="https://placeholdit.imgix.net/~text?txtsize=33&txt=%3Cimg%20over%20/%3E&w=342&h=300" />

Demo: JSFiddle demo

Regards

Spring Boot application.properties value not populating

The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.

Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

Stash only one file out of multiple files that have changed with Git?

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

This method works in git versions 2.13+

How do I calculate the date six months from the current date using the datetime Python module?

I have a better way to solve the 'February 31st' problem:

def add_months(start_date, months):
    import calendar

    year = start_date.year + (months / 12)
    month = start_date.month + (months % 12)
    day = start_date.day

    if month > 12:
        month = month % 12
        year = year + 1

    days_next = calendar.monthrange(year, month)[1]
    if day > days_next:
        day = days_next

    return start_date.replace(year, month, day)

I think that it also works with negative numbers (to subtract months), but I haven't tested this very much.

Windows command to get service status?

according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST but i can't get it to work on by XP box. I'm sure there's some WMI that will give you the list.

For a boolean field, what is the naming convention for its getter/setter?

Maybe it is time to start revising this answer? Personally I would vote for setActive() and unsetActive() (alternatives can be setUnActive(), notActive(), disable(), etc. depending on context) since "setActive" implies you activate it at all times, which you don't. It's kind of counter intuitive to say "setActive" but actually remove the active state.

Another problem is, you can can not listen to specifically a SetActive event in a CQRS way, you would need to listen to a 'setActiveEvent' and determine inside that listener wether is was actually set active or not. Or of course determine which event to call when calling setActive() but that then goes against the Separation of Concerns principle.

A good read on this is the FlagArgument article by Martin Fowler: http://martinfowler.com/bliki/FlagArgument.html

However, I come from a PHP background and see this trend being adopted more and more. Not sure how much this lives with Java development.

jQuery: Return data after ajax call success

The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.

You can pass in a callback function that handles the result:

function testAjax(handleData) {
  $.ajax({
    url:"getvalue.php",  
    success:function(data) {
      handleData(data); 
    }
  });
}

Call it like this:

testAjax(function(output){
  // here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

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

I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:

cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'

I can then run this in the terminal or with a ssh to check files against a constant file.

jquery's append not working with svg element?

This is working for me today with FF 57:

function () {
    // JQuery, today, doesn't play well with adding SVG elements - tricks required
    $(selector_to_node_in_svg_doc).parent().prepend($(this).clone().text("Your"));
    $(selector_to_node_in_svg_doc).text("New").attr("x", "340").text("New")
        .attr('stroke', 'blue').attr("style", "text-decoration: line-through");
}

Makes:

this SVG image as seen in Firefox 57

converting CSV/XLS to JSON?

I just found this:

http://tamlyn.org/tools/csv2json/

( Note: you have to have your csv file available via a web address )

How can I copy a file on Unix using C?

sprintf( cmd, "/bin/cp -p \'%s\' \'%s\'", old, new);

system( cmd);

Add some error checks...

Otherwise, open both and loop on read/write, but probably not what you want.

...

UPDATE to address valid security concerns:

Rather than using "system()", do a fork/wait, and call execv() or execl() in the child.

execl( "/bin/cp", "-p", old, new);

TypeError: 'list' object is not callable while trying to access a list

Check your file name in which you have saved your program. If the file name is wordlists then you will get an error. Your filename should not be same as any of methods{functions} that you use in your program.

How do I extract the contents of an rpm?

Most distributions have installed the GUI app file-roller which unpacks tar, zip, rpm and many more.

file-roller --extract-here package.rpm

This will extract the contents in the current directory.

How to remove certain characters from a string in C++?

remove_if() has already been mentioned. But, with C++0x, you can specify the predicate for it with a lambda instead.

Below is an example of that with 3 different ways of doing the filtering. "copy" versions of the functions are included too for cases when you're working with a const or don't want to modify the original.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

string& remove_chars(string& s, const string& chars) {
    s.erase(remove_if(s.begin(), s.end(), [&chars](const char& c) {
        return chars.find(c) != string::npos;
    }), s.end());
    return s;
}
string remove_chars_copy(string s, const string& chars) {
    return remove_chars(s, chars);
}

string& remove_nondigit(string& s) {
    s.erase(remove_if(s.begin(), s.end(), [](const char& c) {
        return !isdigit(c);
    }), s.end());
    return s;
}
string remove_nondigit_copy(string s) {
    return remove_nondigit(s);
}

string& remove_chars_if_not(string& s, const string& allowed) {
    s.erase(remove_if(s.begin(), s.end(), [&allowed](const char& c) {
        return allowed.find(c) == string::npos;
    }), s.end());
    return s;
}
string remove_chars_if_not_copy(string s, const string& allowed) {
    return remove_chars_if_not(s, allowed);
}

int main() {
    const string test1("(555) 555-5555");
    string test2(test1);
    string test3(test1);
    string test4(test1);
    cout << remove_chars_copy(test1, "()- ") << endl;
    cout << remove_chars(test2, "()- ") << endl;
    cout << remove_nondigit_copy(test1) << endl;
    cout << remove_nondigit(test3) << endl;
    cout << remove_chars_if_not_copy(test1, "0123456789") << endl;
    cout << remove_chars_if_not(test4, "0123456789") << endl;
}

javascript code to check special characters

Try This one.

_x000D_
_x000D_
function containsSpecialCharacters(str){_x000D_
    var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;_x000D_
 return regex.test(str);_x000D_
}
_x000D_
_x000D_
_x000D_

req.body empty on posts

I made a really dumb mistake and forgot to define name attributes for inputs in my html file.

So instead of

<input type="password" class="form-control" id="password">

I have this.

<input type="password" class="form-control" id="password" name="password">

Now request.body is populated like this: { password: 'hhiiii' }

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

I was looking for a simple answer to solve this myself. here is what I found

This will split the year and month, take one month off and get the first day.

firstDayInPreviousMonth = DateSerial(Year(dtmDate), Month(dtmDate) - 1, 1)

Gets the first day of the previous month from the current

lastDayInPreviousMonth = DateSerial(Year(dtmDate), Month(dtmDate), 0)

More details can be found at: http://msdn.microsoft.com/en-us/library/aa227522%28v=vs.60%29.aspx

Debugging JavaScript in IE7

Use Internet Explorer 8. Then Try the developer tool.. You can debug based on IE 7 also in compatibility mode

Best way to unselect a <select> in jQuery?

Another simple way:

$("#selectedID")[0].selectedIndex = -1

Checking for empty queryset in Django

To check the emptiness of a queryset:

if orgs.exists():
    # Do something

or you can check for a the first item in a queryset, if it doesn't exist it will return None:

if orgs.first():
    # Do something

TSQL Pivot without aggregate function

yes, but why !!??

   Select CustomerID,
     Min(Case DBColumnName When 'FirstName' Then Data End) FirstName,
     Min(Case DBColumnName When 'MiddleName' Then Data End) MiddleName,
     Min(Case DBColumnName When 'LastName' Then Data End) LastName,
     Min(Case DBColumnName When 'Date' Then Data End) Date
   From table
   Group By CustomerId

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

How to empty a file using Python

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass

Does Java read integers in little endian or big endian?

If it fits the protocol you use, consider using a DataInputStream, where the behavior is very well defined.

How to run a .jar in mac?

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

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

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

Then, you need to install JRE to your machine.

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
          numeric values in fixed or exponential notation.  Positive
          values bias towards fixed and negative towards scientific
          notation: fixed notation will be preferred unless it is more
          than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

How to send and receive JSON data from a restful webservice using Jersey API

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));

How do I specify "close existing connections" in sql script

Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

Angular 2 'component' is not a known element

I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50

Resolved by killing the terminal (ng serve) and restarting VScode.

COALESCE with Hive SQL

If customer primary contact medium is email, if email is null then phonenumber, and if phonenumber is also null then address. It would be written using COALESCE as

coalesce(email,phonenumber,address) 

while the same in hive can be achieved by chaining together nvl as

nvl(email,nvl(phonenumber,nvl(address,'n/a')))

Java System.out.print formatting

Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.

That should just mean dropping the '0' (zero-fill) flag.

e.g., change System.out.printf("%03d ", x); to the simpler System.out.printf("%3d ", x);

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

3 column layout HTML/CSS

.container{
height:100px;
width:500px;
border:2px dotted #F00;
border-left:none;
border-right:none;
text-align:center;
}
.container div{
display: inline-block;
border-left: 2px dotted #ccc;
vertical-align: middle;
line-height: 100px;
} 
 .column-left{ float: left; width: 32%;  height:100px;}
.column-right{ float: right; width: 32%;  height:100px; border-right: 2px dotted #ccc;}
.column-center{ display: inline-block; width: 33%; height:100px;}

 <div class="container">
   <div class="column-left">Column left</div>
   <div class="column-center">Column center</div>
   <div class="column-right">Column right</div>
</div> 

See this link http://jsfiddle.net/bipin_kumar/XD8RW/2/

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

Random number from a range in a Bash Script

Same with ruby:

echo $(ruby -e 'puts rand(20..65)') #=> 65 (inclusive ending)
echo $(ruby -e 'puts rand(20...65)') #=> 37 (exclusive ending)

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your HTML you have set a "base" tag:

<base href="http://www.cyclistinsuranceaustralia.com.au/">
  1. Delete that line from your HTML if you don't need it. This should make the fonts work when viewed from http://cyclistinsuranceaustralia.com.au.
  2. You'll probably need to redirect http://www.cyclistinsuranceaustralia.com.au to http://cyclistinsuranceaustralia.com.au

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

What is the difference between x86 and x64

If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:

  • x86 is for 32-bit OS
  • x64 is for 64-bit OS

In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.

At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.

What are MVP and MVC and what is the difference?

Also worth remembering is that there are different types of MVPs as well. Fowler has broken the pattern into two - Passive View and Supervising Controller.

When using Passive View, your View typically implement a fine-grained interface with properties mapping more or less directly to the underlaying UI widget. For instance, you might have a ICustomerView with properties like Name and Address.

Your implementation might look something like this:

public class CustomerView : ICustomerView
{
    public string Name
    { 
        get { return txtName.Text; }
        set { txtName.Text = value; }
    }
}

Your Presenter class will talk to the model and "map" it to the view. This approach is called the "Passive View". The benefit is that the view is easy to test, and it is easier to move between UI platforms (Web, Windows/XAML, etc.). The disadvantage is that you can't leverage things like databinding (which is really powerful in frameworks like WPF and Silverlight).

The second flavor of MVP is the Supervising Controller. In that case your View might have a property called Customer, which then again is databound to the UI widgets. You don't have to think about synchronizing and micro-manage the view, and the Supervising Controller can step in and help when needed, for instance with compled interaction logic.

The third "flavor" of MVP (or someone would perhaps call it a separate pattern) is the Presentation Model (or sometimes referred to Model-View-ViewModel). Compared to the MVP you "merge" the M and the P into one class. You have your customer object which your UI widgets is data bound to, but you also have additional UI-spesific fields like "IsButtonEnabled", or "IsReadOnly", etc.

I think the best resource I've found to UI architecture is the series of blog posts done by Jeremy Miller over at The Build Your Own CAB Series Table of Contents. He covered all the flavors of MVP and showed C# code to implement them.

I have also blogged about the Model-View-ViewModel pattern in the context of Silverlight over at YouCard Re-visited: Implementing the ViewModel pattern.

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

Logging with Retrofit 2

Here is an Interceptor that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers):

public class TimberLoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        Timber.i("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers());
        Timber.v("REQUEST BODY BEGIN\n%s\nREQUEST BODY END", bodyToString(request));

        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        String responseBodyString = response.body().string();

        // now we have extracted the response body but in the process
        // we have consumed the original reponse and can't read it again
        // so we need to build a new one to return from this method

        Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();

        long t2 = System.nanoTime();
        Timber.i("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers());
        Timber.v("RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyString);

        return newResponse;
    }

    private static String bodyToString(final Request request){

        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}

Structure of a PDF file?

When I first started working with PDF, I found the PDF reference very hard to navigate. It might help you to know that the overview of the file structure is found in syntax, and what Adobe call the document structure is the object structure and not the file structure. That is also found in Syntax. The description of operators is hidden away in Appendix A - very useful for understanding what is happening in content streams. If you ever have the pain of working with colour spaces you will find that hidden in Graphics! Hopefully these pointers will help you find things more quickly than I did.

If you are using windows, pdftron CosEdit allows you to browse the object structure to understand it. There is a free demo available that allows you to examine the file but not save it.

mcrypt is deprecated, what is the alternative?

As suggested by @rqLizard, you can use openssl_encrypt/openssl_decrypt PHP functions instead which provides a much better alternative to implement AES (The Advanced Encryption Standard) also known as Rijndael encryption.

As per the following Scott's comment at php.net:

If you're writing code to encrypt/encrypt data in 2015, you should use openssl_encrypt() and openssl_decrypt(). The underlying library (libmcrypt) has been abandoned since 2007, and performs far worse than OpenSSL (which leverages AES-NI on modern processors and is cache-timing safe).

Also, MCRYPT_RIJNDAEL_256 is not AES-256, it's a different variant of the Rijndael block cipher. If you want AES-256 in mcrypt, you have to use MCRYPT_RIJNDAEL_128 with a 32-byte key. OpenSSL makes it more obvious which mode you are using (i.e. aes-128-cbc vs aes-256-ctr).

OpenSSL also uses PKCS7 padding with CBC mode rather than mcrypt's NULL byte padding. Thus, mcrypt is more likely to make your code vulnerable to padding oracle attacks than OpenSSL.

Finally, if you are not authenticating your ciphertexts (Encrypt Then MAC), you're doing it wrong.

Further reading:

Code examples

Example #1

AES Authenticated Encryption in GCM mode example for PHP 7.1+

<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
    //store $cipher, $iv, and $tag for decryption later
    $original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
    echo $original_plaintext."\n";
}
?>

Example #2

AES Authenticated Encryption example for PHP 5.6+

<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
    echo $original_plaintext."\n";
}
?>

Example #3

Based on above examples, I've changed the following code which aims at encrypting user's session id:

class Session {

  /**
   * Encrypts the session ID and returns it as a base 64 encoded string.
   *
   * @param $session_id
   * @return string
   */
  public function encrypt($session_id) {
    // Get the MD5 hash salt as a key.
    $key = $this->_getSalt();
    // For an easy iv, MD5 the salt again.
    $iv = $this->_getIv();
    // Encrypt the session ID.
    $encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $session_id, MCRYPT_MODE_CBC, $iv);
    // Base 64 encode the encrypted session ID.
    $encryptedSessionId = base64_encode($encrypt);
    // Return it.
    return $encryptedSessionId;
  }

  /**
   * Decrypts a base 64 encoded encrypted session ID back to its original form.
   *
   * @param $encryptedSessionId
   * @return string
   */
  public function decrypt($encryptedSessionId) {
    // Get the MD5 hash salt as a key.
    $key = $this->_getSalt();
    // For an easy iv, MD5 the salt again.
    $iv = $this->_getIv();
    // Decode the encrypted session ID from base 64.
    $decoded = base64_decode($encryptedSessionId);
    // Decrypt the string.
    $decryptedSessionId = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decoded, MCRYPT_MODE_CBC, $iv);
    // Trim the whitespace from the end.
    $session_id = rtrim($decryptedSessionId, "\0");
    // Return it.
    return $session_id;
  }

  public function _getIv() {
    return md5($this->_getSalt());
  }

  public function _getSalt() {
    return md5($this->drupal->drupalGetHashSalt());
  }

}

into:

class Session {

  const SESS_CIPHER = 'aes-128-cbc';

  /**
   * Encrypts the session ID and returns it as a base 64 encoded string.
   *
   * @param $session_id
   * @return string
   */
  public function encrypt($session_id) {
    // Get the MD5 hash salt as a key.
    $key = $this->_getSalt();
    // For an easy iv, MD5 the salt again.
    $iv = $this->_getIv();
    // Encrypt the session ID.
    $ciphertext = openssl_encrypt($session_id, self::SESS_CIPHER, $key, $options=OPENSSL_RAW_DATA, $iv);
    // Base 64 encode the encrypted session ID.
    $encryptedSessionId = base64_encode($ciphertext);
    // Return it.
    return $encryptedSessionId;
  }

  /**
   * Decrypts a base 64 encoded encrypted session ID back to its original form.
   *
   * @param $encryptedSessionId
   * @return string
   */
  public function decrypt($encryptedSessionId) {
    // Get the Drupal hash salt as a key.
    $key = $this->_getSalt();
    // Get the iv.
    $iv = $this->_getIv();
    // Decode the encrypted session ID from base 64.
    $decoded = base64_decode($encryptedSessionId, TRUE);
    // Decrypt the string.
    $decryptedSessionId = openssl_decrypt($decoded, self::SESS_CIPHER, $key, $options=OPENSSL_RAW_DATA, $iv);
    // Trim the whitespace from the end.
    $session_id = rtrim($decryptedSessionId, '\0');
    // Return it.
    return $session_id;
  }

  public function _getIv() {
    $ivlen = openssl_cipher_iv_length(self::SESS_CIPHER);
    return substr(md5($this->_getSalt()), 0, $ivlen);
  }

  public function _getSalt() {
    return $this->drupal->drupalGetHashSalt();
  }

}

To clarify, above change is not a true conversion since the two encryption uses a different block size and a different encrypted data. Additionally, the default padding is different, MCRYPT_RIJNDAEL only supports non-standard null padding. @zaph


Additional notes (from the @zaph's comments):

  • Rijndael 128 (MCRYPT_RIJNDAEL_128) is equivalent to AES, however Rijndael 256 (MCRYPT_RIJNDAEL_256) is not AES-256 as the 256 specifies a block size of 256-bits, whereas AES has only one block size: 128-bits. So basically Rijndael with a block size of 256-bits (MCRYPT_RIJNDAEL_256) has been mistakenly named due to the choices by the mcrypt developers. @zaph
  • Rijndael with a block size of 256 may be less secure than with a block size of 128-bits because the latter has had much more reviews and uses. Secondly, interoperability is hindered in that while AES is generally available, where Rijndael with a block size of 256-bits is not.
  • Encryption with different block sizes for Rijndael produces different encrypted data.

    For example, MCRYPT_RIJNDAEL_256 (not equivalent to AES-256) defines a different variant of the Rijndael block cipher with size of 256-bits and a key size based on the passed in key, where aes-256-cbc is Rijndael with a block size of 128-bits with a key size of 256-bits. Therefore they're using different block sizes which produces entirely different encrypted data as mcrypt uses the number to specify the block size, where OpenSSL used the number to specify the key size (AES only has one block size of 128-bits). So basically AES is Rijndael with a block size of 128-bits and key sizes of 128, 192 and 256 bits. Therefore it's better to use AES, which is called Rijndael 128 in OpenSSL.

Use multiple custom fonts using @font-face?

I use this method in my css file

@font-face {
  font-family: FontName1;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
  font-family: FontName2;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
  font-family: FontName3;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}

Exploring Docker container's file system

For docker aufs driver:

The script will find the container root dir(Test on docker 1.7.1 and 1.10.3 )

if [ -z "$1" ] ; then
 echo 'docker-find-root $container_id_or_name '
 exit 1
fi
CID=$(docker inspect   --format {{.Id}} $1)
if [ -n "$CID" ] ; then
    if [ -f  /var/lib/docker/image/aufs/layerdb/mounts/$CID/mount-id ] ; then
        F1=$(cat /var/lib/docker/image/aufs/layerdb/mounts/$CID/mount-id)
       d1=/var/lib/docker/aufs/mnt/$F1
    fi
    if [ ! -d "$d1" ] ; then
        d1=/var/lib/docker/aufs/diff/$CID
    fi
    echo $d1
fi

how to reference a YAML "setting" from elsewhere in the same YAML file?

YML definition:

dir:
  default: /home/data/in/
  proj1: ${dir.default}p1
  proj2: ${dir.default}p2
  proj3: ${dir.default}p3 

Somewhere in thymeleaf

<p th:utext='${@environment.getProperty("dir.default")}' />
<p th:utext='${@environment.getProperty("dir.proj1")}' /> 

Output: /home/data/in/ /home/data/in/p1

How to pause / sleep thread or process in Android?

I use CountDownTime

new CountDownTimer(5000, 1000) {

    @Override
    public void onTick(long millisUntilFinished) {
        // do something after 1s
    }

    @Override
    public void onFinish() {
        // do something end times 5s
    }

}.start(); 

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

How to programmatically set drawableLeft on Android button?

Worked for me. To set drawable at the right

tvBioLive.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_red_400_24dp, 0)

ImportError: No module named 'Queue'

In my case it should be:

from multiprocessing import JoinableQueue

Since in python2, Queue has methods like .task_done(), but in python3 multiprocessing.Queue doesn't have this method, and multiprocessing.JoinableQueue does.

How to resolve "Waiting for Debugger" message?

I was also having the same problem when using Android Studio and GenyMotion. I am able to solve this problem by pausing the program and resuming it again after "Waiting for debugger" message is shown. It may work while using other IDEs and emulators as well.enter image description here

Ruby: Merging variables in to a string

The standard ERB templating system may work for your scenario.

def merge_into_string(animal, second_animal, action)
  template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
  ERB.new(template).result(binding)
end

merge_into_string('tiger', 'deer', 'eats')
=> "The tiger eats the deer"

merge_into_string('bird', 'worm', 'finds')
=> "The bird finds the worm"

FirebaseInstanceIdService is deprecated

firebaser here

Check the reference documentation for FirebaseInstanceIdService:

This class was deprecated.

In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

Weirdly enough the JavaDoc for FirebaseMessagingService doesn't mention the onNewToken method yet. It looks like not all updated documentation has been published yet. I've filed an internal issue to get the updates to the reference docs published, and to get the samples in the guide updated too.

In the meantime both the old/deprecated calls, and the new ones should work. If you're having trouble with either, post the code and I'll have a look.

How to combine two vectors into a data frame

df = data.frame(cond=c(rep("x",3),rep("y",3)),rating=c(x,y))

Date / Timestamp to record when a record was added to the table?

You can use a datetime field and set it's default value to GetDate().

CREATE TABLE [dbo].[Test](
    [TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
    [Foo] [varchar](50) NOT NULL
) ON [PRIMARY]

Android: ProgressDialog.show() crashes with getApplicationContext

This is a common problem. Use this instead of getApplicationContext() That should solve your problem

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

Cloning an Object in Node.js

None of the answers satisfied me, several don't work or are just shallow clones, answers from @clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone

Visual Studio Code pylint: Unable to import 'protorpc'

I find the solutions stated above very useful. Especially the Python's Virtual Environment explanation by jrc.

In my case, I was using Docker and was editing 'local' files (not direcly inside the docker). So I installed Remote Development extension by Microsoft.

ext install ms-vscode-remote.vscode-remote-extensionpack

More details can be found at https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack

I should say, it was not easy to play around at first. What worked for me was...
1. starting docker
2. In vscode, Remote-container: Attach to running container
3. Adding folder /code/<path-to-code-folder> from root of the machine to vscode

and then installing python extension + pylint

Check if element is clickable in Selenium Java

the class attribute contains disabled when the element is not clickable.

WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
    webElement.click();
}

How to convert unsigned long to string

you can write a function which converts from unsigned long to str, similar to ltostr library function.

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long tmp = value;
  int count = 0;

  if (NULL == ptr)
  {
    return NULL;
  }

  if (tmp == 0)
  {
    count++;
  }

  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }

  ptr += count;

  *ptr = '\0';

  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * -- ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * --ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);

  return(ptr);
}

you can refer to my blog here which explains implementation and usage with example.

How to search images from private 1.0 registry in docker?

Modifying the answer from @mre to get the list just from one command (valid at least for Docker Registry v2).

docker exec -it <your_registry_container_id> ls -a /var/lib/registry/docker/registry/v2/repositories/

JavaScript Array to Set

If you start out with:

let array = [
    {name: "malcom", dogType: "four-legged"},
    {name: "peabody", dogType: "three-legged"},
    {name: "pablo", dogType: "two-legged"}
];

And you want a set of, say, names, you would do:

let namesSet = new Set(array.map(item => item.name));

Finding the number of days between two dates

You can try the code below:

$dt1 = strtotime("2019-12-12"); //Enter your first date
$dt2 = strtotime("12-12-2020"); //Enter your second date
echo abs(($dt1 - $dt2) / (60 * 60 * 24));

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

Common elements comparison between 2 lists

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

In CSS, for the font-weight property, the value: normal defaults to the numeric value 400, and bold to 700.

If you want to specify other weights, you need to give the number value. That number value needs to be supported for the font family that you are using.

For example you would define semi-bold like this:

font-weight: 600;

Here an JSFiddle using 'Open Sans' font family, loaded with the above weights.

Disable back button in android

if you are using FragmentActivity. then do like this

first call This inside your Fragment.

public void callParentMethod(){
    getActivity().onBackPressed();
}

and then Call onBackPressed method in side your parent FragmentActivity class.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}

How do I make flex box work in safari?

display: flex;
display: -webkit-box;

did it for me. Also there were two display: flex; on the same element from different classes. So I removed the other one.

Interface/enum listing standard mime-type constants

If you are using Spring Framework then there is a MediaType class for common content types:

MediaType.TEXT_HTML 
MediaType.TEXT_PLAIN 
MediaType.TEXT_XML 
MediaType.APPLICATION_JSON 
MediaType.IMAGE_JPEG 
...

How to add multiple jar files in classpath in linux

The classpath is the place(s) where the java compiler (command: javac) and the JVM (command:java) look in order to find classes which your application reference. What does it mean for an application to reference another class ? In simple words it means to use that class somewhere in its code:

Example:

public class MyClass{
    private AnotherClass referenceToAnotherClass;
    .....
}

When you try to compile this (javac) the compiler will need the AnotherClass class. The same when you try to run your application: the JVM will need the AnotherClass class. In order to to find this class the javac and the JVM look in a particular (set of) place(s). Those places are specified by the classpath which on linux is a colon separated list of directories (directories where the javac/JVM should look in order to locate the AnotherClass when they need it).

So in order to compile your class and then to run it, you should make sure that the classpath contains the directory containing the AnotherClass class. Then you invoke it like this:

javac -classpath "dir1;dir2;path/to/AnotherClass;...;dirN" MyClass.java //to compile it
java -classpath "dir1;dir2;path/to/AnotherClass;...;dirN" MyClass //to run it

Usually classes come in the form of "bundles" called jar files/libraries. In this case you have to make sure that the jar containing the AnotherClass class is on your classpaht:

javac -classpath "dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" MyClass.java //to compile it
java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" MyClass //to run it

In the examples above you can see how to compile a class (MyClass.java) located in the working directory and then run the compiled class (Note the "." at the begining of the classpath which stands for current directory). This directory has to be added to the classpath too. Otherwise, the JVM won't be able to find it.

If you have your class in a jar file, as you specified in the question, then you have to make sure that jar is in the classpath too , together with the rest of the needed directories.

Example:

java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar...;dirN" MyClass //to run it

or more general (assuming some package hierarchy):

java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar...;dirN" package.subpackage.MyClass //to run it

In order to avoid setting the classpath everytime you want to run an application you can define an environment variable called CLASSPATH.

In linux, in command prompt:

export CLASSPATH="dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" 

or edit the ~/.bashrc and add this line somewhere at the end;

However, the class path is subject to frequent changes so, you might want to have the classpath set to a core set of dirs, which you need frequently and then extends the classpath each time you need for that session only. Like this:

export CLASSPATH=$CLASSPATH:"new directories according to your current needs" 

How to open a web page from my application?

Accepted answer no longer works on .NET Core 3. To make it work, use the following method:

var psi = new ProcessStartInfo
{
    FileName = url,
    UseShellExecute = true
};
Process.Start (psi);

open() in Python does not create a file if it doesn't exist

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.

How to stretch in width a WPF user control to its window?

This worked for me. don't assign any width or height to the UserControl and define row and column definition in the parent window.

<UserControl x:Class="MySampleApp.myUC"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"  
        >
   <Grid>

    </Grid>
</UserControl>


 <Window xmlns:MySampleApp="clr-namespace:MySampleApp"  x:Class="MySampleApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="auto" Width="auto" MinWidth="1000" >
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />           
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />            
    </Grid.ColumnDefinitions>
    <MySampleApp:myUC Grid.Column="0" Grid.Row="0" />       
</Grid>

Bootstrap datepicker hide after selection

I changed to datetimepicker and format to 'DD/MM/YYYY'

$("id").datetimepicker({
    format: 'DD/MM/YYYY',
}).on('changeDate', function() {
    $('.datepicker').hide();
});

Usage of unicode() and encode() functions in Python

You are using encode("utf-8") incorrectly. Python byte strings (str type) have an encoding, Unicode does not. You can convert a Unicode string to a Python byte string using uni.encode(encoding), and you can convert a byte string to a Unicode string using s.decode(encoding) (or equivalently, unicode(s, encoding)).

If fullFilePath and path are currently a str type, you should figure out how they are encoded. For example, if the current encoding is utf-8, you would use:

path = path.decode('utf-8')
fullFilePath = fullFilePath.decode('utf-8')

If this doesn't fix it, the actual issue may be that you are not using a Unicode string in your execute() call, try changing it to the following:

cur.execute(u"update docs set path = :fullFilePath where path = :path", locals())

Set attribute without value

You can do it without jQuery!

Example:

_x000D_
_x000D_
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
_x000D_
_x000D_

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

From MDN Element.setAttribute()

Naming threads and thread-pools of ExecutorService

Extend ThreadFactory

public interface ThreadFactory

An object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

Thread newThread(Runnable r)

Constructs a new Thread. Implementations may also initialize priority, name, daemon status, ThreadGroup, etc.

Sample code:

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

import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;

class SimpleThreadFactory implements ThreadFactory {
   String name;
   AtomicInteger threadNo = new AtomicInteger(0);

   public SimpleThreadFactory (String name){
       this.name = name;
   }
   public Thread newThread(Runnable r) {
     String threadName = name+":"+threadNo.incrementAndGet();
     System.out.println("threadName:"+threadName);
     return new Thread(r,threadName );
   }
   public static void main(String args[]){
        SimpleThreadFactory factory = new SimpleThreadFactory("Factory Thread");
        ThreadPoolExecutor executor= new ThreadPoolExecutor(1,1,60,
                    TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(1),new ThreadPoolExecutor.DiscardPolicy());


        final ExecutorService executorService = Executors.newFixedThreadPool(5,factory);

        for ( int i=0; i < 100; i++){
            executorService.submit(new Runnable(){
                 public void run(){
                    System.out.println("Thread Name in Runnable:"+Thread.currentThread().getName());
                 }
            });
        }
        executorService.shutdown();
    }
 }

output:

java SimpleThreadFactory

thread no:1
thread no:2
Thread Name in Runnable:Factory Thread:1
Thread Name in Runnable:Factory Thread:2
thread no:3
thread no:4
Thread Name in Runnable:Factory Thread:3
Thread Name in Runnable:Factory Thread:4
thread no:5
Thread Name in Runnable:Factory Thread:5

....etc

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

ECMAScript 6 class destructor

Is there such a thing as destructors for ECMAScript 6?

No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.

If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted

A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).

1): Well, there is a beginning with the specification of WeakMap and WeakSet objects. However, true weak references are still in the pipeline [1][2].

CSS text-decoration underline color

As far as I know it's not possible... but you can try something like this:

_x000D_
_x000D_
.underline _x000D_
{_x000D_
    color: blue;_x000D_
    border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <span class="underline">hello world</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to view an HTML file in the browser with Visual Studio Code

Openning files in Opera browser (on Windows 64 bits). Just add this lines:

{
"version": "0.1.0",
"command": "opera",
"windows": {
    "command": "///Program Files (x86)/Opera/launcher.exe"
},
"args": ["${file}"] }

Pay attention to the path format on "command": line. Don't use the "C:\path_to_exe\runme.exe" format.

To run this task, open the html file you want to view, press F1, type task opera and press enter

How to add new column to MYSQL table?

Based on your comment it looks like your'e only adding the new column if: mysql_query("SELECT * FROM assessment"); returns false. That's probably not what you wanted. Try removing the '!' on front of $sql in the first 'if' statement. So your code will look like:

$sql=mysql_query("SELECT * FROM assessment");
if ($sql) {
 mysql_query("ALTER TABLE assessment ADD q6 INT(1) NOT NULL AFTER q5");
 echo 'Q6 created'; 
}else...

Jquery Date picker Default Date

interesting, datepicker default date is current date as I found,

but you can set date by

$("#yourinput").datepicker( "setDate" , "7/11/2011" );

don't forget to check you system date :)

How to change colors of a Drawable in Android?

Int color = Color.GRAY; 
// or int color = Color.argb(123,255,0,5);
// or int color = 0xaaff000;

in XML /res/values/color.xml

<?xml version="1.0" encoding="utf-8">
<resources>
    <color name="colorRed">#ff0000</color>
</resoures> 

Java Code

int color = ContextCompat.getColor(context, R.color.colorRed);

GradientDrawable drawableBg = yourView.getBackground().mutate();
drawableBg.setColor(color);

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

  1. Stop your Apache server from running.
  2. Download the most recent version of XAMPP that contains a release of PHP 5.2.* from the SourceForge site linked at the apachefriends website.
  3. Rename the PHP file in your current installation (MAC OSX: /xamppfiles/modules/libphp.so) to something else (just in case).
  4. Copy the PHP file located in the same directory tree from the older XAMPP installation that you just downloaded, and place it in the directory of the file you just renamed.
  5. Start the Apache server, and generate a fresh version of phpinfo().
  6. Once you confirm that the PHP version has been lowered, delete the remaining files from the older XAMPP install.
  7. Fun ensues.

I just confirmed that this works when using a version of PHP 5.2.9 from XAMPP for OS X 1.0.1 (April 2009), and surgically moving it to XAMPP for OS X 1.7.2 (August 2009).

Changing route doesn't scroll to top in the new page

I found this solution. If you go to a new view the function gets executed.

var app = angular.module('hoofdModule', ['ngRoute']);

    app.controller('indexController', function ($scope, $window) {
        $scope.$on('$viewContentLoaded', function () {
            $window.scrollTo(0, 0);
        });
    });

How to show first commit by 'git log'?

You can just reverse your log and just head it for the first result.

git log --pretty=oneline --reverse | head -1

How to extract public key using OpenSSL?

openssl rsa -in privkey.pem -pubout > key.pub

That writes the public key to key.pub

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

AndroidManifest.xml:

<uses-sdk
    android:minSdkVersion=...
    android:targetSdkVersion="11" />

and

Project Properties -> Project Build Target = 11 or above

These 2 things fixed the problem for me!

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

PHP + MySQL transactions examples

As this is the first result on google for "php mysql transaction", I thought I'd add an answer that explicitly demonstrates how to do this with mysqli (as the original author wanted examples). Here's a simplified example of transactions with PHP/mysqli:

// let's pretend that a user wants to create a new "group". we will do so
// while at the same time creating a "membership" for the group which
// consists solely of the user themselves (at first). accordingly, the group
// and membership records should be created together, or not at all.
// this sounds like a job for: TRANSACTIONS! (*cue music*)

$group_name = "The Thursday Thumpers";
$member_name = "EleventyOne";
$conn = new mysqli($db_host,$db_user,$db_passwd,$db_name); // error-check this

// note: this is meant for InnoDB tables. won't work with MyISAM tables.

try {

    $conn->autocommit(FALSE); // i.e., start transaction

    // assume that the TABLE groups has an auto_increment id field
    $query = "INSERT INTO groups (name) ";
    $query .= "VALUES ('$group_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    $group_id = $conn->insert_id; // last auto_inc id from *this* connection

    $query = "INSERT INTO group_membership (group_id,name) ";
    $query .= "VALUES ('$group_id','$member_name')";
    $result = $conn->query($query);
    if ( !$result ) {
        $result->free();
        throw new Exception($conn->error);
    }

    // our SQL queries have been successful. commit them
    // and go back to non-transaction mode.

    $conn->commit();
    $conn->autocommit(TRUE); // i.e., end transaction
}
catch ( Exception $e ) {

    // before rolling back the transaction, you'd want
    // to make sure that the exception was db-related
    $conn->rollback(); 
    $conn->autocommit(TRUE); // i.e., end transaction   
}

Also, keep in mind that PHP 5.5 has a new method mysqli::begin_transaction. However, this has not been documented yet by the PHP team, and I'm still stuck in PHP 5.3, so I can't comment on it.

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I had this problem too on a win7 machine. I wanted to update the jre with a jdk. So i deleted the jre folder and downloaded and unzipped the new jdk. The issue was i manually deleted the jre folder, when instead i should've uninstalled it. This leaves a bunch of registry entries that still point to the old jre. Somehow eclipse still wants to use the old jre. I couldn't uninstall the old java vm, i kept getting this error:

Error 1723. There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor

So i had to use this MS utility to fix the uninstall:

http://support.microsoft.com/kb/2438651/

Then i had to install again the vm. I installed to the same location the original one was at, to avoid losing another hour! After that eclipse started correctly.

Julio

How to get the body's content of an iframe in Javascript?

it works perfectly for me :

document.getElementById('iframe_id').contentWindow.document.body.innerHTML;

Push method in React Hooks (useState)?

Most recommended method is using wrapper function and spread operator together. For example, if you have initialized a state called name like this,

const [names, setNames] = useState([])

You can push to this array like this,

setNames(names => [...names, newName])

Hope that helps.

How to get detailed list of connections to database in sql server 2005?

As @Hutch pointed out, one of the major limitations of sp_who2 is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE).

Instead, you can just go directly to the source on master.dbo.sysprocesses

I've constructed this to output almost exactly the same thing that sp_who2 generates, except that you can easily add ORDER BY and WHERE clauses to get meaningful output.

SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid 

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText;
      container.style.visibility = 'visible';
      // or 
      container.style.display = 'block';
}

but this depend entirely on how you hid the div in the first place

Convert string to Time

This gives you the needed results:

string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM"  string

You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

List all of the possible goals in Maven 2?

The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

  • validate: validate the project is correct and all necessary information is available.
  • compile: compile the source code of the project.
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally.
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

How to get the last five characters of a string using Substring() in C#?

Here is a quick extension method you can use that mimics PHP syntax. Include AssemblyName.Extensions to the code file you are using the extension in.

Then you could call:

input.SubstringReverse(-5) and it will return "Three".

namespace AssemblyName.Extensions {

    public static class StringExtensions
    {
        /// <summary>
        /// Takes a negative integer - counts back from the end of the string.
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        public static string SubstringReverse(this string str, int length)
        {
            if (length > 0) 
            {
                throw new ArgumentOutOfRangeException("Length must be less than zero.");
            }

            if (str.Length < Math.Abs(length))
            {
                throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
            }

            return str.Substring((str.Length + length), Math.Abs(length));
        }
    }
}

Importing CommonCrypto in a Swift framework

It happened the same to me after updating Xcode. I tried everything I can do such as reinstalling cocoapods and cleaning the project, but it didn't work. Now it's been solved after restart the system.

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

Get a Windows Forms control by name in C#

Assuming you have the menuStrip object and the menu is only one level deep, use:

ToolStripMenuItem item = menuStrip.Items
    .OfType<ToolStripMenuItem>()
    .SelectMany(it => it.DropDownItems.OfType<ToolStripMenuItem>())
    .SingleOrDefault(n => n.Name == "MyMenu");

For deeper menu levels add more SelectMany operators in the statement.

if you want to search all menu items in the strip then use

ToolStripMenuItem item = menuStrip.Items
    .Find("MyMenu",true)
    .OfType<ToolStripMenuItem>()
    .Single();

However, make sure each menu has a different name to avoid exception thrown by key duplicates.

To avoid exceptions you could use FirstOrDefault instead of SingleOrDefault / Single, or just return a sequence if you might have Name duplicates.

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

Git error on git pull (unable to update local ref)

This error with (unable to update local ref) can also happen if you have changed passwords recently and there's some fancy stuff integrating your Windows and Linux logins.

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

What does the red exclamation point icon in Eclipse mean?

Make sure you don't have any undefined classpath variables (like M2_REPO).

PostgreSQL: How to make "case-insensitive" query

The most common approach is to either lowercase or uppercase the search string and the data. But there are two problems with that.

  1. It works in English, but not in all languages. (Maybe not even in most languages.) Not every lowercase letter has a corresponding uppercase letter; not every uppercase letter has a corresponding lowercase letter.
  2. Using functions like lower() and upper() will give you a sequential scan. It can't use indexes. On my test system, using lower() takes about 2000 times longer than a query that can use an index. (Test data has a little over 100k rows.)

There are at least three less frequently used solutions that might be more effective.

  1. Use the citext module, which mostly mimics the behavior of a case-insensitive data type. Having loaded that module, you can create a case-insensitive index by CREATE INDEX ON groups (name::citext);. (But see below.)
  2. Use a case-insensitive collation. This is set when you initialize a database. Using a case-insensitive collation means you can accept just about any format from client code, and you'll still return useful results. (It also means you can't do case-sensitive queries. Duh.)
  3. Create a functional index. Create a lowercase index by using CREATE INDEX ON groups (LOWER(name));. Having done that, you can take advantage of the index with queries like SELECT id FROM groups WHERE LOWER(name) = LOWER('ADMINISTRATOR');, or SELECT id FROM groups WHERE LOWER(name) = 'administrator'; You have to remember to use LOWER(), though.

The citext module doesn't provide a true case-insensitive data type. Instead, it behaves as if each string were lowercased. That is, it behaves as if you had called lower() on each string, as in number 3 above. The advantage is that programmers don't have to remember to lowercase strings. But you need to read the sections "String Comparison Behavior" and "Limitations" in the docs before you decide to use citext.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

You can have the script call itself with psexec's -h option to run elevated.

I'm not sure how you would detect if it's already running as elevated or not... maybe re-try with elevated perms only if there's an Access Denied error?

Or, you could simply have the commands for the xcopy and reg.exe always be run with psexec -h, but it would be annoying for the end-user if they need to input their password each time (or insecure if you included the password in the script)...

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Alan is correct when he says there's designer support. Rhywun is incorrect when he implies you cannot choose the foreign key table. What he means is that in the UI the foreign key table drop down is greyed out - all that means is he has not right clicked on the correct table to add the foreign key to.

In summary, right click on the foriegn key table and then via the 'Table Properties' > 'Add Relations' option you select the related primary key table.

I've done it numerous times and it works.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to turn on WCF tracing?

In your web.config (on the server) add

<system.diagnostics>
 <sources>
  <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
   <listeners>
    <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\logs\Traces.svclog"/>
   </listeners>
  </source>
 </sources>
</system.diagnostics>

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

How do I apply a perspective transform to a UIView?

As Ben said, you'll need to work with the UIView's layer, using a CATransform3D to perform the layer's rotation. The trick to get perspective working, as described here, is to directly access one of the matrix cells of the CATransform3D (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:

Objective-C

UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;

Swift 5.0

if let myView = self.subviews.first {
    let layer = myView.layer
    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
    layer.transform = rotationAndPerspectiveTransform
}

which rebuilds the layer transform from scratch for each rotation.

A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.

The sublayerTransform you refer to in your response is a transform that is applied to the sublayers of your UIView's CALayer. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers contained within the one layer that I'm rotating.

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

I.e. for Visual Studio 2013 I would reference this assembly:

Microsoft.VisualStudio.Shell.14.0.dll

You can find it i.e. here:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\BugAid Software\BugAid\1.0

and don't forget to implement:

using Microsoft.VisualStudio;

How to only get file name with Linux 'find'?

If you are using GNU find

find . -type f -printf "%f\n"

Or you can use a programming language such as Ruby(1.9+)

$ ruby -e 'Dir["**/*"].each{|x| puts File.basename(x)}'

If you fancy a bash (at least 4) solution

shopt -s globstar
for file in **; do echo ${file##*/}; done

How to return a resolved promise from an AngularJS Service using $q?

Try this:

myApp.service('userService', [
    '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
      var deferred= $q.defer();
      this.user = {
        access: false
      };
      try
      {
      this.isAuthenticated = function() {
        this.user = {
          first_name: 'First',
          last_name: 'Last',
          email: '[email protected]',
          access: 'institution'
        };
        deferred.resolve();
      };
    }
    catch
    {
        deferred.reject();
    }

    return deferred.promise;
  ]);

How to see query history in SQL Server Management Studio

If the queries you are interested in are dynamic queries that fail intermittently, you could log the SQL and the datetime and user in a table at the time the dynamic statement is created. It would be done on a case-by case basis though as it requires specific programming to happen and it takes a littel extra processing time, so do it only for those few queries you are most concerned about. But having a log of the specific statements executed can really help when you are trying to find out why it fails once a month only. Dynamic queries are hard to thoroughly test and sometimes you get one specific input value that just won't work and doing this logging at the time the SQL is created is often the best way to see what specifically wasn in the sql that was built.

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

AngularJS access parent scope from child controller

Super easy and works, but not sure why....

angular.module('testing')
  .directive('details', function () {
        return {
              templateUrl: 'components/details.template.html',
              restrict: 'E',                 
              controller: function ($scope) {
                    $scope.details=$scope.details;  <=== can see the parent details doing this                     
              }
        };
  });

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

I just made the right-most sticky column of a table sticky.

th:last-of-type {
 position: sticky;
 right: 0;
 width: 120px;
 background: #f7f7f7;
}


td:last-of-type {
 position: sticky;
 right: 0;
 background: #f7f7f7;
 width: 120px;
}

I believe if you'll do {position: sticky; left: 0;}, you'll get the desired result.

wamp server mysql user id and password

You can create a user using MySQL like this:

CREATE USER 'username'@'servername' IDENTIFIED BY 'password';

and if you want to do that for a specific database, simply you can write in the MySQL:

GRANT ALL PRIVILEGES ON database_name.*
TO 'username'@'servername'
IDENTIFIED BY 'password';

Note that it's all one sentence, also note that you need to change:

database_name // your database name
username      // any name you want to use as username
servername    // the name of your server, for example: localhost
password      // any text you want to use as user password

Append values to query string

This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri as obsolete.

Anyway, probably a better way to manipulate relative Uris is to give it what it wants:

var requestUri = new Uri("x://x").MakeRelativeUri(
   new UriBuilder("x://x") { Path = path, Query = query }.Uri);

You can use the other answers to actually build the query string.

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);