Programs & Examples On #System administration

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

How do I extract the contents of an rpm?

$ mkdir packagecontents; cd packagecontents
$ rpm2cpio ../foo.rpm | cpio -idmv
$ find . 

For Reference: the cpio arguments are

-i = extract
-d = make directories
-m = preserve modification time
-v = verbose

I found the answer over here: lontar's answer

Map a network drive to be used by a service

You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.

The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:

  • The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)

  • Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.

What Process is using all of my disk IO

To find out which processes in state 'D' (waiting for disk response) are currently running:

while true; do date; ps aux | awk '{if($8=="D") print $0;}'; sleep 1; done

or

watch -n1 -d "ps axu | awk '{if (\$8==\"D\") {print \$0}}'"

Wed Aug 29 13:00:46 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:47 CLT 2012
Wed Aug 29 13:00:48 CLT 2012
Wed Aug 29 13:00:49 CLT 2012
Wed Aug 29 13:00:50 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:51 CLT 2012
Wed Aug 29 13:00:52 CLT 2012
Wed Aug 29 13:00:53 CLT 2012
Wed Aug 29 13:00:55 CLT 2012
Wed Aug 29 13:00:56 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:57 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:58 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:00:59 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:01:00 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:01:01 CLT 2012
root       302  0.0  0.0      0     0 ?        D    May28   3:07  \_ [kdmflush]
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]
Wed Aug 29 13:01:02 CLT 2012
Wed Aug 29 13:01:03 CLT 2012
root       321  0.0  0.0      0     0 ?        D    May28   4:25  \_ [jbd2/dm-0-8]

As you can see from the result, the jdb2/dm-0-8 (ext4 journal process), and kdmflush are constantly block your Linux.

For more details this URL could be helpful: Linux Wait-IO Problem

How do I properly force a Git push?

And if push --force doesn't work you can do push --delete. Look at 2nd line on this instance:

git reset --hard HEAD~3  # reset current branch to 3 commits ago
git push origin master --delete  # do a very very bad bad thing
git push origin master  # regular push

But beware...

Never ever go back on a public git history!

In other words:

  • Don't ever force push on a public repository.
  • Don't do this or anything that can break someone's pull.
  • Don't ever reset or rewrite history in a repo someone might have already pulled.

Of course there are exceptionally rare exceptions even to this rule, but in most cases it's not needed to do it and it will generate problems to everyone else.

Do a revert instead.

And always be careful with what you push to a public repo. Reverting:

git revert -n HEAD~3..HEAD  # prepare a new commit reverting last 3 commits
git commit -m "sorry - revert last 3 commits because I was not careful"
git push origin master  # regular push

In effect, both origin HEADs (from the revert and from the evil reset) will contain the same files.


edit to add updated info and more arguments around push --force

Consider pushing force with lease instead of push, but still prefer revert

Another problem push --force may bring is when someone push anything before you do, but after you've already fetched. If you push force your rebased version now you will replace work from others.

git push --force-with-lease introduced in the git 1.8.5 (thanks to @VonC comment on the question) tries to address this specific issue. Basically, it will bring an error and not push if the remote was modified since your latest fetch.

This is good if you're really sure a push --force is needed, but still want to prevent more problems. I'd go as far to say it should be the default push --force behaviour. But it's still far from being an excuse to force a push. People who fetched before your rebase will still have lots of troubles, which could be easily avoided if you had reverted instead.

And since we're talking about git --push instances...

Why would anyone want to force push?

@linquize brought a good push force example on the comments: sensitive data. You've wrongly leaked data that shouldn't be pushed. If you're fast enough, you can "fix"* it by forcing a push on top.

* The data will still be on the remote unless you also do a garbage collect, or clean it somehow. There is also the obvious potential for it to be spread by others who'd fetched it already, but you get the idea.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

javac option to compile all java files under a given directory recursively

I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.

You would just have to define a target like this in the build.xml file:

<target name="compile">
    <javac srcdir="your/source/directory"
           destdir="your/output/directory"
           classpath="xyz.jar" />
</target>

Where does MySQL store database files on Windows and what are the names of the files?

You can check my.ini file to see where the data folder is located.

Usually there is a folder {mysqlDirectory}/data

MySQL data storage:

Commands.frm
Commands.myd
Commands.myi

The *.frm files contain the table definitions. Your *.myi files are MyISAM index files. Your *.myd files contain the table data.

Edit/Update. Because of the interest shown in the question here is more info which is found also in the comments.

In Windows 8.1, the MySQL databases are stored (by default) here: C:\ProgramData\MySQL\MySQL Server 5.6\data

The folder C:\ProgramData is a hidden folder, so you must type it into Windows Explorer address to get there. In that data folder, the databases are named /{database_name_folder}/{database_tables_and_files}.

For instance,

C:\ProgramData\MySQL\MySQL Server 5.6\data\mydatabase\mytable.frm
C:\ProgramData\MySQL\MySQL Server 5.6\data\mydatabase\mytable.ibd 

Thank @marty-mcgee for this content

File Explorer in Android Studio

enter image description here

Then the Android Device Monitor window will pop up. Click on the emulator & File Explorer.

Shared Preference files should be in:

DDMS-> File Explorer ->data -> data -> MY_PACKAGE_NAME -> shared_prefs -> YOUR_PREFERENCE_NAME.xml

enter image description here

How can I increment a date by one day in Java?

You can use this package from "org.apache.commons.lang3.time":

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 Date myNewDate = DateUtils.addDays(myDate, 4);
 Date yesterday = DateUtils.addDays(myDate, -1);
 String formatedDate = sdf.format(myNewDate);  

How to pass macro definition from "make" command line arguments (-D) to C source code?

Find the C file and Makefile implementation in below to meet your requirements

foo.c

 main ()
    {
        int a = MAKE_DEFINE;
        printf ("MAKE_DEFINE value:%d\n", a);
    }

Makefile

all:
    gcc -DMAKE_DEFINE=11 foo.c

Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

As per keras tutorial, you can simply use the same tf.device scope as in regular tensorflow:

