Programs & Examples On #Nautilus

Nautilus is the official file manager and desktop shell for the GNOME desktop. Nautilus is is extensible via C and Python.

How do I change file permissions in Ubuntu

If you just want to change file permissions, you want to be careful about using -R on chmod since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:

sudo chmod -R a+w /var/www

But if you want to use the literal permissions of read/write, you may want to select files versus folders:

sudo find /var/www -type f -exec chmod 666 {} \;

(Which, by the way, for security reasons, I wouldn't recommend either of these.)

Or for folders:

sudo find /var/www -type d -exec chmod 755 {} \;

What does set -e mean in a bash script?

set -e stops the execution of a script if a command or pipeline has an error - which is the opposite of the default shell behaviour, which is to ignore errors in scripts. Type help set in a terminal to see the documentation for this built-in command.

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

Have log4net use application config file for configuration data

Add a line to your app.config in the configSections element

<configSections>
 <section name="log4net" 
   type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, 
         Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>

Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...

<log4net configSource="Config\Log4Net.config" />

In your application code, when you create the log, write

private static ILog GetLog(string logName)
{
    ILog log = LogManager.GetLogger(logName);
    return log;
}

Calculate last day of month in JavaScript

This works for me. Will provide last day of given year and month:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);

How to change XAMPP apache server port?

The best solution is to reconfigure the XAMPP Apache server to listen and use different port numbers. Here is how you do it:

1) First, you need to open the Apache “httpd.conf” file and configure it to use/listen on a new port no. To open httpd.conf file, click the “Config” button next to Apache “Start” and “Admin” buttons. In the popup menu that opens, click and open httpd.conf

2) Within the httpd.conf file search for “listen”. You’ll find two rows with something like:

#Listen 12.34.56.78:80
Listen 80

Change the port no to a port no. of your choice (e.g. port 1234) like below

#Listen 12.34.56.78:1234
Listen 1234

3) Next, in the same httpd.conf file look for “ServerName localhost:” Set it to the new port no.

ServerName localhost:1234

4) Save and close the httpd.conf file.

5) Now click the Apache config button again and open the “httpd-ssl.conf” file.

6) In the httpd-ssl.conf file, look for “Listen” again. You may find:

Listen 443

Change it to listen on a new port no of your choice. Say like:

Listen 1443

7) In the same httpd-ssl.conf file find another line that says <VirtualHost _default_:443>. Change this to your new port no. (like 1443)

8) Also in the same httpd-ssl.conf you can find another line defining the port no. For that look for “ServerName”. you might find something like:

ServerName www.example.com:443 or  ServerName localhost:433

Change this ServerName to your new port no.

8) Save and close the httpd-ssl.conf file.

9) Finally, there’s just one more place you should change the port no. For that, click and open the “Config” button of your XAMPP Control Panel. Then click the, “Service and Port Settings” button. Within it, click the “Apache” tab and enter and save the new port nos in the “main port” and “SSL port” boxes. Click save and close the config boxes.

That should do the trick. Now “Start” Apache and if everything goes well, your Apache server should start up.

You will also see the Apache Port/s no in the XAMPP control panel has change to the new port IDs you set.

How can I set the focus (and display the keyboard) on my EditText programmatically

editTxt.setOnFocusChangeListener { v, hasFocus ->
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (hasFocus) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
            } else {
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }

Convert from days to milliseconds

You can use this utility class -

public class DateUtils
{
    public static final long SECOND_IN_MILLIS = 1000;
    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
    public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
}

If you are working on Android framework then just import it (also named DateUtils) under package android.text.format

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

Convert LocalDate to LocalDateTime or java.sql.Timestamp

The best way use Java 8 time API:

  LocalDateTime ldt = timeStamp.toLocalDateTime();
  Timestamp ts = Timestamp.valueOf(ldt);

For use with JPA put in with your model (https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa):

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
        return Timestamp.valueOf(ldt);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp ts) {
        return ts.toLocalDateTime();
    }
}

So now it is relative timezone independent time. Additionally it is easy do:

  LocalDate ld = ldt.toLocalDate();
  LocalTime lt = ldt.toLocalTime();

Formatting:

 DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
 String str = ldt.format(DATE_TME_FORMATTER);
 ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);

UPDATE: postgres 9.4.1208, HSQLDB 2.4.0 etc understand Java 8 Time API without any conversations!

Jquery: how to trigger click event on pressing enter key

You were almost there. Here is what you can try though.

$(function(){
  $("#txtSearchProdAssign").keyup(function (e) {
    if (e.which == 13) {
      $('input[name="butAssignProd"]').trigger('click');
    }
  });
});

I have used trigger() to execute click and bind it on the keyup event insted of keydown because click event comprises of two events actually i.e. mousedown then mouseup. So to resemble things same as possible with keydown and keyup.

Here is a Demo

java- reset list iterator to first element of the list

What you may actually want to use is an Iterable that can return a fresh Iterator multiple times by calling iterator().

//A function that needs to iterate multiple times can be given one Iterable:
public void func(Iterable<Type> ible) {
    Iterator<Type> it = ible.iterator(); //Gets an iterator
    while (it.hasNext()) {
        it.next();
    }
    it = ible.iterator(); //Gets a NEW iterator, also from the beginning
    while (it.hasNext()) {
        it.next();
    }
}

You must define what the iterator() method does just once beforehand:

void main() {
    LinkedList<String> list; //This could be any type of object that has an iterator
    //Define an Iterable that knows how to retrieve a fresh iterator
    Iterable<Type> ible = new Iterable<Type>() {
        @Override
        public Iterator<Type> iterator() {
            return list.listIterator(); //Define how to get a fresh iterator from any object
        }
    };
    //Now with a single instance of an Iterable,
    func(ible); //you can iterate through it multiple times.
}

How to add a search box with icon to the navbar in Bootstrap 3?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <meta name="description" content="">_x000D_
    <meta name="author" content="">_x000D_
_x000D_
    <title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
    <!-- Bootstrap Core CSS -->_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <!-- Navigation -->_x000D_
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
        <div class="container">_x000D_
            <!-- Brand and toggle get grouped for better mobile display -->_x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
            </div>_x000D_
            <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li>_x000D_
                        <a href="#">About</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Services</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Contact</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
                <form class="navbar-form navbar-right">_x000D_
                    <div class="input-group">_x000D_
                        <input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
                        <span class="input-group-btn">_x000D_
                            <button class="btn btn-default">Go</button>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </form>_x000D_
            </div>_x000D_
            <!-- /.navbar-collapse -->_x000D_
        </div>_x000D_
        <!-- /.container -->_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content -->_x000D_
    <div class="container">_x000D_
_x000D_
        <!-- Page Header -->_x000D_
        <div class="row">_x000D_
            <div class="col-lg-12">_x000D_
                <h1 class="page-header">Page Heading_x000D_
                    <small>Secondary Text</small>_x000D_
                </h1>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <hr>_x000D_
_x000D_
        <!-- Pagination -->_x000D_
        <div class="row text-center">_x000D_
            <div class="col-lg-12">_x000D_
                <ul class="pagination">_x000D_
                    <li>_x000D_
                        <a href="#">&laquo;</a>_x000D_
                    </li>_x000D_
                    <li class="active">_x000D_
                        <a href="#">1</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">2</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">3</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">4</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">5</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">&raquo;</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </div>_x000D_
    <!-- Footer -->_x000D_
    <footer>_x000D_
        <div class="container">_x000D_
            <div class="row">_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>About</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Support</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Terms of Service</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Privacy policy</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Warranty commitment</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Site map</a>_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Other</h3>_x000D_
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </footer>_x000D_
_x000D_
    <!-- /.container -->_x000D_
_x000D_
    <!-- jQuery -->_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
    <!-- Bootstrap Core JavaScript -->_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

how to check if List<T> element contains an item with a Particular Property Value

If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex instance method. Such as

int index = list.FindIndex(f => f.Bar == 17);

Where f => f.Bar == 17 is a predicate with the matching criteria.

In your case you might write

int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0) 
{
    // element exists, do what you need
}

Merge or combine by rownames

Not perfect but close:

newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)

How to split a string content into an array of strings in PowerShell?

[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)

Spring @Value is not resolving to value from property file

Please note that if you have multiple application.properties files throughout your codebase, then try adding your value to the parent project's property file.

You can check your project's pom.xml file to identify what the parent project of your current project is.

Alternatively, try using environment.getProperty() instead of @Value.

git: fatal: I don't handle protocol '??http'

Well looks like if you copy paste the repository link you end up with this issue.

What I have noticed it this

  1. If you use the copy button on GitHub and then paste the URL in GitBash(Windows) it throws this error
  2. If you select the link and then paste then it works, or you could also just type the URL that works as well.

So I think it might be an issue with the GitHub copy button

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

The -i flag specifies the private key (.pem file) to use. If you don't specify that flag (as in your first command) it will use your default ssh key (usually under ~/.ssh/).

So in your first command, you are actually asking scp to upload the .pem file itself using your default ssh key. I don't think that is what you want.

Try instead with:

