Programs & Examples On #Setsockopt

When is TCP option SO_LINGER (0) required?

For my suggestion, please read the last section: “When to use SO_LINGER with timeout 0”.

Before we come to that a little lecture about:

  • Normal TCP termination
  • TIME_WAIT
  • FIN, ACK and RST

Normal TCP termination

The normal TCP termination sequence looks like this (simplified):

We have two peers: A and B

  1. A calls close()
    • A sends FIN to B
    • A goes into FIN_WAIT_1 state
  2. B receives FIN
    • B sends ACK to A
    • B goes into CLOSE_WAIT state
  3. A receives ACK
    • A goes into FIN_WAIT_2 state
  4. B calls close()
    • B sends FIN to A
    • B goes into LAST_ACK state
  5. A receives FIN
    • A sends ACK to B
    • A goes into TIME_WAIT state
  6. B receives ACK
    • B goes to CLOSED state – i.e. is removed from the socket tables

TIME_WAIT

So the peer that initiates the termination – i.e. calls close() first – will end up in the TIME_WAIT state.

To understand why the TIME_WAIT state is our friend, please read section 2.7 in "UNIX Network Programming" third edition by Stevens et al (page 43).

However, it can be a problem with lots of sockets in TIME_WAIT state on a server as it could eventually prevent new connections from being accepted.

To work around this problem, I have seen many suggesting to set the SO_LINGER socket option with timeout 0 before calling close(). However, this is a bad solution as it causes the TCP connection to be terminated with an error.

Instead, design your application protocol so the connection termination is always initiated from the client side. If the client always knows when it has read all remaining data it can initiate the termination sequence. As an example, a browser knows from the Content-Length HTTP header when it has read all data and can initiate the close. (I know that in HTTP 1.1 it will keep it open for a while for a possible reuse, and then close it.)

If the server needs to close the connection, design the application protocol so the server asks the client to call close().

When to use SO_LINGER with timeout 0

Again, according to "UNIX Network Programming" third edition page 202-203, setting SO_LINGER with timeout 0 prior to calling close() will cause the normal termination sequence not to be initiated.

Instead, the peer setting this option and calling close() will send a RST (connection reset) which indicates an error condition and this is how it will be perceived at the other end. You will typically see errors like "Connection reset by peer".

Therefore, in the normal situation it is a really bad idea to set SO_LINGER with timeout 0 prior to calling close() – from now on called abortive close – in a server application.

However, certain situation warrants doing so anyway:

  • If the a client of your server application misbehaves (times out, returns invalid data, etc.) an abortive close makes sense to avoid being stuck in CLOSE_WAIT or ending up in the TIME_WAIT state.
  • If you must restart your server application which currently has thousands of client connections you might consider setting this socket option to avoid thousands of server sockets in TIME_WAIT (when calling close() from the server end) as this might prevent the server from getting available ports for new client connections after being restarted.
  • On page 202 in the aforementioned book it specifically says: "There are certain circumstances which warrant using this feature to send an abortive close. One example is an RS-232 terminal server, which might hang forever in CLOSE_WAIT trying to deliver data to a stuck terminal port, but would properly reset the stuck port if it got an RST to discard the pending data."

I would recommend this long article which I believe gives a very good answer to your question.

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

On Mac OS X, I was experiencing the same problem. I wasn't able to launch a Xamarin app from Visual Studio, but a native Java Android project in Android Studio did work in the Virtual Device.

What I did was:

  1. Unset the ANDROID_HOME and ANDROID_SDK_ROOT environment variables.
unset ANDROID_HOME
unset ANDROID_SDK_ROOT
  1. Remove the existing virtual device that crashes. I did this in Visual Studio.
  2. Create a new virtual device.

Is there a command to undo git init?

You can just delete .git. Typically:

rm -rf .git

Then, recreate as the right user.

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

Change Activity's theme programmatically

This one works fine for me :

theme.applyStyle(R.style.AppTheme, true)

Usage:

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //The call goes right after super.onCreate() and before setContentView()
    theme.applyStyle(R.style.AppTheme, true)
    setContentView(layoutId)
    onViewCreated(savedInstanceState)
}

Setting the default page for ASP.NET (Visual Studio) server configuration

The built-in webserver is hardwired to use Default.aspx as the default page.

The project must have atleast an empty Default.aspx file to overcome the Directory Listing problem for Global.asax.

:)

Once you add that empty file all requests can be handled in one location.

public class Global : System.Web.HttpApplication
{
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
        this.Response.StatusCode = 200;
        this.Response.ContentType = "text/plain";

        this.Response.End();
    }
}

Converting a String array into an int Array in java

public static int[] strArrayToIntArray(String[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.parseInt(a[i]);
    }

    return b;
}

This is a simple function, that should help you. You can use him like this:

int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);

What's the difference between StaticResource and DynamicResource in WPF?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

PostgreSQL: role is not permitted to log in

CREATE ROLE blog WITH
  LOGIN
  SUPERUSER
  INHERIT
  CREATEDB
  CREATEROLE
  REPLICATION;

COMMENT ON ROLE blog IS 'Test';

how to get multiple checkbox value using jquery

Try getPrameterValues() for getting values from multiple checkboxes.

How do I alter the position of a column in a PostgreSQL database table?

I was working on re-ordering a lot of tables and didn't want to have to write the same queries over and over so I made a script to do it all for me. Essentially, it:

  1. Gets the table creation SQL from pg_dump
  2. Gets all available columns from the dump
  3. Puts the columns in the desired order
  4. Modifies the original pg_dump query to create a re-ordered table with data
  5. Drops old table
  6. Renames new table to match old table

It can be used by running the following simple command:

./reorder.py -n schema -d database table \
    first_col second_col ... penultimate_col ultimate_col --migrate

It prints out the sql so you can verify and test it, that was a big reason I based it on pg_dump. You can find the github repo here.

The view or its master was not found or no view engine supports the searched locations

I got this error because I renamed my View (and POST action).

Finally I found that I forgot to rename BOTH GET and POST actions to new name.

Solution : Rename both GET and POST actions to match the View name.

JQuery / JavaScript - trigger button click from another button click event

You mean this:

jQuery("input.first").click(function(){
   jQuery("input.second").trigger('click');
   return false;
});

Error: JAVA_HOME is not defined correctly executing maven

Assuming you use bash shell and installed Java with the Oracle installer, you could add the following to your .bash_profile

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/jre/bin:$PATH

This would pick the correct JAVA_HOME as defined by the Oracle installer and will set it first in your $PATH making sure it is found.

Also, you don't need to change it later when updating Java.

EDIT

As per the comments:

Making it persistent after a reboot

Just add those lines in the shell configuration file. (Assuming it's bash)

Ex: .bashrc, .bash_profile or .profile (for ubuntu)

Using a custom Java installation

Set JAVA_HOME to the root folder of the custom Java installation path without the $().

Ex: JAVA_HOME=/opt/java/openjdk

What exactly is the function of Application.CutCopyMode property in Excel

Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)

"Select destination and Press Enter or Choose Paste"

Then you press whether Enter or choose paste to paste the value of the cell.

If you didn't press Esc afterwards you will be able to paste the value of the cell several times

Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.

And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'

Define a fixed-size list in Java

Typically an alternative for fixed size Lists are Java arrays. Lists by default are allowed to grow/shrink in Java. However, that does not mean you cannot have a List of a fixed size. You'll need to do some work and create a custom implementation.

You can extend an ArrayList with custom implementations of the clear, add and remove methods.

e.g.

import java.util.ArrayList;

public class FixedSizeList<T> extends ArrayList<T> {

    public FixedSizeList(int capacity) {
        super(capacity);
        for (int i = 0; i < capacity; i++) {
            super.add(null);
        }
    }

    public FixedSizeList(T[] initialElements) {
        super(initialElements.length);
        for (T loopElement : initialElements) {
            super.add(loopElement);
        }
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException("Elements may not be cleared from a fixed size List.");
    }

    @Override
    public boolean add(T o) {
        throw new UnsupportedOperationException("Elements may not be added to a fixed size List, use set() instead.");
    }

    @Override
    public void add(int index, T element) {
        throw new UnsupportedOperationException("Elements may not be added to a fixed size List, use set() instead.");
    }

    @Override
    public T remove(int index) {
        throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
    }

    @Override
    protected void removeRange(int fromIndex, int toIndex) {
        throw new UnsupportedOperationException("Elements may not be removed from a fixed size List.");
    }
}

Adding images to an HTML document with javascript

Get rid of the this statements too

var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)

Android: How to overlay a bitmap and draw over a bitmap?

I think this example will definitely help you overlay a transparent image on top of another image. This is made possible by drawing both the images on canvas and returning a bitmap image.

Read more or download demo here

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

        Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(firstImage, 0f, 0f, null);
        canvas.drawBitmap(secondImage, 10, 10, null);
        return result;
    }

and call the above function on button click and pass the two images to our function as shown below

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

For more than two images, you can follow this link, how to merge multiple images programmatically on android

Using Jquery Ajax to retrieve data from Mysql

For retrieving data using Ajax + jQuery, you should write the following code:

 <html>
 <script type="text/javascript" src="jquery-1.3.2.js"> </script>

 <script type="text/javascript">

 $(document).ready(function() {

    $("#display").click(function() {                

      $.ajax({    //create an ajax request to display.php
        type: "GET",
        url: "display.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){                    
            $("#responsecontainer").html(response); 
            //alert(response);
        }

    });
});
});

</script>

<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Display All Data" /> </td>
   </tr>
</table>
<div id="responsecontainer" align="center">

</div>
</body>
</html>

For mysqli connection, write this:

<?php 
$con=mysqli_connect("localhost","root",""); 

For displaying the data from database, you should write this :

<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($data = mysqli_fetch_row($result))
{   
    echo "<tr>";
    echo "<td align=center>$data[0]</td>";
    echo "<td align=center>$data[1]</td>";
    echo "<td align=center>$data[2]</td>";
    echo "<td align=center>$data[3]</td>";
    echo "<td align=center>$data[4]</td>";
    echo "</tr>";
}
echo "</table>";
?>

