Programs & Examples On #Tree left right

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

jQuery event handlers always execute in order they were bound - any way around this?

I'm assuming you are talking about the event bubbling aspect of it. It would be helpful to see your HTML for the said span elements as well. I can't see why you'd want to change the core behavior like this, I don't find it at all annoying. I suggest going with your second block of code:

$('span').click(function (){
  doStuff2();
  doStuff1();
});

Most importantly I think you'll find it more organized if you manage all the events for a given element in the same block like you've illustrated. Can you explain why you find this annoying?

How can I select rows with most recent timestamp for each key value?

You can only select columns that are in the group or used in an aggregate function. You can use a join to get this working

select s1.* 
from sensorTable s1
inner join 
(
  SELECT sensorID, max(timestamp) as mts
  FROM sensorTable 
  GROUP BY sensorID 
) s2 on s2.sensorID = s1.sensorID and s1.timestamp = s2.mts

Making custom right-click context menus for my web-app

As Adrian said, the plugins are going to work the same way. There are three basic parts you're going to need:

1: Event handler for 'contextmenu' event:

$(document).bind("contextmenu", function(event) {
    event.preventDefault();
    $("<div class='custom-menu'>Custom menu</div>")
        .appendTo("body")
        .css({top: event.pageY + "px", left: event.pageX + "px"});
});

Here, you could bind the event handler to any selector that you want to show a menu for. I've chosen the entire document.

2: Event handler for 'click' event (to close the custom menu):

$(document).bind("click", function(event) {
    $("div.custom-menu").hide();
});

3: CSS to control the position of the menu:

.custom-menu {
    z-index:1000;
    position: absolute;
    background-color:#C0C0C0;
    border: 1px solid black;
    padding: 2px;
}

The important thing with the CSS is to include the z-index and position: absolute

It wouldn't be too tough to wrap all of this in a slick jQuery plugin.

You can see a simple demo here: http://jsfiddle.net/andrewwhitaker/fELma/

Batch Script to Run as Administrator

Following is a work-around:

  1. Create a shortcut of the .bat file
  2. Open the properties of the shortcut. Under the shortcut tab, click on advanced.
  3. Tick "Run as administrator"

Running the shortcut will execute your batch script as administrator.

Get JSON data from external URL and display it in a div as plain text

Since it's an external resource you'd need to go with JSONP because of the Same origin policy.
To do that you need to add the querystring parameter callback:

$.getJSON("http://myjsonsource?callback=?", function(data) {
    // Get the element with id summary and set the inner text to the result.
    $('#summary').text(data.result);
});

How to make (link)button function as hyperlink?

There is a middle way. If you want a HTML control but you need to access it server side you can simply add the runat="server" attribute:

<a runat="server" Id="lnkBack">Back</a>

You can then alter the href server side using Attributes

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       lnkBack.Attributes.Add("href", url);
    }
}

resulting in:

<a id="ctl00_ctl00_mainContentPlaceHolder_contentPlaceHolder_lnkBack" 
      href="url.aspx">Back</a>

Update label from another thread

Use MethodInvoker for updating label text in other thread.

private void AggiornaContatore()
{
    MethodInvoker inv = delegate 
    {
      this.lblCounter.Text = this.index.ToString(); 
    }

 this.Invoke(inv);
}

You are getting the error because your UI thread is holding the label, and since you are trying to update it through another thread you are getting cross thread exception.

You may also see: Threading in Windows Forms

How / can I display a console window in Intellij IDEA?

On IntelliJ IDEA 2020.2.1

Click on the tab that you want to open as window mode.

Right-click on the tab name and select View mode > Window

As this image

jquery $(this).id return Undefined

use this actiion

$(document).ready(function () {
var a = this.id;

alert (a);
});

How to import a jar in Eclipse

Jar File in the system path is:

C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar

ojdbc14.jar(it's jar file)

To import jar file in your Eclipse IDE, follow the steps given below.

  1. Right-click on your project
  2. Select Build Path
  3. Click on Configure Build Path
  4. Click on Libraries, select Modulepath and select Add External JARs
  5. Select the jar file from the required folder
  6. Click and Apply and Ok

Select the first row by group

(1) SQLite has a built in rowid pseudo-column so this works:

sqldf("select min(rowid) rowid, id, string 
               from test 
               group by id")

giving:

  rowid id string
1     1  1      A
2     3  2      B
3     5  3      C
4     7  4      D
5     9  5      E

(2) Also sqldf itself has a row.names= argument:

sqldf("select min(cast(row_names as real)) row_names, id, string 
              from test 
              group by id", row.names = TRUE)

giving:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

(3) A third alternative which mixes the elements of the above two might be even better:

sqldf("select min(rowid) row_names, id, string 
               from test 
               group by id", row.names = TRUE)

giving:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

Note that all three of these rely on a SQLite extension to SQL where the use of min or max is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)

Postgresql : syntax error at or near "-"

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

Using a custom typeface in Android

The default implementations of LayoutInflater do not support specifying the font typeface from xml. I have however seen it done in xml by providing a custom factory for the LayoutInflater that will parse such attributes from the xml tag.

The basic structure would like this.

public class TypefaceInflaterFactory implements LayoutInflater.Factory {

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        // CUSTOM CODE TO CREATE VIEW WITH TYPEFACE HERE
        // RETURNING NULL HERE WILL TELL THE INFLATER TO USE THE
        // DEFAULT MECHANISMS FOR INFLATING THE VIEW FROM THE XML
    }

}

public class BaseActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater.from(this).setFactory(new TypefaceInflaterFactory());
    }
}

This article provides a more in depth explanation of these mechanisms and how the author attempts to provide xml layout support for typefaces in this way. The code for the author's implementation can be found here.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You can try and check for the referer, which should be the parent site if you're an iframe

you can do that like this:

var href = document.referrer;

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

Call asynchronous method in constructor?

A little late to the party, but I think many are struggling with this...

I've been searching for this as well. And to get your method/action running async without waiting or blocking the thread, you'll need to queue it via the SynchronizationContext, so I came up with this solution:

I've made a helper-class for it.

public static class ASyncHelper
{

    public static void RunAsync(Func<Task> func)
    {
        var context = SynchronizationContext.Current;

        // you don't want to run it on a threadpool. So if it is null, 
        // you're not on a UI thread.
        if (context == null)
            throw new NotSupportedException(
                "The current thread doesn't have a SynchronizationContext");

        // post an Action as async and await the function in it.
        context.Post(new SendOrPostCallback(async state => await func()), null);
    }

    public static void RunAsync<T>(Func<T, Task> func, T argument)
    {
        var context = SynchronizationContext.Current;

        // you don't want to run it on a threadpool. So if it is null, 
        // you're not on a UI thread.
        if (context == null)
            throw new NotSupportedException(
                "The current thread doesn't have a SynchronizationContext");

        // post an Action as async and await the function in it.
        context.Post(new SendOrPostCallback(async state => await func((T)state)), argument);
    }
}

Usage/Example:

public partial class Form1 : Form
{

    private async Task Initialize()
    {
        // replace code here...
        await Task.Delay(1000);
    }

    private async Task Run(string myString)
    {

        // replace code here...
        await Task.Delay(1000);
    }

    public Form1()
    {
        InitializeComponent();

        // you don't have to await nothing.. (the thread must be running)
        ASyncHelper.RunAsync(Initialize);
        ASyncHelper.RunAsync(Run, "test");

        // In your case
        ASyncHelper.RunAsync(getWritings);
    }
}

This works for Windows.Forms and WPF

How to include a PHP variable inside a MySQL statement

That's the easy answer:

$query="SELECT * FROM CountryInfo WHERE Name = '".$name."'";

and you define $name whatever you want.
And another way, the complex way, is like that:

$query = " SELECT '" . $GLOBALS['Name'] . "' .* " .
         " FROM CountryInfo " .
         " INNER JOIN District " .
         " ON District.CountryInfoId = CountryInfo.CountryInfoId " .
         " INNER JOIN City " .
         " ON City.DistrictId = District.DistrictId " .
         " INNER JOIN '" . $GLOBALS['Name'] . "' " .
         " ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " .
         " WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] .
         "'";

Get real path from URI, Android KitKat new storage access framework

This answer is based on your somewhat vague description. I assume that you fired an intent with action: Intent.ACTION_GET_CONTENT

And now you get content://com.android.providers.media.documents/document/image:62 back instead of the previously media provider URI, correct?

On Android 4.4 (KitKat) the new DocumentsActivity gets opened when an Intent.ACTION_GET_CONTENT is fired thus leading to grid view (or list view) where you can pick an image, this will return the following URIs to calling context (example): content://com.android.providers.media.documents/document/image:62 (these are the URIs to the new document provider, it abstracts away the underlying data by providing generic document provider URIs to clients).

