Programs & Examples On #Program flow

What is the difference between a deep copy and a shallow copy?

In short, it depends on what points to what. In a shallow copy, object B points to object A's location in memory. In deep copy, all things in object A's memory location get copied to object B's memory location.

This wiki article has a great diagram.

http://en.wikipedia.org/wiki/Object_copy

adb connection over tcp not working now

if you use Android M:

Step 1 : adb usb
Step 2 : adb devices
Step 3 :adb tcpip 5556
Go to Settings -> About phone/tablet -> Status -> IP address.
Step 4 : adb connect ADDRESS IP OF YOUR PHONE:5556

Difference between 'cls' and 'self' in Python classes?

It's used in case of a class method. Check this reference for further details.

EDIT: As clarified by Adrien, it's a convention. You can actually use anything but cls and self are used (PEP8).

Any good, visual HTML5 Editor or IDE?

Radrails 3 is supposed to have it, Aptana Studio 3 will have it. Radrails is in beta, so thats kind of a downer, but none the less it is there to give'r a whirl.

It is multi-platform too, for those of us non-Windoze fellas.

cannot find zip-align when publishing app

If zipalign command is not found from Command-Line add file path of zipalign to environmental variables. As mentioned above, it's never good to change exe file location.

For Windows users:

Add to User->PATH->"path to zipalign folder"

In my case it path was C:\adt-bundle-windows-x86_64-20140702\sdk\build-tools\android-4.4W. In that folder is zipalign.exe

This link can help you with setting path and understanding it http://www.voidspace.org.uk/python/articles/command_line.shtml#path

Redeploy alternatives to JRebel

Hotswap Agent is an extension to DCEVM which supports many Java frameworks (reload Spring bean definition, Hibernate entity mapping, logger level setup, ...).

There is also lot of documentation how to setup DCEVM and compiled binaries for Java 1.7.

How do I check if a number is positive or negative in C#?

if (num < 0) {
  //negative
}
if (num > 0) {
  //positive
}
if (num == 0) {
  //neither positive or negative,
}

or use "else ifs"

Add a string of text into an input field when user clicks a button

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/ ?

Have a div cling to top of screen if scrolled down past it

The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.

This is done with something like this, attaching a handler to the window.scroll event

   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#the-sticky-div'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    });

This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.

And the CSS class looks like this

  #the-sticky-div.sticky {
     position: fixed;
     top: 0;
  }

EDIT- Modified code to cache jQuery objects, faster now.

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Perfect Tree:

       x
     /   \
    /     \
   x       x
  / \     / \
 x   x   x   x
/ \ / \ / \ / \
x x x x x x x x

Complete Tree:

       x
     /   \
    /     \
   x       x
  / \     / \
 x   x   x   x
/ \ /
x x x

Strict/Full Tree:

       x
     /   \
    /     \
   x       x
  / \ 
 x   x 
    / \
    x x 

Python integer incrementing with ++

The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++ is the next method of iterators.

What is the IntelliJ shortcut key to create a javadoc comment?

Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".

Html.ActionLink as a button or an image, not a link

<button onclick="location.href='@Url.Action("NewCustomer", "Customers")'">Checkout >></button>

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Scroll to a div using jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

( Scroll to function taken from here )


PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

How to make matrices in Python?

you can also use append function

b = [ ]

for x in range(0, 5):
    b.append(["O"] * 5)

def print_b(b):
    for row in b:
        print " ".join(row)

How to call a method daily, at specific time, in C#?

As others have said you can use a console app to run when scheduled. What others haven't said is that you can this app trigger a cross process EventWaitHandle which you are waiting on in your main application.

Console App:

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle handle = 
            new EventWaitHandle(true, EventResetMode.ManualReset, "GoodMutexName");
        handle.Set();
    }
}

Main App:

private void Form1_Load(object sender, EventArgs e)
{
    // Background thread, will die with application
    ThreadPool.QueueUserWorkItem((dumby) => EmailWait());
}

private void EmailWait()
{
    EventWaitHandle handle = 
        new EventWaitHandle(false, EventResetMode.ManualReset, "GoodMutexName");

    while (true)
    {
        handle.WaitOne();

        SendEmail();

        handle.Reset();
    }
}

Calling a particular PHP function on form submit

PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.

To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy

json call with C#

Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this. Link 1 and Link 2

Code that works(unit tested)

           //Get Example
            var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";

            var username = "usernameForYourApi";
            var password = "passwordForYourApi";

            var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
            var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
            }


            //Post Example
            var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequestPost.ContentType = "application/json";
            httpWebRequestPost.Method = "POST";
            bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));

            //POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
            //json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
            // fill File model with some test data
            CSharpComplexClass fileModel = new CSharpComplexClass();
            fileModel.CarrierID = 2;
            fileModel.InvoiceFileDate = DateTime.Now;
            fileModel.EntryMethodID = EntryMethod.Manual;
            fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
            fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
            string json = new JavaScriptSerializer().Serialize(fileModel);
            Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
            byte[] byteArray = Encoding.UTF8.GetBytes(json);
            httpWebRequestPost.ContentLength = byteArray.Length;
            // Get the request stream.  
            Stream dataStream = httpWebRequestPost.GetRequestStream();
            // Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.  
            dataStream.Close();
            // Get the response.  
            WebResponse response = httpWebRequestPost.GetResponse();
            // Display the status.  
            //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
            // Get the stream containing content returned by the server.  
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.  
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);

References in my test script task inside BIDS 2008(having SP1 and 3.5 framework) enter image description here

How to make tesseract to recognize only numbers, when they are mixed with letters?

What I do is to recognize everything, and when I have the text, I take out all the characters except numbers

//This replaces all except numbers from 0 to 9
recognizedText = recognizedText.replaceAll("[^0-9]+", " ");

This works pretty well for me.

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

It is possible, with the usual CSS caveats and if the HTML code can be modified. If you add the required attribute to the element, then the element will match :invalid or :valid according to whether the value of the control is empty or not. If the element has no value attribute (or it has value=""), the value of the control is initially empty and becomes nonempty when any character (even a space) is entered.

Example:

<style>
#foo { background: yellow; }
#foo:valid { outline: solid blue 2px; }
#foo:invalid { outline: solid red 2px; }
</style>
<input id=foo required>

The pseudo-classed :valid and :invalid are defined in Working Draft level CSS documents only, but support is rather widespread in browsers, except that in IE, it came with IE 10.

If you would like to make “empty” include values that consist of spaces only, you can add the attribute pattern=.*\S.*.

There is (currently) no CSS selector for detecting directly whether an input control has a nonempty value, so we need to do it indirectly, as described above.

Generally, CSS selectors refer to markup or, in some cases, to element properties as set with scripting (client-side JavaScript), rather than user actions. For example, :empty matches element with empty content in markup; all input elements are unavoidably empty in this sense. The selector [value=""] tests whether the element has the value attribute in markup and has the empty string as its value. And :checked and :indeterminate are similar things. They are not affected by actual user input.

How can I move a tag on a git branch to a different commit?

Alias to move one tag to a different commit.

In your sample, to move commit with hash e2ea1639 do: git tagm v0.1 e2ea1639.

For pushed tags, use git tagmp v0.1 e2ea1639.

Both alias keeps you original date and message. If you use git tag -d you lost your original message.

Save them on your .gitconfig file

# Return date of tag. (To use in another alias)
tag-date = "!git show $1 | awk '{ if ($1 == \"Date:\") { print substr($0, index($0,$3)) }}' | tail -2 | head -1 #"

# Show tag message
tag-message = "!git show $1 | awk -v capture=0 '{ if(capture) message=message\"\\n\"$0}; BEGIN {message=\"\"}; { if ($1 == \"Date:\" && length(message)==0 ) {capture=1}; if ($1 == \"commit\" ) {capture=0}  }; END { print message }' | sed '$ d' | cat -s #"

### Move tag. Use: git tagm <tagname> <newcommit> 
tagm = "!GIT_TAG_MESSAGE=$(git tag-message $1) && GIT_COMMITTER_DATE=$(git tag-date $1) && git tag-message $1 && git tag -d $1 && git tag -a $1 $2 -m \"$GIT_TAG_MESSAGE\" #"

### Move pushed tag. Use: git tagmp <tagname> <newcommit> 
tagmp = "!git tagm $1 $2 && git push --delete origin $1 && git push origin $1 #"

How to export a Hive table into a CSV file?

That should work for you

  • tab separated

    hive -e 'select * from some_table' > /home/yourfile.tsv
  • comma separated

    hive -e 'select * from some_table' | sed 's/[\t]/,/g' > /home/yourfile.csv

How to get file size in Java

Use the length() method in the File class. From the javadocs:

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

UPDATED Nowadays we should use the Files.size() method:

Paths path = Paths.get("/path/to/file");
long size = Files.size(path);

For the second part of the question, straight from File's javadocs:

  • getUsableSpace() Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname

  • getTotalSpace() Returns the size of the partition named by this abstract pathname

  • getFreeSpace() Returns the number of unallocated bytes in the partition named by this abstract path name

How to ignore HTML element from tabindex?

The way to do this is by adding tabindex="-1". By adding this to a specific element, it becomes unreachable by the keyboard navigation. There is a great article here that will help you further understand tabindex.

Jquery get form field value

var textValue = $("input[type=text]").val()

this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get last article or any other element:

document.querySelector("article:last-child")

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

We get err_cache_miss error while using the bowser. Its mean there may be a problem with your browser. It due the items in the cache may be unusable or some configurations are not configured correctly. You may get the solution to clear browser data or Check browser extensions and remove extensions which you felt cause the problem or Resetting your browser or Update your browser or Disabling cache system. These are some tricks to come out this error.

How to center horizontally div inside parent div

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   

Syntax for a single-line Bash infinite while loop

It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done

Stop and Start a service via batch or cmd file?

Sometimes you can find the stop does not work..