scp -r -i /Applications/XAMPP/htdocs/keypairfile.pem uploads/* ec2-user@publicdns:/var/www/html/uploads

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).

With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.

There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.

Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

What's the meaning of System.out.println in Java?

System is a class in java.lang package.

out is the static data member in System class and reference variable of PrintStream class.

Println() is a normal (overloaded) method of PrintStream class.

Best practices with STDIN in Ruby?

I'll add that in order to use ARGF with parameters, you need to clear ARGV before calling ARGF.each. This is because ARGF will treat anything in ARGV as a filename and read lines from there first.

Here's an example 'tee' implementation:

File.open(ARGV[0], 'w') do |file|
  ARGV.clear

  ARGF.each do |line|
    puts line
    file.write(line)
  end
end

A div with auto resize when changing window width\height

Code Snippet:

div{height: calc(100vh - 10vmax)}

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL 9.2 and above, to disconnect everything except your session from the database you are connected to:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid();

In older versions it's the same, just change pid to procpid. To disconnect from a different database just change current_database() to the name of the database you want to disconnect users from.

You may want to REVOKE the CONNECT right from users of the database before disconnecting users, otherwise users will just keep on reconnecting and you'll never get the chance to drop the DB. See this comment and the question it's associated with, How do I detach all other users from the database.

If you just want to disconnect idle users, see this question.

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

I had this problem to install laravel/lumen.

It can be resolved with the following command:

$ sudo chown -R $USER ~/.composer/

IDEA: javac: source release 1.7 requires target release 1.7

I've found required options ('target bytecode version') in settings > compiler > java compiler in my case (intelij idea 12.1.3)

Found a swap file by the name

More info... Some times .swp files might be holded by vm that was running in backgroung. You may see permission denied message when try to delete the files.

Check and kill process vm

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Git submodule head 'reference is not a tree' error

Just to be sure, try updating your git binaries.

GitHub for Windows has the version git version 1.8.4.msysgit.0 which in my case was the problem. Updating solved it.

Check line for unprintable characters while reading text file

The answer by @T.J.Crowder is Java 6 - in java 7 the valid answer is the one by @McIntosh - though its use of Charset for name for UTF -8 is discouraged:

List<String> lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
    StandardCharsets.UTF_8);
for(String line: lines){ /* DO */ }

Reminds a lot of the Guava way posted by Skeet above - and of course same caveats apply. That is, for big files (Java 7):

BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {}

Best C++ IDE or Editor for Windows

I think the anwser to this question depends on following question: Do you want to develop cross-platform applications ?
If the anwser to this question is a clear YES, than you should start right away with some IDE that support cross-platform compilers like gcc/mingw.

Personally ive tried CodeBlocks and QtCreator beside VS... If developing cross-platform software using Qt, surely QtCreator is the best choice. Since QtCreator is still a quite new IDE, it still has some bugs... for example it's "intelli-sense" doesnt support namespace aliaces yet.. but i think it will evolve pretty fast, to a very good and complete IDE.
Codeblocks is a quite "small" IDE, but has everything an IDE needs. Still its "Intelli-Sense" (especially when dealing with meta-programming stuff like boost), and debugger is less powerful than VS's.

Dictionary returning a default value if the key does not exist

I created a DefaultableDictionary to do exactly what you are asking for!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace DefaultableDictionary {
    public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
        private readonly IDictionary<TKey, TValue> dictionary;
        private readonly TValue defaultValue;

        public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
            this.dictionary = dictionary;
            this.defaultValue = defaultValue;
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
            return dictionary.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Add(KeyValuePair<TKey, TValue> item) {
            dictionary.Add(item);
        }

        public void Clear() {
            dictionary.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item) {
            return dictionary.Contains(item);
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
            dictionary.CopyTo(array, arrayIndex);
        }

        public bool Remove(KeyValuePair<TKey, TValue> item) {
            return dictionary.Remove(item);
        }

        public int Count {
            get { return dictionary.Count; }
        }

        public bool IsReadOnly {
            get { return dictionary.IsReadOnly; }
        }

        public bool ContainsKey(TKey key) {
            return dictionary.ContainsKey(key);
        }

        public void Add(TKey key, TValue value) {
            dictionary.Add(key, value);
        }

        public bool Remove(TKey key) {
            return dictionary.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value) {
            if (!dictionary.TryGetValue(key, out value)) {
                value = defaultValue;
            }

            return true;
        }

        public TValue this[TKey key] {
            get
            {
                try
                {
                    return dictionary[key];
                } catch (KeyNotFoundException) {
                    return defaultValue;
                }
            }

            set { dictionary[key] = value; }
        }

        public ICollection<TKey> Keys {
            get { return dictionary.Keys; }
        }

        public ICollection<TValue> Values {
            get
            {
                var values = new List<TValue>(dictionary.Values) {
                    defaultValue
                };
                return values;
            }
        }
    }

    public static class DefaultableDictionaryExtensions {
        public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
            return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
        }
    }
}

This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.

The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.

Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);

Blog post on the usage as well.

Getting Checkbox Value in ASP.NET MVC 4

For multiple checkbox with same name... Code to remove unnecessary false :

List<string> d_taxe1 = new List<string>(Request.Form.GetValues("taxe1"));
d_taxe1 = form_checkbox.RemoveExtraFalseFromCheckbox(d_taxe1);

Function

public class form_checkbox
{

    public static List<string> RemoveExtraFalseFromCheckbox(List<string> val)
    {
        List<string> d_taxe1_list = new List<string>(val);

        int y = 0;

        foreach (string cbox in val)
        {

            if (val[y] == "false")
            {
                if (y > 0)
                {
                    if (val[y - 1] == "true")
                    {
                        d_taxe1_list[y] = "remove";
                    }
                }

            }

            y++;
        }

        val = new List<string>(d_taxe1_list);

        foreach (var del in d_taxe1_list)
            if (del == "remove") val.Remove(del);

        return val;

    }      



}

Use it :

int x = 0;
foreach (var detail in d_prix){
factured.taxe1 = (d_taxe1[x] == "true") ? true : false;
x++;
}

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following for loop you are comparing string to bytes and that is where the code is failing.

Decoding the bytes while adding to the list should work. The changed code should look as follows:

with open(fname, 'rb') as f:
    lines = [x.decode('utf8').strip() for x in f.readlines()]

The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:

>>> s=bytes('hello')
>>> type(s)
<type 'str'>

Call static method with reflection

Class that will call the methods:

namespace myNamespace
{
    public class myClass
    {
        public static void voidMethodWithoutParameters()
        {
            // code here
        }
        public static string stringReturnMethodWithParameters(string param1, string param2)
        {
            // code here
            return "output";
        }
    }
}

Calling myClass static methods using Reflection:

var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
                    
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());

Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static.

Great resources:

How to use bootstrap datepicker

Just add this below JS file