with tf.device('/gpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on GPU:0

with tf.device('/cpu:0'):
    x = tf.placeholder(tf.float32, shape=(None, 20, 64))
    y = LSTM(32)(x)  # all ops in the LSTM layer will live on CPU:0

How to pass a JSON array as a parameter in URL

I would suggest to pass the JSON data in the body as a POST request.But if you still want to pass this as a parameter in URL,you will have to encode your URL like below just for example:-

for ex json is :->{"name":"ABC","id":"1"}

testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

for more information on URL encoding refer below

https://en.wikipedia.org/wiki/Percent-encoding

How to programmatically take a screenshot on Android?

You can try to do something like this,

Getting a bitmap cache from a layout or a view by doing something like First you gotta setDrawingCacheEnabled to a layout(a linearlayout or relativelayout, or a view)

then

Bitmap bm = layout.getDrawingCache()

Then you do whatever you want with the bitmap. Either turning it into an image file, or send the bitmap's uri to somewhere else.

Radio button checked event handling

You can simply use the method change of JQuery to get the value of the current radio checked with the following code:

$(document).on('change', '[type="radio"]', function() {
    var currentlyValue = $(this).val(); // Get the radio checked value
        
    alert('Currently value: '+currentlyValue); // Show a alert with the current value
});

You can change the selector '[type="radio"]' for a class or id that you want.

What is the main difference between Collection and Collections in Java?

Collection is an interface from which other class forms like List, Set are derived. Collections (with "S") is a utility class having static methods to simplify work on collection. Ex : Collections.sort()

Pass a data.frame column name to a function

Personally I think that passing the column as a string is pretty ugly. I like to do something like:

get.max <- function(column,data=NULL){
    column<-eval(substitute(column),data, parent.frame())
    max(column)
}

which will yield:

> get.max(mpg,mtcars)
[1] 33.9
> get.max(c(1,2,3,4,5))
[1] 5

Notice how the specification of a data.frame is optional. you can even work with functions of your columns:

> get.max(1/mpg,mtcars)
[1] 0.09615385

Given a class, see if instance has method (Ruby)

I don't know why everyone is suggesting you should be using instance_methods and include? when method_defined? does the job.

class Test
  def hello; end
end

Test.method_defined? :hello #=> true

NOTE

In case you are coming to Ruby from another OO language OR you think that method_defined means ONLY methods that you defined explicitly with:

def my_method
end

then read this:

In Ruby, a property (attribute) on your model is basically a method also. So method_defined? will also return true for properties, not just methods.

For example:

Given an instance of a class that has a String attribute first_name:

<instance>.first_name.class #=> String

<instance>.class.method_defined?(:first_name) #=> true

since first_name is both an attribute and a method (and a string of type String).

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

Change default timeout for mocha

In current versions of Mocha, the timeout can be changed globally like this:

mocha.timeout(5000);

Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.


In older versions, and only in a browser, you could change the global configuration using mocha.setup.

mocha.setup({ timeout: 5000 });

The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.

IF... OR IF... in a windows batch file

The goal can be achieved by using IFs indirectly.

Below is an example of a complex expression that can be written quite concisely and logically in a CMD batch, without incoherent labels and GOTOs.

Code blocks between () brackets are handled by CMD as a (pathetic) kind of subshell. Whatever exit code comes out of a block will be used to determine the true/false value the block plays in a larger boolean expression. Arbitrarily large boolean expressions can be built with these code blocks.

Simple example

Each block is resolved to true (i.e. ERRORLEVEL = 0 after the last statement in the block has executed) / false, until the value of the whole expression has been determined or control jumps out (e.g. via GOTO):

 ((DIR c:\xsgdde /w) || (DIR c:\ /w)) && (ECHO -=BINGO=-)

Complex example

This solves the problem raised initially. Multiple statements are possible in each block but in the || || || expression it's preferable to be concise so that it's as readable as possible. ^ is an escape char in CMD batches and when placed at the end of a line it will escape the EOL and instruct CMD to continue reading the current batch of statements on the next line.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

(
    (CALL :ProcedureType1 a b) ^
        || (CALL :ProcedureType2 sgd) ^
            || (CALL :ProcedureType1 c c)
) ^
    && (
        ECHO -=BINGO=-
        GOTO :EOF
    )
ECHO -=no bingo for you=-
GOTO :EOF

:ProcedureType1
    IF "%~1" == "%~2" (EXIT /B 0) ELSE (EXIT /B 1)
GOTO :EOF (this line is decorative as it's never reached)

:ProcedureType2
    ECHO :ax:xa:xx:aa:|FINDSTR /I /L /C:":%~1:">nul
GOTO :EOF

Transparent scrollbar with css

    .scrollable-content {
      overflow-x:hidden;
      overflow-y:scroll; // manage scrollbar content overflow settings
    }
    .scrollable-content::-webkit-scrollbar {
      width:30px; // manage scrollbar width here
    }
    .scrollable-content::-webkit-scrollbar * {
      background:transparent; // manage scrollbar background color here
    }
    .scrollable-content::-webkit-scrollbar-thumb {
      background:rgba(255,0,0,0.1) !important; // manage scrollbar thumb background color here
    }

Avoid synchronized(this) in Java?

Well, firstly it should be pointed out that:

public void blah() {
  synchronized (this) {
    // do stuff
  }
}

is semantically equivalent to:

public synchronized void blah() {
  // do stuff
}

which is one reason not to use synchronized(this). You might argue that you can do stuff around the synchronized(this) block. The usual reason is to try and avoid having to do the synchronized check at all, which leads to all sorts of concurrency problems, specifically the double checked-locking problem, which just goes to show how difficult it can be to make a relatively simple check threadsafe.

A private lock is a defensive mechanism, which is never a bad idea.

Also, as you alluded to, private locks can control granularity. One set of operations on an object might be totally unrelated to another but synchronized(this) will mutually exclude access to all of them.

synchronized(this) just really doesn't give you anything.

Display Records From MySQL Database using JTable in Java

Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFromMySqlDatabase extends JFrame
{
    public TableFromMySqlDatabase()
    {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();

        //  Connect to an MySQL Database, run query, get result set
        String url = "jdbc:mysql://localhost:3306/yourdb";
        String userid = "root";
        String password = "sesame";
        String sql = "SELECT * FROM animals";

        // Java SE 7 has try-with-resources
        // This will ensure that the sql objects are closed when the program 
        // is finished with them
        try (Connection connection = DriverManager.getConnection( url, userid, password );
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery( sql ))
        {
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++)
            {
                columnNames.add( md.getColumnName(i) );
            }

            //  Get row data
            while (rs.next())
            {
                ArrayList row = new ArrayList(columns);

                for (int i = 1; i <= columns; i++)
                {
                    row.add( rs.getObject(i) );
                }

                data.add( row );
            }
        }
        catch (SQLException e)
        {
            System.out.println( e.getMessage() );
        }

        // Create Vectors and copy over elements from ArrayLists to them
        // Vector is deprecated but I am using them in this example to keep 
        // things simple - the best practice would be to create a custom defined
        // class which inherits from the AbstractTableModel class
        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();

        for (int i = 0; i < data.size(); i++)
        {
            ArrayList subArray = (ArrayList)data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++)
            {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }

        for (int i = 0; i < columnNames.size(); i++ )
            columnNamesVector.add(columnNames.get(i));

        //  Create table with database data    
        JTable table = new JTable(dataVector, columnNamesVector)
        {
            public Class getColumnClass(int column)
            {
                for (int row = 0; row < getRowCount(); row++)
                {
                    Object o = getValueAt(row, column);

                    if (o != null)
                    {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );

        JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }

    public static void main(String[] args)
    {
        TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    }
}

In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:

enter image description here

Otherwise the code will throw an SQLException stating that the driver cannot be found.

Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.

Here is what will be output:

enter image description here

Parting note:

You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.

How to print a linebreak in a python function?

Also if you're making it a console program, you can do: print(" ") and continue your program. I've found it the easiest way to separate my text.

Convert datetime value into string

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

form confirm before submit

Based on easy-confirm-plugin i did it:

(function($) {
    $.postconfirm = {};
    $.postconfirm.locales = {};
    $.postconfirm.locales.ptBR = {
        title: 'Esta certo disto?',
        text: 'Esta certo que quer realmente ?',
        button: ['Cancela', 'Confirma'],
        closeText: 'fecha'
    };
    $.fn.postconfirm = function(options) {
        var options = jQuery.extend({
            eventType: 'click',
            icon: 'help'
        }, options);
        var locale = jQuery.extend({}, $.postconfirm.locales.ptBR, options.locale);
        var type = options.eventType;
        return this.each(function() {
            var target = this;
            var $target = jQuery(target);
            var getDlgDv = function() {
                var dlger = (options.dialog === undefined || typeof(options.dialog) != 'object');
                var dlgdv = $('<div class="dialog confirm">' + locale.text + '</div>');         
                return dlger ? dlgdv : options.dialog;          
            }           
            var dialog = getDlgDv();
            var handler = function(event) {
                    $(dialog).dialog('open');
                    event.stopImmediatePropagation();
                    event.preventDefault();
                    return false;
            };
            var init = function() 
            {
                $target.bind(type, handler); 
            };
            var buttons = {};
            buttons[locale.button[0]] = function() { $(dialog).dialog("close"); };
            buttons[locale.button[1]] = function() {
                $(dialog).dialog("close");
                alert('1');
                $target.unbind(type, handler);
                $target.click();
                $target.attr("disabled", true);
            };            
            $(dialog).dialog({
                autoOpen: false,
                resizable: false,
                draggable: true,
                closeOnEscape: true,
                width: 'auto',
                minHeight: 120,
                maxHeight: 200,
                buttons: buttons,
                title: locale.title,
                closeText: locale.closeText,
                modal: true
            });
            init();
        });
        var _attr = $.fn.attr;
        $.fn.attr = function(attr, value) {
            var returned = _attr.apply(this, arguments);
            if (attr == 'title' && returned === undefined) 
            {
                returned = '';
            }
            return returned;
        };
    };
})(jQuery);

you only need call in this way:

    <script type="text/javascript">     
        $(document).ready(function () {
            $(".mybuttonselector").postconfirm({ locale: {
                        title: 'title',
                        text: 'message',
                        button: ['bt_0', 'bt_1'],
                        closeText: 'X'
                    }
                });
        });
    </script>

Playing a MP3 file in a WinForm application

The link below, gives a very good tutorial, about playing mp3 files from a windows form with c#:

http://www.daniweb.com/software-development/csharp/threads/292695/playing-mp3-in-c

This link will lead you to a topic, which contains a lot information about how to play an mp3 song, using Windows forms. It also contains a lot of other projects, trying to achieve the same thing:

http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/3dbfb9a3-4e14-41d1-afbb-1790420706fe

For example use this code for .mp3:

WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

wplayer.URL = "My MP3 file.mp3";
wplayer.Controls.Play();

Then only put the wplayer.Controls.Play(); in the Button_Click event.

For example use this code for .wav:

System.Media.SoundPlayer player = new System.Media.SoundPlayer();

player.SoundLocation = "Sound.wav";
player.Play();

Put the player.Play(); in the Button_Click event, and it will work.

Styling every 3rd item of a list using CSS?

You can use the :nth-child selector for that

li:nth-child(3n) {
 /* your rules here */
}

How to find GCD, LCM on a set of numbers

for gcd you cad do as below:

    String[] ss = new Scanner(System.in).nextLine().split("\\s+");
    BigInteger bi,bi2 = null;
    bi2 = new BigInteger(ss[1]);
    for(int i = 0 ; i<ss.length-1 ; i+=2 )
    {
        bi = new BigInteger(ss[i]);
        bi2 = bi.gcd(bi2);
    }
    System.out.println(bi2.toString());

Convert a char to upper case using regular expressions (EditPad Pro)

Just an another ussage example for Notepad++ (regular expression search mode)

Find: (g|c|u|d)(et|reate|pdate|elete)_(.)([^\s (]+)
Replace: \U\1\E$2\U\3\E$4

Example:

get_user -> GetUser
create_user -> CreateUser
update_user -> UpdateUser
delete_user -> DeleteUser

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

How do I get the function name inside a function in PHP?

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

What's the difference between next() and nextLine() methods from Scanner class?

From javadocs

next() Returns the next token if it matches the pattern constructed from the specified string. nextLine() Advances this scanner past the current line and returns the input that was skipped.

Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.

Table cell widths - fixing width, wrapping/truncating long words

<style type="text/css">
td { word-wrap: break-word;max-width:50px; }            
</style>

How to refresh page on back button click?

You can use the following to refresh the page by clicking the back button:

window.addEventListener('popstate', () => {
  location.reload();
}, false);

How to open child forms positioned within MDI parent in VB.NET?

If your form is "outside" the MDI parent, then you most likely didn't set the MdiParent property:

Dim f As New Form
f.MdiParent = Me
f.Show()

Me, in this example, is a form that has IsMdiContainer = True so that it can host child forms.

For re-arranging the child form layout, you just call the method from your MdiContainer form:

Me.LayoutMdi(MdiLayout.Cascade)

The MdiLayout enum also has tiling and arrange icons values.

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was just banging my head against a wall just trying to get S3 uploads to work with large files. Initially my error was:

An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied

Then I tried copying a smaller file and got:

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I could list objects fine but I couldn't do anything else even though I had s3:* permissions in my Role policy. I ended up reworking the policy to this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::my-bucket/*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucketMultipartUploads",
                "s3:AbortMultipartUpload",
                "s3:ListMultipartUploadParts"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "*"
        }
    ]
}

Now I'm able to upload any file. Replace my-bucket with your bucket name. I hope this helps somebody else that's going thru this.

Your branch is ahead of 'origin/master' by 3 commits

There is nothing to fix. You simply have made 3 commits and haven't moved them to the remote branch yet. There are several options, depending on what you want to do:

  • git push: move your changes to the remote (this might get rejected if there are already other changes on the remote)
  • do nothing and keep coding, sync another day
  • git pull: get the changes (if any) from the remote and merge them into your changes
  • git pull --rebase: as above, but try to redo your commits on top of the remote changes

You are in a classical situation (although usually you wouldn't commit a lot on master in most workflows). Here is what I would normally do: Review my changes. Maybe do a git rebase --interactive to do some cosmetics on them, drop the ones that suck, reorder them to make them more logical. Now move them to the remote with git push. If this gets rejected because my local branch is not up to date: git pull --rebase to redo my work on top of the most recent changes and git push again.

css ellipsis on second line

here is good example in pure css.

_x000D_
_x000D_
.container{_x000D_
  width: 200px;_x000D_
}_x000D_
.block-with-text {_x000D_
  overflow: hidden;_x000D_
  position: relative; _x000D_
  line-height: 1.2em;_x000D_
  max-height: 3.6em;_x000D_
  text-align: justify;  _x000D_
  margin-right: -1em;_x000D_
  padding-right: 1em;_x000D_
}_x000D_
.block-with-text+.block-with-text{_x000D_
  margin-top:10px;_x000D_
}_x000D_
.block-with-text:before {_x000D_
  content: '...';_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}_x000D_
.block-with-text:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  width: 1em;_x000D_
  height: 1em;_x000D_
  margin-top: 0.2em;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
_x000D_
<div class="block-with-text">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a_x000D_
</div>_x000D_
_x000D_
<div class="block-with-text">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="block-with-text">_x000D_
Lorem Ipsum is simply_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Preloading CSS Images

Preloading images using CSS only

In the below code I am randomly choosing the body element, since it is one of the only elements guaranteed to exist on the page.

For the "trick" to work, we shall use the content property which comfortably allows setting multiple URLs to be loaded, but as shown, the ::after pseudo element is kept hidden so the images won't be rendered:

body::after{
   position:absolute; width:0; height:0; overflow:hidden; z-index:-1; // hide images
   content:url(img1.png) url(img2.png) url(img3.gif) url(img4.jpg);   // load images
}

Demo


it's better to use a sprite image to reduce http requests...(if there are many relatively small sized images) and make sure the images are hosted where HTTP2 is used.

How to do error logging in CodeIgniter (PHP)

CodeIgniter has some error logging functions built in.

  • Make your /application/logs folder writable
  • In /application/config/config.php set
    $config['log_threshold'] = 1;
    or use a higher number, depending on how much detail you want in your logs
  • Use log_message('error', 'Some variable did not contain a value.');
  • To send an email you need to extend the core CI_Exceptions class method log_exceptions(). You can do this yourself or use this. More info on extending the core here

See http://www.codeigniter.com/user_guide/general/errors.html

How to do vlookup and fill down (like in Excel) in R?

If I understand your question correctly, here are four methods to do the equivalent of Excel's VLOOKUP and fill down using R:

# load sample data from Q
hous <- read.table(header = TRUE, 
                   stringsAsFactors = FALSE, 
text="HouseType HouseTypeNo
Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3")

# create a toy large table with a 'HouseType' column 
# but no 'HouseTypeNo' column (yet)
largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)

# create a lookup table to get the numbers to fill
# the large table
lookup <- unique(hous)
  HouseType HouseTypeNo
1      Semi           1
2    Single           2
3       Row           3
5 Apartment           4

Here are four methods to fill the HouseTypeNo in the largetable using the values in the lookup table:

First with merge in base:

# 1. using base 
base1 <- (merge(lookup, largetable, by = 'HouseType'))

A second method with named vectors in base:

# 2. using base and a named vector
housenames <- as.numeric(1:length(unique(hous$HouseType)))
names(housenames) <- unique(hous$HouseType)

base2 <- data.frame(HouseType = largetable$HouseType,
                    HouseTypeNo = (housenames[largetable$HouseType]))

Third, using the plyr package:

# 3. using the plyr package
library(plyr)
plyr1 <- join(largetable, lookup, by = "HouseType")

Fourth, using the sqldf package

# 4. using the sqldf package
library(sqldf)
sqldf1 <- sqldf("SELECT largetable.HouseType, lookup.HouseTypeNo
FROM largetable
INNER JOIN lookup
ON largetable.HouseType = lookup.HouseType")

If it's possible that some house types in largetable do not exist in lookup then a left join would be used:

sqldf("select * from largetable left join lookup using (HouseType)")

Corresponding changes to the other solutions would be needed too.

Is that what you wanted to do? Let me know which method you like and I'll add commentary.

How do I get the directory that a program is running from?

Filesystem TS is now a standard ( and supported by gcc 5.3+ and clang 3.9+ ), so you can use current_path() function from it:

std::string path = std::experimental::filesystem::current_path();

In gcc (5.3+) to include Filesystem you need to use:

#include <experimental/filesystem>

and link your code with -lstdc++fs flag.

If you want to use Filesystem with Microsoft Visual Studio, then read this.

How to get single value from this multi-dimensional PHP array

You can also use array_column(). It's available from PHP 5.5: php.net/manual/en/function.array-column.php

It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

print_r(array_column($myarray, 'email'));

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

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

Omitting the second expression when using the if-else shorthand

Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.

As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:

if (x==2) doSomething;
else doSomethingElse

or, in your case,

if (x==2) doSomething;

Change <select>'s option and trigger events with JavaScript

These questions may be relevant to what you're asking for:

Here are my thoughts: You can stack up more than one call in your onclick event like this:

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true; alert("changed");' value="Change option to 2" />

You could also call a function to do this.

If you really want to call one function and have both behave the same way, I think something like this should work. It doesn't really follow the best practice of "Functions should do one thing and do it well", but it does allow you to call one function to handle both ways of changing the dropdown. Basically I pass (value) on the onchange event and (null, index of option) on the onclick event.

Here is the codepen: http://codepen.io/mmaynar1/pen/ZYJaaj

<select id="sel" onchange='doThisOnChange(this.value)'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='doThisOnChange(null,1);' value="Change option to 2"/>

<script>
doThisOnChange = function( value, optionIndex)
{
    if ( optionIndex != null )
    {
       var option = document.getElementById( "sel" ).options[optionIndex];
       option.selected = true;
       value = option.value;
    }
    alert( "Do something with the value: " + value );
}
</script>

Breaking to a new line with inline-block?

You can try with:

    display: inline-table;

For me it works fine.

AWK to print field $2 first, then field $1

Maybe your file contains CRLF terminator. Every lines followed by \r\n.

awk recognizes the $2 actually $2\r. The \r means goto the start of the line.

{print $2\r$1} will print $2 first, then return to the head, then print $1. So the field 2 is overlaid by the field 1.

Enable IIS7 gzip

Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup

test gzip

To add to web.config: http://www.iis.net/configreference/system.webserver/httpcompression

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

The above mentioned solutions didn't work for me.

I just restarted my IDE by closing it and reopening it.

And then error disappeared and its working fine now.

What does @@variable mean in Ruby?

@@ denotes a class variable, i.e. it can be inherited.

This means that if you create a subclass of that class, it will inherit the variable. So if you have a class Vehicle with the class variable @@number_of_wheels then if you create a class Car < Vehicle then it too will have the class variable @@number_of_wheels

Stored procedure - return identity as output parameter or scalar

SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;

How to write text on a image in windows using python opencv2

for the example above the solution would look like this:

import PILasOPENCV as Image
import PILasOPENCV as ImageDraw
import PILasOPENCV as ImageFont
# from PIL import ImageFont, ImageDraw, Image
import numpy as np
import cv2

image = cv2.imread("lena.jpg")

# Convert to PIL Image
cv2_im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(cv2_im_rgb)

draw = ImageDraw.Draw(pil_im)

# Choose a font
font = ImageFont.truetype("Roboto-Regular.ttf", 40)

# Draw the text
draw.text((0, 0), "Your Text Here", font=font)

# Save the image
cv2_im_processed = pil_im.getim()
cv2.imshow("cv2_im_processed", cv2_im_processed)
cv2.waitKey()

Input from the keyboard in command line application

Here is simple example of taking input from user on console based application: You can use readLine(). Take input from console for first number then press enter. After that take input for second number as shown in the image below:

func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
    return firstNo + secondNo
}

let num1 = readLine()
let num2 = readLine()

var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)

let sum = solveMefirst(IntNum1!, secondNo: IntNum2!)
print(sum)

Output

How do I declare and assign a variable on a single line in SQL

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

jQuery Dialog Box

I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.

The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.

So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!

<script type="text/javascript"> 
        jQuery(document).ready( function(){       
            jQuery("#myButton").click( showDialog );

            //variable to reference window
            $myWindow = jQuery('#myDiv');

            //instantiate the dialog
            $myWindow.dialog({ height: 350,
                width: 400,
                modal: true,
                position: 'center',
                autoOpen:false,
                title:'Hello World',
                overlay: { opacity: 0.5, background: 'black'}
                });
            }

        );
    //function to show dialog   
    var showDialog = function() {
        //if the contents have been hidden with css, you need this
        $myWindow.show(); 
        //open the dialog
        $myWindow.dialog("open");
        }

    //function to close dialog, probably called by a button in the dialog
    var closeDialog = function() {
        $myWindow.dialog("close");
    }


</script>
</head>

<body>

<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
    <p>I am a modal dialog</p>
</div>

What is the final version of the ADT Bundle?

You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.

How to print a specific row of a pandas DataFrame?

To print a specific row we have couple of pandas method

  1. loc - It only get label i.e column name or Features
  2. iloc - Here i stands for integer, actually row number
  3. ix - It is a mix of label as well as integer

How to use for specific row

  1. loc
df.loc[row,column]

For first row and all column

df.loc[0,:]

For first row and some specific column

df.loc[0,'column_name']
  1. iloc

For first row and all column

df.iloc[0,:]

For first row and some specific column i.e first three cols

df.iloc[0,0:3]

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

How to play or open *.mp3 or *.wav sound file in c++ program?

http://sfml-dev.org/documentation/2.0/classsf_1_1Music.php

SFML does not have mp3 support as another has suggested. What I always do is use Audacity and make all my music into ogg, and leave all my sound effects as wav.

Loading and playing a wav is simple (crude example):

http://www.sfml-dev.org/tutorials/2.0/audio-sounds.php

#include <SFML/Audio.hpp>
...
sf::SoundBuffer buffer;
if (!buffer.loadFromFile("sound.wav")){
    return -1;
}
sf::Sound sound;
sound.setBuffer(buffer);
sound.play();

Streaming an ogg music file is also simple:

#include <SFML/Audio.hpp>
...
sf::Music music;
if (!music.openFromFile("music.ogg"))
    return -1; // error
music.play();

Update multiple rows using select statement

You can use alias to improve the query:

UPDATE t1
   SET t1.Value = t2.Value
  FROM table1 AS t1
         INNER JOIN 
       table2 AS t2
         ON t1.ID = t2.ID

How to sort mongodb with pymongo

Sort by _id descending:

collection.find(filter={"keyword": keyword}, sort=[( "_id", -1 )])

Sort by _id ascending:

collection.find(filter={"keyword": keyword}, sort=[( "_id", 1 )])

How do I test if a variable does not equal either of two values?

Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.

Thus:

if(!(a || b)) {
  // means neither a nor b
}

However, using De Morgan's Law, it could be written as:

if(!a && !b) {
  // is not a and is not b
}

a and b above can be any expression (such as test == 'B' or whatever it needs to be).

Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:

// if(!(a || b)) 
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')

How can I calculate the number of lines changed between two commits in Git?

I just solved this problem for myself, so I'll share what I came up with. Here's the end result:

> git summary --since=yesterday
total: 114 file changes, 13800 insertions(+) 638 deletions(-)

The underlying command looks like this:

git log --numstat --format="" "$@" | awk '{files += 1}{ins += $1}{del += $2} END{print "total: "files" files, "ins" insertions(+) "del" deletions(-)"}'

Note the $@ in the log command to pass on your arguments such as --author="Brian" or --since=yesterday.

Escaping the awk to put it into a git alias was messy, so instead, I put it into an executable script on my path (~/bin/git-stat-sum), then used the script in the alias in my .gitconfig:

[alias]
    summary = !git-stat-sum \"$@\"

And it works really well. One last thing to note is that file changes is the number of changes to files, not the number of unique files changed. That's what I was looking for, but it may not be what you expect.

Here's another example or two

git summary --author=brian
git summary master..dev
# combine them as you like
git summary --author=brian master..dev
git summary --all

Really, you should be able to replace any git log command with git summary.

how to convert a string date into datetime format in python?

You should use datetime.datetime.strptime:

import datetime

dt = datetime.datetime.strptime(string_date, fmt)

fmt will need to be the appropriate format for your string. You'll find the reference on how to build your format here.

NSOperation vs Grand Central Dispatch

GCD is indeed lower-level than NSOperationQueue, its major advantage is that its implementation is very light-weight and focused on lock-free algorithms and performance.

NSOperationQueue does provide facilities that are not available in GCD, but they come at non-trivial cost, the implementation of NSOperationQueue is complex and heavy-weight, involves a lot of locking, and uses GCD internally only in a very minimal fashion.

If you need the facilities provided by NSOperationQueue by all means use it, but if GCD is sufficient for your needs, I would recommend using it directly for better performance, significantly lower CPU and power cost and more flexibility.

How to loop through a checkboxlist and to find what's checked and not checked?

for (int i = 0; i < clbIncludes.Items.Count; i++)
  if (clbIncludes.GetItemChecked(i))
    // Do selected stuff
  else
    // Do unselected stuff

If the the check is in indeterminate state, this will still return true. You may want to replace

if (clbIncludes.GetItemChecked(i))

with

if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)

if you want to only include actually checked items.

Best practice for Django project working directory structure

As per the Django Project Skeleton, the proper directory structure that could be followed is :

[projectname]/                  <- project root
+-- [projectname]/              <- Django root
¦   +-- __init__.py
¦   +-- settings/
¦   ¦   +-- common.py
¦   ¦   +-- development.py
¦   ¦   +-- i18n.py
¦   ¦   +-- __init__.py
¦   ¦   +-- production.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- apps/
¦   +-- __init__.py
+-- configs/
¦   +-- apache2_vhost.sample
¦   +-- README
+-- doc/
¦   +-- Makefile
¦   +-- source/
¦       +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦   +-- media/
¦   ¦   +-- README
¦   +-- README
¦   +-- static/
¦       +-- README
+-- static/
¦   +-- README
+-- templates/
    +-- base.html
    +-- core
    ¦   +-- login.html
    +-- README

Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.

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

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

Regular Expression to get a string between parentheses in Javascript

Alternative:

var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
? (2) ["$500", "$1"]

It is possible to replace brackets with square or curly brackets if you need

Gitignore not working

Also, comments have to be on their own line. They can't be put after an entry. So this won't work:

/node_modules  # DON'T COMMENT HERE (since nullifies entire line)

But this will work:

# fine to comment here
/node_modules

Android - styling seek bar

With the Material Component Library version 1.2.0 you can use the new Slider component.

 <com.google.android.material.slider.Slider
       android:valueFrom="0"
       android:valueTo="300"
       android:value="200"
       android:theme="@style/slider_red"
       />

You can override the default color using something like:

  <style name="slider_red">
    <item name="colorPrimary">#......</item>
  </style>

enter image description here

Otherwise you can use these attribute in the layout to define a color or a color selector:

   <com.google.android.material.slider.Slider
       app:activeTrackColor="@color/...."
       app:inactiveTrackColor="@color/...."
       app:thumbColor="@color/...."
       />

or you can use a custom style:

 <style name="customSlider" parent="Widget.MaterialComponents.Slider">
    <item name="activeTrackColor">@color/....</item>
    <item name="inactiveTrackColor">@color/....</item>
    <item name="thumbColor">@color/....</item>
  </style>

Random String Generator Returning Same String

I created this method.

It works great.

public static string GeneratePassword(int Lenght, int NonAlphaNumericChars)
    {
        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
        string allowedNonAlphaNum = "!@#$%^&*()_-+=[{]};:<>|./?";
        Random rd = new Random();

        if (NonAlphaNumericChars > Lenght || Lenght <= 0 || NonAlphaNumericChars < 0)
            throw new ArgumentOutOfRangeException();

            char[] pass = new char[Lenght];
            int[] pos = new int[Lenght];
            int i = 0, j = 0, temp = 0;
            bool flag = false;

            //Random the position values of the pos array for the string Pass
            while (i < Lenght - 1)
            {
                j = 0;
                flag = false;
                temp = rd.Next(0, Lenght);
                for (j = 0; j < Lenght; j++)
                    if (temp == pos[j])
                    {
                        flag = true;
                        j = Lenght;
                    }

                if (!flag)
                {
                    pos[i] = temp;
                    i++;
                }
            }

            //Random the AlphaNumericChars
            for (i = 0; i < Lenght - NonAlphaNumericChars; i++)
                pass[i] = allowedChars[rd.Next(0, allowedChars.Length)];

            //Random the NonAlphaNumericChars
            for (i = Lenght - NonAlphaNumericChars; i < Lenght; i++)
                pass[i] = allowedNonAlphaNum[rd.Next(0, allowedNonAlphaNum.Length)];

            //Set the sorted array values by the pos array for the rigth posistion
            char[] sorted = new char[Lenght];
            for (i = 0; i < Lenght; i++)
                sorted[i] = pass[pos[i]];

            string Pass = new String(sorted);

            return Pass;
    }

Python memory usage of numpy arrays

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

Cross-Origin Read Blocking (CORB)

In a Chrome extension, you can use

chrome.webRequest.onHeadersReceived.addListener

to rewrite the server response headers. You can either replace an existing header or add an additional header. This is the header you want:

Access-Control-Allow-Origin: *

https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived

I was stuck on CORB issues, and this fixed it for me.

OraOLEDB.Oracle provider is not registered on the local machine

I had the same issue after installing the 64 bit Oracle client on Windows 7 64 bit. The solution that worked for me:

  1. Open a command prompt in administrator mode
  2. cd \oracle\product\11.2.0\client_64\BIN
  3. c:\Windows\system32\regsvr32.exe OraOLEDB11.dll

SQL Server, division returns zero

if you declare it as float or any decimal format it will display

0

only

E.g :

declare @weight float;

SET @weight= 47 / 638; PRINT @weight

Output : 0

If you want the output as

0.073667712

E.g

declare @weight float;

SET @weight= 47.000000000 / 638.000000000; PRINT @weight

convert month from name to number

<?php
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
echo $monthName; //output: May
?>

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

Make sure that the controller has a parameterless public constructor error

What's happening is that you're bitten by this problem. Basically, what happened is that you didn't register your controllers explicitly in your container. Unity tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. Since Unity returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. This exception message is misleading and doesn't explain the real cause.

You would have seen a much clearer exception message if you registered your controllers explicitly, and that's why you should always register all root types explicitly.

But of course, the configuration error comes from you adding the second constructor to your DbContext. Unity always tries to pick the constructor with the most arguments, but it has no idea how to resolve this particular constructor.

So the real cause is that you are trying to use Unity's auto-wiring capabilities to create the DbContext. DbContext is a special type that shouldn't be auto-wired. It is a framework type and you should therefore fallback to registering it using a factory delegate:

container.Register<DashboardDbContext>(
    new InjectionFactory(c => new DashboardDbContext())); 

How can I add to a List's first position?

You do that by inserting into position 0:

List myList = new List();
myList.Insert(0, "test");

eslint: error Parsing error: The keyword 'const' is reserved

I used .eslintrc.js and I have added following code.

module.exports = {
    "parserOptions": {
        "ecmaVersion": 6
    }
};

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

Enable UTF-8 encoding for JavaScript

For others, I just had a similar problem and had to copy all code from my file, put it to simple notepad, save it with utf-8 coding and then replace my original file.

The problem at my side was caused by using PSpad editor.

Find element in List<> that contains a value

I would use .Equals() for comparison instead of ==.

Like so:

MyClass item = MyList.Find(item => item.name.Equals("foo"));

Particularly because it gives you options like StringComparison, which is awesome. Example:

MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);