MySQL Like multiple values

Faster way of doing this:

WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'

is this:

WHERE interests REGEXP 'sports|pub'

Found this solution here: http://forums.mysql.com/read.php?10,392332,392950#msg-392950

More about REGEXP here: http://www.tutorialspoint.com/mysql/mysql-regexps.htm

Get month and year from date cells Excel

Try this formula (it will return value from A1 as is if it's not a date):

=TEXT(A1,"mm-yyyy")

Or this formula (it's more strict, it will return #VALUE error if A1 is not date):

=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)

Spring Data: "delete by" is supported?

2 ways:-

1st one Custom Query

@Modifying
@Query("delete from User where firstName = :firstName")
void deleteUsersByFirstName(@Param("firstName") String firstName);

2nd one JPA Query by method

List<User> deleteByLastname(String lastname);

When you go with query by method (2nd way) it will first do a get call

select * from user where last_name = :firstName

Then it will load it in a List Then it will call delete id one by one

delete from user where id = 18
delete from user where id = 19

First fetch list of object, then for loop to delete id one by one

But, the 1st option (custom query),

It's just a single query It will delete wherever the value exists.

Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby

Strip / trim all strings of a dataframe

You can use the apply function of the Series object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df[0][0]
'  a  '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]
'a'

Note the usage of strip and not the regex which is much faster

Another option - use the apply function of the DataFrame object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)

   0   1
0  a  10
1  c   5

Get specific objects from ArrayList when objects were added anonymously?

If you want to lookup objects based on their String name, this is a textbook case for a Map, say a HashMap. You could use a LinkedHashMap and convert it to a List or Array later (Chris has covered this nicely in the comments below).

LinkedHashMap because it lets you access the elements in the order you insert them if you want to do so. Otherwise HashMap or TreeMap will do.

You could get this to work with List as the others are suggesting, but that feels Hacky to me.. and this will be cleaner both in short and long run.

If you MUST use a list for the object, you could still store a Map of the object name to the index in the array. This is a bit uglier, but you get almost the same performance as a plain Map.

Paging with Oracle

In the interest of completeness, for people looking for a more modern solution, in Oracle 12c there are some new features including better paging and top handling.

Paging

The paging looks like this:

SELECT *
FROM user
ORDER BY first_name
OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY;

Top N Records

Getting the top records looks like this:

SELECT *
FROM user
ORDER BY first_name
FETCH FIRST 5 ROWS ONLY

Notice how both the above query examples have ORDER BY clauses. The new commands respect these and are run on the sorted data.

I couldn't find a good Oracle reference page for FETCH or OFFSET but this page has a great overview of these new features.

Performance

As @wweicker points out in the comments below, performance is an issue with the new syntax in 12c. I didn't have a copy of 18c to test if Oracle has since improved it.

Interestingly enough, my actual results were returned slightly quicker the first time I ran the queries on my table (113 million+ rows) for the new method:

  • New method: 0.013 seconds.
  • Old method: 0.107 seconds.

However, as @wweicker mentioned, the explain plan looks much worse for the new method:

  • New method cost: 300,110
  • Old method cost: 30

The new syntax caused a full scan of the index on my column, which was the entire cost. Chances are, things get much worse when limiting on unindexed data.

Let's have a look when including a single unindexed column on the previous dataset:

  • New method time/cost: 189.55 seconds/998,908
  • Old method time/cost: 1.973 seconds/256

Summary: use with caution until Oracle improves this handling. If you have an index to work with, perhaps you can get away with using the new method.

Hopefully I'll have a copy of 18c to play with soon and can update

Serializing PHP object to JSON

I spent some hours on the same problem. My object to convert contains many others whose definitions I'm not supposed to touch (API), so I've came up with a solution which could be slow I guess, but I'm using it for development purposes.

This one converts any object to array

function objToArr($o) {
$s = '<?php
class base {
    public static function __set_state($array) {
        return $array;
    }
}
function __autoload($class) {
    eval("class $class extends base {}");
}
$a = '.var_export($o,true).';
var_export($a);
';
$f = './tmp_'.uniqid().'.php';
file_put_contents($f,$s);
chmod($f,0755);
$r = eval('return '.shell_exec('php -f '.$f).';');
unlink($f);
return $r;
}

This converts any object to stdClass

class base {
    public static function __set_state($array) {
        return (object)$array;
    }
}
function objToStd($o) {
$s = '<?php
class base {
    public static function __set_state($array) {
        $o = new self;
        foreach($array as $k => $v) $o->$k = $v;
        return $o;
    }
}
function __autoload($class) {
    eval("class $class extends base {}");
}
$a = '.var_export($o,true).';
var_export($a);
';
$f = './tmp_'.uniqid().'.php';
file_put_contents($f,$s);
chmod($f,0755);
$r = eval('return '.shell_exec('php -f '.$f).';');
unlink($f);
return $r;
}

Replacing .NET WebBrowser control with a better browser, like Chrome?

Geckofx and Webkit.net were both promising at first, but they didn't keep up to date with Firefox and Chrome respectively while as Internet Explorer improved, so did the Webbrowser control, though it behaves like IE7 by default regardless of what IE version you have but that can be fixed by going into the registry and change it to IE9 allowing HTML5.

How can I check Drupal log files?

If you love the command line, you can also do this using drush with the watchdog show command:

drush ws

More information about this command available here:

https://drushcommands.com/drush-7x/watchdog/watchdog-show/

What is the difference between HTTP status code 200 (cache) vs status code 304?

HTTP 304 is "not modified". Your web server is basically telling the browser "this file hasn't changed since the last time you requested it." Whereas an HTTP 200 is telling the browser "here is a successful response" - which should be returned when it's either the first time your browser is accessing the file or the first time a modified copy is being accessed.

For more info on status codes check out http://en.wikipedia.org/wiki/List_of_HTTP_status_codes.

Android: Share plain text using intent (to all messaging apps)

Below is the code that works with both the email or messaging app. If you share through email then the subject and body both are added.

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");

                String shareString = Html.fromHtml("Medicine Name:" + medicine_name +
                        "<p>Store Name:" + “store_name “+ "</p>" +
                        "<p>Store Address:" + “store_address” + "</p>")  .toString();
                                      sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Medicine Enquiry");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareString);

                if (sharingIntent.resolveActivity(context.getPackageManager()) != null)
                    context.startActivity(Intent.createChooser(sharingIntent, "Share using"));
                else {
                    Toast.makeText(context, "No app found on your phone which can perform this action", Toast.LENGTH_SHORT).show();
                }

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

How to break out of jQuery each Loop

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

Plot multiple lines in one graph

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)

tab<-t(tab)

plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

R multiple lines plot

How to run a cron job on every Monday, Wednesday and Friday?

Here's my example crontab I always use as a template:

    # Use the hash sign to prefix a comment
    # +---------------- minute (0 - 59)
    # |  +------------- hour (0 - 23)
    # |  |  +---------- day of month (1 - 31)
    # |  |  |  +------- month (1 - 12)
    # |  |  |  |  +---- day of week (0 - 7) (Sunday=0 or 7)
    # |  |  |  |  |
    # *  *  *  *  *  command to be executed
    #--------------------------------------------------------------------------

To run my cron job every Monday, Wednesady and Friday at 7:00PM, the result will be:

      0 19 * * 1,3,5 nohup /home/lathonez/script.sh > /tmp/script.log 2>&1

source

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

How to round up a number in Javascript?

parseInt always rounds down soo.....

_x000D_
_x000D_
console.log(parseInt(5.8)+1);
_x000D_
_x000D_
_x000D_

do parseInt()+1

How to resize image automatically on browser width resize but keep same height?

You should learn about the Media queries for CSS. The site you referring to is using the same. The site is basically using the different CSS everytime the browser window size is changining. Here's the link for samples

http://css-tricks.com/css-media-queries/

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

List of lists into numpy array

Just use pandas

list(pd.DataFrame(listofstuff).melt().values)

this only works for a list of lists

if you have a list of list of lists you might want to try something along the lines of

lists(pd.DataFrame(listofstuff).melt().apply(pd.Series).melt().values)

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:

#!/bin/bash

exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"
}

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

foo
Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

Page vs Window in WPF?

A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

   Class.forName("oracle.jdbc.driver.OracleDriver");

This line causes ClassNotFoundException, because you haven't placed ojdbc14.jar file in your lib folder of the project. or YOu haven't set the classpath of the required jar

JavaScript getElementByID() not working

You need to put the JavaScript at the end of the body tag.

It doesn't find it because it's not in the DOM yet!

You can also wrap it in the onload event handler like this:

window.onload = function() {
var refButton = document.getElementById( 'btnButton' );
refButton.onclick = function() {
   alert( 'I am clicked!' );
}
}

How can I copy a file on Unix using C?

One option is that you could use system() to execute cp. This just re-uses the cp(1) command to do the work. If you only need to make another link to the file, this can be done with link() or symlink().

How to delete an element from an array in C#

Balabaster's answer is correct if you want to remove all instances of the element. If you want to remove only the first one, you would do something like this:

int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int firstFoundIndex = Array.IndexOf(numbers, numToRemove);
if (numbers >= 0)
{
    numbers = numbers.Take(firstFoundIndex).Concat(numbers.Skip(firstFoundIndex + 1)).ToArray();
}

no sqljdbc_auth in java.library.path

For easy fix follow these steps:

  1. goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
  2. Download the JDBC file and extract to your preferred location
  3. open the auth folder matching your OS x64 or x86
  4. copy sqljdbc_auth.dll file
  5. paste in: C:\Program Files\Java\jdk_version\bin
  6. restart either eclipse or netbeans

100% Min Height CSS layout

Probably the shortest solution (works only in modern browsers)

This small piece of CSS makes "the middle content part fill 100% of the space in between with the footer fixed to the bottom":

html, body { height: 100%; }
your_container { min-height: calc(100% - height_of_your_footer); }

the only requirement is that you need to have a fixed height footer.

For example for this layout:

    <html><head></head><body>
      <main> your main content </main>
      </footer> your footer content </footer>
    </body></html>