My SQlServer sometimes does this. Using the following commandline kills it. If you really really need your script to kill stuff that doesn't stop. I would have it do this as a last resort

taskkill /pid [pid number] /f

Merge Two Lists in R

Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind and those that are just connected with c:

# Decided to move this outside the mapply, not sure this is 
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
  if (is.list(n_element)){
    # Fill in non-existant element with NA elements
    if (length(n_element) != length(o_element)){
      n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
      if (length(n_unique) > 0){
        for (n in n_unique){
          if (is.matrix(n_element[[n]])){
            o_element[[n]] <- matrix(NA, 
                                     nrow=nrow(n_element[[n]]), 
                                     ncol=ncol(n_element[[n]]))
          }else{
            o_element[[n]] <- rep(NA, 
                                  times=length(n_element[[n]]))
          }
        }
      }

      o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
      if (length(o_unique) > 0){
        for (n in o_unique){
          if (is.matrix(n_element[[n]])){
            n_element[[n]] <- matrix(NA, 
                                     nrow=nrow(o_element[[n]]), 
                                     ncol=ncol(o_element[[n]]))
          }else{
            n_element[[n]] <- rep(NA, 
                                  times=length(o_element[[n]]))
          }
        }
      }
    }  

    # Now merge the two lists
    return(mergeLists(o_element, 
                      n_element))

  }
  if(length(n_element)>1){
    new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
    old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
    if (new_cols != old_cols)
      stop("Your length doesn't match on the elements,",
           " new element (", new_cols , ") !=",
           " old element (", old_cols , ")")
  }

  return(rbind(o_element, 
               n_element, 
               deparse.level=0))
  return(c(o_element, 
           n_element))
}
mergeLists <- function(old, new){
  if (is.null(old))
    return (new)

  m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
  return(m)
}

Here's my example:

v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)

This results in:

$a
     [,1] [,2]
[1,]    1    2
[2,]    3    4

$b
[1] "test 1" "test 2"

$sublist
$sublist$one
     [,1] [,2]
[1,]   20   21
[2,]   10   11

$sublist$two
     [,1] [,2]
[1,]   21   22
[2,]   11   12

$sublist$three
     [,1] [,2]
[1,]   NA   NA
[2,]    1    2

Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine function for, and therefore I wrote this monster :-)

MySQL select 10 random rows from 600K rows fast

The following should be fast, unbiased and independent of id column. However it does not guarantee that the number of rows returned will match the number of rows requested.

SELECT *
FROM t
WHERE RAND() < (SELECT 10 / COUNT(*) FROM t)

Explanation: assuming you want 10 rows out of 100 then each row has 1/10 probability of getting SELECTed which could be achieved by WHERE RAND() < 0.1. This approach does not guarantee 10 rows; but if the query is run enough times the average number of rows per execution will be around 10 and each row in the table will be selected evenly.

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

Strtotime() doesn't work with dd/mm/YYYY format

I tried to convert ddmmyy format to date("Y-m-d" format but was not working when I directly pass ddmmyy =date('dmy')

then realized it has to be in yyyy-mm-dd format so. used substring to organize

$strParam = '20'.substr($_GET['date'], 4, 2).'-'.substr($_GET['date'], 2, 2).'-'.substr($_GET['date'], 0, 2);  

then passed to date("Y-m-d",strtotime($strParam));

it worked!

JavaScript: Check if mouse button down?

        var mousedown = 0;
        $(function(){
            document.onmousedown = function(e){
                mousedown = mousedown | getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.onmouseup = function(e){
                mousedown = mousedown ^ getWindowStyleButton(e);
                e = e || window.event;
                console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
            }

            document.oncontextmenu = function(e){
                // to suppress oncontextmenu because it blocks
                // a mouseup when two buttons are pressed and 
                // the right-mouse button is released before
                // the other button.
                return false;
            }
        });

        function getWindowStyleButton(e){
            var button = 0;
                if (e) {
                    if (e.button === 0) button = 1;
                    else if (e.button === 1) button = 4;
                    else if (e.button === 2) button = 2;  
                }else if (window.event){
                    button = window.event.button;
                }
            return button;
        }

this cross-browser version works fine for me.

How to let an ASMX file output JSON

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).

Create Excel files from C# without office

There are a handful of options:

  • NPOI - Which is free and open source.
  • Aspose - Is definitely not free but robust.
  • Spreadsheet ML - Basically XML for creating spreadsheets.

Using the Interop will require that the Excel be installed on the machine from which it is running. In a server side solution, this will be awful. Instead, you should use a tool like the ones above that lets you build an Excel file without Excel being installed.

If the user does not have Excel but has a tool that will read Excel (like Open Office), then obviously they will be able to open it. Microsoft has a free Excel viewer available for those users that do not have Excel.

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Array oList = ((from m in dc.Reviews
                           join n in dc.Users on m.authorID equals n.userID
                           orderby m.createdDate descending
                           where m.foodID == _id                      
                           select new
                           {
                               authorID = m.authorID,
                               createdDate = m.createdDate,
                               review = m.review1,
                               author = n.username,
                               profileImgUrl = n.profileImgUrl
                           }).Take(2)).ToArray();

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

Set the display.max_colwidth option to None (or -1 before version 1.0):

pd.set_option('display.max_colwidth', None)

set_option docs

For example, in iPython, we see that the information is truncated to 50 characters. Anything in excess is ellipsized:

Truncated result

If you set the display.max_colwidth option, the information will be displayed fully:

Non-truncated result

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

Check if a Class Object is subclass of another Class Object in Java

You want this method:

boolean isList = List.class.isAssignableFrom(myClass);

where in general, List (above) should be replaced with superclass and myClass should be replaced with subclass

From the JavaDoc:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Reference:


Related:

a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:

boolean isInstance = someObject instanceof SomeTypeOrInterface;

Example:

assertTrue(Arrays.asList("a", "b", "c") instanceof List<?>);

b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:

Class<?> typeOrInterface = // acquire class somehow
boolean isInstance = typeOrInterface.isInstance(someObject);

Example:

public boolean checkForType(Object candidate, Class<?> type){
    return type.isInstance(candidate);
}

Is it safe to use Project Lombok?

There are long-term maintenance risks as well. First, I'd recommend reading about how Lombok actually works, e.g. some answers from its developers here.

The official site also contains a list of downsides, including this quote from Reinier Zwitserloot:

It's a total hack. Using non-public API. Presumptuous casting (knowing that an annotation processor running in javac will get an instance of JavacAnnotationProcessor, which is the internal implementation of AnnotationProcessor (an interface), which so happens to have a couple of extra methods that are used to get at the live AST).

On eclipse, it's arguably worse (and yet more robust) - a java agent is used to inject code into the eclipse grammar and parser class, which is of course entirely non-public API and totally off limits.

If you could do what lombok does with standard API, I would have done it that way, but you can't. Still, for what its worth, I developed the eclipse plugin for eclipse v3.5 running on java 1.6, and without making any changes it worked on eclipse v3.4 running on java 1.5 as well, so it's not completely fragile.

As a summary, while Lombok may save you some development time, if there is a non-backwards compatible javac update (e.g. a vulnerability mitigation) Lombok might get you stuck with an old version of Java while the developers scramble to update their usage of those internal APIs. Whether this is a serious risk obviously depends on the project.

Is there a way to make Firefox ignore invalid ssl-certificates?

Instead of using invalid/outdated SSL certificates, why not use self-signed SSL certificates? Then you can add an exception in Firefox for just that site.

What is difference between XML Schema and DTD?

DTD indicates the syntax of the XML element

XML Schemas are Microsoft's alternative to DTD for validating XML

Granting Rights on Stored Procedure to another user of Oracle

Packages and stored procedures in Oracle execute by default using the rights of the package/procedure OWNER, not the currently logged on user.

So if you call a package that creates a user for example, its the package owner, not the calling user that needs create user privilege. The caller just needs to have execute permission on the package.

If you would prefer that the package should be run using the calling user's permissions, then when creating the package you need to specify AUTHID CURRENT_USER

Oracle documentation "Invoker Rights vs Definer Rights" has more information http://docs.oracle.com/cd/A97630_01/appdev.920/a96624/08_subs.htm#18575

Hope this helps.

Read Content from Files which are inside Zip file

Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata

Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.

How do you get the list of targets in a makefile?

Focusing on an easy syntax for describing a make target, and having a clean output, I chose this approach:

help:
    @grep -B1 -E "^[a-zA-Z0-9_-]+\:([^\=]|$$)" Makefile \
     | grep -v -- -- \
     | sed 'N;s/\n/###/' \
     | sed -n 's/^#: \(.*\)###\(.*\):.*/\2###\1/p' \
     | column -t  -s '###'


#: Starts the container stack
up: a b
  command

#: Pulls in new container images
pull: c d 
    another command

make-target-not-shown:

# this does not count as a description, so leaving
# your implementation comments alone, e.g TODOs
also-not-shown:

So treating the above as a Makefile and running it gives you something like

> make help
up          Starts the container stack
pull        Pulls in new container images

Explanation for the chain of commands:

Prevent jQuery UI dialog from setting focus to first textbox

I'd the same issue and solved it by inserting an empty input before the datepicker, that steals the focus every time the dialog is opened. This input is hidden on every opening of the dialog and shown again on closing.

Newline in JLabel

JLabel is actually capable of displaying some rudimentary HTML, which is why it is not responding to your use of the newline character (unlike, say, System.out).

If you put in the corresponding HTML and used <BR>, you would get your newlines.

How to use if, else condition in jsf to display image

Instead of using the "c" tags, you could also do the following:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?

Excel VBA For Each Worksheet Loop

You need to put the worksheet identifier in your range statements as shown below ...

 Option Explicit
 Dim ws As Worksheet, a As Range

Sub forEachWs()

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next

End Sub

Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub

JavaScript: Parsing a string Boolean value?

I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:

var BoolHelpers = {
    tryParse: function (value) {
        if (typeof value == 'boolean' || value instanceof Boolean)
            return value;
        if (typeof value == 'string' || value instanceof String) {
            value = value.trim().toLowerCase();
            if (value === 'true' || value === 'false')
                return value === 'true';
        }
        return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
    }
}

The usage:

var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);