This enables your code to ignore special characters, upper and lower case. There are more options.

Change border color on <select> HTML form

I would consinder enclosing that select block within a div block and setting the border property like this:

_x000D_
_x000D_
<div style="border: 2px solid blue;">_x000D_
  <select style="width: 100%;">_x000D_
    <option value="Sal">Sal</option>_x000D_
    <option value="Awesome">Awesome!</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You should be able to play with that to accomplish what you need.

Command to get time in milliseconds

I just wanted to add to Alper's answer what I had to do to get this stuff working:

On Mac, you'll need brew install coreutils, so we can use gdate. Otherwise on Linux, it's just date. And this function will help you time commands without having to create temporary files or anything:

function timeit() {
    start=`gdate +%s%N`
    bash -c $1
    end=`gdate +%s%N`
    runtime=$(((end-start)/1000000000.0))
    echo " seconds"
}

And you can use it with a string:

timeit 'tsc --noEmit'

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

array of string with unknown size

string foo = "Apple, Plum, Cherry";

string[] myArr = null;

myArr = foo.Split(',');

How to change spinner text size and text color?

To prevent lagging, you need to not only set the text properties in the onItemSelected listener, but also in the Activity's onCreate method (but it's a little tricky).

Specifically, you need to put this in onCreate after setting the adapter:

spinner.setSelection(0, true);
View v = spinner.getSelectedView();
((TextView)v).setTextColor(backgroundColor);

And then put this in onItemSelected:

((TextView) view).setTextColor(backgroundColor);

Here is a full example:

@Override  
protected void onCreate(Bundle savedInstanceState)
{  
    Spinner spinner = (Spinner) findViewById(R.id.spinner); 

    //Set the choices on the spinner by setting the adapter.  
    spinner.setAdapter(new SpinnerAdapter(toolbar.getContext(), new String[]{"Overview", "Story", "Specifications", "Poll", "Video"}, accentColor, backgroundColor));

    //Set the text color of the Spinner's selected view (not a drop down list view) 
    spinner.setSelection(0, true);
    View v = spinner.getSelectedView();
    ((TextView)v).setTextColor(backgroundColor);

    //Set the listener for when each option is clicked.  
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {  

        @Override  
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {  
           //Change the selected item's text color  
           ((TextView) view).setTextColor(backgroundColor);
        }  

        @Override  
        public void onNothingSelected(AdapterView<?> parent)
        {  
        }  
    });  

}  

For more details, see my question.

How to make Bootstrap 4 cards the same height in card-columns?

You can use card-deck, it will align all the cards... this come from bootstrap 4 official page.

<div class="card-deck">
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
  <div class="card">
    <img class="card-img-top" src="..." alt="Card image cap">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
      <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
    </div>
  </div>