you need this CSS:

    html, body { height: 100%; }
    main { min-height: calc(100% - 2em); }
    footer { height: 2em; }

Debugging in Maven?

I found an easy way to do this -

Just enter a command like this -

>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test

It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.

Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

How to find server name of SQL Server Management Studio

my problem was that when connecting to SQL Database in the add reference wizard, to find the SERVERNAME. i found it by: running a query(SELECT @@SERVERNAME) inside SQL management studio and the reusl was my servername. I put that in my server name box and it worked all fine.

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

How to overcome "'aclocal-1.15' is missing on your system" warning?

Before running ./configure try running autoreconf -f -i. The autoreconf program automatically runs autoheader, aclocal, automake, autopoint and libtoolize as required.

Edit to add: This is usually caused by checking out code from Git instead of extracting it from a .zip or .tar.gz archive. In order to trigger rebuilds when files change, Git does not preserve files' timestamps, so the configure script might appear to be out of date. As others have mentioned, there are ways to get around this if you don't have a sufficiently recent version of autoreconf.

Another edit: This error can also be caused by copying the source folder extracted from an archive with scp to another machine. The timestamps can be updated, suggesting that a rebuild is necessary. To avoid this, copy the archive and extract it in place.

DataColumn Name from DataRow (not DataTable)

You would still need to go through the DataTable class. But you can do so using your DataRow instance by using the Table property.

foreach (DataColumn c in dr.Table.Columns)  //loop through the columns. 
{
    MessageBox.Show(c.ColumnName);
}

Convert Enum to String

I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName works but requires a lot more keystrokes. ToString() seems to do the job very well.

Does Java support structs?

Actually a struct in C++ is a class (e.g. you can define methods there, it can be extended, it works exactly like a class), the only difference is that the default access modfiers are set to public (for classes they are set to private by default).

This is really the only difference in C++, many people don't know that. ; )

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

How to copy a file from one directory to another using PHP?

You could use the rename() function :

rename('foo/test.php', 'bar/test.php');

This however will move the file not copy

SVN undo delete before commit

What worked for me is

svn revert --depth infinity deletedDir

Changing the current working directory in Java?

If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.

Adding an image to a project in Visual Studio

If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :

enter image description here

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

After done trying everything that I found on this issue, in eclipse,

I selected my project --> right click --> Run as --> Maven generate-sources

enter image description here

Then I re-ran my TestNG project and it ran perfectly fine without any issues.Hope that helps :)

The name does not exist in the namespace error in XAML

I went through all the answers and none helped me. Finally was able to solve it by myself, so presenting the answer as it might help others.

In my case, the solution had two projects, one containing the models (say the project and assembly name was Models) and another containing the views and view models (as per our convention: project, assembly name and default namespace were Models.Monitor). The Models.Monitor referred Models project.

In the Models.Monitor project, in one of the xaml I included the following namespace: xmlns:monitor="clr-namespace:Models.Monitor"

I suspect that MsBuild and Visual Studio then were erroring out as they were trying to find a 'Monitor' type in the assembly 'Models'. To resolve I tried the following:

  1. xmlns:monitor="clr-namespace:Models.Monitor;assembly=" - which is valid if the namespace is in same assembly as per https://msdn.microsoft.com/en-us/library/ms747086(v=vs.110).aspx
  2. also tried the explicit namespace declaration: xmlns:monitor="clr-namespace:Models.Monitor;assembly=Models.Monitor"

Neither of the above worked.

Finally I gave up, and as a work around moved the UserControl I was trying to use to another namespace: 'ModelsMonitor'. I was able to compile fine after that.

Why do multiple-table joins produce duplicate rows?

When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.

Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:

TableA
Id Field1
1  test
2  another test

TableB
ID Field2 field3
1  Test1  something
1  test1  More something
2  Test2  Anything

So when you join them and select all the files you get:

select * 
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1        b.id   b.field2  b.field3
1    test            1      Test1     something
1    test            1      Test1     More something
2    another test 2  2      Test2     Anything

These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.

select a.Id, a.Field1,  b.field2
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1       b.field2  
1    test           Test1     
1    test           Test1 
2    another test   Test2

This appears to be duplicates but it is not because of the multiple records in TableB.

You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

react-native :app:installDebug FAILED

If none of the above solutions works then try the following steps to cold boot the emulator

open AVD manager -> Edit device -> Show Advanced Settings -> Boot option -> select Cold Boot instead of Quick boot.

Checking if a number is a prime number in Python

def isPrime(x):
    if x<2:
        return False
    for i in range(2,x):
        if not x%i:
           return False
    return True  

print isPrime(2)
True
print isPrime(3)
True
print isPrime(9)
False

How to use PrintWriter and File classes in Java?

Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException ) and then also use full path of file in which you are writing as

PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");

all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as

import java.io.*;
public class PrintWriterClass {

public static void main(String arg[]) throws IOException{
    PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
    pw.println("hiiiiiii");
    pw.close();
}   

}

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

Replacement for "rename" in dplyr

While not exactly renaming, dplyr::select_all() can be used to reformat column names. This example replaces spaces and periods with an underscore and converts everything to lower case:

iris %>%  
  select_all(~gsub("\\s+|\\.", "_", .)) %>% 
  select_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

What does the "@" symbol do in SQL?

@ is used as a prefix denoting stored procedure and function parameter names, and also variable names

phpmyadmin logs out after 1440 secs

drive here your wamp installed then go to wamp then apps then your phpmyadmin version folder then go to libraries then edit config.default.php file e.g

E:\wamp\apps\phpmyadmin4.6.4\libraries\config.default.php

here you have to change

$cfg['LoginCookieRecall'] = true;

to

$cfg['LoginCookieRecall'] = false;

also you can change time of cookie instead to disable cookie recall

$cfg['LoginCookieValidity'] = 1440;

to

$cfg['LoginCookieValidity'] = anthing grater then 1440 

mine is

 $cfg['LoginCookieValidity'] = 199000;

after changing restart your server enter image description here

also there is another method but it reset when ever we restart our wamp server and here is that method also

login to your phpmyadmin dashbord then go to setting then click on features and in general tab you will see Login cookie validity put anything greater then 14400 but this is valid until next restart of your server.

enter image description here

Git: How to update/checkout a single file from remote origin master?

Following code worked for me:

     git fetch
     git checkout <branch from which file needs to be fetched> <filepath> 

Fixed size div?

You can set the height and width of your divs with css.

<style type="text/css">
.box {
     height: 150px;
     width: 150px;
}
</style> 

Is this what you're looking for?

How can I display a pdf document into a Webview?

String webviewurl = "http://test.com/testing.pdf";
webView.getSettings().setJavaScriptEnabled(true); 
if(webviewurl.contains(".pdf")){
    webviewurl = "http://docs.google.com/gview?embedded=true&url=" + webviewurl;        }
webview.loadUrl(webviewurl);

How to add new column to an dataframe (to the front not end)?

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
##   b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3

df <- data.frame(a = c(0, 0, 0), df)
df
##   a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3

Forgot Oracle username and password, how to retrieve?

Go to SQL command line:- type:

sql>connect / as sysdba;

then type:

sql>desc dba_users;

then type:

sql>select username,password from dba_users;

If sysdba doesn't work then try connecting with username:scott and password: Tiger

You will be able to see all users with passwords. Probably you might find your's. Hope this helps

How to configure the web.config to allow requests of any length

I had a similar issue trying to deploy an ASP Web Application to IIS 8. To fix it I did as Matt and Leniel suggested above. But also had to configure the Authentication setting of my site to enable Anonymous Authentication. And that Worked for me.

How can I print each command before executing?

set -o xtrace

or

bash -x myscript.sh

This works with standard /bin/sh as well IIRC (it might be a POSIX thing then)

And remember, there is bashdb (bash Shell Debugger, release 4.0-0.4)


To revert to normal, exit the subshell or

set +o xtrace

Ubuntu: OpenJDK 8 - Unable to locate package

I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:

sudo apt-get install debian-keyring debian-archive-keyring

Make /etc/apt/sources.list.d/debian-jessie-backports.list:

deb http://httpredir.debian.org/debian/ jessie-backports main

Make /etc/apt/preferences.d/debian-jessie-backports:

Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200

Then finally do the install:

sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk

Difference between variable declaration syntaxes in Javascript (including global variables)?

Keeping it simple :

a = 0

The code above gives a global scope variable

var a = 0;

This code will give a variable to be used in the current scope, and under it

window.a = 0;

This generally is same as the global variable.

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

Something like this could be it?

HTML

 <div class="random">
        SOMETHING
 </div>

CSS

body{

    text-align: center;
}

.random{

    width: 60%;
    margin: auto;
    background-color: yellow;
    display:block;

}

DEMO: http://jsfiddle.net/t5Pp2/2/

Edit: adding display:block doesn't ruin the thing, so...

You can also set the margin to: margin: 0 auto 0 auto; just to be sure it centers only this way not from the top too.

How do I read the source code of shell commands?

You can have it on github using the command

git clone https://github.com/coreutils/coreutils.git

You can find all the source codes in the src folder.

You need to have git installed.

Things have changed since 2012, ls source code has now 5309 lines

Xcode 6 Storyboard the wrong size?

On your storyboard page, go to File Inspector and uncheck 'Use Size Classes'. This should shrink your view controller to regular IPhone size you were familiar with. Note that using 'size classes' will let you design your project across many devices. Once you uncheck this the Xcode will give you a warning dialogue as follows. This should be self-explainatory.

"Disabling size classes will limit this document to storing data for a single device family. The data for the size class best representing the targeted device will be retained, and all other data will be removed. In addition, segues will be converted to their non-adaptive equivalents."

SQL Server CASE .. WHEN .. IN statement

It might be easier to read when written out in longhand using the 'simple case' e.g.