<script type="text/javascript">
    $(document).ready(function () {
        $('your input's id or class with # or .').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

C# string replace

Use:

line.Replace(@""",""", ";");

What is the reason behind "non-static method cannot be referenced from a static context"?

If we try to access an instance method from a static context , the compiler has no way to guess which instance method ( variable for which object ), you are referring to. Though, you can always access it using an object reference.

How to create a blank/empty column with SELECT query in oracle?

I guess you will get ORA-01741: illegal zero-length identifier if you use the following

SELECT "" AS Contact  FROM Customers;

And if you use the following 2 statements, you will be getting the same null value populated in the column.

SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;

How can I increase the size of a bootstrap button?

You can try to use btn-sm, btn-xs and btn-lg classes like this:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
}

JSFIDDLE DEMO

You can make use of Bootstrap .btn-group-justified css class. Or you can simply add:

.btn-xl {
    padding: 10px 20px;
    font-size: 20px;
    border-radius: 10px;
    width:50%;    //Specify your width here
}

JSFIDDLE DEMO

Send POST data via raw json with postman

Install Postman native app, Chrome extension has been deprecated. (Mine was opening in own window but still ran as Chrome app)

SQL: sum 3 columns when one column has a null value?

The previous answers using the ISNULL function are correct only for MS Sql Server. The COALESCE function will also work in SQL Server. But will also work in standard SQL database systems. In the given example:

SELECT sum(COALESCE(TotalHoursM,0))
          + COALESCE(TotalHoursT,0)
          + COALESCE(TotalHoursW,0)
          + COALESCE(TotalHoursTH,0)
          + COALESCE(TotalHoursF,0) AS TOTAL FROM LeaveRequest

This is identical to the ISNULL solution with the only difference being the name of the function. Both work in SQL Server but, COALESCE is ANSI standard and ISNULL is not. Also, COALESCE is more flexible. ISNULL will only work with two parameters. If the first parameter is NULL then the value of the second parameter is returned, else the value of the first is returned. COALESCE will take 2 to 'n' (I don't know the limit of 'n') parameters and return the value of the first parameter that is not NULL. When there are only two parameters the effect is the same as ISNULL.

Does MySQL foreign_key_checks affect the entire database?

In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0; does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17

Adding a line break in MySQL INSERT INTO text

For the record, I wanted to add some line breaks into existing data and I got \n to work ok...

Sample data:

Sentence. Sentence. Sentence

I did:

UPDATE table SET field = REPLACE(field, '. ', '.\r\n')

However, it also worked with just \r and just \n.

How can I debug git/git-shell related problems?

try this one:

GIT_TRACE=1 git pull origin master

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

Xpath: select div that contains class AND whose specific child element contains text

To find a div of a certain class that contains a span at any depth containing certain text, try:

//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]

That said, this solution looks extremely fragile. If the table happens to contain a span with the text you're looking for, the div containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.

What is use of c_str function In c++

c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).

Converting Decimal to Binary Java

The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function

private static int decimalToBinary(int N) {
    StringBuilder builder = new StringBuilder();
    int base = 2;
    while (N != 0) {
        int reminder = N % base;
        builder.append(reminder);
        N = N / base;
    }

    return Integer.parseInt(builder.reverse().toString());
}

What's the best way to iterate an Android Cursor?

How about using foreach loop:

Cursor cursor;
for (Cursor c : CursorUtils.iterate(cursor)) {
    //c.doSth()
}

However my version of CursorUtils should be less ugly, but it automatically closes the cursor:

public class CursorUtils {
public static Iterable<Cursor> iterate(Cursor cursor) {
    return new IterableWithObject<Cursor>(cursor) {
        @Override
        public Iterator<Cursor> iterator() {
            return new IteratorWithObject<Cursor>(t) {
                @Override
                public boolean hasNext() {
                    t.moveToNext();
                    if (t.isAfterLast()) {
                        t.close();
                        return false;
                    }
                    return true;
                }
                @Override
                public Cursor next() {
                    return t;
                }
                @Override
                public void remove() {
                    throw new UnsupportedOperationException("CursorUtils : remove : ");
                }
                @Override
                protected void onCreate() {
                    t.moveToPosition(-1);
                }
            };
        }
    };
}

private static abstract class IteratorWithObject<T> implements Iterator<T> {
    protected T t;
    public IteratorWithObject(T t) {
        this.t = t;
        this.onCreate();
    }
    protected abstract void onCreate();
}

private static abstract class IterableWithObject<T> implements Iterable<T> {
    protected T t;
    public IterableWithObject(T t) {
        this.t = t;
    }
}
}

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

How to print strings with line breaks in java

Adding /r/n between the Strings solved the problem for me. give it a try. On pasting dont include the '//' for excluding.

Eg: Option01\r\nOption02\r\nOption03

this will give output as
Option01
Option02
Option03

How to concatenate items in a list to a single string?

If you want to generate a string of strings separated by commas in final result, you can use something like this:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"

I hope this can help someone.

How to compare arrays in JavaScript?

Shortest

For an array of numbers try:

a1==''+a2

_x000D_
_x000D_
var a1 = [1,2,3];
var a2 = [1,2,3];

console.log( a1==''+a2 )
_x000D_
_x000D_
_x000D_

Note: this method will not work when the array also contains strings, e.g. a2 = [1, "2,3"].

How to force a component's re-rendering in Angular 2?

I force reload my component using *ngIf.

All the components inside my container goes back to the full lifecycle hooks .

In the template :

<ng-container *ngIf="_reload">
    components here 
</ng-container>

Then in the ts file :

public _reload = true;

private reload() {
    setTimeout(() => this._reload = false);
    setTimeout(() => this._reload = true);
}

What's the purpose of META-INF?

All answers are correct. Meta-inf has many purposes. In addition, here is an example about using tomcat container.

Go to Tomcat Doc and check " Standard Implementation > copyXML " attribute.

Description is below.

Set to true if you want a context XML descriptor embedded inside the application (located at /META-INF/context.xml) to be copied to the owning Host's xmlBase when the application is deployed. On subsequent starts, the copied context XML descriptor will be used in preference to any context XML descriptor embedded inside the application even if the descriptor embedded inside the application is more recent. The flag's value defaults to false. Note if the deployXML attribute of the owning Host is false or if the copyXML attribute of the owning Host is true, this attribute will have no effect.

How to export DataTable to Excel

I would recommend ClosedXML -

You can turn a DataTable into an Excel worksheet with some very readable code:

XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");

The developer is responsive and helpful. The project is actively developed, and the documentation is superb.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

Showing line numbers in IPython/Jupyter Notebooks

To turn line numbers on by default in all cells at startup I recommend this link. I quote:

  1. Navigate to your jupyter config directory, which you can find by typing the following at the command line:

    jupyter --config-dir
    
  2. From there, open or create the custom folder.

  3. In that folder, you should find a custom.js file. If there isn’t one, you should be able to create one. Open it in a text editor and add this code:

    define([
        'base/js/namespace',
        'base/js/events'
        ],
        function(IPython, events) {
            events.on("app_initialized.NotebookApp",
                function () {
                    IPython.Cell.options_default.cm_config.lineNumbers = true;
                }
            );
        }
    );
    

pip install gives error: Unable to find vcvarsall.bat

Thanks to "msoliman" for his hint, however his answer doesn't give clear solution for those who doesn't have VS2010
For example I have VS2012 and VS2013 and there are no such KEYs in system registry.

Solution:
Edit file: "[Python_install_loc]/Lib/distutils/msvc9compiler.py"
Change on line 224:

productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
                               "productdir")

to:

productdir = "C:\Program Files (x86)\Microsoft Visual Studio [your_vs_version(11/12...)]\VC"

and that should work

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

Python: finding an element in a list

assuming you want to find a value in a numpy array, I guess something like this might work:

Numpy.where(arr=="value")[0]

bash: pip: command not found

Avoiding sudo:

python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile

From:

http://www.pip-command-not-found.com

Rails - controller action name to string

In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]

Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.

Cannot use Server.MapPath

You need to add reference (System.Web) Reference to System.Web

Eclipse interface icons very small on high resolution screen in Windows 8.1

Best effortless solution is to go for Eclipse Neon. All bugs are fixed as a part of this release. https://bugs.eclipse.org/bugs/show_bug.cgi?id=421383

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

What is the naming convention in Python for variable and function names?

The Google Python Style Guide has the following convention:

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name.

A similar naming scheme should be applied to a CLASS_CONSTANT_NAME

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Now I return Object. I don't know better solution, but it works.

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity<Object>(entities, HttpStatus.OK);
}

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I ran into this problem when I simply mistyped my jdbc url in application.properties. Hope this helps someone: before:

spring.datasource.url=jdbc://localhost:3306/test

after:

spring.datasource.url=jdbc:mysql://localhost:3306/test

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";

        System.out.println(hasNewline.contains("\n"));
        System.out.println(hasNewline.contains("\\n"));
        System.out.println(noNewline.contains("\n"));
        System.out.println(noNewline.contains("\\n"));

    }

}

Resulted in

true
false
false
false

In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        System.out.println(word.length());
        System.out.println(word);
        word = word.replace("\n","\n ");
        System.out.println(word.length());
        System.out.println(word);

    }

}

Results in

6
test
.
7
test
 .

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

If you are running in Android 29 then you have to use scoped storage or for now, you can bypass this issue by using:

android:requestLegacyExternalStorage="true"

in manifest in the application tag.

Using Spring RestTemplate in generic method with generic parameter

As the code below shows it, it works.

public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<ResponseWrapper<T>>() {
            public Type getType() {
                return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
        }
    });
    return response;
}

public class MyParameterizedTypeImpl implements ParameterizedType {
    private ParameterizedType delegate;
    private Type[] actualTypeArguments;

    MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
        this.delegate = delegate;
        this.actualTypeArguments = actualTypeArguments;
    }

    @Override
    public Type[] getActualTypeArguments() {
        return actualTypeArguments;
    }

    @Override
    public Type getRawType() {
        return delegate.getRawType();
    }

    @Override
    public Type getOwnerType() {
        return delegate.getOwnerType();
    }

}

Python 2.6: Class inside a Class?

It sounds like you are talking about aggregation. Each instance of your player class can contain zero or more instances of Airplane, which, in turn, can contain zero or more instances of Flight. You can implement this in Python using the built-in list type to save you naming variables with numbers.

class Flight(object):

    def __init__(self, duration):
        self.duration = duration


class Airplane(object):

    def __init__(self):
        self.flights = []

    def add_flight(self, duration):
        self.flights.append(Flight(duration))


class Player(object):

    def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
        self.stock = stock
        self.bank = bank
        self.fuel = fuel
        self.total_pax = total_pax
        self.airplanes = []


    def add_planes(self):
        self.airplanes.append(Airplane())



if __name__ == '__main__':
    player = Player()
    player.add_planes()
    player.airplanes[0].add_flight(5)

How to change text and background color?

`enter code here`#include <stdafx.h> // Used with MS Visual Studio Express. Delete line if using something different
#include <conio.h> // Just for WaitKey() routine
#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // For use of SetConsoleTextAttribute()

void WaitKey();

int main()
{

    int len = 0,x, y=240; // 240 = white background, black foreground 

    string text = "Hello World. I feel pretty today!";
    len = text.length();
    cout << endl << endl << endl << "\t\t"; // start 3 down, 2 tabs, right
    for ( x=0;x<len;x++)
    {
        SetConsoleTextAttribute(console, y); // set color for the next print
        cout << text[x];
        y++; // add 1 to y, for a new color
        if ( y >254) // There are 255 colors. 255 being white on white. Nothing to see. Bypass it
            y=240; // if y > 254, start colors back at white background, black chars
        Sleep(250); // Pause between letters 
    }

    SetConsoleTextAttribute(console, 15); // set color to black background, white chars
    WaitKey(); // Program over, wait for a keypress to close program
}


void WaitKey()
{
    cout  << endl << endl << endl << "\t\t\tPress any key";
    while (_kbhit()) _getch(); // Empty the input buffer
    _getch(); // Wait for a key
    while (_kbhit()) _getch(); // Empty the input buffer (some keys sends two messages)
}

How to pick a new color for each plotted line within a figure in matplotlib?

You can also change the default color cycle in your matplotlibrc file. If you don't know where that file is, do the following in python:

import matplotlib
matplotlib.matplotlib_fname()

This will show you the path to your currently used matplotlibrc file. In that file you will find amongst many other settings also the one for axes.color.cycle. Just put in your desired sequence of colors and you will find it in every plot you make. Note that you can also use all valid html color names in matplotlib.

Search in all files in a project in Sublime Text 3

You can put <project> in "Where:" box to search from the current Sublime project from the Find in Files menu.

This is more useful than searching from the root folder for when your project is including or excluding particular folders or file extensions.

Why does "npm install" rewrite package-lock.json?

Short Answer:

  • npm install honors package-lock.json only if it satisfies the requirements of package.json.
  • If it doesn't satisfy those requirements, packages are updated & package-lock is overwritten.
  • If you want the install to fail instead of overwriting package-lock when this happens, use npm ci.

Here is a scenario that might explain things (Verified with NPM 6.3.0)

You declare a dependency in package.json like:

"depA": "^1.0.0"

Then you do, npm install which will generate a package-lock.json with:

"depA": "1.0.0"

Few days later, a newer minor version of "depA" is released, say "1.1.0", then the following holds true:

npm ci       # respects only package-lock.json and installs 1.0.0