</div>

Finding child element of parent pure javascript

If you already have var parent = document.querySelector('.parent'); you can do this to scope the search to parent's children:

parent.querySelector('.child')

How do I get rid of an element's offset using CSS?

If you're using the IE developer tools, make sure you haven't accidentally left them at an older setting. I was making myself crazy with this same issue until I saw that it was set to Internet Explorer 7 Standards. Changed it to Internet Explorer 9 Standards and everything snapped right into place.

forEach loop Java 8 for Map entry set

Stream API

public void iterateStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Regular Expression: Any character that is NOT a letter or number

You are looking for:

var yourVar = '1324567890abc§$)%';
yourVar = yourVar.replace(/[^a-zA-Z0-9]/g, ' ');

This replaces all non-alphanumeric characters with a space.

The "g" on the end replaces all occurrences.

Instead of specifying a-z (lowercase) and A-Z (uppercase) you can also use the in-case-sensitive option: /[^a-z0-9]/gi.

How do you clone an Array of Objects in Javascript?

I think managed to write a generic method of deep cloning any JavaScript structure mainly using Object.create which is supported in all modern browsers. The code is like this:

function deepClone (item) {
  if (Array.isArray(item)) {
    var newArr = [];

    for (var i = item.length; i-- !== 0;) {
      newArr[i] = deepClone(item[i]);
    }

    return newArr;
  }
  else if (typeof item === 'function') {
    eval('var temp = '+ item.toString());
    return temp;
  }
  else if (typeof item === 'object')
    return Object.create(item);
  else
    return item;
}

Check if value is zero or not null in python

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

How to find day of week in php in a specific timezone

Check date is monday or sunday before get last monday or last sunday

 public function getWeek($date){
    $date_stamp = strtotime(date('Y-m-d', strtotime($date)));

     //check date is sunday or monday
    $stamp = date('l', $date_stamp);      
    $timestamp = strtotime($date);
    //start week
    if(date('D', $timestamp) == 'Mon'){            
        $week_start = $date;
    }else{
        $week_start = date('Y-m-d', strtotime('Last Monday', $date_stamp));
    }
    //end week
    if($stamp == 'Sunday'){
        $week_end = $date;
    }else{
        $week_end = date('Y-m-d', strtotime('Next Sunday', $date_stamp));
    }        
    return array($week_start, $week_end);
}

How can I use a custom font in Java?

Here is how I did it!

//create the font

try {
    //create the font to use. Specify the size!
    Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //register the font
    ge.registerFont(customFont);
} catch (IOException e) {
    e.printStackTrace();
} catch(FontFormatException e) {
    e.printStackTrace();
}

//use the font
yourSwingComponent.setFont(customFont);

Expected response code 220 but got code "", with message "" in Laravel

For me the problem was the port. I first incorrectly used port 465, which works for SSL but not TLS. So the key thing was changing the port to 587.

java build path problems

Go for the second option, Edit the project to agree with the latest JDK

  • Right click "JRE System Library [J2SE 1.5] in your project"
  • Choose "Properties"
  • Select "Workspace default JRE (jdk1.6)

enter image description here

Node.js heap out of memory

if you want to change the memory globally for node (windows) go to advanced system settings -> environment variables -> new user variable

variable name = NODE_OPTIONS
variable value = --max-old-space-size=4096

Notify ObservableCollection when Item changes

The spot you have commented as // Code to trig on item change... will only trigger when the collection object gets changed, such as when it gets set to a new object, or set to null.

With your current implementation of TrulyObservableCollection, to handle the property changed events of your collection, register something to the CollectionChanged event of MyItemsSource

public MyViewModel()
{
    MyItemsSource = new TrulyObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}


void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // Handle here
}

Personally I really don't like this implementation. You are raising a CollectionChanged event that says the entire collection has been reset, anytime a property changes. Sure it'll make the UI update anytime an item in the collection changes, but I see that being bad on performance, and it doesn't seem to have a way to identify what property changed, which is one of the key pieces of information I usually need when doing something on PropertyChanged.

I prefer using a regular ObservableCollection and just hooking up the PropertyChanged events to it's items on CollectionChanged. Providing your UI is bound correctly to the items in the ObservableCollection, you shouldn't need to tell the UI to update when a property on an item in the collection changes.

public MyViewModel()
{
    MyItemsSource = new ObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}

void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach(MyType item in e.NewItems)
            item.PropertyChanged += MyType_PropertyChanged;

    if (e.OldItems != null)
        foreach(MyType item in e.OldItems)
            item.PropertyChanged -= MyType_PropertyChanged;
}

void MyType_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "MyProperty")
        DoWork();
}

A free tool to check C/C++ source code against a set of coding standards?

Check universalindentgui on sourceforge.net.

it has many style checkers for C and you can customise the checkers.

How do I copy folder with files to another folder in Unix/Linux?

The option you're looking for is -R.

cp -R path_to_source path_to_destination/
  • If destination doesn't exist, it will be created.
  • -R means copy directories recursively. You can also use -r since it's case-insensitive.
  • Note the nuances with adding the trailing / as per @muni764's comment.

Fastest JavaScript summation

I tried using performance.now() to analyze the performance of the different types of loops. I took a very large array and found the sum of all elements of the array. I ran the code three times every time and found forEach and reduce to be a clear winner.

// For loop

let arr = [...Array(100000).keys()]
function addUsingForLoop(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
    sum += ar[i];
  }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingForLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 42.17500000959262 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.41999999107793 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 49.845000030472875 milliseconds"

// While loop

let arr = [...Array(100000).keys()]
function addUsingWhileLoop(ar){
let sum = 0;
let index = 0;
while (index < ar.length) {
  sum += ar[index];
  index++;
}
  console.log(`Sum: ${sum}`)
  return sum;
}
let t1 = performance.now();
addUsingWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 44.2499999771826 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.01999997207895 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 41.71000001952052 milliseconds"

// do-while