CASE DeviceID 
   WHEN '7  ' THEN '01'
   WHEN '10 ' THEN '01'
   WHEN '62 ' THEN '01'
   WHEN '58 ' THEN '01'
   WHEN '60 ' THEN '01'
   WHEN '46 ' THEN '01'
   WHEN '48 ' THEN '01'
   WHEN '50 ' THEN '01'
   WHEN '137' THEN '01'
   WHEN '139' THEN '01'
   WHEN '142' THEN '01'
   WHEN '143' THEN '01'
   WHEN '164' THEN '01'
   WHEN '8  ' THEN '02'
   WHEN '9  ' THEN '02'
   WHEN '63 ' THEN '02'
   WHEN '59 ' THEN '02'
   WHEN '61 ' THEN '02'
   WHEN '47 ' THEN '02'
   WHEN '49 ' THEN '02'
   WHEN '51 ' THEN '02'
   WHEN '138' THEN '02'
   WHEN '140' THEN '02'
   WHEN '141' THEN '02'
   WHEN '144' THEN '02'
   WHEN '165' THEN '02'
   ELSE 'NA' 
END AS clocking

...which kind makes me thing that perhaps you could benefit from a lookup table to which you can JOIN to eliminate the CASE expression entirely.

Declaring variables inside or outside of a loop

Declaring objects in the smallest scope improve readability.

Performance doesn't matter for today's compilers.(in this scenario)
From a maintenance perspective, 2nd option is better.
Declare and initialize variables in the same place, in the narrowest scope possible.

As Donald Ervin Knuth told:

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.

IntelliJ: Never use wildcard imports

Shortcut doing this on Mac: Press command+Shift+A (Action) and type "class count to use import with *" Press Enter. Enter a higher number there like 999

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

Indentation Error in Python

In Notepad++

View --->Show Symbols --->Show White Spaces and Tabs(select)

replace all tabs with spaces.

How can we programmatically detect which iOS version is device running on?

In MonoTouch:

To get the Major version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[0]

For minor version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[1]

Remove all unused resources from an android project

When we define shrink resources true that time we can also define which resources we wanna keep and which don't I have added xml file in res/raw folder named keep.xml

before going further generate a single signed build and check in apk analyser tool which will show drawable-xhdpi-v4 has messenger_button_send_round_shadow.png which i want to remove for this test

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
       tools:shrinkMode="strict"
       tools:discard="@drawable/com_facebook_button_icon_blue.png,
       @drawable/com_facebook_button_icon_white.png,
       @drawable/com_facebook_button_like_icon_selected.png,
       @drawable/messenger_button_send_round_shadow.png,
       @drawable/messenger_*"  />

by doing messenger_* all files starting from name messenger in drawable folder will be removed or other way around is i have defines specific file to be removed

so that way you can remove files from library it self you can also remove layouts by @layout/layout name if that drawable has been used by layout and so....

'this' vs $scope in AngularJS controllers

In this course(https://www.codeschool.com/courses/shaping-up-with-angular-js) they explain how to use "this" and many other stuff.

If you add method to the controller through "this" method, you have to call it in the view with controller's name "dot" your property or method.

For example using your controller in the view you may have code like this:

    <div data-ng-controller="YourController as aliasOfYourController">

       Your first pane is {{aliasOfYourController.panes[0]}}

    </div>

Where's my JSON data in my incoming Django request?

request.raw_response is now deprecated. Use request.body instead to process non-conventional form data such as XML payloads, binary images, etc.

Django documentation on the issue.

How do I directly modify a Google Chrome Extension File? (.CRX)

I searched it in Google and I found this:

The Google Chrome Extension file type is CRX. It is essentially a compression format. So if you want to see what is behind an extension, the scripts and the code, just change the file-type from “CRX” to “ZIP” .

Unzip the file and you will get all the info you need. This way you can see the guts, learn how to write an extension yourself, or modify it for your own needs.

Then you can pack it back up with Chrome’s internal tools which automatically create the file back into CRX. Installing it just requires a click.

Measuring the distance between two coordinates in PHP

For the ones who like shorter and faster(not calling deg2rad()).

function circle_distance($lat1, $lon1, $lat2, $lon2) {
  $rad = M_PI / 180;
  return acos(sin($lat2*$rad) * sin($lat1*$rad) + cos($lat2*$rad) * cos($lat1*$rad) * cos($lon2*$rad - $lon1*$rad)) * 6371;// Kilometers
}

What is the difference between atomic / volatile / synchronized?

The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.

Android: how to make keyboard enter button say "Search" and handle its click?

Hide keyboard when user clicks search. Addition to Robby Pond answer

private void performSearch() {
    editText.clearFocus();
    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    //...perform search
}

How to disable horizontal scrolling of UIScrollView?

You can select the view, then under Attributes Inspector uncheck User Interaction Enabled .

Docker: How to use bash with an Alpine based docker image?

Try using RUN /bin/sh instead of bash.

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

React Hooks useState() with Object

Thanks Philip this helped me - my use case was I had a form with lot of input fields so I maintained initial state as object and I was not able to update the object state.The above post helped me :)

const [projectGroupDetails, setProjectGroupDetails] = useState({
    "projectGroupId": "",
    "projectGroup": "DDD",
    "project-id": "",
    "appd-ui": "",
    "appd-node": ""    
});

const inputGroupChangeHandler = (event) => {
    setProjectGroupDetails((prevState) => ({
       ...prevState,
       [event.target.id]: event.target.value
    }));
}

<Input 
    id="projectGroupId" 
    labelText="Project Group Id" 
    value={projectGroupDetails.projectGroupId} 
    onChange={inputGroupChangeHandler} 
/>


Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

R adding days to a date

You could also use

library(lubridate)
dmy("1/1/2001") + days(45)

Finding CN of users in Active Directory

Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:

cn=admin,cn=users,DC=domain,DC=company,DC=com

Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin). If so, you should get the full DN back in that query.

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

Get the position of a spinner in Android

if (position ==0) {
    if (rYes.isChecked()) {
        Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
    } else if (rNo.isChecked()) {
        Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to select both check boxes.
Is there a problem with it?

How to center icon and text in a android button with width set to "fill parent"

I know I am late in answering this question, but this helped me:

<FrameLayout
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="10dp"
            android:background="@color/fb" >

            <Button
                android:id="@+id/fbLogin"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:background="@null"
                android:drawableLeft="@drawable/ic_facebook"
                android:gravity="center"
                android:minHeight="0dp"
                android:minWidth="0dp"
                android:text="FACEBOOK"
                android:textColor="@android:color/white" />
        </FrameLayout>

I found this solution from here: Android UI struggles: making a button with centered text and icon

enter image description here

How to return XML in ASP.NET?

I'm surprised that nobody seems to have ever mentioned that you can use XDocument / XElement which are available in .NET 4.0 and make it much easier to output XML.

How to show math equations in general github's markdown(not github's blog)

It ’s 2020 now, let me summarize the progress of the mathematical formula rendering support of source code repository hosts.

GitHub & Bitbucket

GitHub and Bitbucket still do not support the rendering of mathematical formulas, whether it is the default delimiters or other.

Bitbucket Cloud / BCLOUD-11192 -- Add LaTeX Support in MarkDown Documents (BB-12552)

GitHub / markup -- Rendering math equations

GitHub / markup -- Support latex

GitHub Community Forum -- [FEATURE REQUEST] LaTeX Math in Markdown

talk.commonmark.org -- Can math formula added to the markdown

GitHub has hardly made any substantial progress in recent years.

GitLab

GitLab is already supported, but not the most common way. It uses its own delimiter.

This math is inline $`a^2+b^2=c^2`$.

This is on a separate line

```math
a^2+b^2=c^2
```

GitLab Flavored Markdown -- Math

Who supports the universal delimiters?

A Markdown parser used by Hugo

Other ways to render

Get all Attributes from a HTML element with Javascript/jQuery

Does this help?

This property returns all the attributes of an element into an array for you. Here is an example.

_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
  var result = document.getElementById('result');_x000D_
  var spanAttributes = document.getElementsByTagName('span')[0].attributes;_x000D_
  for (var i = 0; i != spanAttributes.length; i++) {_x000D_
    result.innerHTML += spanAttributes[i].value + ',';_x000D_
  }_x000D_
});
_x000D_
<span name="test" message="test2"></span>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

To get the attributes of many elements and organize them, I suggest making an array of all the elements that you want to loop through and then create a sub array for all the attributes of each element looped through.

This is an example of a script that will loop through the collected elements and print out two attributes. This script assumes that there will always be two attributes but you can easily fix this with further mapping.