How to find first element of array matching a boolean condition in JavaScript?

Since ES6 there is the native find method for arrays; this stops enumerating the array once it finds the first match and returns the value.

const result = someArray.find(isNotNullNorUndefined);

Old answer:

I have to post an answer to stop these filter suggestions :-)

since there are so many functional-style array methods in ECMAScript, perhaps there's something out there already like this?

You can use the some Array method to iterate the array until a condition is met (and then stop). Unfortunately it will only return whether the condition was met once, not by which element (or at what index) it was met. So we have to amend it a little:

function find(arr, test, ctx) {
    var result = null;
    arr.some(function(el, i) {
        return test.call(ctx, el, i, arr) ? ((result = el), true) : false;
    });
    return result;
}
var result = find(someArray, isNotNullNorUndefined);

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

HTML form readonly SELECT tag/input

Easier still: add the style attribute to your select tag:

style="pointer-events: none;"

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

Error in setting JAVA_HOME

JAVA_HOME = C:\Program Files\Java\jdk(JDK version number)

Example: C:\Program Files\Java\jdk-10

And then restart you command prompt it works.

How can I remove a commit on GitHub?

You'll need to clear out your cache to have it completely wiped. this help page from git will help you out. (it helped me) http://help.github.com/remove-sensitive-data/

Get drop down value

var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;

jQuery: selecting each td in a tr

Your $(magicSelector) could be $('td', this). This will grab all td that are children of this, which in your case is each tr. This is the same as doing $(this).find('td').

$('td', this).each(function() {
// Logic
});

Pandas - Get first row value of a given column

In a general way, if you want to pick up the first N rows from the J column from pandas dataframe the best way to do this is:

data = dataframe[0:N][:,J]

Changing background color of selected cell?

I finally managed to get this to work in a table view with style set to Grouped.

First set the selectionStyle property of all cells to UITableViewCellSelectionStyleNone.

cell.selectionStyle = UITableViewCellSelectionStyleNone;

Then implement the following in your table view delegate:

static NSColor *SelectedCellBGColor = ...;
static NSColor *NotSelectedCellBGColor = ...;

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *currentSelectedIndexPath = [tableView indexPathForSelectedRow];
    if (currentSelectedIndexPath != nil)
    {
        [[tableView cellForRowAtIndexPath:currentSelectedIndexPath] setBackgroundColor:NotSelectedCellBGColor];
    }

    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[tableView cellForRowAtIndexPath:indexPath] setBackgroundColor:SelectedCellBGColor];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (cell.isSelected == YES)
    {
        [cell setBackgroundColor:SelectedCellBGColor];
    }
    else
    {
        [cell setBackgroundColor:NotSelectedCellBGColor];
    }
}

Bash tool to get nth line from a file

I've put some of the above answers into a short bash script that you can put into a file called get.sh and link to /usr/local/bin/get (or whatever other name you prefer).

#!/bin/bash
if [ "${1}" == "" ]; then
    echo "error: blank line number";
    exit 1
fi
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
    echo "error: line number arg not a number";
    exit 1
fi
if [ "${2}" == "" ]; then
    echo "error: blank file name";
    exit 1
fi
sed "${1}q;d" $2;
exit 0

Ensure it's executable with

$ chmod +x get

Link it to make it available on the PATH with

$ ln -s get.sh /usr/local/bin/get

Enjoy responsibly!

P

How to update/modify an XML file in python?

To make this process more robust, you could consider using the SAX parser (that way you don't have to hold the whole file in memory), read & write till the end of tree and then start appending.

How do I REALLY reset the Visual Studio window layout?

I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I have upgraded my older version of WCF to WCF 4 with below changes, hope you can also make the similar changes.

1. Web.config:

<system.serviceModel>
      <bindings>
        <basicHttpBinding>
          <binding name="Demo_BasicHttp">
            <security mode="TransportCredentialOnly">
              <transport clientCredentialType="InheritedFromHost"/>
            </security>
          </binding>
        </basicHttpBinding>
      </bindings>
      <services>
        <service name="DemoServices.CalculatorService.ServiceImplementation.CalculatorService" behaviorConfiguration="Demo_ServiceBehavior">
          <endpoint address="" binding="basicHttpBinding"
              bindingConfiguration="Demo_BasicHttp" contract="DemoServices.CalculatorService.ServiceContracts.ICalculatorServiceContract">
            <identity>
              <dns value="localhost"/>
            </identity>
          </endpoint>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="Demo_ServiceBehavior">
            <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
            <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <protocolMapping>
        <add scheme="http" binding="basicHttpBinding" bindingConfiguration="Demo_BasicHttp"/>
      </protocolMapping>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    </system.serviceModel>

2. App.config:

    <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ICalculatorServiceContract" maxBufferSize="2147483647" maxBufferPoolSize="33554432" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="00:10:00">
          <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="4096" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Ntlm" proxyCredentialType="None" realm="" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:24357/CalculatorService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICalculatorServiceContract" contract="ICalculatorServiceContract" name="Demo_BasicHttp" />
    </client>
  </system.serviceModel>

How to remove gem from Ruby on Rails application?

For Rails 4 - remove the gem name from Gemfile and then run bundle install in your terminal. Also restart the server afterwards.

How do you copy and paste into Git Bash

if your intention is copy/paste comments for git commits, try set the enviromental variable EDITOR as your favorite plain-text editor (notepad, notepad++ ...) and when you will commit, don't give him the -m option and Git will open your favorite editor for copy/paste you comment

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Try this:

int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);  
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

Difference between SelectedItem, SelectedValue and SelectedValuePath

To answer a little more conceptually:

SelectedValuePath defines which property (by its name) of the objects bound to the ListBox's ItemsSource will be used as the item's SelectedValue.

For example, if your ListBox is bound to a collection of Person objects, each of which has Name, Age, and Gender properties, SelectedValuePath=Name will cause the value of the selected Person's Name property to be returned in SelectedValue.

Note that if you override the ListBox's ControlTemplate (or apply a Style) that specifies what property should display, SelectedValuePath cannot be used.

SelectedItem, meanwhile, returns the entire Person object currently selected.

(Here's a further example from MSDN, using TreeView)

Update: As @Joe pointed out, the DisplayMemberPath property is unrelated to the Selected* properties. Its proper description follows:

Note that these values are distinct from DisplayMemberPath (which is defined on ItemsControl, not Selector), but that property has similar behavior to SelectedValuePath: in the absence of a style/template, it identifies which property of the object bound to item should be used as its string representation.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

I found this reference:

create trigger myTrigger
on SomeTable
for insert 
as 
if (select count(*) 
    from SomeTable, inserted 
    where IsNumeric(SomeField) = 1) <> 0
/* Cancel the insert and print a message.*/
  begin
    rollback transaction 
    print "You can't do that!"  
  end  
/* Otherwise, allow it. */
else
  print "Added successfully."

I haven't tested it, but logically it looks like it should dp what you're after...rather than deleting the inserted data, prevent the insertion completely, thus not requiring you to have to undo the insert. It should perform better and should therefore ultimately handle a higher load with more ease.

Edit: Of course, there is the potential that if the insert happened inside of an otherwise valid transaction that the wole transaction could be rolled back so you would need to take that scenario into account and determine if the insertion of an invalid data row would constitute a completely invalid transaction...

flutter run: No connected devices

I tried a lot of the recommended steps listed here but the only thing it helps me was this:

File -> Settings -> Language & Support -> Dart -->

Activate the checkbox "Enable Dart support for the project ..."

enter image description here

jQuery find() method not working in AngularJS directive

find() - Limited to lookups by tag name you can see more information https://docs.angularjs.org/api/ng/function/angular.element

Also you can access by name or id or call please following example:

angular.element(document.querySelector('#txtName')).attr('class', 'error');

How can I convert a .py to .exe for Python?

Python 3.6 is supported by PyInstaller.

Open a cmd window in your Python folder (open a command window and use cd or while holding shift, right click it on Windows Explorer and choose 'Open command window here'). Then just enter

pip install pyinstaller

And that's it.

The simplest way to use it is by entering on your command prompt

pyinstaller file_name.py

For more details on how to use it, take a look at this question.

How to make a checkbox checked with jQuery?

$('#test').attr('checked','checked');

$('#test').removeAttr('checked');

How to Apply Mask to Image in OpenCV?

Here is some code to apply binary mask on a video frame sequence acquired from a webcam. comment and uncomment the "bitwise_not(Mon_mask,Mon_mask);"line and see the effect.

bests, Ahmed.

#include "cv.h"      // include it to used Main OpenCV functions.
#include "highgui.h" //include it to use GUI functions.

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    int c;

int radius=100;
      CvPoint2D32f center;
    //IplImage* color_img;
      Mat image, image0,image1; 
        IplImage *tmp;
    CvCapture* cv_cap = cvCaptureFromCAM(0);

    while(1)  {
        tmp = cvQueryFrame(cv_cap); // get frame
          // IplImage to Mat
            Mat imgMat(tmp);
            image =tmp; 



    center.x = tmp->width/2;
    center.y = tmp->height/2;

         Mat Mon_mask(image.size(), CV_8UC1, Scalar(0,0,0));


        circle(Mon_mask, center, radius, Scalar(255,255,255), -1, 8, 0 ); //-1 means filled

        bitwise_not(Mon_mask,Mon_mask);// commenté ou pas = RP ou DMLA 





        if(tmp != 0)

           imshow("Glaucom", image); // show frame

     c = cvWaitKey(10); // wait 10 ms or for key stroke
    if(c == 27)
        break; // if ESC, break and quit
    }
    /* clean up */
    cvReleaseCapture( &cv_cap );
    cvDestroyWindow("Glaucom");

}

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