let arr = [...Array(100000).keys()]
function addUsingDoWhileLoop(ar){
let sum = 0;
let index = 0;
do {
   sum += index;
   index++;
} while (index < ar.length);
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingDoWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 43.79500000504777 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.47500001313165 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 47.535000019706786 milliseconds"

// Reverse loop

let arr = [...Array(100000).keys()]
function addUsingReverseLoop(ar){
   var sum=0;
   for (var i=ar.length; i--;) {
     sum+=arr[i];
   }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingReverseLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.199999982491136 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.96500000823289 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.880000011995435 milliseconds"

// Reverse while loop

let arr = [...Array(100000).keys()]
function addUsingReverseWhileLoop(ar){
    var sum = 0;
    var i = ar.length; 
    while (i--) {
        sum += ar[i];
    }
    console.log(`Sum: ${sum}`);
    return sum;
}
var t1 = performance.now();
addUsingReverseWhileLoop(arr);
var t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.26999999163672 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 42.97000000951812 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.31500000646338 milliseconds"

// reduce

let arr = [...Array(100000).keys()]
let t1 = performance.now();
sum = arr.reduce((pv, cv) => pv + cv, 0);
console.log(`Sum: ${sum}`)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 4.654999997001141 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.040000018198043 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 4.835000028833747 milliseconds"

// forEach

let arr = [...Array(100000).keys()]
function addUsingForEach(ar){
  let sum = 0;
  ar.forEach(item => {
    sum += item;
  })
    console.log(`Sum: ${sum}`);
    return sum
}
let t1 = performance.now();
addUsingForEach(arr)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 5.315000016707927 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.869999993592501 mienter code herelliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.405000003520399 milliseconds"

How to build minified and uncompressed bundle with webpack?

You can format your webpack.config.js like this:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./entry.js",
    output: {
        path: __dirname + "/dist",
        filename: "library.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
};'

And then to build it unminified run (while in the project's main directory):

$ webpack

To build it minified run:

$ NODE_ENV=production webpack

Notes: Make sure that for the unminified version you change the output file name to library.js and for the minified library.min.js so they do not overwrite each other.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

Found out that there's no bug there. Just add:

<base href="/" />

to your <head />.

How to center horizontal table-cell

Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...

<style>
    div.centered {
        margin: auto;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>

Then declare a div with class="centered" inside each table cell you want centered.

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

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

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

How to truncate the time on a DateTime object in Python?

You can use datetime.strftime to extract the day, the month, the year...

Example :

from datetime import datetime
d = datetime.today()

# Retrieves the day and the year
print d.strftime("%d-%Y")

Output (for today):

29-2011

If you just want to retrieve the day, you can use day attribute like :

from datetime import datetime
d = datetime.today()

# Retrieves the day
print d.day

Ouput (for today):

29

Java Embedded Databases Comparison

I guess I'm a little late (a lot late;-)) to this post, but I'd like to add Perst, an open source, object-oriented embedded database for Java &.NET. for your consideration. Perst is an open source / dual license embedded database for Java. The distribution is compatible with Google's Android platform, and also includes Perst Lite for Java ME. We've even built an Android benchmark and produced a whitepaper on the subject...you can take a look here: http://www.mcobject.com/index.cfm?fuseaction=download&pageid=581&sectionid=133

All the best, Chris

How to get the absolute path to the public_html folder?

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

wait() or sleep() function in jquery?

You can use the .delay() function.
This is what you're after:

.addClass("load").delay(2000).addClass("done");

ERROR: Sonar server 'http://localhost:9000' can not be reached

In the config file there is a colon instead of an equal sign after the sonar.web.host.

Is:

sonar.web.host:sonarqube

Should be

sonar.web.host=sonarqube

How to parse a String containing XML in Java and retrieve the value of the root node?

Using JDOM:

String xml = "<message>HELLO!</message>";
org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
    org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
    String message = doc.getRootElement().getText();
    System.out.println(message);
} catch (JDOMException e) {
    // handle JDOMException
} catch (IOException e) {
    // handle IOException
}

Using the Xerces DOMParser:

String xml = "<message>HELLO!</message>";
DOMParser parser = new DOMParser();
try {
    parser.parse(new InputSource(new java.io.StringReader(xml)));
    Document doc = parser.getDocument();
    String message = doc.getDocumentElement().getTextContent();
    System.out.println(message);
} catch (SAXException e) {
    // handle SAXException 
} catch (IOException e) {
    // handle IOException 
}

Using the JAXP interfaces:

String xml = "<message>HELLO!</message>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
    db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    try {
        Document doc = db.parse(is);
        String message = doc.getDocumentElement().getTextContent();
        System.out.println(message);
    } catch (SAXException e) {
        // handle SAXException
    } catch (IOException e) {
        // handle IOException
    }
} catch (ParserConfigurationException e1) {
    // handle ParserConfigurationException
}

Unable to ping vmware guest from another vmware guest

  1. Try installing VMware tools in guest operating system.
  2. Check if firewall is enable
  3. If 1 and 2 are ok, try using share internet connection

Share internet

After sharing connection the VMnet8 IP address will be changed to 192.168.137.1, set up the IP 192.168.18.1 and try again

Converting Swagger specification JSON to HTML documentation

There's a small Java program which generates docs (adoc or md) from a yaml file.

Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
        .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
        .withSwaggerMarkupLanguage(MarkupLanguage.ASCIIDOC)
        .withOutputLanguage(Language.DE)
        .build();

Swagger2MarkupConverter builder = Swagger2MarkupConverter.from(yamlFileAsString).withConfig(config).build();
return builder.toFileWithoutExtension(outFile);

Unfortunately it only supports OpenAPI 2.0 but not OpenAPI 3.0.

finding the type of an element using jQuery

You can use .prop() with tagName as the name of the property that you want to get:

$("#elementId").prop('tagName'); 

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you are just visiting a webpage that you trust and you want to move forward fast, just:

1- Click the shield icon in the far right of the address bar.

Allow mixed content in Google Chrome

2- In the pop-up window, click "Load anyway" or "Load unsafe script" (depending on your Chrome version).


If you want to set your Chrome browser to ALWAYS(in all webpages) allow mixed content:

1- In an open Chrome browser, press Ctrl+Shift+Q on your keyboard to force close Chrome. Chrome must be fully closed before the next steps.

2- Right-click the Google Chrome desktop icon (or Start Menu link). Select Properties.

3- At the end of the existing information in the Target field, add: " --allow-running-insecure-content" (There is a space before the first dash.)

4- Click OK.

5- Open Chrome and try to launch the content that was blocked earlier. It should work now.

File upload from <input type="file">

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input name="file" type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  file: File;
  onChange(event: EventTarget) {
        let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        let files: FileList = target.files;
        this.file = files[0];
        console.log(this.file);
    }

   doAnythingWithFile() {
   }

}

How to post JSON to PHP with curl

You need to set a few extra flags so that curl sends the data as JSON.

command

$ curl -H "Content-Type: application/json" \
       -X POST \
       -d '{"JSON": "HERE"}' \
       http://localhost:3000/api/url

flags

  • -H: custom header, next argument is expected to be header
  • -X: custom HTTP verb, next argument is expected to be verb
  • -d: sends the next argument as data in an HTTP POST request

resources

How to Delete node_modules - Deep Nested Folder in Windows

I had a similar problem and RD didn't work, for some unknown reason.

NPM can get rid of its own mess though, so if you do npm uninstall [module-name] for each directory in node_modules, you'll get rid of them.

(I'll look up how to batch loop this later, for those who have lots of dependencies.)

How can I convert a DateTime to an int?

I think you want (this won't fit in a int though, you'll need to store it as a long):

long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;

Alternatively, storing the ticks is a better idea.

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I am also new to MVC and I received the same error and found that it is not passing proper routeValues in the Index view or whatever view is present to view the all data.

It was as below

<td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>

I changed it to the as show below and started to work properly.

<td>
            @Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>

Basically this error can also come because of improper navigation also.

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

Cleanest Way to Invoke Cross-Thread Events

Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.

    #region SyncContextCancel

    private SynchronizationContext _syncContextCancel;

    /// <summary>
    /// Gets the synchronization context used for UI-related operations.
    /// </summary>
    /// <value>The synchronization context.</value>
    protected SynchronizationContext SyncContextCancel
    {
        get { return _syncContextCancel; }
    }

    #endregion //SyncContextCancel

    public void CancelCurrentDbCommand()
    {
        _syncContextCancel = SynchronizationContext.Current;

        //ThreadPool.QueueUserWorkItem(CancelWork, null);

        Thread worker = new Thread(new ThreadStart(CancelWork));
        worker.Priority = ThreadPriority.Highest;
        worker.Start();
    }

    SQLiteConnection _connection;
    private void CancelWork()//object state
    {
        bool success = false;

        try
        {
            if (_connection != null)
            {
                log.Debug("call cancel");
                _connection.Cancel();
                log.Debug("cancel complete");
                _connection.Close();
                log.Debug("close complete");
                success = true;
                log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
            }
        }
        catch (Exception ex)
        {
            log.Error(ex.Message, ex);
        }

        SyncContextCancel.Send(CancelCompleted, new object[] { success });
    }

    public void CancelCompleted(object state)
    {
        object[] args = (object[])state;
        bool success = (bool)args[0];

        if (success)
        {
            log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());

        }
    }

Garbage collector in Android

Out of memory in android application is very common if we not handle the bitmap properly, The solution for the problem would be

if(imageBitmap != null) {
    imageBitmap.recycle();
    imageBitmap = null;
}
System.gc();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
imageBitmap = BitmapFactory.decodeFile(URI, options);
Bitmap  scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 200, 200, true);
imageView.setImageBitmap(scaledBitmap);

In the above code Have just tried to recycle the bitmap which will allow you to free up the used memory space ,so out of memory may not happen.I have tried it worked for me.

If still facing the problem you can also add these line as well

BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;

for more information take a look at this link

https://web.archive.org/web/20140514092802/http://voices.yahoo.com/android-virtual-machine-vm-out-memory-error-7342266.html?cat=59


NOTE: Due to the momentary "pause" caused by performing gc, it is not recommended to do this before each bitmap allocation.

Optimum design is:

  1. Free all bitmaps that are no longer needed, by the if / recycle / nullcode shown. (Make a method to help with that.)

  2. System.gc();

  3. Allocate the new bitmaps.

Find the least number of coins required that can make any change from 1 to 99 cents

In general, if you have your coins COIN[] and your "change range" 1..MAX, the following should find the maximum number of coins.

Initialise array CHANGEVAL[MAX] to -1

For each element coin in COIN:
  set CHANGEVAL[coin] to 1
Until there are no more -1 in CHANGEVAL:
  For each index I over CHANGEVAL:
    if CHANGEVAL[I] != -1:
      let coincount = CHANGEVAL[I]
      For each element coin in COIN:
        let sum = coin + I
        if (COINS[sum]=-1) OR ((coincount+1)<COINS[sum]):
          COINS[sum]=coincount+1

I don't know if the check for coin-minimality in the inner conditional is, strictly speaking, necessary. I would think that the minimal chain of coin-additions would end up being correct, but better safe than sorry.

How to make html table vertically scrollable

Why don't you place your table in a div?

<div style="height:100px;overflow:auto;">

 ... Your code goes here ...

</div>

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

How to present popover properly in iOS 8

The following has a pretty comprehensive guide on how to configure and present popovers. https://www.appcoda.com/presentation-controllers-tutorial/

In summary, a viable implementation (with some updates from the original article syntax for Swift 4.2), to then be called from elsewhere, would be something like the following:

func showPopover(ofViewController popoverViewController: UIViewController, originView: UIView) {
    popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
    if let popoverController = popoverViewController.popoverPresentationController {
        popoverController.delegate = self
        popoverController.sourceView = originView
        popoverController.sourceRect = originView.bounds
        popoverController.permittedArrowDirections = UIPopoverArrowDirection.any
    }
    self.present(popoverViewController, animated: true)
}

A lot of this was already covered in the answer from @mmc, but the article helps to explain some of those code elements used, and also show how it could be expanded.

It also provides a lot of additional detail about using delegation to handle the presentation style for iPhone vs. iPad, and to allow dismissal of the popover if it's ever shown full-screen. Again, updated for Swift 4.2:

func adaptivePresentationStyle(for: UIPresentationController) -> UIModalPresentationStyle {
    //return UIModalPresentationStyle.fullScreen
    return UIModalPresentationStyle.none
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    if traitCollection.horizontalSizeClass == .compact {
        return UIModalPresentationStyle.none
        //return UIModalPresentationStyle.fullScreen
    }
    //return UIModalPresentationStyle.fullScreen
    return UIModalPresentationStyle.none
}

func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
    switch style {
    case .fullScreen:
        let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(doneWithPopover))
        navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton
        return navigationController
    default:
        return controller.presentedViewController
    }
}

// As of Swift 4, functions used in selectors must be declared as @objc
@objc private func doneWithPopover() {
    self.dismiss(animated: true, completion: nil)
}

Hope this helps.

Non-recursive depth first search algorithm

Suppose you want to execute a notification when each node in a graph is visited. The simple recursive implementation is:

void DFSRecursive(Node n, Set<Node> visited) {
  visited.add(n);
  for (Node x : neighbors_of(n)) {  // iterate over all neighbors
    if (!visited.contains(x)) {
      DFSRecursive(x, visited);
    }
  }
  OnVisit(n);  // callback to say node is finally visited, after all its non-visited neighbors
}

Ok, now you want a stack-based implementation because your example doesn't work. Complex graphs might for instance cause this to blow the stack of your program and you need to implement a non-recursive version. The biggest issue is to know when to issue a notification.

The following pseudo-code works (mix of Java and C++ for readability):