_x000D_
_x000D_
window.addEventListener('load',function(){_x000D_
  /*_x000D_
  collect all the elements you want the attributes_x000D_
  for into the variable "elementsToTrack"_x000D_
  */ _x000D_
  var elementsToTrack = $('body span, body div');_x000D_
  //variable to store all attributes for each element_x000D_
  var attributes = [];_x000D_
  //gather all attributes of selected elements_x000D_
  for(var i = 0; i != elementsToTrack.length; i++){_x000D_
    var currentAttr = elementsToTrack[i].attributes;_x000D_
    attributes.push(currentAttr);_x000D_
  }_x000D_
  _x000D_
  //print out all the attrbute names and values_x000D_
  var result = document.getElementById('result');_x000D_
  for(var i = 0; i != attributes.length; i++){_x000D_
    result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'<br>';  _x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<span name="test" message="test2"></span>_x000D_
<div name="test" message="test2"></div>_x000D_
<div name="test" message="test2"></div>_x000D_
<div name="test" message="test2"></div>_x000D_
<div name="test" message="test2"></div>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

ReactJS - Get Height of an element

Here's a nice reusable hook amended from https://swizec.com/blog/usedimensions-a-react-hook-to-measure-dom-nodes:

import { useState, useCallback, useEffect } from 'react';

function getDimensionObject(node) {
  const rect = node.getBoundingClientRect();

  return {
    width: rect.width,
    height: rect.height,
    top: 'x' in rect ? rect.x : rect.top,
    left: 'y' in rect ? rect.y : rect.left,
    x: 'x' in rect ? rect.x : rect.left,
    y: 'y' in rect ? rect.y : rect.top,
    right: rect.right,
    bottom: rect.bottom
  };
}

export function useDimensions(data = null, liveMeasure = true) {
  const [dimensions, setDimensions] = useState({});
  const [node, setNode] = useState(null);

  const ref = useCallback(node => {
    setNode(node);
  }, []);

  useEffect(() => {
    if (node) {
      const measure = () =>
        window.requestAnimationFrame(() =>
          setDimensions(getDimensionObject(node))
        );
      measure();

      if (liveMeasure) {
        window.addEventListener('resize', measure);
        window.addEventListener('scroll', measure);

        return () => {
          window.removeEventListener('resize', measure);
          window.removeEventListener('scroll', measure);
        };
      }
    }
  }, [node, data]);

  return [ref, dimensions, node];
}

To implement:

import { useDimensions } from '../hooks';

// Include data if you want updated dimensions based on a change.
const MyComponent = ({ data }) => {
  const [
    ref,
    { height, width, top, left, x, y, right, bottom }
  ] = useDimensions(data);

  console.log({ height, width, top, left, x, y, right, bottom });

  return (
    <div ref={ref}>
      {data.map(d => (
        <h2>{d.title}</h2>
      ))}
    </div>
  );
};

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

Command line for looking at specific port

In RHEL 7, I use this command to filter several ports in LISTEN State:

sudo netstat -tulpn | grep LISTEN | egrep '(8080 |8082 |8083 | etc )'

How do I see what character set a MySQL database / table / column is?

For databases:

SHOW CREATE DATABASE "DB_NAME_HERE";

In creating a Database (MySQL), default character set/collation is always LATIN, instead that you have selected a different one on initially creating your database

How to add an element at the end of an array?

As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.

For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.

Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.

Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).

How do you share code between projects/solutions in Visual Studio?

It is a good idea to create a dll class library that contain all common functionality. Each solution can reference this dll indepently regardless of other solutions.

Infact , this is how our sources are organized in my work (and I believe in many other places).

By the way , Solution can't explicitly depend on another solution.

Send HTML in email via PHP

I have a this code and it will run perfectly for my site

  public function forgotpassword($pass,$name,$to)
    {
        $body ="<table  width=100% border=0><tr><td>";
        $body .= "<img width=200 src='";
        $body .= $this->imageUrl();
        $body .="'></img></td><td style=position:absolute;left:350;top:60;><h2><font color = #346699>PMS Pvt Ltd.</font><h2></td></tr>";
        $body .='<tr><td colspan=2><br/><br/><br/><strong>Dear '.$name.',</strong></td></tr>';
        $body .= '<tr><td colspan=2><br/><font size=3>As per Your request we send Your Password.</font><br/><br/>Password is : <b>'.$pass.'</b></td></tr>';
        $body .= '<tr><td colspan=2><br/>If you have any questions, please feel free to contact us at:<br/><a href="mailto:[email protected]" target="_blank">[email protected]</a></td></tr>';
        $body .= '<tr><td colspan=2><br/><br/>Best regards,<br>The PMS Team.</td></tr></table>';
        $subject = "Forgot Password";
        $this->sendmail($body,$to,$subject);
    }

mail function

   function sendmail($body,$to,$subject)
        {
            //require_once 'init.php';


            $from='[email protected]';      
            $headersfrom='';
            $headersfrom .= 'MIME-Version: 1.0' . "\r\n";
            $headersfrom .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headersfrom .= 'From: '.$from.' '. "\r\n";
            mail($to,$subject,$body,$headersfrom);
        }

image url function is use for if you want to change the image you have change in only one function i have many mail function like forgot password create user there for i am use image url function you can directly set path.

function imageUrl()
    {
        return "http://".$_SERVER['SERVER_NAME'].substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1)."images/capacity.jpg";
    }

Use index in pandas to plot data

Also,

monthly_mean.plot(x=df.index, y='A')

Understanding events and event handlers in C#

To understand event handlers, you need to understand delegates. In C#, you can think of a delegate as a pointer (or a reference) to a method. This is useful because the pointer can be passed around as a value.

The central concept of a delegate is its signature, or shape. That is (1) the return type and (2) the input arguments. For example, if we create a delegate void MyDelegate(object sender, EventArgs e), it can only point to methods which return void, and take an object and EventArgs. Kind of like a square hole and a square peg. So we say these methods have the same signature, or shape, as the delegate.

So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called.

So the default EventHandler (and many like it) represents a specific shape of method (again, void/object-EventArgs). When you declare an event, you are saying which shape of method (EventHandler) that event will invoke, by specifying a delegate:

//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyEventHandler(string foo);

//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyEventHandler SomethingHappened;

//Here is some code I want to be executed
//when SomethingHappened fires.
void HandleSomethingHappened(string foo)
{
    //Do some stuff
}

//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);

//To raise the event within a method.
SomethingHappened("bar");

(*This is the key to events in .NET and peels away the "magic" - an event is really, under the covers, just a list of methods of the same "shape". The list is stored where the event lives. When the event is "raised", it's really just "go through this list of methods and call each one, using these values as the parameters". Assigning an event handler is just a prettier, easier way of adding your method to this list of methods to be called).

Error while sending QUERY packet

You cannot have the WHERE clause in an INSERT statement.

insert into table1(data) VALUES(:data) where sno ='45830'

Should be

insert into table1(data) VALUES(:data)


Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:

SET GLOBAL max_allowed_packet=32M

Change the 32M (32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.

Adb Devices can't find my phone

I did the following to get my Mac to see the devices again:

  • Run android update adb
  • Run adb kill-server
  • Run adb start-server

At this point, calling adb devices started returning devices again. Now run or debug your project to test it on your device.

How to use glyphicons in bootstrap 3.0

This might help. It contains many examples which will be useful in understanding.

http://www.w3schools.com/bootstrap/bootstrap_ref_comp_glyphs.asp

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.

AngularJS routing without the hash '#'

Using HTML5 mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base> tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application. For more information, see AngularJS Developer Guide - Using $location HTML5 mode Server Side.


Update

How to: Configure your server to work with html5Mode1

When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:

Apache Rewrites

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Nginx Rewrites

server {
    server_name my-app;

    index index.html;

    root /path/to/app;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Azure IIS Rewrites

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Express Rewrites

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

app.listen(3006); //the port you want to use

See also

Webpack - webpack-dev-server: command not found

Yarn

I had the problem when running: yarn start

It was fixed with running first: yarn install

Regular expression include and exclude special characters

You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

How to pass data to view in Laravel?

You can also do like this

$arr_view_data['var1'] = $value1;
$arr_view_data['var2'] = $value2;
$arr_view_data['var3'] = $value3;

return view('your_viewname_here',$arr_view_data);

And you access this variable to view as $var1,$var2,$var3

PHP - iterate on string characters

You can also just access $s1 like an array, if you only need to access it:

$s1 = "hello world";
echo $s1[0]; // -> h

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I had a similar issue after upgrading from PHP 5.5 to PHP 5.6. The phpize and php-config libraries being used to compile the phalcon extension were still the ones from PHP 5.5. I had to run the command below:

sudo apt-get install php5.6-dev

There will be a long stacktrace, the key information I saw was this:

update-alternatives: using /usr/bin/php-config5.6 to provide /usr/bin/php-config (php-config) in auto mode
update-alternatives: using /usr/bin/phpize5.6 to provide /usr/bin/phpize (phpize) in auto mode

I hope this helps someone.

How do you use the ? : (conditional) operator in JavaScript?

 (sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";

 sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"

How to update npm

nvm install-latest-npm

if you happen to use nvm

HTML form submit to PHP script

Assuming you've fixed the syntax errors (you've closed the select box before the name attribute), you're using the same name for the select box as the submit button. Give the select box a different name.

How to fill in form field, and submit, using javascript?

You can try something like this:

    <script type="text/javascript">
        function simulateLogin(userName)
        {
            var userNameField = document.getElementById("username");
            userNameField.value = userName;
            var goButton = document.getElementById("go");
            goButton.click();
        }

        simulateLogin("testUser");
</script>

View list of all JavaScript variables in Google Chrome Console

David Walsh has a nice solution for this. Here is my take on this, combining his solution with what has been discovered on this thread as well.

https://davidwalsh.name/global-variables-javascript

x = {};
var iframe = document.createElement('iframe');
iframe.onload = function() {
    var standardGlobals = Object.keys(iframe.contentWindow);
    for(var b in window) { 
      const prop = window[b];
      if(window.hasOwnProperty(b) && prop && !prop.toString().includes('native code') && !standardGlobals.includes(b)) {
        x[b] = prop;
      }
    }
    console.log(x)
};
iframe.src = 'about:blank';
document.body.appendChild(iframe);

x now has only the globals.

Java 8 stream reverse order

the simplest solution is using List::listIterator and Stream::generate

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
ListIterator<Integer> listIterator = list.listIterator(list.size());

Stream.generate(listIterator::previous)
      .limit(list.size())
      .forEach(System.out::println);

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Printing 2D array in matrix format

You can do it like this (with a slightly modified array to show it works for non-square arrays):

        long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };

        int rowLength = arr.GetLength(0);
        int colLength = arr.GetLength(1);

        for (int i = 0; i < rowLength; i++)
        {
            for (int j = 0; j < colLength; j++)
            {
                Console.Write(string.Format("{0} ", arr[i, j]));
            }
            Console.Write(Environment.NewLine + Environment.NewLine);
        }
        Console.ReadLine();

nodejs - first argument must be a string or Buffer - when using response.write with http.request

Although the question is solved, sharing knowledge for clarification of the correct meaning of the error.

The error says that the parameter needed to the concerned breaking function is not in the required format i.e. string or Buffer

The solution is to change the parameter to string

breakingFunction(JSON.stringify(offendingParameter), ... other params...);

or buffer

breakingFunction(BSON.serialize(offendingParameter), ... other params...);

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How to handle notification when app in background in Firebase

According to docs

Handle messages in a backgrounded app

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.

This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

If you want to open your app and perform a specific action, set click_action in the notification payload and map it to an intent filter in the Activity you want to launch. For example, set click_action to OPEN_ACTIVITY_1 to trigger an intent filter like the following:

 <intent-filter>   <action android:name="OPEN_ACTIVITY_1" />  
 <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>

Edit :

Based on this thread :

You can't set click_action payload using Firebase Console. You could try testing with a curl command or a custom http server

curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" 
     --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send  
     -d "{\"to\":\"/topics/news\",\"notification\": 
         {\"title\": \"Click Action Message\",\"text\": \"Sample message\",
            \"click_action\":\"OPEN_ACTIVITY_1\"}}"

Update Jenkins from a war file

#on ubuntu, in /usr/share/jenkins:

sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start

Using bootstrap with bower

You have install nodeJs on your system in order to execute npm commands. Once npm is properly working you can visit bower.io. There you will find complete documentation on this topic. You will find a command $ npm install bower. this will install bower on your machine. After installing bower you can install Bootstrap easily.

Here is a video tutorial on that

How to set tbody height with overflow scroll

I guess what you're trying to do, is to keep the header fixed and to scroll the body content. You can scroll the content into 2 directions:

  • horizontally: you won't be able to scroll the content horizontally unless you use a slider (a jQuery slider for example). I would recommend to avoid using a table in this case.
  • vertically: you won't be able to achieve that with a tbody tag, because assigning display:block or display:inline-block will break the layout of the table.

Here's a solution using divs: JSFiddle

HTML:

<div class="wrap_header">
    <div class="column">
        Name
    </div>
    <div class="column">
        Phone
    </div>
    <div class="clearfix"></div>
</div>
<div class="wrap_body">
    <div class="sliding_wrapper">
        <div class="serie">
            <div class="cell">
                AAAAAA
            </div>
            <div class="cell">
                323232
            </div>
            <div class="clearfix"></div>
        </div>
        <div class="serie">
            <div class="cell">
                BBBBBB
            </div>
            <div class="cell">
                323232
            </div>
            <div class="clearfix"></div>
        </div>
        <div class="serie">
            <div class="cell">
                CCCCCC
            </div>
            <div class="cell">
                3435656
            </div>
            <div class="clearfix"></div>
        </div>
    </div>
</div>

CSS:

.wrap_header{width:204px;}
.sliding_wrapper,
.wrap_body {width:221px;}
.sliding_wrapper {overflow-y:scroll; overflow-x:none;}
.sliding_wrapper,
.wrap_body {height:45px;}
.wrap_header,
.wrap_body {overflow:hidden;}
.column {width:100px; float:left; border:1px solid red;}
.cell {width:100px; float:left; border:1px solid red;}

/**
 * @info Clearfix: clear all the floated elements
 */
.clearfix:after {
    visibility:hidden;
    display:block;
    font-size:0;
    content:" ";
    clear:both;
    height:0;
}
.clearfix {display:inline-table;}

/**
 * @hack Display the Clearfix as a block element
 * @hackfor Every browser except IE for Macintosh
 */
    /* Hides from IE-mac \*/
    * html .clearfix {height:1%;}
    .clearfix {display:block;}
    /* End hide from IE-mac */

Explanation:

You have a sliding wrapper which will contain all the data.

Note the following:

.wrap_header{width:204px;}
.sliding_wrapper,
.wrap_body {width:221px;}

There's a difference of 17px because we need to take into consideration the width of the scrollbar.

How do I make an asynchronous GET request in PHP?

Based on this thread I made this for my codeigniter project. It works just fine. You can have any function processed in the background.

A controller that accepts the async calls.

class Daemon extends CI_Controller
{
    // Remember to disable CI's csrf-checks for this controller

    function index( )
    {
        ignore_user_abort( 1 );
        try
        {
            if ( strcmp( $_SERVER['REMOTE_ADDR'], $_SERVER['SERVER_ADDR'] ) != 0 && !in_array( $_SERVER['REMOTE_ADDR'], $this->config->item( 'proxy_ips' ) ) )
            {
                log_message( "error", "Daemon called from untrusted IP-address: " . $_SERVER['REMOTE_ADDR'] );
                show_404( '/daemon' );
                return;
            }

            $this->load->library( 'encrypt' );
            $params = unserialize( urldecode( $this->encrypt->decode( $_POST['data'] ) ) );
            unset( $_POST );
            $model = array_shift( $params );
            $method = array_shift( $params );
            $this->load->model( $model );
            if ( call_user_func_array( array( $this->$model, $method ), $params ) === FALSE )
            {
                log_message( "error", "Daemon could not call: " . $model . "::" . $method . "()" );
            }
        }
        catch(Exception $e)
        {
            log_message( "error", "Daemon has error: " . $e->getMessage( ) . $e->getFile( ) . $e->getLine( ) );
        }
    }
}

And a library that does the async calls

class Daemon
{
    public function execute_background( /* model, method, params */ )
    {
        $ci = &get_instance( );
        // The callback URL (its ourselves)
        $parts = parse_url( $ci->config->item( 'base_url' ) . "/daemon" );
        if ( strcmp( $parts['scheme'], 'https' ) == 0 )
        {
            $port = 443;
            $host = "ssl://" . $parts['host'];
        }
        else 
        {
            $port = 80;
            $host = $parts['host'];
        }
        if ( ( $fp = fsockopen( $host, isset( $parts['port'] ) ? $parts['port'] : $port, $errno, $errstr, 30 ) ) === FALSE )
        {
            throw new Exception( "Internal server error: background process could not be started" );
        }
        $ci->load->library( 'encrypt' );
        $post_string = "data=" . urlencode( $ci->encrypt->encode( serialize( func_get_args( ) ) ) );
        $out = "POST " . $parts['path'] . " HTTP/1.1\r\n";
        $out .= "Host: " . $host . "\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "Content-Length: " . strlen( $post_string ) . "\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $out .= $post_string;
        fwrite( $fp, $out );
        fclose( $fp );
    }
}

This method can be called to process any model::method() in the 'background'. It uses variable arguments.

$this->load->library('daemon');
$this->daemon->execute_background( 'model', 'method', $arg1, $arg2, ... );

How do you set the document title in React?

I use this method, which I found out since it's easier for me. I use it in combination with function component. Only do this, if you don't care that it won't display any title if the user disables Javascript on your page.

There are two things you need to do.

1.Go into your index.html and delete this line here

<title>React App</title>

2.Go into your mainapp function and return this which is just a normal html structure, you can copy and paste your main content from your website in between the body tags:

return (
        <html>
          <head>
            <title>hi</title>
          </head>
          <body></body>
        </html>
      );

You can replace the title as you wish.

Remove multiple items from a Python list in just one statement

I don't know why everyone forgot to mention the amazing capability of sets in python. You can simply cast your list into a set and then remove whatever you want to remove in a simple expression like so:

>>> item_list = ['item', 5, 'foo', 3.14, True]
>>> item_list = set(item_list) - {'item', 5}
>>> item_list
{True, 3.14, 'foo'}
>>> # you can cast it again in a list-from like so
>>> item_list = list(item_list)
>>> item_list
[True, 3.14, 'foo']

Turning a Comma Separated string into individual rows

Very late but try this out:

SELECT ColumnID, Column1, value  --Do not change 'value' name. Leave it as it is.
FROM tbl_Sample  
CROSS APPLY STRING_SPLIT(Tags, ','); --'Tags' is the name of column containing comma separated values

So we were having this: tbl_Sample :

ColumnID|   Column1 |   Tags
--------|-----------|-------------
1       |   ABC     |   10,11,12    
2       |   PQR     |   20,21,22

After running this query:

ColumnID|   Column1 |   value
--------|-----------|-----------
1       |   ABC     |   10
1       |   ABC     |   11
1       |   ABC     |   12
2       |   PQR     |   20
2       |   PQR     |   21
2       |   PQR     |   22

Thanks!

NuGet auto package restore does not work with MSBuild

UPDATED with latest official NuGet documentation as of v3.3.0

Package Restore Approaches

NuGet offers three approaches to using package restore.


Automatic Package Restore is the NuGet team's recommended approach to Package Restore within Visual Studio, and it was introduced in NuGet 2.7. Beginning with NuGet 2.7, the NuGet Visual Studio extension integrates into Visual Studio's build events and restores missing packages when a build begins. This feature is enabled by default, but developers can opt out if desired.


Here's how it works:

  1. On project or solution build, Visual Studio raises an event that a build is beginning within the solution.
  2. NuGet responds to this event and checks for packages.config files included in the solution.
  3. For each packages.config file found, its packages are enumerated and Checked for exists in the solution's packages folder.
  4. Any missing packages are downloaded from the user's configured (and enabled) package sources, respecting the order of the package sources.
  5. As packages are downloaded, they are unzipped into the solution's packages folder.

If you have Nuget 2.7+ installed; it's important to pick one method for > managing Automatic Package Restore in Visual Studio.

Two methods are available:

  1. (Nuget 2.7+): Visual Studio -> Tools -> Package Manager -> Package Manager Settings -> Enable Automatic Package Restore
  2. (Nuget 2.6 and below) Right clicking on a solution and clicking "Enable Package Restore for this solution".


Command-Line Package Restore is required when building a solution from the command-line; it was introduced in early versions of NuGet, but was improved in NuGet 2.7.

nuget.exe restore contoso.sln

The MSBuild-integrated package restore approach is the original Package Restore implementation and though it continues to work in many scenarios, it does not cover the full set of scenarios addressed by the other two approaches.

sed edit file in place

sed supports in-place editing. From man sed:

-i[SUFFIX], --in-place[=SUFFIX]

    edit files in place (makes backup if extension supplied)

Example:

Let's say you have a file hello.txtwith the text:

hello world!

If you want to keep a backup of the old file, use:

sed -i.bak 's/hello/bonjour' hello.txt

You will end up with two files: hello.txt with the content:

bonjour world!

and hello.txt.bak with the old content.

If you don't want to keep a copy, just don't pass the extension parameter.

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

How do I import material design library to Android Studio?

There is a new official design library, just add this to your build.gradle: for details visit android developers page

compile 'com.android.support:design:27.0.0'

How do I use variables in Oracle SQL Developer?

Use the next query:

DECLARE 
  EmpIDVar INT;

BEGIN
  EmpIDVar := 1234;

  SELECT *
  FROM Employees
  WHERE EmployeeID = EmpIDVar;
END;

What does this GCC error "... relocation truncated to fit..." mean?

On Cygwin -mcmodel=medium is already default and doesn't help. To me adding -Wl,--image-base -Wl,0x10000000 to GCC linker did fixed the error.

How to set Apache Spark Executor memory

You need to increase the driver memory.On mac(i.e when running on local master), the default driver-memory is 1024M). By default, thus 380Mb is allotted to the executor.

Screenshot

Upon increasing [--driver-memory 2G], executor memory got increased to ~950Mb. enter image description here

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String? = "Bertie"

Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea of what they are. Compare the optional above to creating a normal String:

var name: String = "Bertie" // No "?" after String

From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.

Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.

You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ?-clicking on it. Here's the important part of the definition:

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

Optional is just an enum which can be one of two cases: .none or .some. If it's .some, there's an associated value which, in the example above, would be the String "Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String, it's Optional, or more precisely Optional<String>.

Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.

Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.


How to create optionals

To create an optional, append a ? after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?.

var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)

// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}

Using optionals

You can compare an optional to nil to see if it has a value:

var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
    print("There is a name")
}
if name == nil { // Could also use an "else"
    print("Name has no value")
}

This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none.


Only optionals can be nil

If you try to set a non-optional variable to nil, you'll get an error.

var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'

Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil and when the image is retrieved, the optional gets a value.

Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.


To use an optional, you "unwrap" it

An optional String cannot be used in place of an actual String. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil, it causes a runtime crash. Before unwrapping you should be sure there's a value.

var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: \(unwrappedName)")

name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.

Checking and using an optional

Because you should always check for nil before unwrapping and using an optional, this is a common pattern:

var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
    let unwrappedMealPreference: String = mealPreference!
    print("Meal: \(unwrappedMealPreference)") // or do something useful
}