You can however access both gallery and other activities responding to Intent.ACTION_GET_CONTENT by using the drawer in the DocumentsActivity (drag from left to right and you'll see a drawer UI with Gallery to choose from). Just as pre KitKat.

If you still which to pick in DocumentsActivity class and need the file URI, you should be able to do the following (warning this is hacky!) query (with contentresolver):content://com.android.providers.media.documents/document/image:62 URI and read the _display_name value from the cursor. This is somewhat unique name (just the filename on local files) and use that in a selection (when querying) to mediaprovider to get the correct row corresponding to this selection from here you can fetch the file URI as well.

The recommended ways of accessing document provider can be found here (get an inputstream or file descriptor to read file/bitmap):

Examples of using documentprovider

Connect Java to a MySQL database

Download JDBC Driver

Download link (Select platform independent): https://dev.mysql.com/downloads/connector/j/

Move JDBC Driver to C Drive

Unzip the files and move to C:\ drive. Your driver path should be like C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19

Run Your Java

java -cp "C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19.jar" testMySQL.java

testMySQL.java

import java.sql.*;
import java.io.*;

public class testMySQL {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
        try
        {  
            Class.forName("com.mysql.cj.jdbc.Driver");  
            Connection con=DriverManager.getConnection(  
                "jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");  
            Statement stmt=con.createStatement();  
            ResultSet rs=stmt.executeQuery("show databases;");  
            System.out.println("Connected");  
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

    }  

}

enter image description here

Move SQL data from one table to another

Here is how do it with single statement

WITH deleted_rows AS (
DELETE FROM source_table WHERE id = 1
RETURNING *
) 
INSERT INTO destination_table 
SELECT * FROM deleted_rows;

EXAMPLE:

    postgres=# select * from test1 ;
 id |  name
----+--------
  1 | yogesh
  2 | Raunak
  3 | Varun
(3 rows)


postgres=# select * from test2;
 id | name
----+------
(0 rows)


postgres=# WITH deleted_rows AS (
postgres(# DELETE FROM test1 WHERE id = 1
postgres(# RETURNING *
postgres(# )
postgres-# INSERT INTO test2
postgres-# SELECT * FROM deleted_rows;
INSERT 0 1


postgres=# select * from test2;
 id |  name
----+--------
  1 | yogesh
(1 row)

postgres=# select * from test1;
 id |  name
----+--------
  2 | Raunak
  3 | Varun

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

If your info.plist is shown as a property list (and not xml), the text you need to enter for the key is:
App Uses Non-Exempt Encryption

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

Removing multiple keys from a dictionary safely

Using dict.pop:

d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
    d.pop(k, None)

How can I remove a character from a string using JavaScript?

return this.substr(0, index) + char + this.substr(index + char.length);

char.length is zero. You need to add 1 in this case in order to skip character.

How to draw a path on a map using kml file?

There is now a beta available of Google Maps KML Importing Utility.

It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams

KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());

or local resources

KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());

After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.

layer.addLayerToMap();

Best Practices: working with long, multiline strings in PHP?

you can also use:

<?php
ob_start();
echo "some text";
echo "\n";

// you can also use: 
?> 
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then: 
$long_text = ob_get_clean();

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

I used the answer given by Carcione and modified it to use JSON.

 function getUrlJsonSync(url){

    var jqxhr = $.ajax({
        type: "GET",
        url: url,
        dataType: 'json',
        cache: false,
        async: false
    });

    // 'async' has to be 'false' for this to work
    var response = {valid: jqxhr.statusText,  data: jqxhr.responseJSON};

    return response;
}    

function testGetUrlJsonSync()
{
    var reply = getUrlJsonSync("myurl");

    if (reply.valid == 'OK')
    {
        console.dir(reply.data);
    }
    else
    {
        alert('not valid');
    }    
}

I added the dataType of 'JSON' and changed the .responseText to responseJSON.

I also retrieved the status using the statusText property of the returned object. Note, that this is the status of the Ajax response, not whether the JSON is valid.

The back-end has to return the response in correct (well-formed) JSON, otherwise the returned object will be undefined.

There are two aspects to consider when answering the original question. One is telling Ajax to perform synchronously (by setting async: false) and the other is returning the response via the calling function's return statement, rather than into a callback function.

I also tried it with POST and it worked.

I changed the GET to POST and added data: postdata

function postUrlJsonSync(url, postdata){

    var jqxhr = $.ajax({
        type: "POST",
        url: url,
        data: postdata,
        dataType: 'json',
        cache: false,
        async: false
    });

    // 'async' has to be 'false' for this to work
    var response = {valid: jqxhr.statusText,  data: jqxhr.responseJSON};

    return response;
}

Note that the above code only works in the case where async is false. If you were to set async: true the returned object jqxhr would not be valid at the time the AJAX call returns, only later when the asynchronous call has finished, but that is much too late to set the response variable.

Controlling Spacing Between Table Cells

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.

JSFiddle

TransactionRequiredException Executing an update/delete query

In my case, I had the wrong @Transactional imported.

The correct one is:

import org.springframework.transaction.annotation.Transactional;

and not

import javax.transaction.Transactional;

File Not Found when running PHP with Nginx

After upgrading to PHP72, we had an issue where the php-fpm.d/www.conf lost the settings for user/group which was causing this error. Be sure to double check those if your setup involves php-fpm.

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Change / Add syntax highlighting for a language in Sublime 2/3

The "this" is already coloured in Javascript.

View->Syntax-> and choose your language to highlight.

Why does z-index not work?

Your elements need to have a position attribute. (e.g. absolute, relative, fixed) or z-index won't work.

How to convert java.lang.Object to ArrayList?

    Object object = new Object();

    // First way
    List objects1 = new ArrayList<Object>();
    objects1.add(object);

    // second way
    List<Object> objects2 = Arrays.asList(object);

    // Third way
    List<Object> objects3 = Collections.singletonList(object);

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

jquery .html() vs .append()

They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.

One jQuery Wrapper (per example):

$("#myDiv").html('<div id="mySecondDiv"></div>');

$("#myDiv").append('<div id="mySecondDiv"></div>');

Two jQuery Wrappers (per example):

var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);

var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);

You have a few different use cases going on. If you want to replace the content, .html is a great call since its the equivalent of innerHTML = "...". However, if you just want to append content, the extra $() wrapper set is unneeded.

Only use two wrappers if you need to manipulate the added div later on. Even in that case, you still might only need to use one:

var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();

Difference between try-catch and throw in java

try - Add sensitive code catch - to handle exception finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block throw - To handover our created exception to JVM manually. Used to throw customized exception throws - To delegate the responsibility of exception handling to caller method or main method.

here-document gives 'unexpected end of file' error

The EOF token must be at the beginning of the line, you can't indent it along with the block of code it goes with.

If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Also make sure you have no whitespace after the EOF token on the line.

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

When to use .First and when to use .FirstOrDefault with LINQ?

This type of the function belongs to element operators. Some useful element operators are defined below.

  1. First/FirstOrDefault
  2. Last/LastOrDefault
  3. Single/SingleOrDefault

We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.

  List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };

First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.

int result = items.Where(item => item == 2).First();

FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.

int result1 = items.Where(item => item == 2).FirstOrDefault();

Py_Initialize fails - unable to load the file system codec

Parts of this have been mentioned before, but in a nutshell this is what worked for my environment where I have multiple Python installs and my global OS environment set-up to point to a different install than the one I attempt to work with when encountering the problem.

Make sure your (local or global) environment is fully set-up to point to the install you aim to work with, e.g. you have two (or more) installs of, let's say a python27 and python33 (sorry these are windows paths but the following should be valid for equivalent UNIX-style paths just as well, please let me know about anything I'm missing here (probably the DLLs path might differ)):

C:\python27_x86

C:\python33_x64

Now, if you intend to work with your python33 install but your global environment is pointing to python27, make sure you update your environment as such (while PATH and PYTHONHOME may be optional (e.g. if you temporarily work in a local shell)):

PATH="C:\python33_x64;%PATH%"

PYTHONPATH="C:\python33_x64\DLLs;C:\python33_x64\Lib;C:\python33_x64\Lib\site-packages"

PYTHONHOME=C:\python33_x64

Note, that you might need/want to append any other library paths to your PYTHONPATH if required by your development environment, but having your DLLs, Lib and site-packages properly set-up is of prime importance.

Hope this helps.

Multi-select dropdown list in ASP.NET

I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.

How to pass arguments to a Button command in Tkinter?

One simple way would be to configure button with lambda like the following syntax:

button['command'] = lambda arg1 = local_var1, arg2 = local_var2 : function(arg1, arg2)

Set a cookie to never expire

I'm not sure but aren't cookies deleted at browser close? I somehow did a never expiring cookie and chrome recognized expired date as "at browser close" ...

How to access a property of an object (stdClass Object) member/element of an array?

Try this, working fine -

$array = json_decode(json_encode($array), true);

Android: Proper Way to use onBackPressed() with Toast

I use this much simpler approach...

public class XYZ extends Activity {
    private long backPressedTime = 0;    // used by onBackPressed()


    @Override
    public void onBackPressed() {        // to prevent irritating accidental logouts
        long t = System.currentTimeMillis();
        if (t - backPressedTime > 2000) {    // 2 secs
            backPressedTime = t;
            Toast.makeText(this, "Press back again to logout",
                                Toast.LENGTH_SHORT).show();
        } else {    // this guy is serious
            // clean up
            super.onBackPressed();       // bye
        }
    }
}

How to convert .crt to .pem

You can do this conversion with the OpenSSL library

http://www.openssl.org/

Windows binaries can be found here:

http://www.slproweb.com/products/Win32OpenSSL.html

Once you have the library installed, the command you need to issue is:

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

How can I get the root domain URI in ASP.NET?

string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Uri::GetLeftPart Method:

The GetLeftPart method returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.

UriPartial Enumeration:

The scheme and authority segments of the URI.

Enterprise app deployment doesn't work on iOS 7.1

The universal solution is to connect your device to Mac and to observe what's going on during installation. I got an error:

Could not load download manifest with underlying error: Error Domain=NSURLErrorDomain Code=-1202 "Cannot connect to the Store" UserInfo=0x146635d0 {NSLocalizedDescription=Cannot connect to the Store, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSLocalizedFailureReason=A secure connection could not be established. Please check your Date & Time settings., NSErrorFailingURLStringKey=https://myserver.com/app/manifest.plist, NSUnderlyingError=0x14678880 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myserver.com” which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=, NSErrorFailingURLKey=https://myserver.com/app/manifest.plist}

There was even the suggestion in that error to check date settings. For some reason the date was 1 January 1970. Setting correct date solved the problem.

Insert a line at specific line number with sed or awk

sed -i "" -e $'4 a\\n''Project_Name=sowstest' start

  • This line works fine in macOS

Change Select List Option background colour on hover

Select / Option elements are rendered by the OS, not HTML. You cannot change the style for these elements.

Django development IDE

PyCharm. It is best the IDE for Python,Django, and web development I've tried so far. It is totally worth the money.

how to set "camera position" for 3d plots using python/matplotlib?

By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init. I've used the below script to first create the plot, then I determined a good elevation, or elev, from which to view my plot. I then adjusted the azimuth angle, or azim, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.

    from mpl_toolkits.mplot3d import Axes3D
    ax = Axes3D(fig)
    ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
    for ii in xrange(0,360,1):
        ax.view_init(elev=10., azim=ii)
        savefig("movie%d.png" % ii)

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers

What JSON library to use in Scala?

I use uPickle which has the big advantage that it will handle nested case classes automatically:

object SerializingApp extends App {

  case class Person(name: String, address: Address)

  case class Address(street: String, town: String, zipCode: String)

  import upickle.default._

  val john = Person("John Doe", Address("Elm Street 1", "Springfield", "ABC123"))

  val johnAsJson = write(john)
  // Prints {"name":"John Doe","address":{"street":"Elm Street 1","town":"Springfield","zipCode":"ABC123"}}
  Console.println(johnAsJson)

  // Parse the JSON back into a Scala object
  Console.println(read[Person](johnAsJson))  
}

Add this to your build.sbt to use uPickle:

libraryDependencies += "com.lihaoyi" %% "upickle" % "0.4.3"

FormData.append("key", "value") is not working

You say it's not working. What are you expecting to happen?

There's no way of getting the data out of a FormData object; it's just intended for you to use to send data along with an XMLHttpRequest object (for the send method).

Update almost five years later: In some newer browsers, this is no longer true and you can now see the data provided to FormData in addition to just stuffing data into it. See the accepted answer for more info.

What is the advantage of using heredoc in PHP?

The heredoc syntax is much cleaner to me and it is really useful for multi-line strings and avoiding quoting issues. Back in the day I used to use them to construct SQL queries:

$sql = <<<SQL
select *
  from $tablename
 where id in [$order_ids_list]
   and product_name = "widgets"
SQL;

To me this has a lower probability of introducing a syntax error than using quotes:

$sql = "
select *
  from $tablename
 where id in [$order_ids_list]
   and product_name = \"widgets\"
";

Another point is to avoid escaping double quotes in your string:

$x = "The point of the \"argument" was to illustrate the use of here documents";

The problem with the above is the syntax error (the missing escaped quote) I just introduced as opposed to here document syntax:

$x = <<<EOF
The point of the "argument" was to illustrate the use of here documents
EOF;

It is a bit of style, but I use the following as rules for single, double and here documents for defining strings:

  • Single quotes are used when the string is a constant like 'no variables here'
  • Double quotes when I can put the string on a single line and require variable interpolation or an embedded single quote "Today is ${user}'s birthday"
  • Here documents for multi-line strings that require formatting and variable interpolation.

Read Numeric Data from a Text File in C++

The input operator for number skips leading whitespace, so you can just read the number in a loop:

while (myfile >> a)
{
    // ...
}

What is the default font of Sublime Text?

On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:

  1. go to View menu and select Show Console
  2. Then enter this command: view.settings().get('font_face')

You will find your default font.

display html page with node.js

This did the trick for me:

var express = require('express'),
app = express(); 
app.use('/', express.static(__dirname + '/'));
app.listen(8080);

Should I Dispose() DataSet and DataTable?

Do you create the DataTables yourself? Because iterating through the children of any Object (as in DataSet.Tables) is usually not needed, as it's the job of the Parent to dispose all its child members.

Generally, the rule is: If you created it and it implements IDisposable, Dispose it. If you did NOT create it, then do NOT dispose it, that's the job of the parent object. But each object may have special rules, check the Documentation.

For .NET 3.5, it explicitly says "Dispose it when not using anymore", so that's what I would do.

How to change sender name (not email address) when using the linux mail command for autosending mail?

It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.

If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.

from the sendmail manpage :

   -f <address>
                 This  option  sets  the  address  of the envelope sender of a
                 locally-generated message (also known as  the  return  path).
                 The  option  can normally be used only by a trusted user, but
                 untrusted_set_sender can be set to allow untrusted  users  to
                 use it. [...]

Get model's fields in Django

I know this post is pretty old, but I just cared to tell anyone who is searching for the same thing that there is a public and official API to do this: get_fields() and get_field()

Usage:

fields = model._meta.get_fields()
my_field = model._meta.get_field('my_field')

https://docs.djangoproject.com/en/1.8/ref/models/meta/

Create a directly-executable cross-platform GUI app using Python

You don't need to compile python for Mac/Windows/Linux. It is an interpreted language, so you simply need to have the Python interpreter installed on the system of your choice (it is available for all three platforms).

As for a GUI library that works cross platform, Python's Tk/Tcl widget library works very well, and I believe is sufficiently cross platform.

Tkinter is the python interface to Tk/Tcl

From the python project webpage:

Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one, and almost the only one that is portable between Unix, Mac and Windows

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

In my case it was gcc 6 the one missing

sudo apt-get install gcc-6 g++-6 -y 

Update

sudo apt-get install gcc-7 g++-7 -y

how to set radio option checked onload with jQuery

 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);

Unknown column in 'field list' error on MySQL Update query

Just sharing my experience on this. I was having this same issue. My query was like:

select table1.column2 from table1

However, table1 did not have column2 column.

Android Lint contentDescription warning

If you want to suppress this warning in elegant way (because you are sure that accessibility is not needed for this particular ImageView), you can use special attribute:

android:importantForAccessibility="no"

Spring Boot Multiple Datasource

Use multiple datasource or realizing the separation of reading & writing. you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.

Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.

dbServer:
  default: localhost:3306
  read: localhost:3306
  write: localhost:3306
datasource:
  default:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: default
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  read:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: read
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false
  write:
    type: com.zaxxer.hikari.HikariDataSource
    pool-name: write
    continue-on-error: false
    jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: lh1234
    connection-timeout: 30000
    connection-test-query: SELECT 1
    maximum-pool-size: 5
    minimum-idle: 2
    idle-timeout: 600000
    destroy-method: shutdown
    auto-commit: false

How are software license keys generated?

You can use and implement Secure Licensing API from very easily in your Software Projects using it,(you need to download the desktop application for creating secure license from https://www.systemsoulsoftwares.com/)

  1. Creates unique UID for client software based on System Hardware(CPU,Motherboard,Hard-drive) (UID acts as Private Key for that unique system)
  2. Allows to send Encrypted license string very easily to client system, It verifies license string and works on only that particular system
  3. This method allows software developers or company to store more information about software/developer/distributor services/features/client
  4. It gives control for locking and unlocked the client software features, saving time of developers for making more version for same software with changing features
  5. It take cares about trial version too for any number of days
  6. It secures the License timeline by Checking DateTime online during registration
  7. It unlocks all hardware information to developers
  8. It has all pre-build and custom function that developer can access at every process of licensing for making more complex secure code

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables. It's done via "non standard" options. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Python multiprocessing PicklingError: Can't pickle <type 'function'>

When this problem comes up with multiprocessing a simple solution is to switch from Pool to ThreadPool. This can be done with no change of code other than the import-

from multiprocessing.pool import ThreadPool as Pool

This works because ThreadPool shares memory with the main thread, rather than creating a new process- this means that pickling is not required.

The downside to this method is that python isn't the greatest language with handling threads- it uses something called the Global Interpreter Lock to stay thread safe, which can slow down some use cases here. However, if you're primarily interacting with other systems (running HTTP commands, talking with a database, writing to filesystems) then your code is likely not bound by CPU and won't take much of a hit. In fact I've found when writing HTTP/HTTPS benchmarks that the threaded model used here has less overhead and delays, as the overhead from creating new processes is much higher than the overhead for creating new threads.

So if you're processing a ton of stuff in python userspace this might not be the best method.

Purpose of ESI & EDI registers?

In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:

The SSE2 MASKMOVDQU (and the upcoming AVX VMASKMOVDQU) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.

Python3 project remove __pycache__ folders and .pyc files

Using PyCharm

To remove Python compiled files

  1. In the Project Tool Window, right-click a project or directory, where Python compiled files should be deleted from.

  2. On the context menu, choose Clean Python compiled files.

The .pyc files residing in the selected directory are silently deleted.

WebDriver - wait for element using Java

Above wait statement is a nice example of Explicit wait.

As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).

By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.

Python urllib2, basic HTTP authentication, and tr.im

This seems to work really well (taken from another thread)

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

How to provide shadow to Button

Use this approach to get your desired look.
button_selector.xml :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <layer-list>
        <item android:right="5dp" android:top="5dp">
            <shape>
                <corners android:radius="3dp" />
                <solid android:color="#D6D6D6" />
            </shape>
        </item>
        <item android:bottom="2dp" android:left="2dp">
            <shape>
                <gradient android:angle="270" 
                    android:endColor="#E2E2E2" android:startColor="#BABABA" />
                <stroke android:width="1dp" android:color="#BABABA" />
                <corners android:radius="4dp" />
                <padding android:bottom="10dp" android:left="10dp" 
                    android:right="10dp" android:top="10dp" />
            </shape>
        </item>
    </layer-list>
</item>

</selector>

And in your xml layout:

<Button
   android:background="@drawable/button_selector"
   ...
   ..
/>

How to add dll in c# project

In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.

Please post the warning message, we can try help you further.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Since you say that any language is acceptable, the natural choice is PostGIS:

SELECT * FROM places
WHERE ST_DistanceSpheroid(geom, $location, $spheroid) < $max_metres;

If you want to use WGS datum, you should set $spheroid to 'SPHEROID["WGS 84",6378137,298.257223563]'

Assuming that you have indexed places by the geom column, this should be reasonably efficient.

Is quitting an application frowned upon?

You can use Process.killProcess(Process.myPid()); to kill your app, but maybe it is not safe? I didn't encounter any problem or crash after I used this method and after I used this, the process of my app in the DDMS list disappeared.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Heres an example using: getDisplayMedia

document.body.innerHTML = '<video style="width: 100%; height: 100%; border: 1px black solid;"/>';