npm install  # also, respects the package-lock version and keeps 1.0.0 installed 
             # (i.e. when package-lock.json exists, it overrules package.json)

Next, you manually update your package.json to:

"depA": "^1.1.0"

Then rerun:

npm ci      # will try to honor package-lock which says 1.0.0
            # but that does not satisfy package.json requirement of "^1.1.0" 
            # so it would throw an error 

npm install # installs "1.1.0" (as required by the updated package.json)
            # also rewrites package-lock.json version to "1.1.0"
            # (i.e. when package.json is modified, it overrules the package-lock.json)

jQuery get an element by its data-id

You can always use an attribute selector. The selector itself would look something like:

a[data-item-id=stand-out]

Get Android shared preferences value in activity/normal class

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

How to add a spinner icon to button when it's in the Loading state?

A lazy way to do this is with the UTF-8 entity code for a half circle \25E0 (aka &#x25e0;), which looks like ? and then keyframe animate it. It's a simple as:

_x000D_
_x000D_
.busy
{
animation: spin 1s infinite linear;
display:inline-block;
font-weight: bold;
font-family: sans-serif;
font-size: 35px;
font-style:normal;
color:#555;
}

.busy::before
{
content:"\25E0";
}

@keyframes spin
{
0% {transform: rotate(0deg);}
100% {transform: rotate(359deg);}
}
_x000D_
<i class="busy"></i>
_x000D_
_x000D_
_x000D_

C: convert double to float, preserving decimal point precision

float and double don't store decimal places. They store binary places: float is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).

Converting from double to float will give you the closest possible float, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.

#include <stdio.h>

int main(void) {
    double orig = 12345.67;
    float f = (float) orig;
    printf("%.17g\n", f); // prints 12345.669921875
    return 0;
}

To get a double approximation to the nice decimal value you intended, you can write something like:

double round_to_decimal(float f) {
    char buf[42];
    sprintf(buf, "%.7g", f); // round to 7 decimal digits
    return atof(buf);
}

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

How can I convert uppercase letters to lowercase in Notepad++

You could also, higlight the text you want to change, then navigate to - 'Edit' > 'Convert Case to' choose UPPERCASE or lowercase (as required).

jQuery selector regular expressions

You can use the filter function to apply more complicated regex matching.

Here's an example which would just match the first three divs:

_x000D_
_x000D_
$('div')_x000D_
  .filter(function() {_x000D_
    return this.id.match(/abc+d/);_x000D_
  })_x000D_
  .html("Matched!");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="abcd">Not matched</div>_x000D_
<div id="abccd">Not matched</div>_x000D_
<div id="abcccd">Not matched</div>_x000D_
<div id="abd">Not matched</div>
_x000D_
_x000D_
_x000D_

Output PowerShell variables to a text file

The simple solution is to avoid creating an array before piping to Out-File. Rule #1 of PowerShell is that the comma is a special delimiter, and the default behavior is to create an array. Concatenation is done like this.

$computer + "," + $Speed + "," + $Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

This creates an array of three items.

$computer,$Speed,$Regcheck
FYKJ
100
YES

vs. concatenation of three items separated by commas.

$computer + "," + $Speed + "," + $Regcheck
FYKJ,100,YES

Daylight saving time and time zone best practices

Summary of answers and other data: (please add yours)

Do:

  • Whenever you are referring to an exact moment in time, persist the time according to a unified standard that is not affected by daylight savings. (GMT and UTC are equivalent with this regard, but it is preferred to use the term UTC. Notice that UTC is also known as Zulu or Z time.)
  • If instead you choose to persist a time using a local time value, include the local time offset for this particular time from UTC (this offset may change throughout the year), such that the timestamp can later be interpreted unambiguously.
  • In some cases, you may need to store both the UTC time and the equivalent local time. Often this is done with two separate fields, but some platforms support a datetimeoffset type that can store both in a single field.
  • When storing timestamps as a numeric value, use Unix time - which is the number of whole seconds since 1970-01-01T00:00:00Z (excluding leap seconds). If you require higher precision, use milliseconds instead. This value should always be based on UTC, without any time zone adjustment.
  • If you might later need to modify the timestamp, include the original time zone ID so you can determine if the offset may have changed from the original value recorded.
  • When scheduling future events, usually local time is preferred instead of UTC, as it is common for the offset to change. See answer, and blog post.
  • When storing whole dates, such as birthdays and anniversaries, do not convert to UTC or any other time zone.
    • When possible, store in a date-only data type that does not include a time of day.
    • If such a type is not available, be sure to always ignore the time-of-day when interpreting the value. If you cannot be assured that the time-of-day will be ignored, choose 12:00 Noon, rather than 00:00 Midnight as a more safe representative time on that day.
  • Remember that time zone offsets are not always an integer number of hours (for example, Indian Standard Time is UTC+05:30, and Nepal uses UTC+05:45).
  • If using Java, use java.time for Java 8 and later.
  • If using .NET, consider using Noda Time.
  • If using .NET without Noda Time, consider that DateTimeOffset is often a better choice than DateTime.
  • If using Perl, use DateTime.
  • If using Python, use pytz or dateutil.
  • If using JavaScript, use moment.js with the moment-timezone extension.
  • If using PHP > 5.2, use the native time zones conversions provided by DateTime, and DateTimeZone classes. Be careful when using DateTimeZone::listAbbreviations() - see answer. To keep PHP with up to date Olson data, install periodically the timezonedb PECL package; see answer.
  • If using C++, be sure to use a library that uses the properly implements the IANA timezone database. These include cctz, ICU, and Howard Hinnant's "tz" library.
    • Do not use Boost for time zone conversions. While its API claims to support standard IANA (aka "zoneinfo") identifiers, it crudely maps them to POSIX-style data, without considering the rich history of changes each zone may have had. (Also, the file has fallen out of maintenance.)
  • If using Rust, use chrono.
  • Most business rules use civil time, rather than UTC or GMT. Therefore, plan to convert UTC timestamps to a local time zone before applying application logic.
  • Remember that time zones and offsets are not fixed and may change. For instance, historically US and UK used the same dates to 'spring forward' and 'fall back'. However, in 2007 the US changed the dates that the clocks get changed on. This now means that for 48 weeks of the year the difference between London time and New York time is 5 hours and for 4 weeks (3 in the spring, 1 in the autumn) it is 4 hours. Be aware of items like this in any calculations that involve multiple zones.
  • Consider the type of time (actual event time, broadcast time, relative time, historical time, recurring time) what elements (timestamp, time zone offset and time zone name) you need to store for correct retrieval - see "Types of Time" in this answer.
  • Keep your OS, database and application tzdata files in sync, between themselves and the rest of the world.
  • On servers, set hardware clocks and OS clocks to UTC rather than a local time zone.
  • Regardless of the previous bullet point, server-side code, including web sites, should never expect the local time zone of the server to be anything in particular. see answer.
  • Prefer working with time zones on a case-by-case basis in your application code, rather than globally through config file settings or defaults.
  • Use NTP services on all servers.
  • If using FAT32, remember that timestamps are stored in local time, not UTC.
  • When dealing with recurring events (weekly TV show, for example), remember that the time changes with DST and will be different across time zones.
  • Always query date-time values as lower-bound inclusive, upper-bound exclusive (>=, <).

Don't:

  • Do not confuse a "time zone", such as America/New_York with a "time zone offset", such as -05:00. They are two different things. See the timezone tag wiki.
  • Do not use JavaScript's Date object to perform date and time calculations in older web browsers, as ECMAScript 5.1 and lower has a design flaw that may use daylight saving time incorrectly. (This was fixed in ECMAScript 6 / 2015).
  • Never trust the client's clock. It may very well be incorrect.
  • Don't tell people to "always use UTC everywhere". This widespread advice is shortsighted of several valid scenarios that are described earlier in this document. Instead, use the appropriate time reference for the data you are working with. (Timestamping can use UTC, but future time scheduling and date-only values should not.)

Testing:

  • When testing, make sure you test countries in the Western, Eastern, Northern and Southern hemispheres (in fact in each quarter of the globe, so 4 regions), with both DST in progress and not (gives 8), and a country that does not use DST (another 4 to cover all regions, making 12 in total).
  • Test transition of DST, i.e. when you are currently in summer time, select a time value from winter.
  • Test boundary cases, such as a timezone that is UTC+12, with DST, making the local time UTC+13 in summer and even places that are UTC+13 in winter
  • Test all third-party libraries and applications and make sure they handle time zone data correctly.
  • Test half-hour time zones, at least.

Reference:

Other:

  • Lobby your representative to end the abomination that is DST. We can always hope...
  • Lobby for Earth Standard Time

Making a DateTime field in a database automatic?

You need to set the "default value" for the date field to getdate(). Any records inserted into the table will automatically have the insertion date as their value for this field.

The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible if you select the date field of your table when editing the table.

How to use a App.config file in WPF applications?

In my case, I followed the steps below.

App.config

<configuration>  
   <startup> 
       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

 <appSettings>
   <add key="POCPublishSubscribeQueueName" value="FormatName:Direct=OS:localhost\Private$\POCPublishSubscribe"/>
 </appSettings>

</configuration>

Added System.Configuartion to my project.

Added using System.Configuration statement in file at top.

Then used this statement:

string queuePath = ConfigurationManager.AppSettings["POCPublishSubscribeQueueName"].ToString();

Maven : error in opening zip file when running maven

Try to remove your repository in /.m2/repository/ and then do a mvn clean install to download the files again.

plot.new has not been called yet

In my case, I was trying to call plot(x, y) and lines(x, predict(yx.lm), col="red") in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Error: Local workspace file ('angular.json') could not be found

With recent version, without --migrate-only I got the repo updated.

I did ng update

The Angular CLI configuration format has been changed, and your existing configuration can be updated automatically by running the following command:

ng update @angular/cli
            Updating karma configuration
            Updating configuration
            Removing old config file (.angular-cli.json)
            Writing config file (angular.json)
            Some configuration options have been changed, please make sure to update any npm scripts which you may have modified.
DELETE .angular-cli.json
CREATE angular.json (3684 bytes)
UPDATE karma.conf.js (1040 bytes)
UPDATE src/tsconfig.spec.json (322 bytes)
UPDATE package.json (1340 bytes)
UPDATE tslint.json (3140 bytes)

How to get last N records with activerecord?

Updated Answer (2020)

You can get last N records simply by using last method:

Record.last(N)

Example:

User.last(5)

Returns 5 users in descending order by their id.

Deprecated (Old Answer)

An active record query like this I think would get you what you want ('Something' is the model name):

Something.find(:all, :order => "id desc", :limit => 5).reverse

edit: As noted in the comments, another way:

result = Something.find(:all, :order => "id desc", :limit => 5)

while !result.empty?
        puts result.pop
end

Convert DataSet to List

Try something like this:

var empList = ds.Tables[0].AsEnumerable()
    .Select(dataRow => new Employee
    {
        Name = dataRow.Field<string>("Name")
    }).ToList();

Perform .join on value in array of objects

On node or ES6+:

users.map(u => u.name).join(', ')

Difference between text and varchar (character varying)

In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.

TL;DR: If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.

Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

Angular ng-click with call to a controller function not working

Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here

Just take note of the Controller, it has an alias of homeCtrl.

module MongoAngular {
    var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);

    app.config([
        '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
            $routeProvider
                .when('/Home', {
                    templateUrl: '/PartialViews/Home/home.html',
                    controller: 'HomeController as homeCtrl'
                })
                .otherwise({ redirectTo: '/Home' });
        }])
        .config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
        restangularProvider.setBaseUrl('/api');
    }]);
} 