In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".

var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
    print("Meal: \(unwrappedMealPreference)") 
}

This creates a temporary constant (or variable if you replace let with var) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope

var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
    print("Meal: \(mealPreference)") // separate from the other mealPreference
}

Here's some code to demonstrate that a different variable is used:

var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
    print("Meal: \(mealPreference)") // mealPreference is a String, not a String?
    mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: \(mealPreference)") // Prints "Meal: Optional("Vegetarian")"

Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription to silence it:

print("\(mealPreference.debugDescription)")

What are optionals for?

Optionals have two use cases:

  1. Things that can fail (I was expecting something but I got nothing)
  2. Things that are nothing now but might be something later (and vice-versa)

Some concrete examples:

  • A property which can be there or not there, like middleName or spouse in a Person class
  • A method which can return a value or nothing, like searching for a match in an array
  • A method which can return either a result or get an error and return nothing, like trying to read a file's contents (which normally returns the file's data) but the file doesn't exist
  • Delegate properties, which don't always have to be set and are generally set after initialization
  • For weak properties in classes. The thing they point to can be set to nil at any time
  • A large resource that might have to be released to reclaim memory
  • When you need a way to know when a value has been set (data not yet loaded > the data) instead of using a separate dataLoaded Boolean

Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound which is really NSIntegerMax, kCLLocationCoordinate2DInvalid to represent an invalid coordinate, -1 or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil as a parameter, this has to be documented. In Objective-C, nil was a pointer just as all objects were defined as pointers, but nil pointed to a specific (zero) address. In Swift, nil is a literal which means the absence of a certain type.