void DFS(Node root) {
  Set<Node> visited;
  Set<Node> toNotify;  // nodes we want to notify

  Stack<Node> stack;
  stack.add(root);
  toNotify.add(root);  // we won't pop nodes from this until DFS is done
  while (!stack.empty()) {
    Node current = stack.pop();
    visited.add(current);
    for (Node x : neighbors_of(current)) {
      if (!visited.contains(x)) {
        stack.add(x);
        toNotify.add(x);
      }
    }
  }
  // Now issue notifications. toNotifyStack might contain duplicates (will never
  // happen in a tree but easily happens in a graph)
  Set<Node> notified;
  while (!toNotify.empty()) {
  Node n = toNotify.pop();
  if (!toNotify.contains(n)) {
    OnVisit(n);  // issue callback
    toNotify.add(n);
  }
}

It looks complicated but the extra logic needed for issuing notifications exists because you need to notify in reverse order of visit - DFS starts at root but notifies it last, unlike BFS which is very simple to implement.

For kicks, try following graph: nodes are s, t, v and w. directed edges are: s->t, s->v, t->w, v->w, and v->t. Run your own implementation of DFS and the order in which nodes should be visited must be: w, t, v, s A clumsy implementation of DFS would maybe notify t first and that indicates a bug. A recursive implementation of DFS would always reach w last.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

You can install the Active Directory snap-in with Powershell on Windows Server 2012 using the following command:

Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools

This helped me when I had problems with the Features screen due to AppFabric and Windows Update errors.

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

if you use 'Month' in to_char it right pads to 9 characters; you have to use the abbreviated 'MON', or to_char then trim and concatenate it to avoid this. See, http://www.techonthenet.com/oracle/functions/to_char.php

select trim(to_char(date_field, 'month')) || ' ' || to_char(date_field,'dd, yyyy')
  from ...

or

select to_char(date_field,'mon dd, yyyy')
  from ...  

How to add new line into txt file

You could do it easily using

File.AppendAllText("date.txt", DateTime.Now.ToString());

If you need newline

File.AppendAllText("date.txt", 
                   DateTime.Now.ToString() + Environment.NewLine);

Anyway if you need your code do this:

TextWriter tw = new StreamWriter("date.txt", true);

with second parameter telling to append to file.
Check here StreamWriter syntax.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Set element focus in angular way

The problem with your solution is that it does not work well when tied down to other directives that creates a new scope, e.g. ng-repeat. A better solution would be to simply create a service function that enables you to focus elements imperatively within your controllers or to focus elements declaratively in the html.

DEMO

JAVASCRIPT

Service

 .factory('focus', function($timeout, $window) {
    return function(id) {
      // timeout makes sure that it is invoked after any other event has been triggered.
      // e.g. click events that need to run before the focus or
      // inputs elements that are in a disabled state but are enabled when those events
      // are triggered.
      $timeout(function() {
        var element = $window.document.getElementById(id);
        if(element)
          element.focus();
      });
    };
  });

Directive

  .directive('eventFocus', function(focus) {
    return function(scope, elem, attr) {
      elem.on(attr.eventFocus, function() {
        focus(attr.eventFocusId);
      });

      // Removes bound events in the element itself
      // when the scope is destroyed
      scope.$on('$destroy', function() {
        elem.off(attr.eventFocus);
      });
    };
  });

Controller

.controller('Ctrl', function($scope, focus) {
    $scope.doSomething = function() {
      // do something awesome
      focus('email');
    };
  });

HTML

<input type="email" id="email" class="form-control">
<button event-focus="click" event-focus-id="email">Declarative Focus</button>
<button ng-click="doSomething()">Imperative Focus</button>

How do I create an Android Spinner as a popup?

You can create your own custom Dialog. It's fairly easy. If you want to dismiss it with a selection in the spinner, then add an OnItemClickListener and add

int n = mSpinner.getSelectedItemPosition();
mReadyListener.ready(n);
SpinnerDialog.this.dismiss();

as in the OnClickListener for the OK button. There's one caveat, though, and it's that the onclick listener does not fire if you reselect the default option. You need the OK button also.

Start with the layout:

res/layout/spinner_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content">
<TextView 
    android:id="@+id/dialog_label" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    android:hint="Please select an option" 
    />
<Spinner
    android:id="@+id/dialog_spinner" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
    />
<Button
    android:id="@+id/dialogOK" 
    android:layout_width="120dp"
    android:layout_height="wrap_content" 
    android:text="OK"
    android:layout_below="@id/dialog_spinner"
    />
<Button
    android:id="@+id/dialogCancel" 
    android:layout_width="120dp"
    android:layout_height="wrap_content" 
    android:text="Cancel"
    android:layout_below="@id/dialog_spinner"
    android:layout_toRightOf="@id/dialogOK"
    />
</RelativeLayout>

Then, create the class:

src/your/package/SpinnerDialog.java:

public class SpinnerDialog extends Dialog {
    private ArrayList<String> mList;
    private Context mContext;
    private Spinner mSpinner;

   public interface DialogListener {
        public void ready(int n);
        public void cancelled();
    }

    private DialogListener mReadyListener;

    public SpinnerDialog(Context context, ArrayList<String> list, DialogListener readyListener) {
        super(context);
        mReadyListener = readyListener;
        mContext = context;
        mList = new ArrayList<String>();
        mList = list;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner_dialog);
        mSpinner = (Spinner) findViewById (R.id.dialog_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String> (mContext, android.R.layout.simple_spinner_dropdown_item, mList);
        mSpinner.setAdapter(adapter);

        Button buttonOK = (Button) findViewById(R.id.dialogOK);
        Button buttonCancel = (Button) findViewById(R.id.dialogCancel);
        buttonOK.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                int n = mSpinner.getSelectedItemPosition();
                mReadyListener.ready(n);
                SpinnerDialog.this.dismiss();
            }
        });
        buttonCancel.setOnClickListener(new android.view.View.OnClickListener(){
            public void onClick(View v) {
                mReadyListener.cancelled();
                SpinnerDialog.this.dismiss();
            }
        });
    }
}

Finally, use it as:

mSpinnerDialog = new SpinnerDialog(this, mTimers, new SpinnerDialog.DialogListener() {
  public void cancelled() {
    // do your code here
  }
  public void ready(int n) {
    // do your code here
  }
});

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

How to debug ORA-01775: looping chain of synonyms?

Try this select to find the problematic synonyms, it lists all synonyms that are pointing to an object that does not exist (tables,views,sequences,packages, procedures, functions)

SELECT *
FROM dba_synonyms
WHERE table_owner = 'USER'
    AND (
        NOT EXISTS (
            SELECT *
            FROM dba_tables
            WHERE dba_synonyms.table_name = dba_tables.TABLE_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_views
            WHERE dba_synonyms.table_name = dba_views.VIEW_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_sequences
            WHERE dba_synonyms.table_name = dba_sequences.sequence_NAME
            )
        AND NOT EXISTS (
            SELECT *
            FROM dba_dependencies
            WHERE type IN (
                    'PACKAGE'
                    ,'PROCEDURE'
                    ,'FUNCTION'
                    )
                AND dba_synonyms.table_name = dba_dependencies.NAME
            )
        )

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

Removing index column in pandas when reading a csv

df.reset_index(drop=True, inplace=True)

What is the best way to extract the first word from a string in Java?

You could use a Scanner

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 

prints the following output:

     1
     2
     red
     blue

How to plot a function curve in R

Lattice solution with additional settings which I needed:

library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
  1. If you need your range of values for x plotted in increments different from 1, e.g. 0.00001 you can use:

X<-seq(0,10,0.00001)

  1. You can change the colour of your line by defining a rgb value:

col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)

  1. You can change the width of the plotted line by setting:

lwd = 2

  1. You can change the size of the labels by scaling them:

cex.lab = 3.5, cex.axis = 3.5

Example plot

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

What is the recommended way to make a numeric TextField in JavaFX?

Try this simple code it will do the job.

DecimalFormat format = new DecimalFormat( "#.0" );
TextField field = new TextField();
field.setTextFormatter( new TextFormatter<>(c ->
{
    if ( c.getControlNewText().isEmpty() )
    {
        return c;
    }

    ParsePosition parsePosition = new ParsePosition( 0 );
    Object object = format.parse( c.getControlNewText(), parsePosition );

    if ( object == null || parsePosition.getIndex() <          c.getControlNewText().length() )
    {
        return null;
    }
    else
    {
        return c;
    }
}));

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

just open the hive terminal from the hive folder,after editing (bashrc) and (hive-site.xml) files. Steps-- open hive folder where it is installed. now open terminal from folder.

How can I read command line parameters from an R script?

I just put together a nice data structure and chain of processing to generate this switching behaviour, no libraries needed. I'm sure it will have been implemented numerous times over, and came across this thread looking for examples - thought I'd chip in.

I didn't even particularly need flags (the only flag here is a debug mode, creating a variable which I check for as a condition of starting a downstream function if (!exists(debug.mode)) {...} else {print(variables)}). The flag checking lapply statements below produce the same as:

if ("--debug" %in% args) debug.mode <- T
if ("-h" %in% args || "--help" %in% args) 

where args is the variable read in from command line arguments (a character vector, equivalent to c('--debug','--help') when you supply these on for instance)

It's reusable for any other flag and you avoid all the repetition, and no libraries so no dependencies:

args <- commandArgs(TRUE)

flag.details <- list(
"debug" = list(
  def = "Print variables rather than executing function XYZ...",
  flag = "--debug",
  output = "debug.mode <- T"),
"help" = list(
  def = "Display flag definitions",
  flag = c("-h","--help"),
  output = "cat(help.prompt)") )

flag.conditions <- lapply(flag.details, function(x) {
  paste0(paste0('"',x$flag,'"'), sep = " %in% args", collapse = " || ")
})
flag.truth.table <- unlist(lapply(flag.conditions, function(x) {
  if (eval(parse(text = x))) {
    return(T)
  } else return(F)
}))

help.prompts <- lapply(names(flag.truth.table), function(x){
# joins 2-space-separatated flags with a tab-space to the flag description
  paste0(c(paste0(flag.details[x][[1]][['flag']], collapse="  "),
  flag.details[x][[1]][['def']]), collapse="\t")
} )

help.prompt <- paste(c(unlist(help.prompts),''),collapse="\n\n")

# The following lines handle the flags, running the corresponding 'output' entry in flag.details for any supplied
flag.output <- unlist(lapply(names(flag.truth.table), function(x){
  if (flag.truth.table[x]) return(flag.details[x][[1]][['output']])
}))
eval(parse(text = flag.output))

Note that in flag.details here the commands are stored as strings, then evaluated with eval(parse(text = '...')). Optparse is obviously desirable for any serious script, but minimal-functionality code is good too sometimes.

Sample output:

$ Rscript check_mail.Rscript --help
--debug Print  variables rather than executing function XYZ...

-h  --help  Display flag definitions

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Another, and more streamlined, approach to deserializing a camel-cased JSON string to a pascal-cased POCO object is to use the CamelCasePropertyNamesContractResolver.

It's part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between the JSON object and the POCO lies in the casing of the property names. If the property names are spelled differently, then you'll need to resort to using JsonProperty attributes to map property names.

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization;

. . .

private User LoadUserFromJson(string response) 
{
    JsonSerializerSettings serSettings = new JsonSerializerSettings();
    serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings);

    return outObject; 
}

Including another class in SCSS

Using @extend is a fine solution, but be aware that the compiled css will break up the class definition. Any classes that extends the same placeholder will be grouped together and the rules that aren't extended in the class will be in a separate definition. If several classes become extended, it can become unruly to look up a selector in the compiled css or the dev tools. Whereas a mixin will duplicate the mixin code and add any additional styles.

You can see the difference between @extend and @mixin in this sassmeister

Difference between Git and GitHub

In simple:

Git - is local repository.

GitHub - is central repository.

Hope below image will help to understand: Git and GitHub Difference

Git and GitHub Difference more details

How do I debug "Error: spawn ENOENT" on node.js?

I was getting this error when trying to debug a node.js program from within VS Code editor on a Debian Linux system. I noticed the same thing worked OK on Windows. The solutions previously given here weren't much help because I hadn't written any "spawn" commands. The offending code was presumably written by Microsoft and hidden under the hood of the VS Code program.