And here's the way to use it...

ng-click="homeCtrl.addCustomer(customer)"

Try it.. It might work for you as it worked for me... ;)

How to 'grep' a continuous stream?

sed would be a better choice (stream editor)

tail -n0 -f <file> | sed -n '/search string/p'

and then if you wanted the tail command to exit once you found a particular string:

tail --pid=$(($BASHPID+1)) -n0 -f <file> | sed -n '/search string/{p; q}'

Obviously a bashism: $BASHPID will be the process id of the tail command. The sed command is next after tail in the pipe, so the sed process id will be $BASHPID+1.

<button> background image

Delete "button" before # rock:

button #rock {
    background: url(img/rock.png) no-repeat;
} 

Worked for me in Google Chrome.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.

If you have timezone-aware datetime in pandas, technically, tz_localize(None) changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:

import pandas as pd

t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')

t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')

# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')

Note that this will leave you with strange things during DST transitions, e.g.

t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')

t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')

In contrast, tz_convert(None) does not modify the internal timestamp, it just removes the tzinfo.

t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')

My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None) which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.

(Python 3.8.2 x64 on Windows 10, pandas v1.0.5.)

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

Returning a C string from a function

A C string is defined as a pointer to an array of characters.

If you cannot have pointers, by definition you cannot have strings.

Adding an assets folder in Android Studio

According to new Gradle based build system. We have to put assets under main folder.

Or simply right click on your project and create it like

File > New > folder > assets Folder

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:

  1. You can use another nextLine() method just after the nextInt() to move the scanner past the newline character.
  2. You can use different Scanner objects for scanning the integer and string (You can name them scan1 and scan2).
  3. You can use the next method on the scanner object as

    scan.next();

JavaScript to scroll long page to DIV

For smooth scroll this code is useful

$('a[href*=#scrollToDivId]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      var head_height = $('.header').outerHeight(); // if page has any sticky header get the header height else use 0 here
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - head_height
        }, 1000);
        return false;
      }
    }
  });

How to get city name from latitude and longitude coordinates in Google Maps?

try below code hope use full for you:-

CityAsyncTask cst = new CityAsyncTask(HomeScreenUserLocation.this,
                latitude, longitude);
        cst.execute();

        String lo = null;
        try {
            lo = cst.get().toString();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

and AsyncTask

public class CityAsyncTask extends AsyncTask<String, String, String> {
    Activity act;
    double latitude;
    double longitude;

    public CityAsyncTask(Activity act, double latitude, double longitude) {
        // TODO Auto-generated constructor stub
        this.act = act;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        Geocoder geocoder = new Geocoder(act, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            Log.e("Addresses", "-->" + addresses);
            result = addresses.get(0).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    }
}

Domain Account keeping locking out with correct password every few minutes

May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.

YouTube Autoplay not working

mute=1 or muted=1 as suggested by @Fab will work. However, if you wish to enable autoplay with sound you should add allow="autoplay" to your embedded <iframe>.

<iframe type="text/html" src="https://www.youtube.com/embed/-ePDPGXkvlw?autoplay=1" frameborder="0" allow="autoplay"></iframe>

This is officially supported and documented in Google's Autoplay Policy Changes 2017 post

Iframe delegation A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.

<!-- Autoplay is allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay">

<!-- Autoplay and Fullscreen are allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay; fullscreen">

When the feature policy for autoplay is disabled, calls to play() without a user gesture will reject the promise with a NotAllowedError DOMException. And the autoplay attribute will also be ignored.

Subset of rows containing NA (missing) values in a chosen column of a data frame

new_data <- data %>% filter_all(any_vars(is.na(.))) 

This should create a new data frame (new_data) with only the missing values in it.

Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).

Clang vs GCC for my Linux Development project

As of right now, GCC has much better and more complete support for C++11 features than Clang. Also, the code generator for GCC performs better optimisation than the one in Clang (in my experience, I have not seen any exhaustive tests).

On the other hand, Clang often compiles code more quickly than GCC, and produces better error messages when there is something wrong with your code.

The choice of which one to use really depends on what things are important to you. I value C++11 support and code generation quality more than I value convenience of compilation. Because of this, I use GCC. For you, the trade-offs could be different.

swift UITableView set rowHeight

Put the default rowHeight in viewDidLoad or awakeFromNib. As pointed out by Martin R., you cannot call cellForRowAtIndexPath from heightForRowAtIndexPath

self.tableView.rowHeight = 44.0

Pass Model To Controller using Jquery/Ajax

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

Sending complex objects?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

Efficiently test if a port is open on Linux?

There's a very short with "fast answer" here : How to test if remote TCP port is opened from Shell script?

nc -z <host> <port>; echo $?

I use it with 127.0.0.1 as "remote" address.

this returns "0" if the port is open and "1" if the port is closed

e.g.

nc -z 127.0.0.1 80; echo $?

-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunc- tion with the -l option.

Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

Checking for the correct number of arguments

cat script.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

execute it like below -

./script.sh directory1 directory2

Output will be like -

directory1 exit
directory2 Does not exists

When should I use File.separator and when File.pathSeparator?

If you mean File.separator and File.pathSeparator then:

  • File.pathSeparator is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ; to separate the file paths so on Windows File.pathSeparator would be ;.

  • File.separator is either / or \ that is used to split up the path to a specific file. For example on Windows it is \ or C:\Documents\Test

How do I convert a org.w3c.dom.Document object to a String?

A Scala version based on Zaz's answer.

  case class DocumentEx(document: Document) {
    def toXmlString(pretty: Boolean = false):Try[String] = {
      getStringFromDocument(document, pretty)
    }
  }

  implicit def documentToDocumentEx(document: Document):DocumentEx = {
    DocumentEx(document)
  }

  def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
    try
    {
      val domSource= new DOMSource(doc)
      val writer = new StringWriter()
      val result = new StreamResult(writer)
      val tf = TransformerFactory.newInstance()
      val transformer = tf.newTransformer()
      if (pretty)
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
      transformer.transform(domSource, result)
      Success(writer.toString);
    }
    catch {
      case ex: TransformerException =>
        Failure(ex)
    }
  }

With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

How to set focus on input field?

I want to contribute to this discussion after searching for at better solution and not finding it, having to create it instead.

Criteria: 1. Solution should be independent of parent controller scope to increase re-usability. 2. Avoid the use of $watch to monitor some condition, this is both slow, increases the size of the digest loop and makes testing harder. 3. Avoid $timeout or $scope.$apply() to trigger a digest loop. 4. An input element is present within the element where the Directive is used open.

This is the solution I liked the most:

Directive:

.directive('focusInput', [ function () {
    return {
        scope: {},
        restrict: 'A',
        compile: function(elem, attr) {
            elem.bind('click', function() {
                elem.find('input').focus();                
            });
        }        
    };
}]);

Html:

 <div focus-input>
     <input/>
 </div>

I hope this will help someone out there!

How to list the files inside a JAR file?

Some time ago I made a function that gets classess from inside JAR:

public static Class[] getClasses(String packageName) 
throws ClassNotFoundException{
    ArrayList<Class> classes = new ArrayList<Class> ();

    packageName = packageName.replaceAll("\\." , "/");
    File f = new File(jarName);
    if(f.exists()){
        try{
            JarInputStream jarFile = new JarInputStream(
                    new FileInputStream (jarName));
            JarEntry jarEntry;

            while(true) {
                jarEntry=jarFile.getNextJarEntry ();
                if(jarEntry == null){
                    break;
                }
                if((jarEntry.getName ().startsWith (packageName)) &&
                        (jarEntry.getName ().endsWith (".class")) ) {
                    classes.add(Class.forName(jarEntry.getName().
                            replaceAll("/", "\\.").
                            substring(0, jarEntry.getName().length() - 6)));
                }
            }
        }
        catch( Exception e){
            e.printStackTrace ();
        }
        Class[] classesA = new Class[classes.size()];
        classes.toArray(classesA);
        return classesA;
    }else
        return null;
}