How to execute XPath one-liners from shell?

clacke’s answer is great but I think only works if your source is well-formed XML, not normal HTML.

So to do the same for normal Web content—HTML docs that aren’t necessarily well-formed XML:

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
from lxml import html; \
print '\n'.join(html.tostring(node) for node in html.parse(stdin).xpath('//p'))"

And to instead use html5lib (to ensure you get the same parsing behavior as Web browsers—because like browser parsers, html5lib conforms to the parsing requirements in the HTML spec).

echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
import html5lib; from lxml import html; \
doc = html5lib.parse(stdin, treebuilder='lxml', namespaceHTMLElements=False); \
print '\n'.join(html.tostring(node) for node in doc.xpath('//p'))

What's the difference between Apache's Mesos and Google's Kubernetes

Both projects aim to make it easier to deploy & manage applications inside containers in your datacenter or cloud.

In order to deploy applications on top of Mesos, one can use Marathon or Kubernetes for Mesos.

Marathon is a cluster-wide init and control system for running Linux services in cgroups and Docker containers. Marathon has a number of different canary deploy features and is a very mature project.

Marathon runs on top of Mesos, which is a highly scalable, battle tested and flexible resource manager. Marathon is proven to scale and runs in many production environments.

The Mesos and Mesosphere technology stack provides a cloud-like environment for running existing Linux workloads, but it also provides a native environment for building new distributed systems.

Mesos is a distributed systems kernel, with a full API for programming directly against the datacenter. It abstracts underlying hardware (e.g. bare metal or VMs) away and just exposes the resources. It contains primitives for writing distributed applications (e.g. Spark was originally a Mesos App, Chronos, etc.) such as Message Passing, Task Execution, etc. Thus, entirely new applications are made possible. Apache Spark is one example for a new (in Mesos jargon called) framework that was built originally for Mesos. This enabled really fast development - the developers of Spark didn't have to worry about networking to distribute tasks amongst nodes as this is a core primitive in Mesos.

To my knowledge, Kubernetes is not used inside Google in production deployments today. For production, Google uses Omega/Borg, which is much more similar to the Mesos/Marathon model. However the great thing about using Mesos as the foundation is that both Kubernetes and Marathon can run on top of it.

More resources about Marathon:

https://mesosphere.github.io/marathon/

Video: https://www.youtube.com/watch?v=hZNGST2vIds

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

How to link home brew python version and set it as default

I think you have to be precise with which version you want to link with the command brew link python like:

brew link python 3

It will give you an error like that:

Linking /usr/local/Cellar/python3/3.5.2... 
Error: Could not symlink bin/2to3-3.5
Target /usr/local/bin/2to3-3.5
already exists. 

You may want to remove it:

rm '/usr/local/bin/2to3-3.5'

To force the link and overwrite all conflicting files:

brew link --overwrite python3

To list all files that would be deleted:

brew link --overwrite --dry-run python3

but you have to copy/paste the command to force the link which is:

brew link --overwrite python3

I think that you must have the version (the newer) installed.

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

How I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

Above suggestions didn't worked for me. I got it running on my windows, using inspiration from http://butlerccwebdev.net/support/testingserver/vhosts-setup-win.html

For Http inside httpd-vhosts.conf

<Directory "D:/Projects">       
AllowOverride All
Require all granted
</Directory>

##Letzgrow
<VirtualHost *:80>
DocumentRoot "D:/Projects/letzgrow"
ServerName letz.dev
ServerAlias letz.dev    
</VirtualHost>

For using Https (Open SSL) inside httpd-ssl.conf

<Directory "D:/Projects">       
AllowOverride All
Require all granted
</Directory>

##Letzgrow
<VirtualHost *:443>
DocumentRoot "D:/Projects/letzgrow"
ServerName letz.dev
ServerAlias letz.dev    
</VirtualHost>

Hope it helps someone !!

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

How can I remove a specific item from an array?

To me the simpler is the better, and as we are in 2018 (near 2019) I give you this (near) one-liner to answer the original question:

Array.prototype.remove = function (value) {
    return this.filter(f => f != value)
}

The useful thing is that you can use it in a curry expression such as:

[1,2,3].remove(2).sort()

Retrieve the commit log for a specific line in a file?

This will call git blame for every meaningful revision to show line $LINE of file $FILE:

git log --format=format:%H $FILE | xargs -L 1 git blame $FILE -L $LINE,$LINE

As usual, the blame shows the revision number in the beginning of each line. You can append

| sort | uniq -c

to get aggregated results, something like a list of commits that changed this line. (Not quite, if code only has been moved around, this might show the same commit ID twice for different contents of the line. For a more detailed analysis you'd have to do a lagged comparison of the git blame results for adjacent commits. Anyone?)

SSRS the definition of the report is invalid

I just received this obscure message when trying to deploy a report from BIDS.

After a little hunting I found a more descriptive error by going into the Preview window.

How to run single test method with phpunit?

Following command will execute exactly testSaveAndDrop test.

phpunit --filter '/::testSaveAndDrop$/' escalation/EscalationGroupTest.php

pip install: Please check the permissions and owner of that directory

basic info

  • system: mac os 18.0.0
  • current user: yutou

the key

  1. add the current account to wheel group
sudo dscl . -append /Groups/wheel wheel $(whoami)
  1. modify python package mode to 775.
chmod -R 775 ${this_is_your_python_package_path}

the whole thing

  • when python3 compiled well, the infomation is just like the question said.
  • I try to use pip3 install requests and got:
File "/usr/local/python3/lib/python3.6/os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: 
'/usr/local/python3/lib/python3.6/site-packages/requests'
  • so i cd /usr/local/python3/lib/python3.6/site-packages, then ls -al and got:
drwxr-xr-x    6 root   wheel   192B  2 27 18:06 requests/

when i saw this, i understood, makedirs is an action of write, but the requests mode drwxrwxr-x displaied only user root can write the requests file. If add yutou(whoami) to the group wheel, and modify the package to the group wheel can write, then i can write, and the problem solved.

How to add yutou to group wheel? + detect group wheel, sudo dscl . -list /groups GroupMembership, you will find:

wheel                    root

the group wheel only one member root. + add yutou to group wheel, sudo dscl . -append /Groups/wheel wheel yutou. + check, sudo dscl . -list /groups GroupMembership:

wheel                    root yutou

modify the python package mode

chmod -R 775 /usr/local/python3/lib/python3.6

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

How do I kill background processes / jobs when my shell script exits?

To be on the safe side I find it better to define a cleanup function and call it from trap:

cleanup() {
        local pids=$(jobs -pr)
        [ -n "$pids" ] && kill $pids
}
trap "cleanup" INT QUIT TERM EXIT [...]

or avoiding the function altogether:

trap '[ -n "$(jobs -pr)" ] && kill $(jobs -pr)' INT QUIT TERM EXIT [...]

Why? Because by simply using trap 'kill $(jobs -pr)' [...] one assumes that there will be background jobs running when the trap condition is signalled. When there are no jobs one will see the following (or similar) message:

kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]

because jobs -pr is empty - I ended in that 'trap' (pun intended).

The listener supports no services

for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address

alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;

How do I install pip on macOS or OS X?

I recommend Anaconda to you. It's the leading open data science platform powered by Python. There are many basic packages installed. Anaconda (conda) comes with its own installation of pip.

Is there a method that calculates a factorial in Java?

The only business use for a factorial that I can think of is the Erlang B and Erlang C formulas, and not everyone works in a call center or for the phone company. A feature's usefulness for business seems to often dictate what shows up in a language - look at all the data handling, XML, and web functions in the major languages.

It is easy to keep a factorial snippet or library function for something like this around.

Easiest way to change font and font size

Use this one to change only font size not the name of the font

label1.Font = new System.Drawing.Font(label1.Font.Name, 24F);

Searching a list of objects in Python

Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:

for i in list:
  if i.n == 5:
     # do something with it
     print "YAY! Found one!"

Regex pattern for checking if a string starts with a certain substring?

The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

The ^ mathes the start of the string. You can put any protocols between the parentheses separated by | characters.

edit:

Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

I keep getting "Uncaught SyntaxError: Unexpected token o"

I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.

I was accessing the iframe data like this:

$('#load-file-iframe').contents().text()

which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to

$('#load-file-iframe').contents().find('body').text()

once I noticed some garbage in the HTML response.

Long story short check your raw HTML response data and you might turn something up.

Removing X-Powered-By

If you use FastCGI try:

fastcgi_hide_header X-Powered-By;

Adding Python Path on Windows 7

I know this post is old but I'd like to add that the solutions assume admin privs. If you don't have those you can:

Go to control panel, type path (this is Windows 7 now so that's in the Search box) and click "Edit Environment variables for your account". You'll now see the Environment Variable dialog with "User variables" on the top and "System variables" below.

You can, as a user, click the top "New" button and add:

Variable name: PATH
Variable value: C:\Python27

(no spaces anywhere) and click OK. Once your command prompt is restarted, any PATH in the User variables is appended to the end of the System Path. It doesn't replace the PATH in any other way.

If you want a specific full path set up, you're better off creating a batch file like this little one:

@echo off
PATH C:\User\Me\Programs\mingw\bin;C:\User\Me\Programs;C:\Windows\system32
title Compiler Environment - %Username%@%Computername%
cmd

Call it "compiler.bat" or whatever and double click to start it. Or link to it. Or pin it etc...

LINQ query on a DataTable

Try this

var row = (from result in dt.AsEnumerable().OrderBy( result => Guid.NewGuid()) select result).Take(3) ; 

Receiving login prompt using integrated windows authentication

I also had the same issue. Tried most of the things found on this and other forums.

Finally was successful after doing a little own RnD.

I went into IIS Settings and then into my website permission options added my Organizations Domain User Group.

Now as all my domain user have been granted the access to that website i did not encounter that issue.

Hope this helps

Environment variables in Mac OS X

Just open the ~/.profile file, via nano in Terminal and type there :

export PATH=whatever/you/want:$PATH

Save this file (cmd+X and Y). After that please logout/login again or just open a new tab in Terminal and try use your new variable.

PLEASE DON'T forget to add ":$PATH" after whatever/you/want, otherwise you'll erase all paths in PATH variable, which were there before that.

Actionbar notification count icon (badge) like Google has

I found a very good solution here, I'm using it with kotlin.

First, in the drawable folder you have to create item_count.xml:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#f20000" />
<stroke
    android:width="2dip"
    android:color="#FFF" />
<padding
    android:bottom="5dp"
    android:left="5dp"
    android:right="5dp"
    android:top="5dp" />
</shape>

In your Activity_Main Layout some like:

<RelativeLayout
                    android:id="@+id/badgeLayout"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_toRightOf="@+id/badge_layout1"
                    android:layout_gravity="end|center_vertical"
                    android:layout_marginEnd="5dp">

                <RelativeLayout
                        android:id="@+id/relative_layout1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">

                    <Button
                            android:id="@+id/btnBadge"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:background="@mipmap/ic_notification" />

                </RelativeLayout>

                <TextView
                        android:id="@+id/txtBadge"
                        android:layout_width="18dp"
                        android:layout_height="18dp"
                        android:layout_alignRight="@id/relative_layout1"
                        android:background="@drawable/item_count"
                        android:text="22"
                        android:textColor="#FFF"
                        android:textSize="7sp"
                        android:textStyle="bold"
                        android:gravity="center"/>

            </RelativeLayout>

And you can modify like:

btnBadge.setOnClickListener { view ->
        Snackbar.make(view,"badge click", Snackbar.LENGTH_LONG) .setAction("Action", null).show()
        txtBadge.text = "0"
    }

Make absolute positioned div expand parent div height

Try this, it was worked for me

.child {
    width: 100%;
    position: absolute;
    top: 0px;
    bottom: 0px;
    z-index: 1;
}

It will set child height to parent height

cURL POST command line on WINDOWS RESTful service

I ran into the same issue on my win7 x64 laptop and was able to get it working using the curl release that is labeled Win64 - Generic w SSL by using the very similar command line format:

C:\Projects\curl-7.23.1-win64-ssl-sspi>curl -H "Content-Type: application/json" -X POST http://localhost/someapi -d "{\"Name\":\"Test Value\"}"

Which only differs from your 2nd escape version by using double-quotes around the escaped ones and the header parameter value. Definitely prefer the linux shell syntax more.

JOIN two SELECT statement results

Use UNION:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Or UNION ALL if you want duplicates:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Convert Mongoose docs to json

First of all, try toObject() instead of toJSON() maybe?

Secondly, you'll need to call it on the actual documents and not the array, so maybe try something more annoying like this:

var flatUsers = users.map(function() {
  return user.toObject();
})
return res.end(JSON.stringify(flatUsers));

It's a guess, but I hope it helps

what does mysql_real_escape_string() really do?

The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.

How to round up a number in Javascript?

this function limit decimal without round number

function limitDecimal(num,decimal){
     return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}

Get current AUTO_INCREMENT value for any table

Even though methai's answer is correct if you manually run the query, a problem occurs when 2 concurrent transaction/connections actually execute this query at runtime in production (for instance).

Just tried manually in MySQL workbench with 2 connections opened simultaneously:

CREATE TABLE translation (
  id BIGINT PRIMARY KEY AUTO_INCREMENT
);
# Suppose we have already 20 entries, we execute 2 new inserts:

Transaction 1:

21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';

insert into translation (id) values (21);

Transaction 2:

21 = SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'translation';

insert into translation (id) values (21);

# commit transaction 1;
# commit transaction 2;

Insert of transaction 1 is ok: Insert of transaction 2 goes in error: Error Code: 1062. Duplicate entry '21' for key 'PRIMARY'.

A good solution would be jvdub's answer because per transaction/connection the 2 inserts will be:

Transaction 1:

insert into translation (id) values (null);
21 = SELECT LAST_INSERT_ID();

Transaction 2:

insert into translation (id) values (null);
22 = SELECT LAST_INSERT_ID();

# commit transaction 1;
# commit transaction 2;

But we have to execute the last_insert_id() just after the insert! And we can reuse that id to be inserted in others tables where a foreign key is expected!

Also, we cannot execute the 2 queries as following:

insert into translation (id) values ((SELECT AUTO_INCREMENT FROM
    information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()
    AND TABLE_NAME='translation'));

because we actually are interested to grab/reuse that ID in other table or to return!

Convert string to datetime in vb.net

As an alternative, if you put a space between the date and time, DateTime.Parse will recognize the format for you. That's about as simple as you can get it. (If ParseExact was still not being recognized)

Embed a PowerPoint presentation into HTML

An easy (and free) way is to download OpenOffice and use Impress to open the PowerPoint presentation. Then export into a separate folder as HTML. Your presentation will consist of separate HTML files and images for each PowerPoint slide. Link to the title page, and you're done.

Language Books/Tutorials for popular languages

For REALbasic:

Buginning REALbasic, From Novice to Professional by Jerry Lee Ford

Very basic, but a good way to get started

What is the fastest way to send 100,000 HTTP requests in Python?

Using a thread pool is a good option, and will make this fairly easy. Unfortunately, python doesn't have a standard library that makes thread pools ultra easy. But here is a decent library that should get you started: http://www.chrisarndt.de/projects/threadpool/

Code example from their site:

pool = ThreadPool(poolsize)
requests = makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()

Hope this helps.

How do I ZIP a file in C#, using no 3rd-party APIs?

Add these 4 functions to your project:

        public const long BUFFER_SIZE = 4096;
    public static void AddFileToZip(string zipFilename, string fileToAdd)
    {
        using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = ".\\" + Path.GetFileName(fileToAdd);
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
            PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
            using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
            {
                using (Stream dest = part.GetStream())
                {
                    CopyStream(fileStream, dest);
                }
            }
        }
    }
    public static void CopyStream(global::System.IO.FileStream inputStream, global::System.IO.Stream outputStream)
    {
        long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
        byte[] buffer = new byte[bufferSize];
        int bytesRead = 0;
        long bytesWritten = 0;
        while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
            bytesWritten += bytesRead;
        }
    }
    public static void RemoveFileFromZip(string zipFilename, string fileToRemove)
    {
        using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = ".\\" + fileToRemove;
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
        }
    }
    public static void Remove_Content_Types_FromZip(string zipFileName)
    {
        string contents;
        using (ZipFile zipFile = new ZipFile(File.Open(zipFileName, FileMode.Open)))
        {
            /*
            ZipEntry startPartEntry = zipFile.GetEntry("[Content_Types].xml");
            using (StreamReader reader = new StreamReader(zipFile.GetInputStream(startPartEntry)))
            {
                contents = reader.ReadToEnd();
            }
            XElement contentTypes = XElement.Parse(contents);
            XNamespace xs = contentTypes.GetDefaultNamespace();
            XElement newDefExt = new XElement(xs + "Default", new XAttribute("Extension", "sab"), new XAttribute("ContentType", @"application/binary; modeler=Acis; version=18.0.2application/binary; modeler=Acis; version=18.0.2"));
            contentTypes.Add(newDefExt);
            contentTypes.Save("[Content_Types].xml");
            zipFile.BeginUpdate();
            zipFile.Add("[Content_Types].xml");
            zipFile.CommitUpdate();
            File.Delete("[Content_Types].xml");
            */
            zipFile.BeginUpdate();
            try
            {
                zipFile.Delete("[Content_Types].xml");
                zipFile.CommitUpdate();
            }
            catch{}
        }
    }

And use them like this:

foreach (string f in UnitZipList)
{
    AddFileToZip(zipFile, f);
    System.IO.File.Delete(f);
}
Remove_Content_Types_FromZip(zipFile);

How to set custom ActionBar color / style?

You can define the color of the ActionBar (and other stuff) by creating a custom Style:

Simply edit the res/values/styles.xml file of your Android project.

For example like this:

<resources>
    <style name="MyCustomTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBarTheme</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">ANY_HEX_COLOR_CODE</item>
    </style>
</resources>

Then set "MyCustomTheme" as the Theme of your Activity that contains the ActionBar.

You can also set a color for the ActionBar like this:

ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED)); // set your desired color

Taken from here: How do I change the background color of the ActionBar of an ActionBarActivity using XML?

$(document).on("click"... not working?

An old post, but I love to share as I have the same case but I finally knew the problem :

Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.

Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.

But please inspect this sample that did not heed the above case :

<div class="btn-list" id="selected-country"></div>

Dynamically appended :

<button class="btn-map" data-country="'+country+'">'+ country+' </button>

This function is working good by clicking the button :

$(document).ready(function() {    
        $('#selected-country').on('click','.btn-map', function(){ 
        var datacountry = $(this).data('country'); console.log(datacountry);
    });
})

or you can use body like :

$('body').on('click','.btn-map', function(){ 
            var datacountry = $(this).data('country'); console.log(datacountry);
        });

compare to this that not working :

$(document).ready(function() {     
$('.btn-map').on("click", function() { 
        var datacountry = $(this).data('country'); alert(datacountry);
    });
});

hope it will help

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

Passing a 2D array to a C++ function

One important thing for passing multidimensional arrays is:

  • First array dimension need not be specified.
  • Second(any any further)dimension must be specified.

1.When only second dimension is available globally (either as a macro or as a global constant)

const int N = 3;

void print(int arr[][N], int m)
{
int i, j;
for (i = 0; i < m; i++)
  for (j = 0; j < N; j++)
    printf("%d ", arr[i][j]);
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}

2.Using a single pointer: In this method,we must typecast the 2D array when passing to function.

void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
  for (j = 0; j < n; j++)
    printf("%d ", *((arr+i*n) + j));
 }

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);"
print((int *)arr, m, n);
return 0;
}