Next I noticed that node.js is called node on Windows but on Debian (and presumably on Debian-based systems such as Ubuntu) it's called nodejs. So I created an alias - from a root terminal, I ran

ln -s /usr/bin/nodejs /usr/local/bin/node

and this solved the problem. The same or a similar procedure will presumably work in other cases where your node.js is called nodejs but you're running a program which expects it to be called node, or vice-versa.

How do I exit a WPF application programmatically?

If you want to exit from another thread that didn't create the application object, use: System.Windows.Application.Current.Dispatcher.InvokeShutdown()

java SSL and cert keystore

SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

The specific keys you have to set are below:

javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

  1. $JAVA_HOME/lib/security/jssecacerts
  2. $JAVA_HOME/lib/security/cacerts

javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How can I check if a program exists from a Bash script?

Script

#!/bin/bash

# Commands found in the hash table are checked for existence before being
# executed and non-existence forces a normal PATH search.
shopt -s checkhash

function exists() {
 local mycomm=$1; shift || return 1

 hash $mycomm 2>/dev/null || \
 printf "\xe2\x9c\x98 [ABRT]: $mycomm: command does not exist\n"; return 1;
}
readonly -f exists

exists notacmd
exists bash
hash
bash -c 'printf "Fin.\n"'

Result

? [ABRT]: notacmd: command does not exist
hits    command
   0    /usr/bin/bash
Fin.

Convert a 1D array to a 2D array in numpy

Try something like:

B = np.reshape(A,(-1,ncols))

You'll need to make sure that you can divide the number of elements in your array by ncols though. You can also play with the order in which the numbers are pulled into B using the order keyword.

how does Array.prototype.slice.call() work?

I'm just writing this to remind myself...

    Array.prototype.slice.call(arguments);
==  Array.prototype.slice(arguments[1], arguments[2], arguments[3], ...)
==  [ arguments[1], arguments[2], arguments[3], ... ]

Or just use this handy function $A to turn most things into an array.

function hasArrayNature(a) {
    return !!a && (typeof a == "object" || typeof a == "function") && "length" in a && !("setInterval" in a) && (Object.prototype.toString.call(a) === "[object Array]" || "callee" in a || "item" in a);
}

function $A(b) {
    if (!hasArrayNature(b)) return [ b ];
    if (b.item) {
        var a = b.length, c = new Array(a);
        while (a--) c[a] = b[a];
        return c;
    }
    return Array.prototype.slice.call(b);
}

example usage...

function test() {
    $A( arguments ).forEach( function(arg) {
        console.log("Argument: " + arg);
    });
}

null terminating a string

From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

SQL - How to find the highest number in a column?

To get it at any time, you can do SELECT MAX(Id) FROM Customers .

In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY -- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id--just in case others are being added to the database at the same time.

How can I apply a border only inside a table?

that will do it all without css <TABLE BORDER=1 RULES=ALL FRAME=VOID>

code from: HTML CODE TUTORIAL

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

For anyone else and just an addition to Robert, If your nav has flex display value, you can float the element that you need to the right, by adding this to its css

{
    margin-left: auto;
}

Plotting images side by side using matplotlib

If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:

plt.figure(figsize=(10,10)) # specifying the overall grid size

for i in range(25):
    plt.subplot(5,5,i+1)    # the number of images in the grid is 5*5 (25)
    plt.imshow(the_array[i])

plt.show()

Also note that I used subplot and not subplots. They're both different

C++ auto keyword. Why is it magic?

It's just taking a generally useless keyword and giving it a new, better functionality. It's standard in C++11, and most C++ compilers with even some C++11 support will support it.

How to open google chrome from terminal?

just type

google-chrome

it works. Thanks.

C++ vector of char array

Use std::string instead of char-arrays

std::string k ="abcde";
std::vector<std::string> v;
v.push_back(k);

How to resolve TypeError: Cannot convert undefined or null to object

Make sure that destination object is not empty ( null or undefined ).

You can initialize destination object with empty object like below:

var destinationObj = {};

Object.assign(destinationObj, sourceObj);

Find a file with a certain extension in folder

You could use the Directory class

 Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories)

how to prevent css inherit

lets say you have this:

<ul>
    <li></li>
    <li>
        <ul>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li></li>
<ul>

Now if you DONT need IE6 compatibility (reference at Quirksmode) you can have the following css

ul li { background:#fff; }
ul>li { background:#f0f; }

The > is a direct children operator, so in this case only the first level of lis will be purple.

Hope this helps

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

postgresql - sql - count of `true` values

Cast the Boolean to an integer and sum.

SELECT count(*),sum(myCol::int);

You get 6,3.

Stop MySQL service windows

To successfully stop MySQL Service on Windows

  1. Check on services the name of the service for MySQL
  2. Run as administrator : net stop [MySQL Service name]

How to ensure a <select> form field is submitted when it is disabled?

Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".

function changeSelectUserManipulation(obj, disable){
    var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
    disable = disable? !!disable : !$obj.is(':disabled');

    if(disable){
        $obj.prop('disabled', true)
            .after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
    }else{
        $obj.prop('disabled', false)
            .next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
    }
}

changeSelectUserManipulation("select_id");

How to obtain the start time and end time of a day?

For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.

System.out.println(new Date());

final LocalDateTime endOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
final Date          endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));

System.out.println(endOfDayAsDate);

final LocalDateTime startOfDay       = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
final Date          startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));

System.out.println(startOfDayAsDate);

If no time difference with output. Try: ZoneOffset.ofHours(0)

For each row in an R dataframe

You can use the by_row function from the package purrrlyr for this:

myfn <- function(row) {
  #row is a tibble with one row, and the same 
  #number of columns as the original df
  #If you'd rather it be a list, you can use as.list(row)
}

purrrlyr::by_row(df, myfn)

By default, the returned value from myfn is put into a new list column in the df called .out.

If this is the only output you desire, you could write purrrlyr::by_row(df, myfn)$.out

How do I get the Session Object in Spring?

Your friend here is org.springframework.web.context.request.RequestContextHolder

// example usage
public static HttpSession session() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    return attr.getRequest().getSession(true); // true == allow create
}

This will be populated by the standard spring mvc dispatch servlet, but if you are using a different web framework you have add org.springframework.web.filter.RequestContextFilter as a filter in your web.xml to manage the holder.

EDIT: just as a side issue what are you actually trying to do, I'm not sure you should need access to the HttpSession in the retieveUser method of a UserDetailsService. Spring security will put the UserDetails object in the session for you any how. It can be retrieved by accessing the SecurityContextHolder:

public static UserDetails currentUserDetails(){
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        return principal instanceof UserDetails ? (UserDetails) principal : null;
    }
    return null;
}

If input value is blank, assign a value of "empty" with Javascript

I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

Can a Windows batch file determine its own file name?

Yes.

Use the special %0 variable to get the path to the current file.

Write %~n0 to get just the filename without the extension.

Write %~n0%~x0 to get the filename and extension.

Also possible to write %~nx0 to get the filename and extension.

C# : Passing a Generic Object

It doesn't compile because T could be anything, and not everything will have the myvar field.

You could make myvar a property on ITest:

public ITest
{
    string myvar{get;}
}

and implement it on the classes as a property:

public class MyClass1 : ITest
{
    public string myvar{ get { return "hello 1"; } }
}

and then put a generic constraint on your method:

public void PrintGeneric<T>(T test) where T : ITest
{
    Console.WriteLine("Generic : " + test.myvar);
}

but in that case to be honest you are better off just passing in an ITest:

public void PrintGeneric(ITest test)
{
    Console.WriteLine("Generic : " + test.myvar);
}

Find a string between 2 known values

  Regex regex = new Regex("<tag1>(.*)</tag1>");
  var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
  string s = v.Groups[1].ToString();

Or (as mentioned in the comments) to match the minimal subset:

  Regex regex = new Regex("<tag1>(.*?)</tag1>");

Regex class is in System.Text.RegularExpressions namespace.

What is the difference between function and procedure in PL/SQL?

A function can be in-lined into a SQL statement, e.g.

select foo
      ,fn_bar (foo)
  from foobar

Which cannot be done with a stored procedure. The architecture of the query optimiser limits what can be done with functions in this context, requiring that they are pure (i.e. the same inputs always produce the same output). This restricts what can be done in the function, but allows it to be used in-line in the query if it is defined to be "pure".

Otherwise, a function (not necessarily deterministic) can return a variable or a result set. In the case of a function returning a result set, you can join it against some other selection in a query. However, you cannot use a non-deterministic function like this in a correlated subquery as the optimiser cannot predict what sort of result set will be returned (this is computationally intractable, like the halting problem).

Unable to copy file - access to the path is denied

This can be a strange by-product of loading source initially from source control (TFS etc.) where all files and folders are write protected. Go to the top level directory and check the properties and you could find the Read-only attribute checked. Uncheck that and the system should ask you if you want all the dirs under the top level to be set the writable. This should fix it.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

  1. Download the JD-Eclipse Update Site(github.com/java-decompiler/jd-eclipse)
  2. Launch Eclipse,

  3. Click on "Help > Install New Software...",

  4. Click on button "Add..." to add an new repository,

  5. Enter "JD-Eclipse Update Site" and select the local site directory,

  6. Check "Java Decompiler Eclipse Plug-in",

  7. Next, next, next... and restart Eclipse.

How to draw a graph in PHP?

You can use google's chart api to generate charts.

How do I disable a Pylint warning?

In case this helps someone, if you're using Visual Studio Code, it expects the file to be in UTF-8 encoding. To generate the file, I ran pylint --generate-rcfile | out-file -encoding utf8 .pylintrc in PowerShell.

Setting width of spreadsheet cell using PHPExcel

The correct way to set the column width is by using the line as posted by Jahmic, however it is important to note that additionally, you have to apply styling after adding the data, and not before, otherwise on some configurations, the column width is not applied

Clone private git repo with dockerfile

Above solutions did not work for bitbucket. I figured this does the trick:

RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts \
    && eval `ssh-agent` \
    && ssh-add ~/.ssh/[key] \
    && git clone [email protected]:[team]/[repo].git

Getting data posted in between two dates

If you want to compare SQL dates, you can try this:

$this->db->select();
$this->db->from('table_name');
$this->db->where(' date_columnname >= date("'.$from.'")');
$this->db->where( 'date_columnname <= date("'.$to.'")');

That worked for me (PHP and MySQL).

how to prevent "directory already exists error" in a makefile when using mkdir

ifeq "$(wildcard $(MY_DIRNAME) )" ""
  -mkdir $(MY_DIRNAME)
endif

Java Command line arguments

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {
}

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

How to import a SQL Server .bak file into MySQL?

In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL.

Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want.

What is monkey patching?

Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to.

As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.