How can I split a delimited string into an array in PHP?

explode has some very big problems in real life usage:

count(explode(',', null)); // 1 !! 
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8

this is why i prefer preg_split

preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)

the entire boilerplate:

/** @brief wrapper for explode
 * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
 * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
 * @param string $delimiter default ','
 * @return array|mixed
 */
public static function explode($val, $as_is = false, $delimiter = ',')
{
    // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
    return (is_string($val) || is_int($val)) ?
        preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
        :
        ($as_is ? $val : (is_array($val) ? $val : []));
}

How do I check if a property exists on a dynamic anonymous type in c#?

This works also for DynamicJsonObject:

  public static bool PropertyExists(dynamic settings, string name)
  {
    if (settings is ExpandoObject)
      return ((IDictionary<string, object>)settings).ContainsKey(name);
    else if (settings is DynamicJsonObject)
      return ((DynamicJsonObject)settings).GetDynamicMemberNames().Contains(name);

    return settings.GetType().GetProperty(name) != null;
  }

What is LDAP used for?

To take the definitions the other mentioned earlier a bit further, how about this perspective...

LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).

There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).

LDAP is just a very lightweight DAP, as the name suggests.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

C# delete a folder and all files and folders within that folder

public void Empty(System.IO.DirectoryInfo directory)
{
    try
    {
        logger.DebugFormat("Empty directory {0}", directory.FullName);
        foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
        foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
    }
    catch (Exception ex)
    {
        ex.Data.Add("directory", Convert.ToString(directory.FullName, CultureInfo.InvariantCulture));

        throw new Exception(string.Format(CultureInfo.InvariantCulture,"Method:{0}", ex.TargetSite), ex);
    }
}

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

I have adapted the solution of Biju:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";

    private ObjectMapper om = new ObjectMapper();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String jsonBody = getRequestBody(webRequest);

        JsonNode rootNode = om.readTree(jsonBody);
        JsonNode node = rootNode.path(parameter.getParameterName());    

        return om.readValue(node.toString(), parameter.getParameterType());
    }


    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

        String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);
        if (jsonBody==null){
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
                webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return jsonBody;

    }

}

What's the different:

  • I'm using Jackson to convert json
  • I don't need a value in the annotation, you can read the name of the parameter out of the MethodParameter
  • I also read the type of the parameter out of the Methodparameter => so the solution should be generic (i tested it with string and DTOs)

BR

Git Push ERROR: Repository not found

I had the same problem, with a private repo.

do the following:

remove the remote origin

git remote rm origin

re-add the origin but with your username and pwd with writing privileges on this pvt repo

git remote add origin  https://USERNAME:[email protected]/username/reponame.git

What are the various "Build action" settings in Visual Studio project properties and what do they do?

How about this page from Microsoft Connect (explaining the DesignData and DesignDataWithDesignTimeCreatableTypes) types. Quoting:

The following describes the two Build Actions for Sample Data files.

Sample data .xaml files must be assigned one of the below Build Actions:

DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.

DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.

Not so incredibly exhaustive, but it at least gives a hint. This MSDN walkthrough also gives some ideas. I don't know whether these Build Actions are applicable for non-Silverlight projects also.

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

Javascript + Regex = Nothing to repeat error?

Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:

if (name.search(/[\[\]?*+|{}\\()@.\n\r]/) != -1) {
    // ... stuff ...
}

Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).

Get controller and action name from within controller?

Here is the simplest and most practical answer to getting a name:

var actionName = RouteData.Values["action"];
var controllerName = RouteData.Values["controller"];

Or

string actionName = RouteData.Values["action"].ToString();
string controllerName = RouteData.Values["controller"].ToString();

Code above tests with asp.net mvc 5.

Hibernate Annotations - Which is better, field or property access?

i thinking about this and i choose method accesor

why?

because field and methos accesor is the same but if later i need some logic in load field, i save move all annotation placed in fields

regards

Grubhart

php static function

Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.

Well, okay, one other difference: an E_STRICT warning is generated by your first example.

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

How to serialize object to CSV file?

First, serialization is writing the object to a file 'as it is'. AFAIK, you cannot choose file formats and all. The serialized object (in a file) has its own 'file format'

If you want to write the contents of an object (or a list of objects) to a CSV file, you can do it yourself, it should not be complex.

Looks like Java CSV Library can do this, but I have not tried this myself.

EDIT: See following sample. This is by no way foolproof, but you can build on this.

    //European countries use ";" as 
    //CSV separator because "," is their digit separator
    private static final String CSV_SEPARATOR = ",";
    private static void writeToCSV(ArrayList<Product> productList)
    {
        try
        {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8"));
            for (Product product : productList)
            {
                StringBuffer oneLine = new StringBuffer();
                oneLine.append(product.getId() <=0 ? "" : product.getId());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(product.getName().trim().length() == 0? "" : product.getName());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(product.getCostPrice() < 0 ? "" : product.getCostPrice());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(product.isVatApplicable() ? "Yes" : "No");
                bw.write(oneLine.toString());
                bw.newLine();
            }
            bw.flush();
            bw.close();
        }
        catch (UnsupportedEncodingException e) {}
        catch (FileNotFoundException e){}
        catch (IOException e){}
    }

This is product (getters and setters hidden for readability):

class Product
{
    private long id;
    private String name;
    private double costPrice;
    private boolean vatApplicable;
}

And this is how I tested:

public static void main(String[] args)
{
    ArrayList<Product> productList = new ArrayList<Product>();
    productList.add(new Product(1, "Pen", 2.00, false));
    productList.add(new Product(2, "TV", 300, true));
    productList.add(new Product(3, "iPhone", 500, true));
    writeToCSV(productList);
}

Hope this helps.

Cheers.

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

Checking for duplicate strings in JavaScript array

_x000D_
_x000D_
function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

var arr = [1, 1, 2, 3, 4];

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}
_x000D_
_x000D_
_x000D_

Simple Javascript (if you don't know ES6)

function hasDuplicates(arr) {
    var counts = [];

    for (var i = 0; i <= arr.length; i++) {
        if (counts[arr[i]] === undefined) {
            counts[arr[i]] = 1;
        } else {
            return true;
        }
    }
    return false;
}

// [...]

var arr = [1, 1, 2, 3, 4];

if (hasDuplicates(arr)) {
  alert('Error: you have duplicates values !')
}

how to add picasso library in android studio

easiest way to add dependence

hope this help you or Ctrl + Alt + Shift + S => select Dependencies tab and find what you need ( see my image)

How to read pickle file?

There is a read_pickle function as part of pandas 0.22+

import pandas as pd

object = pd.read_pickle(r'filepath')

Opacity of div's background without affecting contained element in IE 8?

The opacity style affects the whole element and everything within it. The correct answer to this is to use an rgba background colour instead.

The CSS is fairly simple:

.myelement {
    background: rgba(200, 54, 54, 0.5);
}

...where the first three numbers are the red, green and blue values for your background colour, and the fourth is the 'alpha' channel value, which works the same way as the opacity value.

See this page for more info: http://css-tricks.com/rgba-browser-support/

The down-side, is that this doesn't work in IE8 or lower. The page I linked above also lists a few other browsers it doesn't work in, but they're all very old by now; all browsers in current use except IE6/7/8 will work with rgba colours.

The good news is that you can force IE to work with this as well, using a hack called CSS3Pie. CSS3Pie adds a number of modern CSS3 features to older versions of IE, including rgba background colours.

To use CSS3Pie for backgrounds, you need to add a specific -pie-background declaration to your CSS, as well as the PIE behavior style, so your stylesheet would end up looking like this:

.myelement {
    background: rgba(200, 54, 54, 0.5);
    -pie-background:  rgba(200, 54, 54, 0.5);
    behavior: url(PIE.htc);
}

Hope that helps.

[EDIT]

For what it's worth, as others have mentioned, you can use IE's filter style, with the gradient keyword. The CSS3Pie solution does actually use this same technique behind the scenes, but removes the need for you to mess around directly with IE's filters, so your stylesheets are much cleaner. (it also adds a whole bunch of other nice features too, but that's not relevant to this discussion)

Is there a naming convention for MySQL?

Consistency is the key to any naming standard. As long as it's logical and consistent, you're 99% there.

The standard itself is very much personal preference - so if you like your standard, then run with it.

To answer your question outright - no, MySQL doesn't have a preferred naming convention/standard, so rolling your own is fine (and yours seems logical).

How to split a string in Ruby and get all items except the first one?

You can also do this:

String is ex="test1, test2, test3, test4, test5"
array = ex.split(/,/)
array.size.times do |i|
  p array[i]
end 

Cut off text in string after/before separator in powershell

$text = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"

$text.split(';')[1].split(' ')

Sending emails with Javascript

You can use this free service: https://www.smtpjs.com

  1. Include the script:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:
Email.send(
  "[email protected]",
  "[email protected]",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

Spring boot - Not a managed type

I have the same probblem, in version spring boot v1.3.x what i did is upgrade spring boot to version 1.5.7.RELEASE. Then the probblem gone.

How do I make HttpURLConnection use a proxy?

For Java 1.8 and higher you must set -Djdk.http.auth.tunneling.disabledSchemes= to make proxies with Basic Authorization working with https.

How to send only one UDP packet with netcat?

On a current netcat (v0.7.1) you have a -c switch:

-c, --close                close connection on EOF from stdin

Hence,

echo "hi" | nc -cu localhost 8000

should do the trick.

How to check if IEnumerable is null or empty?

I built this off of the answer by @Matt Greer

He answered the OP's question perfectly.

I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.

Specifically I wanted to still be able to pass in a predicate.

public static class Utilities
{
    /// <summary>
    /// Determines whether a sequence has a value and contains any elements.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
    /// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source?.Any() == true;
    }

    /// <summary>
    /// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        return source?.Any(predicate) == true;
    }
}