navigator.mediaDevices.getDisplayMedia()
.then( mediaStream => {
  const video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = e => {
    video.play();
    video.pause();
  };
})
.catch( err => console.log(`${err.name}: ${err.message}`));

Also worth checking out is the Screen Capture API docs.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

Unix's 'ls' sort by name

You can try:

ls -lru

-u with -lt: sort by, and show, access time;

Automatically enter SSH password with script

I got this working as follows

.ssh/config was modified to eliminate the yes/no prompt - I'm behind a firewall so I'm not worried about spoofed ssh keys

host *
     StrictHostKeyChecking no

Create a response file for expect i.e. answer.expect

set timeout 20
set node [lindex $argv 0]
spawn ssh root@node service hadoop-hdfs-datanode restart

expect  "*?assword {
      send "password\r"   <- your password here.

interact

Create your bash script and just call expect in the file

#!/bin/bash
i=1
while [$i -lt 129]    # a few nodes here

  expect answer.expect hadoopslave$i

  i=[$i + 1]
  sleep 5

done

Gets 128 hadoop datanodes refreshed with new config - assuming you are using a NFS mount for the hadoop/conf files

Hope this helps someone - I'm a Windows numpty and this took me about 5 hours to figure out!

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

Differentiate between function overloading and function overriding

You are putting in place an overloading when you change the original types for the arguments in the signature of a method.

You are putting in place an overriding when you change the original Implementation of a method in a derived class.

VS 2017 Git Local Commit DB.lock error on every commit

if you are using an IDE like visual studio and it is open while you sending commands close IDE and try again

git add .

and other commands, it will workout

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

This answer, but with storyboard support.

class SwipeNavigationController: UINavigationController {

    // MARK: - Lifecycle

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.setup()
    }

    private func setup() {
        delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // This needs to be in here, not in init
        interactivePopGestureRecognizer?.delegate = self
    }

    deinit {
        delegate = nil
        interactivePopGestureRecognizer?.delegate = nil
    }

    // MARK: - Overrides

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        duringPushAnimation = true

        super.pushViewController(viewController, animated: animated)
    }

    // MARK: - Private Properties

    fileprivate var duringPushAnimation = false
}

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

How to monitor the memory usage of Node.js?

The built-in process module has a method memoryUsage that offers insight in the memory usage of the current Node.js process. Here is an example from in Node v0.12.2 on a 64-bit system:

$ node --expose-gc
> process.memoryUsage();  // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc();                   // Force a GC for the baseline.
undefined
> process.memoryUsage();  // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage();  // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null;               // Allow the array to be garbage-collected
null
> gc();                   // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage();  // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage();  // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }

In this simple example, you can see that allocating an array of 10M elements consumers approximately 80MB (take a look at heapUsed).
If you look at V8's source code (Array::New, Heap::AllocateRawFixedArray, FixedArray::SizeFor), then you'll see that the memory used by an array is a fixed value plus the length multiplied by the size of a pointer. The latter is 8 bytes on a 64-bit system, which confirms that observed memory difference of 8 x 10 = 80MB makes sense.

Eclipse "this compilation unit is not on the build path of a java project"

Did you have your .project file in your folders?

I got the same problem. Than i realized that I didn't have the .project file.

How can I set the default timezone in node.js?

Sometimes you may be running code on a virtual server elsewhere - That can get muddy when running NODEJS or other flavors.

Here is a fix that will allow you to use any timezone easily.

Check here for list of timezones

Just put your time zone phrase within the brackets of your FORMAT line.

In this case - I am converting EPOCH to Eastern.

//RE: https://www.npmjs.com/package/date-and-time
const date = require('date-and-time');

let unixEpochTime = (seconds * 1000);
const dd=new Date(unixEpochTime);
let myFormattedDateTime = date.format(dd, 'YYYY/MM/DD HH:mm:ss A [America/New_York]Z');
let myFormattedDateTime24 = date.format(dd, 'YYYY/MM/DD HH:mm:ss [America/New_York]Z');

How to read xml file contents in jQuery and display in html elements?

I think you want like this, DEMO

var xmlDoc = $.parseXML( xml ); 

var $xml = $(xmlDoc);

var $person = $xml.find("person");

$person.each(function(){

    var name = $(this).find('name').text(),
        age = $(this).find('age').text();

    $("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');

});

CSS3 transition on click using pure CSS

You can use JavaScript to do this, with onClick method. This maybe helps CSS3 transition click event

How to sleep the thread in node.js without affecting other threads?

Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.

var node = require("deasync");
node.loop = node.runLoopOnce;

var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
    done = 1;
});

while (!done)
    node.loop();

// Now, here you go

Get WooCommerce product categories from WordPress

Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

$sub_cats = get_categories( $args2 );
    if($sub_cats) {
        foreach($sub_cats as $sub_category) {
            echo  $sub_category->name ;
        }

    }

with:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                }
            }

or if you also wish a counter for each subcategory, replace with this:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                    echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
                }
            }

Can JavaScript connect with MySQL?

Typically, you need a server side scripting language like PHP to connect to MySQL, however, if you're just doing a quick mockup, then you can use http://www.mysqljs.com to connect to MySQL from Javascript using code as follows:

MySql.Execute(
    "mysql.yourhost.com", 
    "username", 
    "password", 
    "database", 
    "select * from Users", 
    function (data) {
        console.log(data)
});

It has to be mentioned that this is not a secure way of accessing MySql, and is only suitable for private demos, or scenarios where the source code cannot be accessed by end users, such as within Phonegap iOS apps.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

I had this problem with compiling LXC on a fresh VM with Centos 7.8. I tried all the above and failed. Some suggested removing the -static flag from the compiler configuration but I didn't want to change anything.

The only thing that helped was to install glibc-static and retry. Hope that helps someone.

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

In Rails 4 all I had to do was the def change

def change
  rename_table :old_table_name, :new_table_name
end

And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.

And it works using the change for going up or down in regards to the indexes as well.

Extract Month and Year From Date in R

The zoo package has the function of as.yearmon can help to convert.

require(zoo)

df$ym<-as.yearmon(df$date, "%Y %m")

Form Validation With Bootstrap (jQuery)

You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation

They use JQuery validation.

jquery.validate.js

jquery.validate.min.js

jquery-1.7.1.min.js

enter image description here

And you'll get the source code there.

 <form id="registration-form" class="form-horizontal">
 <h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
 <div class="form-control-group">
        <label class="control-label" for="name">Your Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="name" id="name"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">User Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="username" id="username"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">Password</label>
 <div class="controls">
          <input type="password" class="input-xlarge" name="password" id="password">

</div>
</div>
<div class="form-control-group">
            <label class="control-label" for="name"> Retype Password</label>
<div class="controls">
              <input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="email">Email Address</label>
<div class="controls">
              <input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message">Your Address</label>
<div class="controls">
              <textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
             <input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
            <button type="submit" class="btn btn-success btn-large">Register</button>
            <button type="reset" class="btn">Cancel</button></div>
</form>

And The JQuery :

<script src="assets/js/jquery-1.7.1.min.js"></script>

<script src="assets/js/jquery.validate.js"></script>

<script src="script.js"></script>
<script>
            addEventListener('load', prettyPrint, false);
            $(document).ready(function(){
            $('pre').addClass('prettyprint linenums');
                  });

Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/

Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/

happy coding.

Linux Command History with date and time

In case you are using zsh you can use for example the -E or -i switch:

history -E

If you do a man zshoptions or man zshbuiltins you can find out more information about these switches as well as other info related to history:

Also when listing,
 -d     prints timestamps for each event
 -f     prints full time-date stamps in the US `MM/DD/YY hh:mm' format
 -E     prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
 -i     prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
 -t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions  described  for  the  %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1).  The resulting formatted string must be no more than 256 characters or will not be printed
 -D     prints elapsed times; may be combined with one of the options above

How to initialize a JavaScript Date to a particular time zone

For Ionic users, I had hell with this because .toISOString() has to be used with the html template.

This will grab the current date, but of course can be added to previous answers for a selected date.

I got it fixed using this:

_x000D_
_x000D_
date = new Date();_x000D_
public currentDate: any = new Date(this.date.getTime() - this.date.getTimezoneOffset()*60000).toISOString();
_x000D_
_x000D_
_x000D_

The *60000 is indicating the UTC -6 which is CST so whatever TimeZone is needed, the number and difference can be changed.

Viewing all `git diffs` with vimdiff

For people who want to use another diff tool not listed in git, say with nvim. here is what I ended up using:

git config --global alias.d difftool -x <tool name>

In my case, I set <tool name> to nvim -d and invoke the diff command with

git d <file>

What happens if you mount to a non-empty mount point with fuse?

Just add -o nonempty in command line, like this:

s3fs -o nonempty  <bucket-name> </mount/point/>

How do I add the Java API documentation to Eclipse?

For OpenJDK 8 on Linux see: https://askubuntu.com/questions/755853/how-to-install-jdk-sources

The way that worked for me is:

  • The default src.zip is a symbolic link pointing to a non-existing folder ...
  • sudo apt-get install openjdk-8-source this adds this folder
  • locate "src.zip"
  • Eclipse: Window --> Preferences --> Java --> "Installed JREs", edit and point to src.zip (or open any JRE class like for example HashMap and attach source)

You should now see the JavaDoc when opening JRE classes via Ctrl+Shift+t, previously this was not possible, Eclipse may have got a docs from the default URL on mouse over methods but this requires a stable internet connection.

Import cycle not allowed

This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)

Lets say your project go-circular-dependency have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows

+--go-circular-dependency    
      +--one    
         +-one.go
      +--two        
         +-two.go

This issue occurs when you try to do something like following.

Step 1 - In one.go you import package two (Following is one.go)

package one

import (
    "go-circular-dependency/two"
)

//AddOne is
func AddOne() int {
    a := two.Multiplier()
    return a + 1
}

Step 2 - In two.go you import package one (Following is two.go)

package two

import (
    "fmt"
    "go-circular-dependency/one"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    //import AddOne from "package one"
    x := one.AddOne()
    fmt.Println(x)
}

In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)

Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)

Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.

Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)

So in Step 2 that is in two.go you should not import package one. Instead in two.go you should actually replicate the functionality of AddOne() written in one.go as follows.

package two

import (
    "fmt"
)

//Multiplier is going to be used in package one
func Multiplier() int {
    return 2
}

//Total is
func Total() {
    // x := one.AddOne()
    x := Multiplier() + 1
    fmt.Println(x)
}

Android Animation Alpha

Try this

AlphaAnimation animation1 = new AlphaAnimation(0.2f, 1.0f);
animation1.setDuration(1000);
animation1.setStartOffset(5000);
animation1.setFillAfter(true);
iv.startAnimation(animation1);

How can I see the size of a GitHub repository before cloning it?

For a private repository, you will need to obtain a Personal Access Token from https://github.com/settings/tokens.

Then use the following curl command to get the details (substituting in values for [token], [owner] and [name]):

curl -u git:[token] https://api.github.com/repos/[owner]/[name] 2> /dev/null | grep size

As mentioned earlier, size may be in MB or KB.

Calling Objective-C method from C++ member function?

@DawidDrozd's answer above is excellent.

I would add one point. Recent versions of the Clang compiler complain about requiring a "bridging cast" if attempting to use his code.

This seems reasonable: using a trampoline creates a potential bug: since Objective-C classes are reference counted, if we pass their address around as a void *, we risk having a hanging pointer if the class is garbage collected up while the callback is still active.

Solution 1) Cocoa provides CFBridgingRetain and CFBridgingRelease macro functions which presumably add and subtract one from the reference count of the Objective-C object. We should therefore be careful with multiple callbacks, to release the same number of times as we retain.

// C++ Module
#include <functional>

void cppFnRequiringCallback(std::function<void(void)> callback) {
        callback();
}

//Objective-C Module
#import "CppFnRequiringCallback.h"

@interface MyObj : NSObject
- (void) callCppFunction;
- (void) myCallbackFn;
@end

void cppTrampoline(const void *caller) {
        id callerObjC = CFBridgingRelease(caller);
        [callerObjC myCallbackFn];
}

@implementation MyObj
- (void) callCppFunction {
        auto callback = [self]() {
                const void *caller = CFBridgingRetain(self);
                cppTrampoline(caller);
        };
        cppFnRequiringCallback(callback);
}

- (void) myCallbackFn {
    NSLog(@"Received callback.");
}
@end

Solution 2) The alternative is to use the equivalent of a weak reference (ie. no change to the retain count), without any additional safety.

The Objective-C language provides the __bridge cast qualifier to do this (CFBridgingRetain and CFBridgingRelease seem to be thin Cocoa wrappers over the Objective-C language constructs __bridge_retained and release respectively, but Cocoa does not appear to have an equivalent for __bridge).

The required changes are:

void cppTrampoline(void *caller) {
        id callerObjC = (__bridge id)caller;
        [callerObjC myCallbackFn];
}

- (void) callCppFunction {
        auto callback = [self]() {
                void *caller = (__bridge void *)self;
                cppTrampoline(caller);
        };
        cppFunctionRequiringCallback(callback);
}

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

What's an easy way to read random line from a file in Unix command line?

Here is what I discovery since my Mac OS doesn't use all the easy answers. I used the jot command to generate a number since the $RANDOM variable solutions seems not to be very random in my test. When testing my solution I had a wide variance in the solutions provided in the output.

  RANDOM1=`jot -r 1 1 235886`
   #range of jot ( 1 235886 ) found from earlier wc -w /usr/share/dict/web2
   echo $RANDOM1
   head -n $RANDOM1 /usr/share/dict/web2 | tail -n 1

The echo of the variable is to get a visual of the generated random number.

How to create a JavaScript callback for knowing when an image is loaded?

If you are using React.js, you could do this:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

  • Sort an array in Java

    MOST EFFECTIVE WAY!

    public static void main(String args[])
    {
        int [] array = new int[10];//creates an array named array to hold 10 int's
        for(int x: array)//for-each loop!
          x = ((int)(Math.random()*100+1));
        Array.sort(array);
        for(int x: array)
          System.out.println(x+" ");
    }
    

    Search and replace a particular string in a file using Perl

    Quick and dirty:

    #!/usr/bin/perl -w
    
    use strict;
    
    open(FILE, "</tmp/yourfile.txt") || die "File not found";
    my @lines = <FILE>;
    close(FILE);
    
    foreach(@lines) {
       $_ =~ s/<PREF>/ABCD/g;
    }
    
    open(FILE, ">/tmp/yourfile.txt") || die "File not found";
    print FILE @lines;
    close(FILE);
    

    Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

    On npm install: Unhandled rejection Error: EACCES: permission denied

    sudo npm cache clean --force --unsafe-perm
    

    and then npm i goes normally

    Loading state button in Bootstrap 3

    You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

    $("button").click(function() {
        var $btn = $(this);
        $btn.button('loading');
        // simulating a timeout
        setTimeout(function () {
            $btn.button('reset');
        }, 1000);
    });
    

    Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

    JSFIDDLE

    Official Documentation

    How to parse a JSON string into JsonNode in Jackson?

    A third variant:

    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readValue("{\"k1\":\"v1\"}", JsonNode.class);
    

    Kotlin: How to get and set a text to TextView in Android using Kotlin?

    Use textView.text for getter and setter, ex:

    val textView = findViewById<TextView>(R.id.textView)
    // Set text
    textView.text = "Hello World!"
    // Get text
    val textViewString = textView.text.toString()
    

    Disabling contextual LOB creation as createClob() method threw error

    Remove @Temporal annotations if you use it with java.sql.* classes.

    How do I base64 encode a string efficiently using Excel VBA?

    This code works very fast. It comes from here

    Option Explicit
    
    Private Const clOneMask = 16515072          '000000 111111 111111 111111
    Private Const clTwoMask = 258048            '111111 000000 111111 111111
    Private Const clThreeMask = 4032            '111111 111111 000000 111111
    Private Const clFourMask = 63               '111111 111111 111111 000000
    
    Private Const clHighMask = 16711680         '11111111 00000000 00000000
    Private Const clMidMask = 65280             '00000000 11111111 00000000
    Private Const clLowMask = 255               '00000000 00000000 11111111
    
    Private Const cl2Exp18 = 262144             '2 to the 18th power
    Private Const cl2Exp12 = 4096               '2 to the 12th
    Private Const cl2Exp6 = 64                  '2 to the 6th
    Private Const cl2Exp8 = 256                 '2 to the 8th
    Private Const cl2Exp16 = 65536              '2 to the 16th
    
    Public Function Encode64(sString As String) As String
    
        Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
        Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long
    
        For lTemp = 0 To 63                                 'Fill the translation table.
            Select Case lTemp
                Case 0 To 25
                    bTrans(lTemp) = 65 + lTemp              'A - Z
                Case 26 To 51
                    bTrans(lTemp) = 71 + lTemp              'a - z
                Case 52 To 61
                    bTrans(lTemp) = lTemp - 4               '1 - 0
                Case 62
                    bTrans(lTemp) = 43                      'Chr(43) = "+"
                Case 63
                    bTrans(lTemp) = 47                      'Chr(47) = "/"
            End Select
        Next lTemp
    
        For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
            lPowers8(lTemp) = lTemp * cl2Exp8
            lPowers16(lTemp) = lTemp * cl2Exp16
        Next lTemp
    
        iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
        If iPad Then                                        'If not, figure out the end pad and resize the input.
            iPad = 3 - iPad
            sString = sString & String(iPad, Chr(0))
        End If
    
        bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
        lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
        lTemp = lLen \ 72                                   'Added space for vbCrLfs.
        lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
        ReDim bOut(lOutSize)                                'Make the output buffer.
    
        lLen = 0                                            'Reusing this one, so reset it.
    
        For lChar = LBound(bIn) To UBound(bIn) Step 3
            lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
            lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
            bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
            lTemp = lTrip And clTwoMask                     'Mask for the second set.
            bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
            lTemp = lTrip And clThreeMask                   'Mask for the third set.
            bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
            bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
            If lLen = 68 Then                               'Ready for a newline
                bOut(lPos + 4) = 13                         'Chr(13) = vbCr
                bOut(lPos + 5) = 10                         'Chr(10) = vbLf
                lLen = 0                                    'Reset the counter
                lPos = lPos + 6
            Else
                lLen = lLen + 4
                lPos = lPos + 4
            End If
        Next lChar
    
        If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.
    
        If iPad = 1 Then                                    'Add the padding chars if any.
            bOut(lOutSize) = 61                             'Chr(61) = "="
        ElseIf iPad = 2 Then
            bOut(lOutSize) = 61
            bOut(lOutSize - 1) = 61
        End If
    
        Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.
    
    End Function
    
    Public Function Decode64(sString As String) As String
    
        Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
        Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
        Dim lTemp As Long
    
        sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
        sString = Replace(sString, vbLf, vbNullString)      'either order.
    
        lTemp = Len(sString) Mod 4                          'Test for valid input.
        If lTemp Then
            Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
        End If
    
        If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
            iPad = 2                                        'Note:  These translate to 0, so you can leave them...
        ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
            iPad = 1
        End If
    
        For lTemp = 0 To 255                                'Fill the translation table.
            Select Case lTemp
                Case 65 To 90
                    bTrans(lTemp) = lTemp - 65              'A - Z
                Case 97 To 122
                    bTrans(lTemp) = lTemp - 71              'a - z
                Case 48 To 57
                    bTrans(lTemp) = lTemp + 4               '1 - 0
                Case 43
                    bTrans(lTemp) = 62                      'Chr(43) = "+"
                Case 47
                    bTrans(lTemp) = 63                      'Chr(47) = "/"
            End Select
        Next lTemp
    
        For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
            lPowers6(lTemp) = lTemp * cl2Exp6
            lPowers12(lTemp) = lTemp * cl2Exp12
            lPowers18(lTemp) = lTemp * cl2Exp18
        Next lTemp
    
        bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
        ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.
    
        For lChar = 0 To UBound(bIn) Step 4
            lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                    lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
            lTemp = lQuad And clHighMask                    'Mask for the first byte
            bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
            lTemp = lQuad And clMidMask                     'Mask for the second byte
            bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
            bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
            lPos = lPos + 3
        Next lChar
    
        sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
        If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
        Decode64 = sOut
    
    End Function
    

    Create a branch in Git from another branch

    If you want to make a branch from some another branch then follow bellow steps:

    Assumptions:

    1. You are currently in master branch.
    2. You have no changes to commit. (If you have any changes to commit, stash it!).
    3. BranchExisting is the name of branch from which you need to make a new branch with name BranchMyNew.

    Steps:

    1. Fetch the branch to your local machine.

      $ git fetch origin BranchExisting : BranchExisting
      

    This command will create a new branch in your local with same branch name.

    1. Now, from master branch checkout to the newly fetched branch

      $ git checkout BranchExisting
      
    2. You are now in BranchExisting. Now create a new branch from this existing branch.

      $ git checkout -b BranchMyNew
      

    Here you go!

    How to import local packages in go?

    Local package is a annoying problem in go.

    For some projects in our company we decide not use sub packages at all.

    • $ glide install
    • $ go get
    • $ go install

    All work.

    For some projects we use sub packages, and import local packages with full path:

    import "xxxx.gitlab.xx/xxgroup/xxproject/xxsubpackage

    But if we fork this project, then the subpackages still refer the original one.

    How to check if a user likes my Facebook Page or URL using Facebook's API

    You can use (PHP)

    $isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
    

    That will return one of three:

    • string true string false json
    • formatted response of error if token
    • or page_id are not valid

    I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:

    function isFan(){
        global $facebook;
        $request = $facebook->getSignedRequest();
        return $request['page']['liked'];
    }
    

    Getting Google+ profile picture url with user_id

    Simple answer: No

    You will have to query the person API and the take the profile image.url data to get the photo. AFAIK there is no default format for that url that contains the userID.

    Git - Won't add files?

    It's impossible (for me) to add the first file to an empty repository cloned from GitHub. You need to follow the link README, that GitHub suggests to create. After you create your first file online, you can work normally with git.

    This happened to me Nov 17, 2016.

    How to pull specific directory with git

    After much looking for an answer, not finding, giving up, trying again and so on, I finally found a solution to this in another SO thread:

    How to git-pull all but one folder

    To copy-paste what's there:

    git init
    git remote add -f origin <url>
    git config core.sparsecheckout true
    echo <dir1>/ >> .git/info/sparse-checkout
    echo <dir2>/ >> .git/info/sparse-checkout
    echo <dir3>/ >> .git/info/sparse-checkout
    git pull origin master
    

    To do what OP wants (work on only one dir), just add that one dir to .git/info/sparse-checkout, when doing the steps above.

    Many many thanks to @cforbish !

    How to get html to print return value of javascript function?

    if you really wanted to do that you could then do

    <script type="text/javascript">
        document.write(produceMessage())
    </script>
    

    Wherever in the document you want the message.

    Copy/Paste from Excel to a web page

    Digging this up, in case anyone comes across it in the future. I used the above code as intended, but then ran into an issue displaying the table after it had been submitted to a database. It's much easier once you've stored the data to use PHP to replace the new lines and tabs in your query. You may perform the replace upon submission, $_POST[request] would be the name of your textarea:

    $postrequest = trim($_POST[request]);
    $dirty = array("\n", "\t");
    $clean = array('</tr><tr><td>', '</td><td>');
    $request = str_replace($dirty, $clean, $postrequest);
    

    Now just insert $request into your database, and it will be stored as an HTML table.

    JavaScript - Use variable in string match

    For example:

    let myString = "Hello World"
    let myMatch = myString.match(/H.*/)
    console.log(myMatch)
    

    Or

    let myString = "Hello World"
    let myVariable = "H"
    let myReg = new RegExp(myVariable + ".*")
    let myMatch = myString.match(myReg)
    console.log(myMatch)
    

    Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

    Go to Start and search for cmd. Right click on it, properties then set the Target path in quotes. This worked fine for me.

    Get min and max value in PHP Array

    <?php 
    $array = array (0 => 
      array (
        'id' => '20110209172713',
        'Date' => '2011-02-09',
        'Weight' => '200',
      ),
      1 => 
      array (
        'id' => '20110209172747',
        'Date' => '2011-02-09',
        'Weight' => '180',
      ),
      2 => 
      array (
        'id' => '20110209172827',
        'Date' => '2011-02-09',
        'Weight' => '175',
      ),
      3 => 
      array (
        'id' => '20110211204433',
        'Date' => '2011-02-11',
        'Weight' => '195',
      ),
    );
    
    foreach ($array as $key => $value) {
      $result[$key] = $value['Weight'];
    }
    $min = min($result);
    $max = max($result);
    
    echo " The array in Minnumum number :".$min."<br/>";
    echo " The array in Maximum  number :".$max."<br/>";
    ?> 
    

    Purpose of Activator.CreateInstance with example?

    The Activator.CreateInstance method creates an instance of a specified type using the constructor that best matches the specified parameters.

    For example, let's say that you have the type name as a string, and you want to use the string to create an instance of that type. You could use Activator.CreateInstance for this:

    string objTypeName = "Foo";
    Foo foo = (Foo)Activator.CreateInstance(Type.GetType(objTypeName));
    

    Here's an MSDN article that explains it's application in more detail:

    http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

    iOS: Compare two dates

    NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.

    NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setYear: 2011];
    [dateComponents setMonth: 5];
    [dateComponents setDay: 24];
    /*
     *  Construct two dates that bracket the day you are checking.  
     *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
     */
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
    NSDateComponents* oneDay = [[NSDateComponents alloc] init];
    [oneDay setDay: 1];
    NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
    /*
     *  Compare the date with the start of the day and the end of the day.
     */
    NSComparisonResult startCompare = [startOfDate compare: myDate];
    NSComparisonResult endCompare = [endOfDate compare: myDate];
    
    if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
    {
        // we are on the right date
    } 
    

    JavaScript Adding an ID attribute to another created Element

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

    myPara.id = ID;
    

    CodeIgniter htaccess and URL rewrite issues

    Just add this in the .htaccess file:

    DirectoryIndex index.php
    RewriteEngine on
    RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]
    

    How to split a dos path into its components in Python

    I'm not actually sure if this fully answers the question, but I had a fun time writing this little function that keeps a stack, sticks to os.path-based manipulations, and returns the list/stack of items.

    def components(path):
        ret = []
        while len(path) > 0:
            path, crust = split(path)
            ret.insert(0, crust)
        return ret
    

    Why are you not able to declare a class as static in Java?

    In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1]. A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C#, no such direct support exists in Java. You can however use enums to mimic C# static classes in Java so that a user can never create instances of a given class (even using reflection) [2]:

    public enum StaticClass2 {
        // Empty enum trick to avoid instance creation
        ; // this semi-colon is important
    
        public static boolean isEmpty(final String s) {
            return s == null || s.isEmpty();
        }
    }
    

    How to write a comment in a Razor view?

    Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

    Server side Comments:

    Razor .cshtml

    Like so:

    @* Comment goes here *@
    

    .aspx
    For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

    <%-- Comment goes here --%>
    

    Client Side Comments

    HTML Comment

    <!-- Comment goes here -->
    

    Javascript Comment

    // One line Comment goes Here
    /* Multiline comment
       goes here */
    

    As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

    What exactly is Spring Framework for?

    Very short summarized, I will say that Spring is the "glue" in your application. It's used to integrate different frameworks and your own code.

    Multiple Java versions running concurrently under Windows

    We can install multiple versions of Java Development kits on the same machine using SDKMan.

    Some points about SDKMan are as following:

    1. SDKMan is free to use and it is developed by the open source community.
    2. SDKMan is written in bash and it only requires curl and zip/unzip programs to be present on your system.
    3. SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.
    4. We do not need to worry about setting the _HOME and PATH environment variables because SDKMan handles it automatically.

    SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:

    $ curl -s "https://get.sdkman.io" | bash  
    $ source "$HOME/.sdkman/bin/sdkman-init.sh" 
    

    Because SDKMan is written in bash and only requires curl and zip/unzip to be present on your system. You can install SDKMan on windows as well either by first installing Cygwin or Git Bash for Windows environment and then running above commands.

    Command sdk list java will give us a list of java versions which we can install using SDKMan.

    Installing Java 8

    $ sdk install java 8.0.201-oracle
    

    Installing Java 9

    $ sdk install java 9.0.4-open 
    

    Installing Java 11

    $ sdk install java 11.0.2-open
    

    Uninstalling a Java version

    In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:

    $ sdk uninstall java 11.0.2-open
    

    Switching current Java version

    If you want to activate one version of JDK for all terminals and applications, you can use the command

    sdk default java <your-java_version>
    

    Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article How to Install Multiple Versions of Java on the Same Machine.

    What's the difference between <b> and <strong>, <i> and <em>?

    "They have the same effect. However, XHTML, a cleaner, newer version of HTML, recommends the use of the <strong> tag. Strong is better because it is easier to read - its meaning is clearer. Additionally, <strong> conveys a meaning - showing the text strongly - while <b> (for bold) conveys a method - bolding the text. With strong, your code still makes sense if you use CSS stylesheets to change what the methods of making the text strong is.

    The same goes for the difference between <i> and <em> ".

    Google dixit:

    http://wiki.answers.com/Q/What_is_the_difference_between_HTML_tags_b_and_strong

    How do I check that a Java String is not all whitespaces?

    If you are only checking for whitespace and don't care about null then you can use org.apache.commons.lang.StringUtils.isWhitespace(String str),

    StringUtils.isWhitespace(String str);

    (Checks if the String contains only whitespace.)

    If you also want to check for null(including whitespace) then

    StringUtils.isBlank(String str);
    

    JWT (JSON Web Token) library for Java

    If you only need to parse unsigned unencrypted tokens you could use this code:

    boolean parseJWT_2() {
        String authToken = getToken();
        String[] segments = authToken.split("\\.");
        String base64String = segments[1];
        int requiredLength = (int)(4 * Math.ceil(base64String.length() / 4.0));
        int nbrPaddings = requiredLength - base64String.length();
    
        if (nbrPaddings > 0) {
            base64String = base64String + "====".substring(0, nbrPaddings);
        }
    
        base64String = base64String.replace("-", "+");
        base64String = base64String.replace("_", "/");
    
        try {
            byte[] data = Base64.decode(base64String, Base64.DEFAULT);
    
            String text;
            text = new String(data, "UTF-8");
            tokenInfo = new Gson().fromJson(text, TokenInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    
        return true;
    }
    

    How can I make PHP display the error instead of giving me 500 Internal Server Error

    Be careful to check if

    display_errors
    

    or

    error_reporting
    

    is active (not a comment) somewhere else in the ini file.

    My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my

    display_errors = on;
    

    So remember the last one counts!

    How do I print the content of httprequest request?

    More details that help in logging

        String client = request.getRemoteAddr();
        logger.info("###### requested client: {} , Session ID : {} , URI :" + request.getMethod() + ":" + request.getRequestURI() + "", client, request.getSession().getId());
    
        Map params = request.getParameterMap();
        Iterator i = params.keySet().iterator();
        while (i.hasNext()) {
            String key = (String) i.next();
            String value = ((String[]) params.get(key))[0];
            logger.info("###### Request Param Name : {} , Value :  {} ", key, value);
        }
    

    How to put comments in Django templates

    Using the {# #} notation, like so:

    {# Everything you see here is a comment. It won't show up in the HTML output. #}
    

    Where is the php.ini file on a Linux/CentOS PC?

    #php -i | grep php.ini also will work too!

    Compile a DLL in C/C++, then call it from another program

    For VB6:

    You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:

    can I take arguments by pointer/reference from the VB front-end?

    Yes, use ByRef/ByVal modifiers.

    Can the DLL call a theoretical function in the front-end?

    Yes, use AddressOf statement. You need to pass function pointer to dll before.

    Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)

    Yes, use AddressOf statement.

    update (more questions appeared :)):

    to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?

    You need to decaler API function in VB6 code, like next:

    Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
       (ByVal hwndOwner As Long, _
        ByVal nFolder As Long, _
        ByRef pidl As Long) As Long
    

    Could not insert new outlet connection: Could not find any information for the class named

    Or if none of the above works, type out the name of the outlet into the file first @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! and then click and drag from the outlet in the nib to the variable you just programmatically created. It should work without any of the hassle of cleaning, building, and deleting anything.

    Delete all items from a c++ std::vector

    Is v.clear() not working for some reason?

    How to divide flask app into multiple py files?

    Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.

    I created a Gist with the code for doing this:

    https://gist.github.com/Jaza/61f879f577bc9d06029e

    As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:

    https://github.com/mitsuhiko/flask/issues/593

    Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.

    Vertical align text in block element

    DO NOT USE THE 4th solution from top if you are using ag-grid. It will fix the issue for aligning the element in middle but it might break the thing in ag-grid (for me i was not able to select checkbox after some row). Problem is not with the solution or ag-grid but somehow the combination is not good.

    DO NOT USE THIS SOLUTION FOR AG-GRID

    li a {
        width: 300px;
        height: 100px;
        margin: auto 0;
        display: inline-block;
        vertical-align: middle;
        background: red;  
    }
    
    li a:after {
        content:"";
        display: inline-block;
        width: 1px solid transparent;
        height: 100%;
        vertical-align: middle;
    }
    

    How to select different app.config for several build configurations

    After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

    This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

    Hope this helps.

    Detect Click into Iframe using JavaScript

    This works for me on all browsers (included Firefox)

    https://gist.github.com/jaydson/1780598

    https://jsfiddle.net/sidanmor/v6m9exsw/

    _x000D_
    _x000D_
    var myConfObj = {_x000D_
      iframeMouseOver : false_x000D_
    }_x000D_
    window.addEventListener('blur',function(){_x000D_
      if(myConfObj.iframeMouseOver){_x000D_
        console.log('Wow! Iframe Click!');_x000D_
      }_x000D_
    });_x000D_
    _x000D_
    document.getElementById('idanmorblog').addEventListener('mouseover',function(){_x000D_
       myConfObj.iframeMouseOver = true;_x000D_
    });_x000D_
    document.getElementById('idanmorblog').addEventListener('mouseout',function(){_x000D_
        myConfObj.iframeMouseOver = false;_x000D_
    });
    _x000D_
    <iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
    _x000D_
    _x000D_
    _x000D_

    <iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>

    How make background image on newsletter in outlook?

    The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.

    The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.

    <td bgcolor="#your_color" background="your_image.jpg">
    
    <!--[if gte mso 9]>
    
    <v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>
    
    <v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>
    
    <![endif]-->
    
    <p>Text over background image.</p>
    
    <!--[if gte mso 9]>
    
    </v:shape>
    
    <![endif]-->
    
    </td>
    

    source

    String length in bytes in JavaScript

    Took me a while to find a solution for React Native so I'll put it here:

    First install the buffer package:

    npm install --save buffer
    

    Then user the node method:

    const { Buffer } = require('buffer');
    const length = Buffer.byteLength(string, 'utf-8');
    

    Nginx 403 forbidden for all files

    One permission requirement that is often overlooked is a user needs x permissions in every parent directory of a file to access that file. Check the permissions on /, /home, /home/demo, etc. for www-data x access. My guess is that /home is probably 770 and www-data can't chdir through it to get to any subdir. If it is, try chmod o+x /home (or whatever dir is denying the request).

    EDIT: To easily display all the permissions on a path, you can use namei -om /path/to/check

    How can I lock a file using java (if possible)

    Use a RandomAccessFile, get it's channel, then call lock(). The channel provided by input or output streams does not have sufficient privileges to lock properly. Be sure to call unlock() in the finally block (closing the file doesn't necessarily release the lock).

    Simplest Way to Test ODBC on WIndows

    a simple way is:

    create a fake "*.UDL" file on desktop

    (UDL files are described here: https://msdn.microsoft.com/en-us/library/e38h511e(v=vs.71).aspx.

    in case you can also customized it as explained there. )

    Passing an array/list into a Python function

    When you define your function using this syntax:

    def someFunc(*args):
        for x in args
            print x
    

    You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

    def someFunc(myList = [], *args):
        for x in myList:
            print x
    

    Then you can call it with this:

    items = [1,2,3,4,5]
    
    someFunc(items)
    

    You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

    def someFunc(arg1, arg2, arg3, *args, **kwargs):
        for x in args
            print x
    

    Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

    Draw radius around a point in Google map

    I've had this problem in the past, so I bookmarked this discussion.

    To summarize it, you can:

    1. Take a look at this circle filter's source code and figure out how to incorporate it into your project.
    2. Draw a GPolygon with enough points to simulate a circle.
    3. Generate a KML file by modifying http://www.nearby.org.uk/google/circle.kml.php?radius=30miles&lat=40.173&long=-105.1024 and then importing it. In Google Maps, you can just paste the URI in the search box and it will display on the map. I'm not sure how you might do it using the API though.

    Why does the JFrame setSize() method not set the size correctly?

    I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.

    Using this

    setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));
    

    But this always work in any size:

    setSize(width + 14, height + 7);
    

    If you don't want the border to border, and only want the white area, here:

    setSize(width + 16, height + 39);
    

    Also this only works on Windows 10, for MacOS users, use @ben's answer.

    node.js: cannot find module 'request'

    I was running into the same problem, here is how I got it working..

    open terminal:

    mkdir testExpress
    cd testExpress
    npm install request
    

    or

    sudo npm install -g request // If you would like to globally install.
    

    now don't use

    node app.js or node test.js, you will run into this problem doing so. You can also print the problem that is being cause by using this command.. "node -p app.js"

    The above command to start nodeJs has been deprecated. Instead use

    npm start
    

    You should see this..

    [email protected] start /Users/{username}/testExpress
    node ./bin/www
    

    Open your web browser and check for localhost:3000

    You should see Express install (Welcome to Express)

    In Android EditText, how to force writing uppercase?

    In kotlin, in .kt file make changes:

    edit_text.filters = edit_text.filters + InputFilter.AllCaps()
    

    Use synthetic property for direct access of widget with id. And in XML, for your edit text add a couple of more flag as:

    <EditText
        android:id="@+id/edit_text_qr_code"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ...other attributes...
        android:textAllCaps="true"
        android:inputType="textCapCharacters"
        />
    

    This will update the keyboard as upper case enabled.

    How to disable RecyclerView scrolling?

    Just add this to your recycleview in xml

     android:nestedScrollingEnabled="false"
    

    like this

    <android.support.v7.widget.RecyclerView
                        android:background="#ffffff"
                        android:id="@+id/myrecycle"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:nestedScrollingEnabled="false">
    

    react hooks useEffect() cleanup for only componentWillUnmount?

    function LegoComponent() {
    
      const [lego, setLegos] = React.useState([])
    
      React.useEffect(() => {
        let isSubscribed = true
        fetchLegos().then( legos=> {
          if (isSubscribed) {
            setLegos(legos)
          }
        })
        return () => isSubscribed = false
      }, []);
    
      return (
        <ul>
        {legos.map(lego=> <li>{lego}</li>)}
        </ul>
      )
    }
    

    In the code above, the fetchLegos function returns a promise. We can “cancel” the promise by having a conditional in the scope of useEffect, preventing the app from setting state after the component has unmounted.

    Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

    How to count digits, letters, spaces for a string in Python?

    INPUT :

    1

    26

    sadw96aeafae4awdw2 wd100awd

    import re
    
    a=int(input())
    for i in range(a):
        b=int(input())
        c=input()
    
        w=re.findall(r'\d',c)
        x=re.findall(r'\d+',c)
        y=re.findall(r'\s+',c)
        z=re.findall(r'.',c)
        print(len(x))
        print(len(y))
        print(len(z)-len(y)-len(w))
    

    OUTPUT :

    4

    1

    19

    The four digits are 96, 4, 2, 100 The number of spaces = 1 number of letters = 19

    What does request.getParameter return?

    Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

    If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

    <c:if test='${not empty param.foo}'>
        This page code gets rendered.
    </c:if>
    

    How to know function return type and argument types?

    Yes, you should use docstrings to make your classes and functions more friendly to other programmers:

    More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring

    Some editors allow you to see docstrings while typing, so it really makes work easier.

    Getting All Variables In Scope

    No. "In scope" variables are determined by the "scope chain", which is not accessible programmatically.

    For detail (quite a lot of it), check out the ECMAScript (JavaScript) specification. Here's a link to the official page where you can download the canonical spec (a PDF), and here's one to the official, linkable HTML version.

    Update based on your comment to Camsoft

    The variables in scope for your event function are determined by where you define your event function, not how they call it. But, you may find useful information about what's available to your function via this and arguments by doing something along the lines of what KennyTM pointed out (for (var propName in ____)) since that will tell you what's available on various objects provided to you (this and arguments; if you're not sure what arguments they give you, you can find out via the arguments variable that's implicitly defined for every function).

    So in addition to whatever's in-scope because of where you define your function, you can find out what else is available by other means by doing:

    var n, arg, name;
    alert("typeof this = " + typeof this);
    for (name in this) {
        alert("this[" + name + "]=" + this[name]);
    }
    for (n = 0; n < arguments.length; ++n) {
        arg = arguments[n];
        alert("typeof arguments[" + n + "] = " + typeof arg);
        for (name in arg) {
            alert("arguments[" + n + "][" + name + "]=" + arg[name]);
        }
    }
    

    (You can expand on that to get more useful information.)

    Instead of that, though, I'd probably use a debugger like Chrome's dev tools (even if you don't normally use Chrome for development) or Firebug (even if you don't normally use Firefox for development), or Dragonfly on Opera, or "F12 Developer Tools" on IE. And read through whatever JavaScript files they provide you. And beat them over the head for proper docs. :-)

    what is the use of xsi:schemaLocation?

    If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

    How to count the number of set bits in a 32-bit integer?

    I'm very disappointed to see that nobody has responded with the functional master race recursive solution, by far the purest one (and can be used with any bit length!):

    template<typename T>
    int popcnt(T n)
    {
      if (n>0)
        return n&1 + popcnt(n>>1);
      return 0; 
    }
    

    How to get current user who's accessing an ASP.NET application?

    The general consensus answer above seems to have have a compatibility issue with CORS support. In order to use the HttpContext.Current.User.Identity.Name attribute you must disable anonymous authentication in order to force Windows authentication to provide the authenticated user information. Unfortunately, I believe you must have anonymous authentication enabled in order to process the pre-flight OPTIONS request in a CORS scenario.

    You can get around this by leaving anonymous authentication enabled and using the HttpContext.Current.Request.LogonUserIdentity attribute instead. This will return the authenticated user information (assuming you are in an intranet scenario) even with anonymous authentication enabled. The attribute returns a WindowsUser data structure and both are defined in the System.Web namespace

            using System.Web;
            WindowsIdentity user;
            user  = HttpContext.Current.Request.LogonUserIdentity;
    

    WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

    I solved this by changing transports from 'websocket' to 'polling'

       var socket = io.connect('xxx.xxx.xxx.xxx:8000', {
          transports: ['polling']
       });
    

    What is the JUnit XML format specification that Hudson supports?

    I've decided to post a new answer, because some existing answers are outdated or incomplete.

    First of all: there is nothing like JUnit XML Format Specification, simply because JUnit doesn't produce any kind of XML or HTML report.

    The XML report generation itself comes from the Ant JUnit task/ Maven Surefire Plugin/ Gradle (whichever you use for running your tests). The XML report format was first introduced by Ant and later adapted by Maven (and Gradle).

    If somebody just needs an official XML format then:

    1. There exists a schema for a maven surefire-generated XML report and it can be found here: surefire-test-report.xsd.
    2. For an ant-generated XML there is a 3rd party schema available here (but it might be slightly outdated).

    Hope it will help somebody.

    Disable color change of anchor tag when visited

    Either delete the selector or set it to the same color as your text appears normally.

    CSS transition between left -> right and top -> bottom positions

    This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.

    topleft {
      top: 0%;
      left: 0%;
    }
    bottomright {
      top: 100%;
      left: 100%;
      -webkit-transform: translate(-100%,-100%);
    }
    

    Kill all processes for a given user

    Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!

    pkill -9 -u `id -u username`
    

    Note: if you want to be nice remove -9, but it will not kill all kinds of processes.

    Convert PEM to PPK file format

    If you have Linux machine just install puttygen in your system and use use below command to convert the key

    pem to ppk use below command:

    puttygen keyname -o keyname.ppk

    Below command is use to convert ppk to pem not pem to ppk

    puttygen filename.ppk -O private-openssh -o filename.pem

    Difference between jQuery’s .hide() and setting CSS to display: none

    See there is no difference if you use basic hide method. But jquery provides various hide method which give effects to the element. Refer below link for detailed explanation: Effects for Hide in Jquery

    Disable LESS-CSS Overwriting calc()

    Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

    With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

    width: calc(100% - 200px);
    

    Would work as expected with the strict math option enabled.

    However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

    font-size: 12px + 2px;
    

    The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

    font-size: (12px + 2px);
    

    Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

    Display progress bar while doing some work in C#?

    I have to throw the simplest answer out there. You could always just implement the progress bar and have no relationship to anything of actual progress. Just start filling the bar say 1% a second, or 10% a second whatever seems similar to your action and if it fills over to start again.

    This will atleast give the user the appearance of processing and make them understand to wait instead of just clicking a button and seeing nothing happen then clicking it more.

    Node.js/Express.js App Only Works on Port 3000

    I am using the minimist package and the node startup arguments to control the port.

    node server.js --port 4000

    or

    node server.js -p 4000

    Inside server.js, the port can be determined by

    var argv = parseArgs(process.argv.slice(2))
    
    const port = argv.port || argv.p || 3000;
    console.log(`Listening on port ${port}...`)
    
    //....listen(port);
    

    and it defaults to 3000 if no port is passed as an argument.

    You can then use listen on the port variable.

    How to select rows with no matching entry in another table?

    Where T2 is the table to which you're adding the constraint:

    SELECT *
    FROM T2
    WHERE constrained_field NOT
    IN (
        SELECT DISTINCT t.constrained_field
        FROM T2 
        INNER JOIN T1 t
        USING ( constrained_field )
    )
    

    And delete the results.

    Remove title in Toolbar in appcompat-v7

    The reason for my answer on this is because the most upvoted answer itself failed to solve my problem. I have figured out this problem by doing this.

    <activity android:name="NAME OF YOUR ACTIVITY"
        android:label="" />
    

    Hope this will help others too.

    Search a text file and print related lines in Python?

    searchfile = open("file.txt", "r")
    for line in searchfile:
        if "searchphrase" in line: print line
    searchfile.close()
    

    To print out multiple lines (in a simple way)

    f = open("file.txt", "r")
    searchlines = f.readlines()
    f.close()
    for i, line in enumerate(searchlines):
        if "searchphrase" in line: 
            for l in searchlines[i:i+3]: print l,
            print
    

    The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

    Or better yet (stealing back from Mark Ransom):

    with open("file.txt", "r") as f:
        searchlines = f.readlines()
    for i, line in enumerate(searchlines):
        if "searchphrase" in line: 
            for l in searchlines[i:i+3]: print l,
            print
    

    RegExp in TypeScript

    I think you want to test your RegExp in TypeScript, so you have to do like this:

    var trigger = "2",
        regexp = new RegExp('^[1-9]\d{0,2}$'),
        test = regexp.test(trigger);
    alert(test + ""); // will display true
    

    You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

    Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

    Copying text to the clipboard using Java

    The following class allows you to copy/paste a String to/from the clipboard.

    import java.awt.*;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.StringSelection;
    
    import static java.awt.event.KeyEvent.*;
    import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;
    
    public class SystemClipboard
    {
        public static void copy(String text)
        {
            Clipboard clipboard = getSystemClipboard();
            clipboard.setContents(new StringSelection(text), null);
        }
    
        public static void paste() throws AWTException
        {
            Robot robot = new Robot();
    
            int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
            robot.keyPress(controlKey);
            robot.keyPress(VK_V);
            robot.keyRelease(controlKey);
            robot.keyRelease(VK_V);
        }
    
        public static String get() throws Exception
        {
            Clipboard systemClipboard = getSystemClipboard();
            DataFlavor dataFlavor = DataFlavor.stringFlavor;
    
            if (systemClipboard.isDataFlavorAvailable(dataFlavor))
            {
                Object text = systemClipboard.getData(dataFlavor);
                return (String) text;
            }
    
            return null;
        }
    
        private static Clipboard getSystemClipboard()
        {
            Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
            return defaultToolkit.getSystemClipboard();
        }
    }
    

    How to "add existing frameworks" in Xcode 4?

    Another easy way to do it so that it is referenced in the project folder you want, like "Frameworks", is to:

    1. Select "Show the Project navigator"
    2. Right-click on the project folder you wish to add the framework to.
    3. Select 'Add Files to "YourProjectName"'
    4. Browse to the framework - generally under /Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks
    5. Select the one you want.
    6. Select "Add"

    It will appear in both the project navigator where you want it, as well as in the "Link Binary With Libraries" area of the "Build Phases" pane of your target.