How to pass ArrayList<CustomeObject> from one activity to another?

Use this code to pass arraylist<customobj> to anthother Activity

firstly serialize our contact bean

public class ContactBean implements Serializable {
      //do intialization here
}

Now pass your arraylist

 Intent intent = new Intent(this,name of activity.class);
 contactBean=(ConactBean)_arraylist.get(position);
 intent.putExtra("contactBeanObj",conactBean);
 _activity.startActivity(intent);

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Close iOS Keyboard by touching anywhere using Swift

If you use a scroll view, It could be much simpler.

Just select Dismiss interactively in storyboard.

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

How to get text box value in JavaScript

Here is a simple way

document.getElemmentByName("txtJob").getAttribute("value")

What is the maximum size of a web browser's cookie's key?

Not completely entirely a direct answer to the original question, but relevant for the curious quickly trying to visually understand their cookie information storage planning without implementing a complex limiter algorithm, this string is 4096 ASCII character bytes:

"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"

if variable contains

The fastest way to check if a string contains another string is using indexOf:

if (code.indexOf('ST1') !== -1) {
    // string code has "ST1" in it
} else {
    // string code does not have "ST1" in it
}

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Answer

/[\W\S_]/

Explanation

This creates a character class removing the word characters, space characters, and adding back the underscore character (as underscore is a "word" character). All that is left is the special characters. Capital letters represent the negation of their lowercase counterparts.

\W will select all non "word" characters equivalent to [^a-zA-Z0-9_]
\S will select all non "whitespace" characters equivalent to [ \t\n\r\f\v]
_ will select "_" because we negate it when using the \W and need to add it back in

Ruby get object keys as array

Like taro said, keys returns the array of keys of your Hash:

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

You'll find all the different methods available for each class.

If you don't know what you're dealing with:

 puts my_unknown_variable.class.to_s

This will output the class name.

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

Customize list item bullets using CSS

You have to use an image to change the actual size or form of the bullet itself:

You can use a background image with appropriate padding to nudge content so it doesn't overlap:

list-style-image:url(bigger.gif);

or

background-image: url(images/bullet.gif);

Convert DataTable to IEnumerable<T>

        PagedDataSource objPage = new PagedDataSource();

        DataView dataView = listData.DefaultView;
        objPage.AllowPaging = true;
        objPage.DataSource = dataView;
        objPage.PageSize = PageSize;

        TotalPages = objPage.PageCount;

        objPage.CurrentPageIndex = CurrentPage - 1;

        //Convert PagedDataSource to DataTable
        System.Collections.IEnumerator pagedData = objPage.GetEnumerator();

        DataTable filteredData = new DataTable();
        bool flagToCopyDTStruct = false;
        while (pagedData.MoveNext())
        {
            DataRowView rowView = (DataRowView)pagedData.Current;
            if (!flagToCopyDTStruct)
            {
                filteredData = rowView.Row.Table.Clone();
                flagToCopyDTStruct = true;
            }
            filteredData.LoadDataRow(rowView.Row.ItemArray, true);
        }

        //Here is your filtered DataTable
        return filterData; 

Show and hide divs at a specific time interval using jQuery

Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval so theres no cleanup that has to be done.

Having this HTML

<section id="testimonials">
    <h2>My testimonial spinner</h2>
    <div class="testimonial">
      <p>First content</p>
    </div>
    <div class="testimonial">
      <p>Second content</p>
    </div>
    <div class="testimonial">
       <p>Third content</p>
    </div>
</section>

Using ES2016

Here you call the function recursively and update the arguments.

  const testimonials = $('#testimonials')
      .children()
      .filter('div.testimonial');

  const showTestimonial = index => {

    testimonials.hide();
    $(testimonials[index]).fadeIn();

    return index === testimonials.length
      ? showTestimonial(0)
      : setTimeout(() => { showTestimonial(index + 1); }, 10000);
   }

showTestimonial(0); // id of the first element you want to show.

how to implement a pop up dialog box in iOS

Here is C# version in Xamarin.iOS

var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();

How to create a file in Ruby

Try using "w+" as the write mode instead of just "w":

File.open("out.txt", "w+") { |file| file.write("boo!") }

How do I execute a program from Python? os.system fails due to spaces in path

subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

How can I force gradle to redownload dependencies?

There is 2 ways to do that:

  1. Using command line option to refresh dependenices cashe.
  2. You can delete local cache where artefasts are caches by Gradle and trigger build

Using --refresh-dependencies option:

./gradlew build --refresh-dependencies

Short explanation --refresh-dependencies option tells Gradle to ignore all cached entries for resolved modules and artifacts.

Long explanantion

  • WIth –refresh-dependencies’ Gradle will always hit the remote server to check for updated artifacts: however, Gradle will avoid downloading a file where the same file already exists in the cache.
    • First Gradle will make a HEAD request and check if the server reports the file as unchanged since last time (if the ‘content-length’ and ‘last-modified’ are unchanged). In this case you’ll get the message: "Cached resource is up-to-date (lastModified: {})."
    • Next Gradle will determine the remote checksum if possible (either from the HEAD request or by downloading a ‘.sha1’ file).. If this checksum matches another file already downloaded (from any repository), then Gradle will simply copy the file in the cache, rather than re-downloading. In this case you’ll get the message: "“Found locally available resource with matching checksum: [{}, {}]”.

Using delete: When you delete caches

rm -rf $HOME/.gradle/caches/

You just clean all the cached jars and sha1 sums and Gradle is in situation where there is no artifacts on your machine and has to download everything. Yes it will work 100% for the first time, but when another SNAPSHOT is released and it is part of your dependency tree you will be faced again in front of the choice to refresh or to purge the caches.

Sorting HashMap by values

map.entrySet().stream()
                .sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue()))
                .forEach(k -> System.out.println(k.getKey() + ": " + k.getValue()));

How to do a SQL NOT NULL with a DateTime?

erm it does work? I've just tested it?