The naming of the extension method could probably be better.

How to send a POST request with BODY in swift

Alamofire Fetch data with POST,Parameter and Headers

func feedbackApi(){
    DispatchQueue.main.async {
        let headers = [
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "------"
        ]
        let url = URL(string: "---------")
        var parameters = [String:AnyObject]()
        parameters =  [
            "device_id":"-----" as AnyObject,
            "user_id":"----" as AnyObject,
            "cinema_id":"-----" as AnyObject,
            "session_id":"-----" as AnyObject,
        ]
       Alamofire.request(url!, method: .post, parameters: parameters,headers:headers).responseJSON { response in
                switch response.result{
                case.success(let data):
                    self.myResponse = JSON(data)
                    print(self.myResponse as Any)
                    let slide = self.myResponse!["sliders"]
                    print(slide)
                    print(slide.count)
                    for i in 0..<slide.count{
                        let single = Sliders(sliderJson: slide[i])
                        self.slidersArray.append(single)
                    }
                    DispatchQueue.main.async {
                        self.getSliderCollection.reloadData()
                    }
                case .failure(let error):
                    print("dddd",error)
                }

        }
    }

}

How To fix white screen on app Start up?

enter image description here

Like you tube.. initially they show icon screen instead of white screen. And after 2 seconds shows home screen.

first create an XML drawable in res/drawable.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/gray"/>

    <item>
        <bitmap
            android:gravity="center"
            android:src="@mipmap/ic_launcher"/>
    </item>

</layer-list>

Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@drawable/background_splash</item>
    </style>

</resources>

In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:

<activity
    android:name=".SplashActivity"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

This link gives what you want. step by step procedure. https://www.bignerdranch.com/blog/splash-screens-the-right-way/

UPDATE:

The layer-list can be even simpler like this (which also accepts vector drawables for the centered logo, unlike the <bitmap> tag):

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Background color -->
    <item android:drawable="@color/gray"/>

    <!-- Logo at the center of the screen -->
    <item
        android:drawable="@mipmap/ic_launcher"
        android:gravity="center"/>
</layer-list>

How can I create an error 404 in PHP?

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();

How to execute two mysql queries as one in PHP/MYSQL?

Yes it is possible without using MySQLi extension.

Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.

Refer to the comments below Husni's post for more information.

ngrok command not found

This is how I got it to work..

For Mac

  1. If you downloaded via a download link, you need to add ngrok path to your .bash_profile or .bashrc whichever one you are using.