Comparing to nil

You used to be able to use any optional as a Boolean:

let leatherTrim: CarExtras? = nil
if leatherTrim {
    price = price + 1000
}

In more recent versions of Swift you have to use leatherTrim != nil. Why is this? The problem is that a Boolean can be wrapped in an optional. If you have Boolean like this:

var ambiguous: Boolean? = false

it has two kinds of "false", one where there is no value and one where it has a value but the value is false. Swift hates ambiguity so now you must always check an optional against nil.

You might wonder what the point of an optional Boolean is? As with other optionals the .none state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"


Swift tricks

Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;

var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }

None of these lines should compile.

  • The first line sets an optional String using a String literal, two different types. Even if this was a String the types are different
  • The second line sets an optional String to nil, two different types
  • The third line compares an optional string to nil, two different types

I'll go through some of the implementation details of optionals that allow these lines to work.


Creating an optional

Using ? to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:

var name: Optional<String> = Optional("Bob")

This calls Optional's first initializer, public init(_ some: Wrapped), which infers the optional's associated type from the type used within the parentheses.

The even longer way of creating and setting an optional:

var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("\(serialNumber.debugDescription)")

Setting an optional to nil

You can create an optional with no initial value, or create one with the initial value of nil (both have the same outcome).

var name: String?
var name: String? = nil

Allowing optionals to equal nil is enabled by the protocol ExpressibleByNilLiteral (previously named NilLiteralConvertible). The optional is created with Optional's second initializer, public init(nilLiteral: ()). The docs say that you shouldn't use ExpressibleByNilLiteral for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:

class Clint: ExpressibleByNilLiteral {
    var name: String?
    required init(nilLiteral: ()) {
        name = "The Man with No Name"
    }
}

let clint: Clint = nil // Would normally give an error
print("\(clint.name)")

The same protocol allows you to set an already-created optional to nil. Although it's not recommended, you can use the nil literal initializer directly:

var name: Optional<String> = Optional(nilLiteral: ())

Comparing an optional to nil

Optionals define two special "==" and "!=" operators, which you can see in the Optional definition. The first == allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.

// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
    print("tuxedoRequired is nil")
}

The second == operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable (the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none. Note the distinction between comparing to the nil literal.

Furthermore, it allows you to compare any Equatable type to an optional wrapping that type:

let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
    print("It's a match!") // Prints "It's a match!"
}

Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {)

I said there are two == operators, but there's actually a third which allow you to put nil on the left-hand side of the comparison

if nil == name { ... }

Naming Optionals

There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.


The official definition

From "The Basics" in the Swift Programming Language:

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.


To finish, here's a poem from 1899 about optionals:

Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away

Antigonish


More resources:

$(document).click() not working correctly on iPhone. jquery

CSS Cursor:Pointer; is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer; on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

How to convert an OrderedDict into a regular dict in python3

Its simple way

>>import json 
>>from collection import OrderedDict

>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))

How to remove a file from the index in git?

Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).

Just use one of the GUI-based tools that support index management, for example:

  • git gui <-- uses the Tk windowing framework -- similar style to gitk
  • git cola <-- a more modern-style GUI interface

These let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.


How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:

  • git rm --cached [file]
  • git reset HEAD <file>

...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.


Working without the index

Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:

  • Commit my entire working copy (the typical case): git commit -a
  • Commit just a few files: git commit (list of files)
  • Commit all but a few modified files: git commit -a then amend via git gui
  • Graphically review all changes to working copy: git difftool --dir-diff --tool=meld

jquery function setInterval

This is because you are executing the function not referencing it. You should do:

  setInterval(swapImages,1000);

Why use #define instead of a variable

The #define is part of the preprocessor language for C and C++. When they're used in code, the compiler just replaces the #define statement with what ever you want. For example, if you're sick of writing for (int i=0; i<=10; i++) all the time, you can do the following:

#define fori10 for (int i=0; i<=10; i++)

// some code...

fori10 {
    // do stuff to i
}

If you want something more generic, you can create preprocessor macros:

#define fori(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
fori(20) {
    // do more stuff to i
}

It's also very useful for conditional compilation (the other major use for #define) if you only want certain code used in some particular build:

// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif

Most compilers will allow you to define a macro from the command line (e.g. g++ -DDEBUG something.cpp), but you can also just put a define in your code like so:

#define DEBUG

Some resources:

  1. Wikipedia article
  2. C++ specific site
  3. Documentation on GCC's preprocessor
  4. Microsoft reference
  5. C specific site (I don't think it's different from the C++ version though)

Android Studio - Importing external Library/Jar

I am currently using Android Studio 1.4.

For importing and adding libraries, I used the following flow ->

1. Press **Alt+Ctr+Shift+S** or Go to **File --> Project** Structure to open up the Project Structure Dialog Box.

2. Click on **Modules** to which you want to link the JAR to and Go to the Dependency Tab.

3. Click on "**+**" Button to pop up Choose Library Dependency.

4. Search/Select the dependency and rebuild the project.

I used the above approach to import support v4 and v13 libraries.

I hope this is helpful and clears up the flow.

pip not working in Python Installation in Windows 10

I had the same problem on Visual Studio Code. For various reasons several python versions are installed on my computer. I was thus able to easily solve the problem by switching python interpreter.

If like me you have several versions of python on you machine, in Visual Studio Code, you can easily change the interpreter by clicking on the bottom left corner where it says Python...

enter image description here

ReferenceError: $ is not defined

Your widget has Underscore.js/LoDash.js as dependency.

You can get them here: underscore, lodash

Try prepending this to your code, so you can see if it works:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

JUnit Testing private variables?

First of all, you are in a bad position now - having the task of writing tests for the code you did not originally create and without any changes - nightmare! Talk to your boss and explain, it is not possible to test the code without making it "testable". To make code testable you usually do some important changes;

Regarding private variables. You actually never should do that. Aiming to test private variables is the first sign that something wrong with the current design. Private variables are part of the implementation, tests should focus on behavior rather of implementation details.

Sometimes, private field are exposed to public access with some getter. I do that, but try to avoid as much as possible (mark in comments, like 'used for testing').

Since you have no possibility to change the code, I don't see possibility (I mean real possibility, not like Reflection hacks etc.) to check private variable.

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

As an example of automatic resource management:

void test()
{
    std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

Regular expression to match any character being repeated more than 10 times

The regex you need is /(.)\1{9,}/.

Test:

#!perl
use warnings;
use strict;
my $regex = qr/(.)\1{9,}/;
print "NO" if "abcdefghijklmno" =~ $regex;
print "YES" if "------------------------" =~ $regex;
print "YES" if "========================" =~ $regex;

Here the \1 is called a backreference. It references what is captured by the dot . between the brackets (.) and then the {9,} asks for nine or more of the same character. Thus this matches ten or more of any single character.

Although the above test script is in Perl, this is very standard regex syntax and should work in any language. In some variants you might need to use more backslashes, e.g. Emacs would make you write \(.\)\1\{9,\} here.

If a whole string should consist of 9 or more identical characters, add anchors around the pattern:

my $regex = qr/^(.)\1{9,}$/;

Prevent flex items from overflowing a container

If you want the overflow to wrap: flex-flow: row wrap

Preserve Line Breaks From TextArea When Writing To MySQL

Got my own answer: Using this function from the data from the textarea solves the problem:

function mynl2br($text) { 
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')); 
} 

More here: http://php.net/nl2br

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

Get div to take up 100% body height, minus fixed-height header and footer

This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv, and this javascript snippet will expand that div until the page takes up the full height of the browser window.

It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv by one pixel to make the page height exactly the height of the browser window.

By placing footerspacerdiv just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.

<script>    
//expand footerspacer div so that footer goes to bottom of page on short pages        
  var objSpacerDiv=document.getElementById('footerspacer');          
  var bresize=0;   

  while(document.body.scrollHeight<=document.body.clientHeight) {
    objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
    bresize=1;
  }             
  if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }               
 </script>

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select CONVERT(NVARCHAR, SYSDATETIME(), 106) AS [DD-MON-YYYY]

or else

select REPLACE(CONVERT(NVARCHAR,GETDATE(), 106), ' ', '-')

both works fine

How can I get the concatenation of two lists in Python without modifying either one?

you could always create a new list which is a result of adding two lists.

>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]

Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.

how to call url of any other website in php

Depending on what you mean, either redirect or use curl.

What's the best way to break from nested loops in JavaScript?

XXX.Validation = function() {
    var ok = false;
loop:
    do {
        for (...) {
            while (...) {
                if (...) {
                    break loop; // Exist the outermost do-while loop
                }
                if (...) {
                    continue; // skips current iteration in the while loop
                }
            }
        }
        if (...) {
            break loop;
        }
        if (...) {
            break loop;
        }
        if (...) {
            break loop;
        }
        if (...) {
            break loop;
        }
        ok = true;
        break;
    } while(true);
    CleanupAndCallbackBeforeReturning(ok);
    return ok;
};

How to print time in format: 2009-08-10 18:17:54.811

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

How to combine GROUP BY, ORDER BY and HAVING

ORDER BY is always last...

However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT * and GROUP BY Email will give you RANDOM VALUES for all the fields but Email. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.

SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC

How to correctly set Http Request Header in Angular 2

Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)

How to programmatically set style attribute in a view

Yes, you can use for example in a button

Button b = new Button(this);
b.setBackgroundResource(R.drawable.selector_test);

Add IIS 7 AppPool Identities as SQL Server Logons

In my case the problem was that I started to create an MVC Alloy sample project from scratch in using Visual Studio/Episerver extension and it worked fine when executed using local Visual studio iis express. However by default it points the sql database to LocalDB and when I deployed the site to local IIS it started giving errors some of the initial errors I resolved by: 1.adding the local site url binding to C:/Windows/System32/drivers/etc/hosts 2. Then by editing the application.config found the file location by right clicking on IIS express in botton right corner of the screen when running site using Visual studio and added binding there for local iis url. 3. Finally I was stuck with "unable to access database errors" for which I created a blank new DB in Sql express and changed connection string in web config to point to my new DB and then in package manager console (using Visual Studio) executed Episerver DB commands like - 1. initialize-epidatabase 2. update-epidatabase 3. Convert-EPiDatabaseToUtc

How to do a logical OR operation for integer comparison in shell scripting?

This code works for me:

#!/bin/sh

argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
  echo "foo"
else
  echo "bar"
fi

I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.

man test

for more details.

How to get element by innerText

_x000D_
_x000D_
function findByTextContent(needle, haystack, precise) {_x000D_
  // needle: String, the string to be found within the elements._x000D_
  // haystack: String, a selector to be passed to document.querySelectorAll(),_x000D_
  //           NodeList, Array - to be iterated over within the function:_x000D_
  // precise: Boolean, true - searches for that precise string, surrounded by_x000D_
  //                          word-breaks,_x000D_
  //                   false - searches for the string occurring anywhere_x000D_
  var elems;_x000D_
_x000D_
  // no haystack we quit here, to avoid having to search_x000D_
  // the entire document:_x000D_
  if (!haystack) {_x000D_
    return false;_x000D_
  }_x000D_
  // if haystack is a string, we pass it to document.querySelectorAll(),_x000D_
  // and turn the results into an Array:_x000D_
  else if ('string' == typeof haystack) {_x000D_
    elems = [].slice.call(document.querySelectorAll(haystack), 0);_x000D_
  }_x000D_
  // if haystack has a length property, we convert it to an Array_x000D_
  // (if it's already an array, this is pointless, but not harmful):_x000D_
  else if (haystack.length) {_x000D_
    elems = [].slice.call(haystack, 0);_x000D_
  }_x000D_
_x000D_
  // work out whether we're looking at innerText (IE), or textContent _x000D_
  // (in most other browsers)_x000D_
  var textProp = 'textContent' in document ? 'textContent' : 'innerText',_x000D_
    // creating a regex depending on whether we want a precise match, or not:_x000D_
    reg = precise === true ? new RegExp('\\b' + needle + '\\b') : new RegExp(needle),_x000D_
    // iterating over the elems array:_x000D_
    found = elems.filter(function(el) {_x000D_
      // returning the elements in which the text is, or includes,_x000D_
      // the needle to be found:_x000D_
      return reg.test(el[textProp]);_x000D_
    });_x000D_
  return found.length ? found : false;;_x000D_
}_x000D_
_x000D_
_x000D_
findByTextContent('link', document.querySelectorAll('li'), false).forEach(function(elem) {_x000D_
  elem.style.fontSize = '2em';_x000D_
});_x000D_
_x000D_
findByTextContent('link3', 'a').forEach(function(elem) {_x000D_
  elem.style.color = '#f90';_x000D_
});
_x000D_
<ul>_x000D_
  <li><a href="#">link1</a>_x000D_
  </li>_x000D_
  <li><a href="#">link2</a>_x000D_
  </li>_x000D_
  <li><a href="#">link3</a>_x000D_
  </li>_x000D_
  <li><a href="#">link4</a>_x000D_
  </li>_x000D_
  <li><a href="#">link5</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Of course, a somewhat simpler way still is:

_x000D_
_x000D_
var textProp = 'textContent' in document ? 'textContent' : 'innerText';_x000D_
_x000D_
// directly converting the found 'a' elements into an Array,_x000D_
// then iterating over that array with Array.prototype.forEach():_x000D_
[].slice.call(document.querySelectorAll('a'), 0).forEach(function(aEl) {_x000D_
  // if the text of the aEl Node contains the text 'link1':_x000D_
  if (aEl[textProp].indexOf('link1') > -1) {_x000D_
    // we update its style:_x000D_
    aEl.style.fontSize = '2em';_x000D_
    aEl.style.color = '#f90';_x000D_
  }_x000D_
});
_x000D_
<ul>_x000D_
  <li><a href="#">link1</a>_x000D_
  </li>_x000D_
  <li><a href="#">link2</a>_x000D_
  </li>_x000D_
  <li><a href="#">link3</a>_x000D_
  </li>_x000D_
  <li><a href="#">link4</a>_x000D_
  </li>_x000D_
  <li><a href="#">link5</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

References:

Set initial focus in an Android application

android:focusedByDefault="true"

How do you get the path to the Laravel Storage folder?

In Laravel 3, call path('storage').

In Laravel 4, use the storage_path() helper function.

How to Get a Layout Inflater Given a Context?

You can also use this code to get LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

I get Access Forbidden (Error 403) when setting up new alias

This question is old and although you managed to make it work but I feel it would be helpful if I make clear some of points you have raised here.

First about directory name having spaces. I have been playing with apache2 configuration files and I have discovered that, if the directory name has space then enclose it in double quotes and all problems disappear. For example...

    NameVirtualHost     local.webapp.org
    <VirtualHost local.webapp.org:80>
        ServerAdmin [email protected]
        DocumentRoot "E:/Project/my php webapp"
        ServerName local.webapp.org
    </VirtualHost>

Note the way DocumentRoot line is written.

Second is about Access forbidden from xampp. I found that default xampp configuration (..path to xampp/apache/httpd.conf) has a section that looks like the following.

    <Directory>
        AllowOverride none
        Require all denied
    </Directory>

Change it and make it look like below. Save the file restart apache from xampp and that solves the problem.

    <Directory>
       Options Indexes FollowSymLinks Includes ExecCGI
       AllowOverride none
       Require all granted
    </Directory>

How can I make a button have a rounded border in Swift?

You can use this subclass of UIButton to customize UIButton as per your needs.

visit this github repo for reference

class RoundedRectButton: UIButton {

    var selectedState: Bool = false

    override func awakeFromNib() {
        super.awakeFromNib()
        layer.borderWidth = 2 / UIScreen.main.nativeScale
        layer.borderColor = UIColor.white.cgColor
        contentEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    }


    override func layoutSubviews(){
        super.layoutSubviews()
        layer.cornerRadius = frame.height / 2
        backgroundColor = selectedState ? UIColor.white : UIColor.clear
        self.titleLabel?.textColor = selectedState ? UIColor.green : UIColor.white
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        selectedState = !selectedState
        self.layoutSubviews()
    }
}

Dynamic function name in javascript?

Thank you Marcosc! Building on his answer, if you want to rename any function, use this:

// returns the function named with the passed name
function namedFunction(name, fn) {
    return new Function('fn',
        "return function " + name + "(){ return fn.apply(this,arguments)}"
    )(fn)
}

Remove empty lines in a text file via grep

with awk, just check for number of fields. no need regex

$ more file
hello

world

foo

bar

$ awk 'NF' file
hello
world
foo
bar

Generate UML Class Diagram from Java Project

I´d say MoDisco is by far the most powerful one (though probably not the easiest one to work with).

MoDisco is a generic reverse engineering framework (so that you can customize your reverse engineering project, with MoDisco you can even reverse engineer the behaviour of the java methods, not only the structure and signatures) but also includes some predefined features like the generation of class diagrams out of Java code that you need.