/****** Object:  Table [dbo].[DateTest]    Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
    [Date1] [datetime] NULL,
    [Date2] [datetime] NOT NULL
) ON [PRIMARY]

GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL

Can I run a 64-bit VMware image on a 32-bit machine?

You can if your processor is 64-bit and Virtualization Technology (VT) extension is enabled (it can be switched off in BIOS). You can't do it on 32-bit processor.

To check this under Linux you just need to look into /proc/cpuinfo file. Just look for the appropriate flag (vmx for Intel processor or svm for AMD processor)

egrep '(vmx|svm)' /proc/cpuinfo

To check this under Windows you need to use a program like CPU-Z which will display your processor architecture and supported extensions.

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

Play an audio file using jQuery when a button is clicked

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var audioElement = document.createElement('audio');_x000D_
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
    _x000D_
    audioElement.addEventListener('ended', function() {_x000D_
        this.play();_x000D_
    }, false);_x000D_
    _x000D_
    audioElement.addEventListener("canplay",function(){_x000D_
        $("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
        $("#source").text("Source:" + audioElement.src);_x000D_
        $("#status").text("Status: Ready to play").css("color","green");_x000D_
    });_x000D_
    _x000D_
    audioElement.addEventListener("timeupdate",function(){_x000D_
        $("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
    });_x000D_
    _x000D_
    $('#play').click(function() {_x000D_
        audioElement.play();_x000D_
        $("#status").text("Status: Playing");_x000D_
    });_x000D_
    _x000D_
    $('#pause').click(function() {_x000D_
        audioElement.pause();_x000D_
        $("#status").text("Status: Paused");_x000D_
    });_x000D_
    _x000D_
    $('#restart').click(function() {_x000D_
        audioElement.currentTime = 0;_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
    <h2>Sound Information</h2>_x000D_
    <div id="length">Duration:</div>_x000D_
    <div id="source">Source:</div>_x000D_
    <div id="status" style="color:red;">Status: Loading</div>_x000D_
    <hr>_x000D_
    <h2>Control Buttons</h2>_x000D_
    <button id="play">Play</button>_x000D_
    <button id="pause">Pause</button>_x000D_
    <button id="restart">Restart</button>_x000D_
    <hr>_x000D_
    <h2>Playing Information</h2>_x000D_
    <div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Intellij JAVA_HOME variable

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

To directly answer your question, you can add launchctl line in your ~/.bash_profile

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

how to check if a datareader is null or empty

AMG - Sorry all, was having a blond moment. The field "Additional" was added to the database after I had initially designed the database.

I updated all my code to use this new field, however I forgot to update the actual datareader code that was making the call to select the database fields, therefore it wasn't calling "Additional"

iPhone Debugging: How to resolve 'failed to get the task for process'?

The ad-hoc profile doesn't support debugging. You need to debug with a Development profile, and use the Ad-Hoc profile only for distributing non-debuggable copies.

How do you add an image?

The other option to try is a straightforward

<img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>

i.e. without {} but instead giving the direct image path

How can I limit the visible options in an HTML <select> dropdown?

I have made a simple solution for this in ReactJS you can use this in Vanilla Javascript aswell.

Javascript code

//props.options = [{value:'123',label:'123'},{value:'321',label:'321'},{value:'432',label:'432'}];
<div>
<div
  className="new-user-input"
  style={{ marginTop: '10px' }}
  onClick={() => {
    this.setState({
      showOptions: !this.state.showOptions,
    });
  }}
>
  {selectedOption ? (
    <span className="txt-black-600-12">
      {' '}
      {selectedOption.label}{' '}
    </span>
  ) : (
    <span className="txt-grey-500-12">
      Select Option
    </span>
  )}

  //Font awesome icons
  <span className="float-right">
    {this.state.showOptions ? (
      <FaAngleUp />
    ) : (
      <FaAngleDown />
    )}
  </span>
  {this.state.showOptions && (
    <div className="custom-select mt-10">
      {this.props.options.map(ele => {
        return (
          <span
            className="custom-select-option"
            onClick={() => {
              this.setState({
                selectedOption: ele,
                showOptions: false,
              });
            }}
          >
            {ele.label}
          </span>
        );
      })}
    </div>
  )}
</div>
</div>

CSS

.new-user-input {
  border: none;
  background-image: none;
  background-color: #ffffff;

  box-shadow: 0px 1px 5px 1px #d1d1d1;
  outline: none;
  display: block;
  margin: 20px auto;
  padding: 10px;
  width: 90%;
  border-radius: 8px;
}

.new-user-input:focus {
  border: none;
  background-image: none;
  background-color: #ffffff;
  outline: none;
}
    .custom-select{
  display: flex;
    flex-direction: column;
    max-height: 100px;
    overflow: auto;
    flex: 1 0;
}
.custom-select-option{
  padding: 10px 0;
  border-bottom: 1px solid #ececec;
  font-size: 10px;
  font-weight: 500;
  color: #413958;
}

How do I round a float upwards to the nearest int in C#?

The easiest is to just add 0.5f to it and then cast this to an int.

Add a month to a Date

I turned antonio's thoughts into a specific function:

library(DescTools)

> AddMonths(as.Date('2004-01-01'), 1)
[1] "2004-02-01"

> AddMonths(as.Date('2004-01-31'), 1)
[1] "2004-02-29"

> AddMonths(as.Date('2004-03-30'), -1)
[1] "2004-02-29"

Make body have 100% of the browser height

A quick update

html, body{
    min-height:100%;
    overflow:auto;
}

A better solution with today's CSS

html, body{ 
  min-height: 100vh;
  overflow: auto;
}

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    color = (color=="red") ? "black" : "red" ;
    document.getElementById("test").style.color= color;
}

Removing "http://" from a string

preg_replace('/^[^:\/?]+:\/\//','',$url); 

some results:

input: http://php.net/preg_replace output: php.net/preg_replace  input: https://www.php.net/preg_replace output: www.php.net/preg_replace  input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace  input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com  input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com 

How do you get total amount of RAM the computer has?

Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):

static ulong GetTotalMemoryInBytes()
{
    return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}

Get file size, image width and height before upload

So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.

Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.

_x000D_
_x000D_
$('input').change(function() {_x000D_
    _x000D_
    var fr = new FileReader;_x000D_
    _x000D_
    fr.onload = function() {_x000D_
        var img = new Image;_x000D_
        _x000D_
        img.onload = function() { _x000D_
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader._x000D_
            $.ajax({url: img.src, async: false, success: function(result){_x000D_
              $("#result").html("READING IMAGE, PLEASE WAIT...")_x000D_
              $("#result").html("<img src='" + img.src + "' />");_x000D_
                console.log("Finished reading Image");_x000D_
          }});_x000D_
        };_x000D_
        _x000D_
        img.src = fr.result;_x000D_
    };_x000D_
    _x000D_
    fr.readAsDataURL(this.files[0]);_x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" accept="image/*" capture="camera">_x000D_
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
_x000D_
_x000D_
_x000D_

(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)

How to get the selected radio button’s value?

In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:

var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);

or simpler:

alert(document.theForm.genderS.value);

refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value

How do I profile memory usage in Python?

A simple example to calculate the memory usage of a block of codes / function using memory_profile, while returning result of the function:

import memory_profiler as mp

def fun(n):
    tmp = []
    for i in range(n):
        tmp.extend(list(range(i*i)))
    return "XXXXX"

calculate memory usage before running the code then calculate max usage during the code:

start_mem = mp.memory_usage(max_usage=True)
res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True) 
print('start mem', start_mem)
print('max mem', res[0][0])
print('used mem', res[0][0]-start_mem)
print('fun output', res[1])

calculate usage in sampling points while running function:

res = mp.memory_usage((fun, [100]), interval=.001, retval=True)
print('min mem', min(res[0]))
print('max mem', max(res[0]))
print('used mem', max(res[0])-min(res[0]))
print('fun output', res[1])

Credits: @skeept

Difference between SurfaceView and View?

The main difference is that SurfaceView can be drawn on by background theads but Views can't. SurfaceViews use more resources though so you don't want to use them unless you have to.

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

Investigating this error on my new Win 7 laptop, I found my ADT plugin to be missing. By adding this I solved the problem: Downloading the ADT Plugin

Use the Update Manager feature of your Eclipse installation to install the latest revision of ADT on your development computer.

Assuming that you have a compatible version of the Eclipse IDE installed, as described in Preparing for Installation, above, follow these steps to download the ADT plugin and install it in your Eclipse environment.

Start Eclipse, then select Help > Install New Software.... Click Add, in the top-right corner. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/ Click OK

Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons). In the Available Software dialog, select the checkbox next to Developer Tools and click Next. In the next window, you'll see a list of the tools to be downloaded. Click Next. Read and accept the license agreements, then click Finish.

Note: If you get a security warning saying that the authenticity or validity of the software can't be established, click OK. When the installation completes, restart Eclipse.

SQL query to get most recent row for each instance of a given key

Can't post comments yet, but @Cristi S's answer works a treat for me.

In my scenario, I needed to keep only the most recent 3 records in Lowest_Offers for all product_ids.

Need to rework his SQL to delete - thought that this would be ok, but syntax is wrong.

DELETE from (
SELECT product_id, id, date_checked,
  ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY date_checked DESC) rn
FROM lowest_offers
) tmp WHERE > 3;

Try-catch-finally-return clarification

Here is some code that show how it works.

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

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Git: Create a branch from unstaged/uncommitted changes on master

In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:

enter image description here

The same applies if you simply switch the branch too.

Remove part of string after "."

If the string should be of fixed length, then substr from base R can be used. But, we can get the position of the . with regexpr and use that in substr

substr(a, 1, regexpr("\\.", a)-1)
#[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"   

How to remove the default arrow icon from a dropdown list (select element)?

The previously mentioned solutions work well with chrome but not on Firefox.

I found a Solution that works well both in Chrome and Firefox(not on IE). Add the following attributes to the CSS for your SELECTelement and adjust the margin-top to suit your needs.

select {
    -webkit-appearance: none;
    -moz-appearance: none;
    text-indent: 1px;
    text-overflow: '';
}

Hope this helps :)

On localhost, how do I pick a free port number?

If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:

import socketserver

with socketserver.TCPServer(("localhost", 0), None) as s:
    free_port = s.server_address[1]

Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.

Must declare the scalar variable

You can also get this error message if a variable is declared before a GOand referenced after it.

See this question and this workaround.

How to break lines at a specific character in Notepad++?

  1. Click Ctrl + h or Search -> Replace on the top menu
  2. Under the Search Mode group, select Regular expression
  3. In the Find what text field, type ],\s*
  4. In the Replace with text field, type ],\n
  5. Click Replace All

How can I concatenate two arrays in Java?

I found I had to deal with the case where the arrays can be null...

private double[] concat  (double[]a,double[]b){
    if (a == null) return b;
    if (b == null) return a;
    double[] r = new double[a.length+b.length];
    System.arraycopy(a, 0, r, 0, a.length);
    System.arraycopy(b, 0, r, a.length, b.length);
    return r;

}
private double[] copyRest (double[]a, int start){
    if (a == null) return null;
    if (start > a.length)return null;
    double[]r = new double[a.length-start];
    System.arraycopy(a,start,r,0,a.length-start); 
    return r;
}

How to get the mouse position without events (without moving the mouse)?

I implemented a horizontal/vertical search, (first make a div full of vertical line links arranged horizontally, then make a div full of horizontal line links arranged vertically, and simply see which one has the hover state) like Tim Down's idea above, and it works pretty fast. Sadly, does not work on Chrome 32 on KDE.

jsfiddle.net/5XzeE/4/

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

Android, How to limit width of TextView (and add three dots at the end of text)?

code:

TextView your_text_view = (TextView) findViewById(R.id.your_id_textview);
your_text_view.setEllipsize(TextUtils.TruncateAt.END);

xml:

android:maxLines = "5"

e.g.

In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know the mysteries of the kingdom of heaven, but to them it has not been given.

Output: In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know...

How can I export the schema of a database in PostgreSQL?

For Linux: (data excluded)

  • pg_dump -s -t tablename databasename > dump.sql (For a specific table in database)

  • pg_dump -s databasename > dump.sql (For the entire database)

Press enter in textbox to and execute button command

There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)

Creating a singleton in Python

Here's a one-liner for you:

singleton = lambda c: c()

Here's how you use it:

@singleton
class wat(object):
    def __init__(self): self.x = 1
    def get_x(self): return self.x

assert wat.get_x() == 1

Your object gets instantiated eagerly. This may or may not be what you want.

Invalid Host Header when ngrok tries to connect to React dev server

If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this

devServer: {
    contentBase: path.join(__dirname, './dist'),
    compress: true,
    host: 'localhost',
    // host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true //for ngrok
},

Loop through checkboxes and count each one checked or unchecked

I don't think enough time was paid attention to the schema considerations brought up in the original post. So, here is something to consider for any newbies.

Let's say you went ahead and built this solution. All of your menial values are conctenated into a single value and stored in the database. You are indeed saving [a little] space in your database and some time coding.

Now let's consider that you must perform the frequent and easy task of adding a new checkbox between the current checkboxes 3 & 4. Your development manager, customer, whatever expects this to be a simple change.

So you add the checkbox to the UI (the easy part). Your looping code would already concatenate the values no matter how many checkboxes. You also figure your database field is just a varchar or other string type so it should be fine as well.

What happens when customers or you try to view the data from before the change? You're essentially serializing from left to right. However, now the values after 3 are all off by 1 character. What are you going to do with all of your existing data? Are you going write an application, pull it all back out of the database, process it to add in a default value for the new question position and then store it all back in the database? What happens when you have several new values a week or month apart? What if you move the locations and jQuery processes them in a different order? All your data is hosed and has to be reprocessed again to rearrange it.

The whole concept of NOT providing a tight key-value relationship is ludacris and will wind up getting you into trouble sooner rather than later. For those of you considering this, please don't. The other suggestions for schema changes are fine. Use a child table, more fields in the main table, a question-answer table, etc. Just don't store non-labeled data when the structure of that data is subject to change.

How can I upgrade NumPy?

After installing pytorch, I got a similar error when I used:

import torch

Removing NumPy didn't help (I actually renamed NumPy, so I reverted back after it didn't work). The following commands worked for me:

sudo pip install numpy --upgrade
sudo easy_install numpy

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

Introduction

Whenever an UICommand component (<h:commandXxx>, <p:commandXxx>, etc) fails to invoke the associated action method, or an UIInput component (<h:inputXxx>, <p:inputXxxx>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml,

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>

and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.

Possible causes

  1. UICommand and UIInput components must be placed inside an UIForm component, e.g. <h:form> (and thus not plain HTML <form>), otherwise nothing can be sent to the server. UICommand components must also not have type="button" attribute, otherwise it will be a dead button which is only useful for JavaScript onclick. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.

  2. You cannot nest multiple UIForm components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.

  3. No UIInput value validation/conversion error should have occurred. You can use <h:messages> to show any messages which are not shown by any input-specific <h:message> components. Don't forget to include the id of <h:messages> in the <f:ajax render>, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.

  4. If UICommand or UIInput components are placed inside an iterating component like <h:dataTable>, <ui:repeat>, etc, then you need to ensure that exactly the same value of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.

  5. If UICommand or UIInput components are included by a dynamic source such as <ui:include src="#{bean.include}">, then you need to ensure that exactly the same #{bean.include} value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).

  6. The rendered attribute of the component and all of its parents and the test attribute of any parent <c:if>/<c:when> should not evaluate to false during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a @ViewScoped bean or making sure that you're properly preinitializing the condition in @PostConstruct of a @RequestScoped bean should fix it. The same applies to the disabled and readonly attributes of the component, which should not evaluate to true during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway

  7. The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm component should not return false or cause a JavaScript error. There should in case of <h:commandLink> or <f:ajax> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.

  8. If you're using Ajax via JSF 2.x <f:ajax> or e.g. PrimeFaces <p:commandXxx>, make sure that you have a <h:head> in the master template instead of the <head>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.

  9. If you're using Ajax, and the submitted values end up being null, then make sure that the UIInput and UICommand components of interest are covered by the <f:ajax execute> or e.g. <p:commandXxx process>, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.

  10. If the submitted values still end up being null, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to @Dependent which effectively recreates the bean on every single evaluation of the EL expression. See also @SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?

  11. If a parent of the <h:form> with the UICommand button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form> in the render of the <f:ajax>. See also h:commandButton/h:commandLink does not work on first click, works only on second click.

  12. If the <h:form> has enctype="multipart/form-data" set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>, check this answer and for PrimeFaces <p:fileUpload>, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.

  13. Make sure that the ActionEvent argument of actionListener is an javax.faces.event.ActionEvent and thus not java.awt.event.ActionEvent, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}". If you don't want an argument in your method, use actionListener="#{bean.method()}". Or perhaps you actually want to use action instead of actionListener. See also Differences between action and actionListener.

  14. Make sure that no PhaseListener or any EventListener in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse() or FacesContext#responseComplete().

  15. Make sure that no Filter or Servlet in the same request-response chain has blocked the request fo the FacesServlet somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.

  16. If you are using a PrimeFaces <p:dialog> or a <p:overlayPanel>, then make sure that they have their own <h:form>. Because, these components are by default by JavaScript relocated to end of HTML <body>. So, if they were originally sitting inside a <form>, then they would now not anymore sit in a <form>. See also p:commandbutton action doesn't work inside p:dialog

  17. Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar UI element with a defaultLabel attribute (or, in some cases, a rich:placeholder sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.

Debugging hints

In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax> enabled button while not having <h:head> declared (as described in point 7 above).

js console

Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText> and a single <h:commandButton> with <f:ajax execute="@form" render="@form">.

network monitor

(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)

In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand component, that would be UICommand#queueEvent() and in case of UIInput component, that would be UIInput#validate(). Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.

debug server

CR LF notepad++ removal

The best and quick solution to the problem is first do this: View-> Show Symbol-> uncheck Show End of Line

This will solve problem for 90% of you and as in my case CR LF and its combinations still persist in the code. To fix this simply create a new tab using ctrl+n and copy whole file and paste in this new file. All CRLF gone, copy whole file again and go to original file delete whole code and paste the copied save and you rock!!!

Hope this helps.

SDK Location not found Android Studio + Gradle

To fix this problem, I had to define the ANDROID_HOME environment variable in the Windows OS.

To do this, I went to the System control panel.
I selected "Advanced system settings" in the left column.
On the "Advanced" tab, I selected "Environment Variables" at the bottom.

Here, I did not have an ANDROID_HOME variable defined. For this case, I selected "New..." and:
1) for "Variable name" I typed ANDROID_HOME,
2) for "Variable value", I typed the path to my SDK folder, e.g. "C:\...\AppData\Local\Android\sdk".

I then closed Android Studio and reopened, and everything worked.

Thanks to Dibish (https://stackoverflow.com/users/2244411/dibish) for one of his posts that gave me this idea.

Changing a specific column name in pandas DataFrame

Since inplace argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:

df.rename(columns={'two':'new_name'}, inplace=True)

if, elif, else statement issues in Bash

I would recommend you having a look at the basics of conditioning in bash.

The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.

Usage:

elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]

In short, edit your code segment to:

elif [ "$seconds" -gt 0 ]

You'd be fine with no compilation errors. Your final code segment should look like this:

#!/bin/sh    
if [ "$seconds" -eq 0 ];then
       $timezone_string="Z"
    elif [ "$seconds" -gt 0 ]
    then
       $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
    else
       echo "Unknown parameter"
    fi

How to switch between hide and view password

You can use app:passwordToggleEnabled="true"

here is example given below

<android.support.design.widget.TextInputLayout
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true"
        android:textColorHint="@color/colorhint"
        android:textColor="@color/colortext">

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

Android EditText Hint

You can use the concept of selector. onFocus removes the hint.

android:hint="Email"

So when TextView has focus, or has user input (i.e. not empty) the hint will not display.

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

OpenJDK availability for Windows OS

An interesting alternative with long term support is Corretto. It was anounced by James Gosling on DevOXX recently. It is a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK). Corretto comes with long-term support that will include performance enhancements and security fixes. Currently it provides Java Versions 8 and 11 (12 soon) and you can download binaries for all major platforms

  • Linux
  • Microsoft Windows
  • macOS
  • Docker

And the second interesting alternative is Dragonwell provided by Alibaba. It is a friendly fork but they want to upstream their changes into the openjdk repo regularily... They currently offer Java8 but the have interesting things like a backported Flight Recorder (from 11 to 8) ...

And thirdly as already mentioned by others the adoptOpenJDK initivative is also worth looking at.

Google Play app description formatting

Include emojis; copy and paste them to the description:

http://getemoji.com

Replace Fragment inside a ViewPager

To replace a fragment inside a ViewPager you can move source codes of ViewPager, PagerAdapter and FragmentStatePagerAdapter classes into your project and add following code.

into ViewPager:

public void notifyItemChanged(Object oldItem, Object newItem) {
    if (mItems != null) {
            for (ItemInfo itemInfo : mItems) {
                        if (itemInfo.object.equals(oldItem)) {
                                itemInfo.object = newItem;
                        }
                    }
       }
       invalidate();
    }

into FragmentStatePagerAdapter:

public void replaceFragmetns(ViewPager container, Fragment oldFragment, Fragment newFragment) {
       startUpdate(container);

       // remove old fragment

       if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
       int position = getFragmentPosition(oldFragment);
        while (mSavedState.size() <= position) {
            mSavedState.add(null);
        }
        mSavedState.set(position, null);
        mFragments.set(position, null);

        mCurTransaction.remove(oldFragment);

        // add new fragment

        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        mFragments.set(position, newFragment);
        mCurTransaction.add(container.getId(), newFragment);

       finishUpdate(container);

       // ensure getItem returns newFragemtn after calling handleGetItemInbalidated()
       handleGetItemInbalidated(container, oldFragment, newFragment);

       container.notifyItemChanged(oldFragment, newFragment);
    }

protected abstract void handleGetItemInbalidated(View container, Fragment oldFragment, Fragment newFragment);
protected abstract int  getFragmentPosition(Fragment fragment);

handleGetItemInvalidated() ensures that after next call of getItem() it return newFragment getFragmentPosition() returns position of the fragment in your adapter.

Now, to replace fragments call

mAdapter.replaceFragmetns(mViewPager, oldFragment, newFragment);

If you interested in an example project ask me for the sources.

Java Could not reserve enough space for object heap error

4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.

Before starting jvm just check how much RAM is available and then set memory accordingly.

How to replace comma with a dot in the number (or any replacement)

From the function's definition (http://www.w3schools.com/jsref/jsref_replace.asp):

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

This method does not change the original string.

Hence, the line: tt.replace(/,/g, '.') does not change the value of tt; it just returns the new value.

You need to replace this line with: tt = tt.replace(/,/g, '.')

Using Powershell to stop a service remotely without WMI or remoting

Based on the built-in Powershell examples, this is what Microsoft suggests. Tested and verified:

To stop:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()

To start:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()

Changing the action of a form with JavaScript/jQuery

Use Java script to change action url dynamically Works for me well

function chgAction( action_name )
{

 {% for data in sidebar_menu_data %}

     if( action_name== "ABC"){ document.forms.action = "/ABC/";
     }
     else if( action_name== "XYZ"){ document.forms.action = "/XYZ/";
     }

}

<form name="forms" method="post" action="<put default url>" onSubmit="return checkForm(this);">{% csrf_token %}