For Windows 10 bash:

  1. Download ngrok from https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip
  2. Move executable file ngrok.exe to C:\Windows\system32\ngrok.exe
  3. Add Environment Variables via UI (search for "Edit the environment variables for your account" in the search bar next to windows logo => double click on Path under Users Variables for yourusername => Click New => add your path C:\Windows\system32\ngrok.exe => click OK.
  4. Restart your bash and you should be able to run "ngrok http 80" command.

How to make a div with a circular shape?

HTML div elements, unlike SVG circle primitives, are always rectangular.

You could use round corners (i.e. CSS border-radius) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:

_x000D_
_x000D_
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
_x000D_
_x000D_

Escape Character in SQL Server

You need to just replace ' with '' inside your string

SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'

You can also use REPLACE(@name, '''', '''''') if generating the SQL dynamically

If you want to escape inside a like statement then you need to use the ESCAPE syntax

It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F

Making Enter key on an HTML form submit instead of activating button

$("form#submit input").on('keypress',function(event) {
  event.preventDefault();
  if (event.which === 13) {
    $('button.submit').trigger('click');
  }
});

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

Is there a regular expression to detect a valid regular expression?

Good question.

True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.

However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.

Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.

What are file descriptors, explained in simple terms?

Other answers added great stuff. I will add just my 2 cents.

According to Wikipedia we know for sure: a file descriptor is a non-negative integer. The most important thing I think is missing, would be to say:

File descriptors are bound to a process ID.

We know most famous file descriptors are 0, 1 and 2. 0 corresponds to STDIN, 1 to STDOUT, and 2 to STDERR.

Say, take shell processes as an example and how does it apply for it?

Check out this code

#>sleep 1000 &
[12] 14726

We created a process with the id 14726 (PID). Using the lsof -p 14726 we can get the things like this:

COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF    NODE NAME
sleep   14726 root  cwd    DIR    8,1     4096 1201140 /home/x
sleep   14726 root  rtd    DIR    8,1     4096       2 /
sleep   14726 root  txt    REG    8,1    35000  786587 /bin/sleep
sleep   14726 root  mem    REG    8,1 11864720 1186503 /usr/lib/locale/locale-archive
sleep   14726 root  mem    REG    8,1  2030544  137184 /lib/x86_64-linux-gnu/libc-2.27.so
sleep   14726 root  mem    REG    8,1   170960  137156 /lib/x86_64-linux-gnu/ld-2.27.so
sleep   14726 root    0u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    1u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    2u   CHR  136,6      0t0       9 /dev/pts/6

The 4-th column FD and the very next column TYPE correspond to the File Descriptor and the File Descriptor type.

Some of the values for the FD can be:

cwd – Current Working Directory
txt – Text file
mem – Memory mapped file
mmap – Memory mapped device

But the real file descriptor is under:

NUMBER – Represent the actual file descriptor. 

The character after the number i.e "1u", represents the mode in which the file is opened. r for read, w for write, u for read and write.

TYPE specifies the type of the file. Some of the values of TYPEs are:

REG – Regular File
DIR – Directory
FIFO – First In First Out

But all file descriptors are CHR – Character special file (or character device file)

Now, we can identify the File Descriptors for STDIN, STDOUT and STDERR easy with lsof -p PID, or we can see the same if we ls /proc/PID/fd.

Note also that file descriptor table that kernel keeps track of is not the same as files table or inodes table. These are separate, as some other answers explained.

fd table

You may ask yourself where are these file descriptors physically and what is stored in /dev/pts/6 for instance

sleep   14726 root    0u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    1u   CHR  136,6      0t0       9 /dev/pts/6
sleep   14726 root    2u   CHR  136,6      0t0       9 /dev/pts/6

Well, /dev/pts/6 lives purely in memory. These are not regular files, but so called character device files. You can check this with: ls -l /dev/pts/6 and they will start with c, in my case crw--w----.

Just to recall most Linux like OS define seven types of files:

  • Regular files
  • Directories
  • Character device files
  • Block device files
  • Local domain sockets
  • Named pipes (FIFOs) and
  • Symbolic links

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

Force encode from US-ASCII to UTF-8 (iconv)

Here's a script that will find all files matching a pattern you pass it, and then converting them from their current file encoding to UTF-8. If the encoding is US ASCII, then it will still show as US ASCII, since that is a subset of UTF-8.

#!/usr/bin/env bash
find . -name "${1}" |
    while read line;
    do
        echo "***************************"
        echo "Converting ${line}"

        encoding=$(file -b --mime-encoding ${line})
        echo "Found Encoding: ${encoding}"

        iconv -f "${encoding}" -t "utf-8" ${line} -o ${line}.tmp
        mv ${line}.tmp ${line}
    done

What tools do you use to test your public REST API?

I use http://hurl.it/

Ha. Sorry, I mis-read your post. I've used cucumber to test it before. It worked out nicely.

Understanding typedefs for function pointers in C

A very easy way to understand typedef of function pointer:

int add(int a, int b)
{
    return (a+b);
}

typedef int (*add_integer)(int, int); //declaration of function pointer

int main()
{
    add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
    int c = addition(11, 11);   //calling function via new variable
    printf("%d",c);
    return 0;
}

The "backspace" escape character '\b': unexpected behavior?

..........
^ <= pointer to "print head"
            /* part1 */
            printf("hello worl");
hello worl
          ^ <= pointer to "print head"
            /* part2 */
            printf("\b");
hello worl
         ^ <= pointer to "print head"
            /* part3 */
            printf("\b");
hello worl
        ^ <= pointer to "print head"
            /* part4 */
            printf("d\n");
hello wodl

^ <= pointer to "print head" on the next line

Laravel Rule Validation for Numbers

$this->validate($request,[
        'input_field_name'=>'digits_between:2,5',
       ]);

Try this it will be work

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

How to generate .env file for laravel?

There's another explanation for why .env doesn't exist, and it happens when you move all the Laravel files.

Take this workflow: in your project directory you do laravel new whatever, Laravel is installed in whatever, you do mv * .. to move all the files to your project folder, and you remove whatever. The problem is, mv doesn't move hidden files by default, so the .env files are left behind, and are removed!

When is del useful in Python?

Just another thinking.

When debugging http applications in framework like Django, the call stack full of useless and messed up variables previously used, especially when it's a very long list, could be very painful for developers. so, at this point, namespace controlling could be useful.

Capturing standard out and error with Start-Process

That's how Start-Process was designed for some reason. Here's a way to get it without sending to file:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

How to install a previous exact version of a NPM package?

It's quite easy. Just write this, for example:

npm install -g [email protected]

Or:

npm install -g npm@latest    // For the last stable version
npm install -g npm@next      // For the most recent release

Difference Between $.getJSON() and $.ajax() in jQuery

The only difference I see is that getJSON performs a GET request instead of a POST.

How to add a 'or' condition in #ifdef

#if defined(CONDITION1) || defined(CONDITION2)

should work. :)

#ifdef is a bit less typing, but doesn't work well with more complex conditions

submit the form using ajax

I would suggest to use jquery for this type of requirement . Give this a try

<div id="commentList"></div>
<div id="addCommentContainer">
    <p>Add a Comment</p> <br/> <br/>
    <form id="addCommentForm" method="post" action="">
        <div>
            Your Name <br/>
            <input type="text" name="name" id="name" />


            <br/> <br/>
            Comment Body <br/>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>

            <input type="submit" id="submit" value="Submit" />
        </div>
    </form>
</div>?

$(document).ready(function(){
    /* The following code is executed once the DOM is loaded */

    /* This flag will prevent multiple comment submits: */
    var working = false;
    $("#submit").click(function(){
    $.ajax({
         type: 'POST',
         url: "mysubmitpage.php",
         data: $('#addCommentForm').serialize(), 
         success: function(response) {
            alert("Submitted comment"); 
             $("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
         },
        error: function() {
             //$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
            alert("There was an error submitting comment");
        }
     });
});
});?

Remove empty strings from a list of strings

match using a regular expression and a filter

lstr = ['hello', '', ' ', 'world', ' ']
r=re.compile('^[A-Za-z0-9]+')
results=list(filter(r.match,lstr))
print(results)

How do you run a script on login in *nix?

I was frustrated with this problem for days. Nothing worked on ubuntu. If I put the call in /etc/profile it all crashed at login attempt. I couldn't use "Startup Applications" as that was not what I wanted. That only sets the script for that current user.

Finally I found this little article: http://standards.freedesktop.org/autostart-spec/autostart-spec-0.5.html

The solution would be:

  1. find out the $XDG_CONFIG_DIRS path:

    echo $XDG_CONFIG_DIRS

  2. put your script in that directory

Pretty-Printing JSON with PHP

Classic case for a recursive solution. Here's mine:

class JsonFormatter {
    public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
        $inString = $escaped = false;
        $result = $indent;

        if(is_string($j)) {
            $bak = $j;
            $j = str_split(trim($j, '"'));
        }

        while(count($j)) {
            $c = array_shift($j);
            if(false !== strpos("{[,]}", $c)) {
                if($inString) {
                    $result .= $c;
                } else if($c == '{' || $c == '[') {
                    $result .= $c."\n";
                    $result .= self::prettyPrint($j, $indentor, $indentor.$indent);
                    $result .= $indent.array_shift($j);
                } else if($c == '}' || $c == ']') {
                    array_unshift($j, $c);
                    $result .= "\n";
                    return $result;
                } else {
                    $result .= $c."\n".$indent;
                } 
            } else {
                $result .= $c;
                $c == '"' && !$escaped && $inString = !$inString;
                $escaped = $c == '\\' ? !$escaped : false;
            }
        }

        $j = $bak;
        return $result;
    }
}

Usage:

php > require 'JsonFormatter.php';
php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
php > print_r($a);
Array
(
    [foo] => 1
    [bar] => This "is" bar
    [baz] => Array
        (
            [a] => 1
            [b] => 2
            [c] => "3"
        )

)
php > echo JsonFormatter::prettyPrint(json_encode($a));
{
    "foo":1,
    "bar":"This \"is\" bar",
    "baz":{
        "a":1,
        "b":2,
        "c":"\"3\""
    }
}

Cheers

How to get primary key column in Oracle?

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = 'TABLE_NAME'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;

Make sure that 'TABLE_NAME' is in upper case since Oracle stores table names in upper case.

bootstrap responsive table content wrapping

Add your new class "tableresp" with table-responisve class and then add below code in your js file

$(".tableresp").on('click', '.dropdown-toggle', function(event) {

    if ($('.dropdown-menu').length) {
        var elm = $('.dropdown-menu'),
            docHeight = $(document).height(),
            docWidth = $(document).width(),
            btn_offset = $(this).offset(),
            btn_width = $(this).outerWidth(),
            btn_height = $(this).outerHeight(),
            elm_width = elm.outerWidth(),
            elm_height = elm.outerHeight(),
            table_offset = $(".tableresp").offset(),
            table_width = $(".tableresp").width(),
            table_height = $(".tableresp").height(),

            tableoffright = table_width + table_offset.left,
            tableoffbottom = table_height + table_offset.top,
            rem_tablewidth = docWidth - tableoffright,
            rem_tableheight = docHeight - tableoffbottom,
            elm_offsetleft = btn_offset.left,
            elm_offsetright = btn_offset.left + btn_width,
            elm_offsettop = btn_offset.top + btn_height,
            btn_offsetbottom = elm_offsettop,

            left_edge = (elm_offsetleft - table_offset.left) < elm_width,
            top_edge = btn_offset.top < elm_height,
            right_edge = (table_width - elm_offsetleft) < elm_width,
            bottom_edge = (tableoffbottom - btn_offsetbottom) < elm_height;

        console.log(tableoffbottom);
        console.log(btn_offsetbottom);
        console.log(bottom_edge);
        console.log((tableoffbottom - btn_offsetbottom) + "|| " + elm_height);


        var table_offset_bottom = docHeight - (table_offset.top + table_height);

        var touchTableBottom = (btn_offset.top + btn_height + (elm_height * 2)) - table_offset.top;

        var bottomedge = touchTableBottom > table_offset_bottom;

        if (left_edge) {
            $(this).addClass('left-edge');
        } else {
            $('.dropdown-menu').removeClass('left-edge');
        }
        if (bottom_edge) {
            $(this).parent().addClass('dropup');
        } else {
            $(this).parent().removeClass('dropup');
        }

    }
});
var table_smallheight = $('.tableresp'),
    positioning = table_smallheight.parent();

if (table_smallheight.height() < 320) {
    positioning.addClass('positioning');
    $('.tableresp .dropdown,.tableresp .adropup').css('position', 'static');

} else {
    positioning.removeClass('positioning');
    $('.tableresp .dropdown,.tableresp .dropup').css('position', 'relative');

}

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
  $validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
  if(!$validUser) $errorMsg = "Invalid username or password.";
  else $_SESSION["login"] = true;
}
if($validUser) {
   header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <title>Login</title>
</head>
<body>
  <form name="input" action="" method="post">
    <label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
    <label for="password">Password:</label><input type="password" value="" id="password" name="password" />
    <div class="error"><?= $errorMsg ?></div>
    <input type="submit" value="Home" name="sub" />
  </form>
</body>
</html>

Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well. Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.

How to get a list of installed android applications and pick one to run

To filter on sytem based apps :

private boolean isSystemPackage(ResolveInfo ri) {
    return (ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}

How to assert greater than using JUnit Assert?

you can also try below simple soln:

previousTokenValues[1] = "1378994409108";
currentTokenValues[1] = "1378994416509";

Long prev = Long.parseLong(previousTokenValues[1]);
Long curr = Long.parseLong(currentTokenValues[1]);

Assert.assertTrue(prev  > curr );   

How to get the filename without the extension from a path in Python?

The other methods don't remove multiple extensions. Some also have problems with filenames that don't have extensions. This snippet deals with both instances and works in both Python 2 and 3. It grabs the basename from the path, splits the value on dots, and returns the first one which is the initial part of the filename.

import os

def get_filename_without_extension(file_path):
    file_basename = os.path.basename(file_path)
    filename_without_extension = file_basename.split('.')[0]
    return filename_without_extension

Here's a set of examples to run:

example_paths = [
    "FileName", 
    "./FileName",
    "../../FileName",
    "FileName.txt", 
    "./FileName.txt.zip.asc",
    "/path/to/some/FileName",
    "/path/to/some/FileName.txt",
    "/path/to/some/FileName.txt.zip.asc"
]

for example_path in example_paths:
    print(get_filename_without_extension(example_path))

In every case, the value printed is:

FileName

Passing Javascript variable to <a href >

<script>
   var scrt_var = 10;
   document.getElementById("link").setAttribute("href",scrt_var);
</script>
<a id="link">this is a link</a>

Find object in list that has attribute equal to some value (that meets any condition)

I just ran into a similar problem and devised a small optimization for the case where no object in the list meets the requirement.(for my use-case this resulted in major performance improvement):

Along with the list test_list, I keep an additional set test_value_set which consists of values of the list that I need to filter on. So here the else part of agf's solution becomes very-fast.

jQuery find() method not working in AngularJS directive

You can do it like this:

 var myApp = angular.module('myApp', [])
  .controller('Ctrl', ['$scope', function($scope) {
     $scope.aaa = 3432
 }])
 .directive('test', function () {
    return {
       link: function (scope, elm, attr) {
           var look = elm.children('#findme').addClass("addedclass");
           console.log(look);
        }
   };
});

<div ng-app="myApp" ng-controller="Ctrl">
   <div test>TEST Div
      <div id="findme">{{aaa}}</div>
   </div>
</div>

http://jsfiddle.net/FZGKA/133/

Check for database connection, otherwise display message

Please check this:

$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';

$connection = mysqli_connect($servername,$username,$password);

if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}

/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");

if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}

mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");

$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)"; 
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/

(413) Request Entity Too Large | uploadReadAheadSize

For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service

How can I search an array in VB.NET?

Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.

How to insert element as a first child?

parentNode.insertBefore(newChild, refChild)

Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

Using RegEX To Prefix And Append In Notepad++

Use a Macro.

Macro>Start Recording

Use the keyboard to make your changes in a repeatable manner e.g.

home>type "able">end>down arrow>home

Then go back to the menu and click stop recording then run a macro multiple times.

That should do it and no regex based complications!

Array vs ArrayList in performance

It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.

Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.

How do I list all files of a directory?

Here's my general-purpose function for this. It returns a list of file paths rather than filenames since I found that to be more useful. It has a few optional arguments that make it versatile. For instance, I often use it with arguments like pattern='*.txt' or subfolders=True.

import os
import fnmatch

def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
    """Return a list of the file paths matching the pattern in the specified 
    folder, optionally including files inside subfolders.
    """
    match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
    walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
    return [os.path.join(root, f)
            for root, dirnames, filenames in walked
            for f in filenames if match(f, pattern)]

mat-form-field must contain a MatFormFieldControl

You could try following this guide and implement/provide your own MatFormFieldControl

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()