Programs & Examples On #Binomial cdf

XAMPP, Apache - Error: Apache shutdown unexpectedly

Best Solution for windows user is :

  1. Open netstat (from XAMPP CONTROL PANEL)
  2. Find PID of process which uses port 80.
  3. Open CMD with Administrative.
  4. Run taskkill /pid PID (instead PID use pid u found from netstat)
    Heyy enjoy u Done.....

Java Swing - how to show a panel on top of another panel?

You can add an undecorated JDialog like this:

import java.awt.event.*;

import javax.swing.*;

public class TestSwing {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame("Parent");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setVisible(true);

    final JDialog dialog = new JDialog(frame, "Child", true);    
    dialog.setSize(300, 200);
    dialog.setLocationRelativeTo(frame);
    JButton button = new JButton("Button");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        dialog.dispose();
      }
    });
    dialog.add(button);
    dialog.setUndecorated(true);
    dialog.setVisible(true);
  }
}

Case-insensitive search in Rails model

An alternative can be

c = Product.find_by("LOWER(name)= ?", name.downcase)

Call fragment from fragment

This is my answer which solved the same problem. Fragment2.java is the fragment class which holds the layout of fragment2.xml.

public void onClick(View v) {
                    Fragment  fragment2 = new Fragement2();
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.frame_container, fragment2);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();   
                }

Keylistener in Javascript

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};

How do I get the position selected in a RecyclerView?

No need to have your ViewHolder implementing View.OnClickListener. You can get directly the clicked position by setting a click listener in the method onCreateViewHolder of RecyclerView.Adapter here is a sample of code :

public class ItemListAdapterRecycler extends RecyclerView.Adapter<ItemViewHolder>
{

    private final List<Item> items;

    public ItemListAdapterRecycler(List<Item> items)
    {
        this.items = items;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(final ViewGroup parent, int viewType)
    {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);

        view.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                int currentPosition = getClickedPosition(view);
                Log.d("DEBUG", "" + currentPosition);
            }
        });

        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder itemViewHolder, int position)
    {
        ...
    }

    @Override
    public int getItemCount()
    {
        return items.size();
    }

    private int getClickedPosition(View clickedView)
    {
        RecyclerView recyclerView = (RecyclerView) clickedView.getParent();
        ItemViewHolder currentViewHolder = (ItemViewHolder) recyclerView.getChildViewHolder(clickedView);
        return currentViewHolder.getAdapterPosition();
    }

}

MySQL command line client for Windows

For Windows users: 1.Install the full version of MYSQL 2.On the Windows 10 start button click on search and type in MySQL 3. Select the MYSQL Command Line Client 5.5 (I am using version 5.5) 4. go ahead and run your sql queries/ 5. to exit type \q or quit

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

mongo - couldn't connect to server 127.0.0.1:27017

Start monogdb service using

sudo service mongod start 

then from the new window or terminal start mongo client using

mongo

How can I get the source directory of a Bash script from within the script itself?

Look at the test at bottom with weird directory names.

To change the working directory to the one where the Bash script is located, you should try this simple, tested and verified with shellcheck solution:

#!/bin/bash --
cd "$(dirname "${0}")"/. || exit 2

The test:

$ ls 
application
$ mkdir "$(printf "\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37\40\41\42\43\44\45\46\47testdir" "")"
$ mv application *testdir
$ ln -s *testdir "$(printf "\1\2\3\4\5\6\7\10\11\12\13\14\15\16\17\20\21\22\23\24\25\26\27\30\31\32\33\34\35\36\37\40\41\42\43\44\45\46\47symlink" "")"
$ ls -lb
total 4
lrwxrwxrwx 1 jay stacko   46 Mar 30 20:44 \001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\ !"#$%&'symlink -> \001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\ !"#$%&'testdir
drwxr-xr-x 2 jay stacko 4096 Mar 30 20:44 \001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\ !"#$%&'testdir
$ *testdir/application && printf "SUCCESS\n" ""
SUCCESS
$ *symlink/application && printf "SUCCESS\n" ""
SUCCESS

Eloquent: find() and where() usage laravel

Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '>', 100)->firstOrFail();

If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:

Route::get('/api/flights/{id}', function ($id) {
    return App\Flight::findOrFail($id);
});

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

What's the best way to test SQL Server connection programmatically?

public static class SqlConnectionExtension
{
    #region Public Methods

    public static bool ExIsOpen(
        this SqlConnection connection, MessageString errorMsg = null)
    {
        if (connection == null) { return false; }
        if (connection.State == ConnectionState.Open) { return true; }

        try
        {
            connection.Open();
            return true;
        }
        catch (Exception ex) { errorMsg?.Append(ex.ToString()); }
        return false;
    }

    public static bool ExIsReady(
        this SqlConnection connction, MessageString errorMsg = null)
    {
        if (connction.ExIsOpen(errorMsg) == false) { return false; }
        try
        {
            using (var command = new SqlCommand("select 1", connction))
            { return ((int)command.ExecuteScalar()) == 1; }
        }
        catch (Exception ex) { errorMsg?.Append(ex.ToString()); }
        return false;
    }

    #endregion Public Methods
}

public class MessageString : IDisposable
{
    #region Protected Fields

    protected StringBuilder _messageBuilder = new StringBuilder();

    #endregion Protected Fields

    #region Public Constructors

    public MessageString()
    {
    }

    public MessageString(int capacity)
    {
        _messageBuilder.Capacity = capacity;
    }

    public MessageString(string value)
    {
        _messageBuilder.Append(value);
    }

    #endregion Public Constructors

    #region Public Properties

    public int Length {
        get { return _messageBuilder.Length; }
        set { _messageBuilder.Length = value; }
    }

    public int MaxCapacity {
        get { return _messageBuilder.MaxCapacity; }
    }

    #endregion Public Properties

    #region Public Methods

    public static implicit operator string(MessageString ms)
    {
        return ms.ToString();
    }

    public static MessageString operator +(MessageString ms1, MessageString ms2)
    {
        MessageString ms = new MessageString(ms1.Length + ms2.Length);
        ms.Append(ms1.ToString());
        ms.Append(ms2.ToString());
        return ms;
    }

    public MessageString Append<T>(T value) where T : IConvertible
    {
        _messageBuilder.Append(value);
        return this;
    }

    public MessageString Append(string value)
    {
        return Append<string>(value);
    }

    public MessageString Append(MessageString ms)
    {
        return Append(ms.ToString());
    }

    public MessageString AppendFormat(string format, params object[] args)
    {
        _messageBuilder.AppendFormat(CultureInfo.InvariantCulture, format, args);
        return this;
    }

    public MessageString AppendLine()
    {
        _messageBuilder.AppendLine();
        return this;
    }

    public MessageString AppendLine(string value)
    {
        _messageBuilder.AppendLine(value);
        return this;
    }

    public MessageString AppendLine(MessageString ms)
    {
        _messageBuilder.AppendLine(ms.ToString());
        return this;
    }

    public MessageString AppendLine<T>(T value) where T : IConvertible
    {
        Append<T>(value);
        AppendLine();
        return this;
    }

    public MessageString Clear()
    {
        _messageBuilder.Clear();
        return this;
    }

    public void Dispose()
    {
        _messageBuilder.Clear();
        _messageBuilder = null;
    }

    public int EnsureCapacity(int capacity)
    {
        return _messageBuilder.EnsureCapacity(capacity);
    }

    public bool Equals(MessageString ms)
    {
        return Equals(ms.ToString());
    }

    public bool Equals(StringBuilder sb)
    {
        return _messageBuilder.Equals(sb);
    }

    public bool Equals(string value)
    {
        return Equals(new StringBuilder(value));
    }

    public MessageString Insert<T>(int index, T value)
    {
        _messageBuilder.Insert(index, value);
        return this;
    }

    public MessageString Remove(int startIndex, int length)
    {
        _messageBuilder.Remove(startIndex, length);
        return this;
    }

    public MessageString Replace(char oldChar, char newChar)
    {
        _messageBuilder.Replace(oldChar, newChar);
        return this;
    }

    public MessageString Replace(string oldValue, string newValue)
    {
        _messageBuilder.Replace(oldValue, newValue);
        return this;
    }

    public MessageString Replace(char oldChar, char newChar, int startIndex, int count)
    {
        _messageBuilder.Replace(oldChar, newChar, startIndex, count);
        return this;
    }

    public MessageString Replace(string oldValue, string newValue, int startIndex, int count)
    {
        _messageBuilder.Replace(oldValue, newValue, startIndex, count);
        return this;
    }

    public override string ToString()
    {
        return _messageBuilder.ToString();
    }

    public string ToString(int startIndex, int length)
    {
        return _messageBuilder.ToString(startIndex, length);
    }

    #endregion Public Methods
}

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

DataTable: Hide the Show Entries dropdown but keep the Search box

sDom: "Tfrtip" or via a callback:

"fnHeaderCallback": function(){
    $('#YOURTABLENAME-table_length').hide();
}

Process list on Linux via Python

You could use psutil as a platform independent solution!

import psutil
psutil.pids()

[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 
4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 
4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235, 
5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

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

Hope this helps but please let me know if you need more details.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

The defined macros depend on the compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

How do I turn off the mysql password validation?

For mysql 8.0.7, Go to your mysql directory, and then use:

sudo bin/mysql_secure_installation

to configure the password option.

How do I get the MAX row with a GROUP BY in LINQ query?

var q = from s in db.Serials
        group s by s.Serial_Number into g
        select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

Where are Docker images stored on the host machine?

As answered here, if you're on Mac, it is located at

/Users/MyUserName/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/Docker.qcow2

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

Your vm does not find the class org/apache/juli/logging/LogFactory check if this class is present in the tomcat-juli.jar that you use (unzip it and search the file), if it's not present download the library from apache web site else if it's present put the tomcat-juli.jar in a path (the lib directory) that Tomcat use to load classes. If your Tomcat does not find it you can copy the jar in the lib directory of the JRE that you are using.

How to see the values of a table variable at debug time in T-SQL?

This project https://github.com/FilipDeVos/sp_select has a stored procedure sp_select which allows for selecting from a temp table.

Usage:

exec sp_select 'tempDb..#myTempTable'

While debugging a stored procedure you can open a new tab and run this command to see the contents of the temp table.

How to Enable ActiveX in Chrome?

There is a proprietary plugin called "Neptune" which says that it will allow you to use IE Tab functionality in Chrome on Windows.

Meadroid do this because they have ActiveX controls which they have written and they want them to be able to work in any browser, and they explicitly mention Chrome in the list of supported browsers for enabling ActiveX with this.

There is also a modified version of Chrome, called ChromePlus, which includes IETab, among other extra features.

I've not used either of these personally, but they look like they'll do what you want. I'd be interested to hear if they work out for you, as I know of other people who want to be able to use IEtab in Chrome :)

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

I have read all answers and I want to summarize for better understanding at first glance like following:

Firstly, the whole command that gets executed in the container includes two parts: the command and the arguments

  • ENTRYPOINT defines the executable invoked when the container is started (for command)

  • CMD specifies the arguments that get passed to the ENTRYPOINT (for arguments)

In the Kubernetes In Action book points an important note about it. (chapter 7)

Although you can use the CMD instruction to specify the command you want to execute when the image is run, the correct way is to do it through the ENTRYPOINT instruction and to only specify the CMD if you want to define the default arguments.

You can also read this article for great explanation in a simple way

Installing a dependency with Bower from URL and specify version

Just specifying the uri endpoint worked for me, bower 1.3.9

  "dependencies": {
    "jquery.cookie": "latest",
    "everestjs": "http://www.everestjs.net/static/st.v2.js"
  }

Running bower install, I received following output:

bower new           version for http://www.everestjs.net/static/st.v2.js#*
bower resolve       http://www.everestjs.net/static/st.v2.js#*
bower download      http://www.everestjs.net/static/st.v2.js

You could also try updating bower

  • npm update -g bower

According to documentation: the following types of urls are supported:

http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)

Why does git status show branch is up-to-date when changes exist upstream?

in this case use git add and integrate all pending files and then use git commit and then git push

git add - integrate all pedent files

git commit - save the commit

git push - save to repository

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Difference between setTimeout with and without quotes and parentheses

Totally agree with Joseph.

Here is a fiddle to test this: http://jsfiddle.net/nicocube/63s2s/

In the context of the fiddle, the string argument do not work, in my opinion because the function is not defined in the global scope.

How to check variable type at runtime in Go language

quux00's answer only tells about comparing basic types.

If you need to compare types you defined, you shouldn't use reflect.TypeOf(xxx). Instead, use reflect.TypeOf(xxx).Kind().

There are two categories of types:

  • direct types (the types you defined directly)
  • basic types (int, float64, struct, ...)

Here is a full example:

type MyFloat float64
type Vertex struct {
    X, Y float64
}

type EmptyInterface interface {}

type Abser interface {
    Abs() float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func (f MyFloat) Abs() float64 {
    return math.Abs(float64(f))
}

var ia, ib Abser
ia = Vertex{1, 2}
ib = MyFloat(1)
fmt.Println(reflect.TypeOf(ia))
fmt.Println(reflect.TypeOf(ia).Kind())
fmt.Println(reflect.TypeOf(ib))
fmt.Println(reflect.TypeOf(ib).Kind())

if reflect.TypeOf(ia) != reflect.TypeOf(ib) {
    fmt.Println("Not equal typeOf")
}
if reflect.TypeOf(ia).Kind() != reflect.TypeOf(ib).Kind() {
    fmt.Println("Not equal kind")
}

ib = Vertex{3, 4}
if reflect.TypeOf(ia) == reflect.TypeOf(ib) {
    fmt.Println("Equal typeOf")
}
if reflect.TypeOf(ia).Kind() == reflect.TypeOf(ib).Kind() {
    fmt.Println("Equal kind")
}

The output would be:

main.Vertex
struct
main.MyFloat
float64
Not equal typeOf
Not equal kind
Equal typeOf
Equal kind

As you can see, reflect.TypeOf(xxx) returns the direct types which you might want to use, while reflect.TypeOf(xxx).Kind() returns the basic types.


Here's the conclusion. If you need to compare with basic types, use reflect.TypeOf(xxx).Kind(); and if you need to compare with self-defined types, use reflect.TypeOf(xxx).

if reflect.TypeOf(ia) == reflect.TypeOf(Vertex{}) {
    fmt.Println("self-defined")
} else if reflect.TypeOf(ia).Kind() == reflect.Float64 {
    fmt.Println("basic types")
}

Ifelse statement in R with multiple conditions

Very simple use of any

df <- <your structure>

df$Den <- apply(df,1,function(i) {ifelse(any(is.na(i)) | any(i != 1), 0, 1)})

Check if a variable is between two numbers with Java

You can use this simply:

I'm using this function to check if the input int number is between 20 and 30

    static boolean isValidInput(int input) {
    return (input >= 20 && input <= 30);
}

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

same thing JUST happened to me with NUGET.

the following tag helped

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly>

Also if this is happening on the server, I had to make sure I was running the application pool on a more "privileged account" to the file system, but I don think that's your issue here

Access 2010 VBA query a table and iterate through results

DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.

 Dim rs As DAO.Recordset
 Dim db As Database
 Dim strSQL as String

 Set db=CurrentDB

 strSQL = "select * from table where some condition"

 Set rs = db.OpenRecordset(strSQL)

 Do While Not rs.EOF

    rs.Edit
    rs!SomeField = "Abc"
    rs!OtherField = 2
    rs!ADate = Date()
    rs.Update

    rs.MoveNext
Loop

Invalid shorthand property initializer

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that's solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

how to get a list of dates between two dates in java

java9 features you can calculate like this

public  List<LocalDate> getDatesBetween (
 LocalDate startDate, LocalDate endDate) {

   return startDate.datesUntil(endDate)
     .collect(Collectors.toList());
}
`` 


Calculate the number of business days between two dates?

This is a generic solution.

startdayvalue is day number of start date.

weekendday_1 is day numner of week end.

day number - MON - 1, TUE - 2, ... SAT - 6, SUN -7.

difference is difference between two dates..

Example : Start Date : 4 April, 2013, End Date : 14 April, 2013

Difference : 10, startdayvalue : 4, weekendday_1 : 7 (if SUNDAY is a weekend for you.)

This will give you number of holidays.

No of business day = (Difference + 1) - holiday1

    if (startdayvalue > weekendday_1)
    {

        if (difference > ((7 - startdayvalue) + weekendday_1))
        {
            holiday1 = (difference - ((7 - startdayvalue) + weekendday_1)) / 7;
            holiday1 = holiday1 + 1;
        }
        else
        {
            holiday1 = 0;
        }
    }
    else if (startdayvalue < weekendday_1)
    {

        if (difference > (weekendday_1 - startdayvalue))
        {
            holiday1 = (difference - (weekendday_1 - startdayvalue)) / 7;
            holiday1 = holiday1 + 1;
        }
        else if (difference == (weekendday_1 - startdayvalue))
        {
            holiday1 = 1;
        }
        else
        {
            holiday1 = 0;
        }
    }
    else
    {
        holiday1 = difference / 7;
        holiday1 = holiday1 + 1;
    }

True and False for && logic and || Logic table

I`d like to add to the already good answers:

The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".

Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!

int main ()
{
  std::cout <<  "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
  std::cout <<  "true - false = " << true - false << std::endl;
  std::cout <<  "false - true = " << false - true << std::endl;
  std::cout <<  "false - false = " << false - false << std::endl << std::endl;

  std::cout <<  "true + true = " << true + true << std::endl;
  std::cout <<  "true + false = " << true + false << std::endl;
  std::cout <<  "false + true = " << false + true << std::endl;
  std::cout <<  "false + false = " << false + false << std::endl << std::endl;

  std::cout <<  "true * true = " << true * true << std::endl;
  std::cout <<  "true * false = " << true * false << std::endl;
  std::cout <<  "false * true = " << false * true << std::endl;
  std::cout <<  "false * false = " << false * false << std::endl << std::endl;

  std::cout <<  "true / true = " << true / true << std::endl;
  //  std::cout <<  true / false << std::endl; ///-Wdiv-by-zero
  std::cout <<  "false / true = " << false / true << std::endl << std::endl;
  //  std::cout <<  false / false << std::endl << std::endl; ///-Wdiv-by-zero

  std::cout <<  "(true || true) = " << (true || true) << std::endl;
  std::cout <<  "(true || false) = " << (true || false) << std::endl;
  std::cout <<  "(false || true) = " << (false || true) << std::endl;
  std::cout <<  "(false || false) = " << (false || false) << std::endl << std::endl;

  std::cout <<  "(true && true) = " << (true && true) << std::endl;
  std::cout <<  "(true && false) = " << (true && false) << std::endl;
  std::cout <<  "(false && true) = " << (false && true) << std::endl;
  std::cout <<  "(false && false) = " << (false && false) << std::endl << std::endl;

}

yields :

true - true = 0
true - false = 1
false - true = -1
false - false = 0

true + true = 2
true + false = 1
false + true = 1
false + false = 0

true * true = 1
true * false = 0
false * true = 0
false * false = 0

true / true = 1
false / true = 0

(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0

(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0

jQuery $("#radioButton").change(...) not firing during de-selection

The change event not firing on deselection is the desired behaviour. You should run a selector over the entire radio group rather than just the single radio button. And your radio group should have the same name (with different values)

Consider the following code:

$('input[name="job[video_need]"]').on('change', function () {
    var value;
    if ($(this).val() == 'none') {
        value = 'hide';
    } else {
        value = 'show';
    }
    $('#video-script-collapse').collapse(value);
});

I have same use case as yours i.e. to show an input box when a particular radio button is selected. If the event was fired on de-selection as well, I would get 2 events each time.

Can anyone recommend a simple Java web-app framework?

I really don't see what is the big deal with getting maven + eclipse to work, as long as you don't have to change the pom.xml too much :)

Most frameworks that user maven have maven archetypes that can generate stub project.

So basically the steps should be:

  1. Install maven
  2. Add M2_REPO class path variable to eclipse
  3. Generate project with the archetype
  4. Import project to eclipse

As for Wicket, there is no reason why you couldn't use it without maven. The nice thing about maven is that it takes care of all the dependencies so you don't have to. On the other hand, if the only thing you want to do is to prototype couple of pages than Wicket can be overkill. But, should your application grow, eventually, the benefits of Wicket would keep showing with each added form, link or page :)

Permanently Set Postgresql Schema Path

Josh is correct but he left out one variation:

ALTER ROLE <role_name> IN DATABASE <db_name> SET search_path TO schema1,schema2;

Set the search path for the user, in one particular database.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

Importing CSV data using PHP/MySQL

$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
    $import="INSERT into importing(text,number)values('".$data[0]."','".$data[1]."')";
    mysql_query($import) or die(mysql_error());
}
$i=1;
}

How do you open a file in C++?

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

Rails Active Record find(:all, :order => ) issue

I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails

This is very simple.

@variable=Model.order('columnName DESC')

How to change column order in a table using sql query in sql server 2005?

At the end of the day, you simply cannot do this in MS SQL. I recently created tables on the go (application startup) using a stored Procedure that reads from a lookup table. When I created a view that combined these with another table I had manually created earlier one (same schema, with data), It failed - simply because I was using ''Select * UNION Select * ' for the view. At the same time, if I use only those created through the stored procedure, I am successful.

In conclusion: If there is any application which depends on the order of column it is really not good programming and will for sure create problems in the future. Columns should 'feel' free to be anywhere and be used for any data process (INSERT, UPDATE, SELECT).

Remove Datepicker Function dynamically

Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...

$("#ddlSearchType").change(function () { 
  if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date")                   { 
    $("#txtSearch").addClass("mydate");
    $(".mydate").datepicker()
  } else { 
    $("#txtSearch").removeClass("mydate");
  } 
}); 

How to download Visual Studio 2017 Community Edition for offline installation?

The command above worked for me

C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all

How to install maven on redhat linux

Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.

This exception is because your JDK/Java version need to be updated/installed.

Redirecting to a relative URL in JavaScript

try following js code

_x000D_
_x000D_
location = '..'
_x000D_
_x000D_
_x000D_

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

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.

Static constant string (class member)

The class static variables can be declared in the header but must be defined in a .cpp file. This is because there can be only one instance of a static variable and the compiler can't decide in which generated object file to put it so you have to make the decision, instead.

To keep the definition of a static value with the declaration in C++11 a nested static structure can be used. In this case the static member is a structure and has to be defined in a .cpp file, but the values are in the header.

class A
{
private:
  static struct _Shapes {
     const std::string RECTANGLE {"rectangle"};
     const std::string CIRCLE {"circle"};
  } shape;
};

Instead of initializing individual members the whole static structure is initialized in .cpp:

A::_Shapes A::shape;

The values are accessed with

A::shape.RECTANGLE;

or -- since the members are private and are meant to be used only from A -- with

shape.RECTANGLE;

Note that this solution still suffers from the problem of the order of initialization of the static variables. When a static value is used to initialize another static variable, the first may not be initialized, yet.

// file.h
class File {
public:
  static struct _Extensions {
    const std::string h{ ".h" };
    const std::string hpp{ ".hpp" };
    const std::string c{ ".c" };
    const std::string cpp{ ".cpp" };
  } extension;
};

// file.cpp
File::_Extensions File::extension;

// module.cpp
static std::set<std::string> headers{ File::extension.h, File::extension.hpp };

In this case the static variable headers will contain either { "" } or { ".h", ".hpp" }, depending on the order of initialization created by the linker.

As mentioned by @abyss.7 you could also use constexpr if the value of the variable can be computed at compile time. But if you declare your strings with static constexpr const char* and your program uses std::string otherwise there will be an overhead because a new std::string object will be created every time you use such a constant:

class A {
public:
   static constexpr const char* STRING = "some value";
};
void foo(const std::string& bar);
int main() {
   foo(A::STRING); // a new std::string is constructed and destroyed.
}

HTML table with horizontal scrolling (first column fixed)

Take a look at this JQuery plugin:

http://fixedheadertable.com

It adds vertical (fixed header row) or horizontal (fixed first column) scrolling to an existing HTML table. There is a demo you can check for both cases of scrolling.

Proper way to return JSON using node or Express

The res.json() function should be sufficient for most cases.

app.get('/', (req, res) => res.json({ answer: 42 }));

The res.json() function converts the parameter you pass to JSON using JSON.stringify() and sets the Content-Type header to application/json; charset=utf-8 so HTTP clients know to automatically parse the response.

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

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

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

Twitter bootstrap 3 two columns full height

If there will be no content after the row (whole screen height is taken), the trick with using position: fixed; height: 100% for .col:before element may work well:

_x000D_
_x000D_
header {_x000D_
  background: green;_x000D_
  height: 50px;_x000D_
}_x000D_
.col-xs-3 {_x000D_
  background: pink;_x000D_
}_x000D_
.col-xs-3:before {_x000D_
  background: pink;_x000D_
  content: ' ';_x000D_
  height: 100%;_x000D_
  margin-left: -15px; /* compensates column's padding */_x000D_
  position: fixed;_x000D_
  width: inherit; /* bootstrap column's width */_x000D_
  z-index: -1; /* puts behind content */_x000D_
}_x000D_
.col-xs-9 {_x000D_
  background: yellow;_x000D_
}_x000D_
.col-xs-9:before {_x000D_
  background: yellow;_x000D_
  content: ' ';_x000D_
  height: 100%;_x000D_
  margin-left: -15px; /* compensates column's padding */_x000D_
  position: fixed;_x000D_
  width: inherit; /* bootstrap column's width */_x000D_
  z-index: -1; /* puts behind content */_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<header>Header</header>_x000D_
<div class="container-fluid">_x000D_
    <div class="row">_x000D_
        <div class="col-xs-3">Navigation</div>_x000D_
        <div class="col-xs-9">Content</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Please use SqlBulkCopyColumnMapping.

Example:

private void SaveFileToDatabase(string filePath)
{
    string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MHMRA_TexMedEvsConnectionString"].ConnectionString.ToString();

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
    {
        //Create OleDbCommand to fetch data from Excel 
        using (OleDbCommand cmd = new OleDbCommand("Select * from [Crosswalk$]", excelConnection))
        {
            excelConnection.Open();
            using (OleDbDataReader dReader = cmd.ExecuteReader())
            {
                using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                {
                    //Give your Destination table name 
                    sqlBulk.DestinationTableName = "PaySrcCrosswalk";

                    // this is a simpler alternative to explicit column mappings, if the column names are the same on both sides and data types match
                    foreach(DataColumn column in dt.Columns) {
                         s.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                     }
                   
                    sqlBulk.WriteToServer(dReader);
                }
            }
        }
    }
}  

Execute raw SQL using Doctrine 2

How to execute a raw Query and return the data.

Hook onto your manager and make a new connection:

$manager = $this->getDoctrine()->getManager();
$conn = $manager->getConnection();

Create your query and fetchAll:

$result= $conn->query('select foobar from mytable')->fetchAll();

Get the data out of result like this:

$this->appendStringToFile("first row foobar is: " . $result[0]['foobar']);

What is a Subclass

Subclass is to Class as Java is to Programming Language.

How to run the Python program forever?

for OS's that support select:

import select

# your code

select.select([], [], [])

More than 1 row in <Input type="textarea" />

Why not use the <textarea> tag?

?<textarea id="txtArea" rows="10" cols="70"></textarea>

Properly embedding Youtube video into bootstrap 3.0 page

There is a Bootstrap3 native solution: http://getbootstrap.com/components/#responsive-embed

since Bootstrap 3.2.0!

If you are using Bootstrap < v3.2.0 so look into "responsive-embed.less" file of v3.2.0 - possibly you can use/copy this code in your case (it works for me in v3.1.1).

SQLite select where empty?

It looks like you can simply do:

SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';

Test case:

CREATE TABLE your_table (id int, some_column varchar(10));

INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);

Result:

SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';

id        
----------
1         
2         
5    

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

This was simple for me -

Solution

  1. (pre) the listed directory is not present, see pic
  2. Run Eclipse, see the error shown in pic below. Close Eclipse
  3. Create the directory (RemoteSystemsTempFiles) where it is looking

    • note: ignore the items in this folder (e.g. .markers), they are auto-generated
  4. Restart Eclipse, problem solved!

Example Problem Message

enter image description here

Not sure why this took me so long to resolve, but quite easy now, and quite obvious in retrospect! ;)...

Adding an onclick function to go to url in JavaScript?

Not completely sure I understand the question, but do you mean something like this?

$('#something').click(function() { 
    document.location = 'http://somewhere.com/';
} );

jQuery val is undefined?

you may forgot to wrap your object with $()

  var tableChild = children[i];
  tableChild.val("my Value");// this is wrong 

and the ccorrect one is

$(tableChild).val("my Value");// this is correct

Resize a picture to fit a JLabel

public static void main(String s[]) 
  {

    BufferedImage image = null;
    try 
    {
        image = ImageIO.read(new File("your image path"));

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
    jLabel1.setIcon(imageIcon);
}


private Image fitimage(Image img , int w , int h)
{
    BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedimage.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0, 0,w,h,null);
    g2.dispose();
    return resizedimage;
}

Viewing all `git diffs` with vimdiff

You can try git difftool, it is designed to do this stuff.

First, you need to config diff tool to vimdiff

git config diff.tool vimdiff

Then, when you want to diff, just use git difftool instead of git diff. It will work as you expect.

Convert a tensor to numpy array in Tensorflow?

You can use keras backend function.

import tensorflow as tf
from tensorflow.python.keras import backend 

sess = backend.get_session()
array = sess.run(< Tensor >)

print(type(array))

<class 'numpy.ndarray'>

I hope it helps!

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

Why can't a text column have a default value in MySQL?

Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. WTF?

Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker:

Bryce Nesbitt on April 4 2008 4:36pm:
On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warning. While not a bug, it's possible to get trapped by this if you write code on a lenient platform, and later run it on a strict platform:

Personally, I do view this as a bug. Searching for "BLOB/TEXT column can't have a default value" returns about 2,940 results on Google. Most of them are reports of incompatibilities when trying to install DB scripts that worked on one system but not others.

I am running into the same problem now on a webapp I'm modifying for one of my clients, originally deployed on Linux MySQL v5.0.83-log. I'm running Windows MySQL v5.1.41. Even trying to use the latest version of phpMyAdmin to extract the database, it doesn't report a default for the text column in question. Yet, when I try running an insert on Windows (that works fine on the Linux deployment) I receive an error of no default on ABC column. I try to recreate the table locally with the obvious default (based on a select of unique values for that column) and end up receiving the oh-so-useful BLOB/TEXT column can't have a default value.

Again, not maintaining basic compatability across platforms is unacceptable and is a bug.


How to disable strict mode in MySQL 5 (Windows):

  • Edit /my.ini and look for line

    sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
    
  • Replace it with

    sql_mode='MYSQL40'
    
  • Restart the MySQL service (assuming that it is mysql5)

    net stop mysql5
    net start mysql5
    

If you have root/admin access you might be able to execute

mysql_query("SET @@global.sql_mode='MYSQL40'");

TensorFlow: "Attempting to use uninitialized value" in variable initialization

I want to give my resolution, it work when i replace the line [session = tf.Session()] with [sess = tf.InteractiveSession()]. Hope this will be useful to others.

Cannot kill Python script with Ctrl-C

An improved version of @Thomas K's answer:

  • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

Example codes:

import threading

def job1():
    ...

def job2():
    ...

def is_any_thread_alive(threads):
    return True in [t.is_alive() for t in threads]

if __name__ == "__main__":
    ...
    t1 = threading.Thread(target=job1,daemon=True)
    t2 = threading.Thread(target=job2,daemon=True)
    t1.start()
    t2.start()

    while is_any_thread_alive([t1,t2]):
        time.sleep(0)

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

Centering text in a table in Twitter Bootstrap

<td class="text-center">

and fix .text-center in bootstrap.css:

.text-center {
    text-align: center !important;
}

Spring Security redirect to previous page after successful login

I want to extend Olcay's nice answer. His approach is good, your login page controller should be like this to put the referrer url into session:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request, Model model) {
    String referrer = request.getHeader("Referer");
    request.getSession().setAttribute("url_prior_login", referrer);
    // some other stuff
    return "login";
}

And you should extend SavedRequestAwareAuthenticationSuccessHandler and override its onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) method. Something like this:

public class MyCustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public MyCustomLoginSuccessHandler(String defaultTargetUrl) {
        setDefaultTargetUrl(defaultTargetUrl);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session != null) {
            String redirectUrl = (String) session.getAttribute("url_prior_login");
            if (redirectUrl != null) {
                // we do not forget to clean this attribute from session
                session.removeAttribute("url_prior_login");
                // then we redirect
                getRedirectStrategy().sendRedirect(request, response, redirectUrl);
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}

Then, in your spring configuration, you should define this custom class as a bean and use it on your security configuration. If you are using annotation config, it should look like this (the class you extend from WebSecurityConfigurerAdapter):

@Bean
public AuthenticationSuccessHandler successHandler() {
    return new MyCustomLoginSuccessHandler("/yourdefaultsuccessurl");
}

In configure method:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            // bla bla
            .formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(successHandler())
                .permitAll()
            // etc etc
    ;
}

List<object>.RemoveAll - How to create an appropriate Predicate

This should work (where enquiryId is the id you need to match against):

vehicles.RemoveAll(vehicle => vehicle.EnquiryID == enquiryId);

What this does is passes each vehicle in the list into the lambda predicate, evaluating the predicate. If the predicate returns true (ie. vehicle.EnquiryID == enquiryId), then the current vehicle will be removed from the list.

If you know the types of the objects in your collections, then using the generic collections is a better approach. It avoids casting when retrieving objects from the collections, but can also avoid boxing if the items in the collection are value types (which can cause performance issues).

How to remove duplicates from Python list and keep order?

> but I don't know how to retrieve the list members from the hash in alphabetical order.

Not really your main question, but for future reference Rod's answer using sorted can be used for traversing a dict's keys in sorted order:

for key in sorted(my_dict.keys()):
   print key, my_dict[key]
   ...

and also because tuple's are ordered by the first member of the tuple, you can do the same with items:

for key, val in sorted(my_dict.items()):
    print key, val
    ...

Mailto links do nothing in Chrome but work in Firefox?

You can try going to chrome://settings/handlers and set value for mailto: to none instead of gmail

Format date in a specific timezone

I was having the same issue with Moment.js. I've installed moment-timezone, but the issue wasn't resolved. Then, I did just what here it's exposed, set the timezone and it works like a charm:

moment(new Date({your_date})).zone("+08:00")

Thanks a lot!

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

Npm install cannot find module 'semver'

i was getting an error saying Permission Denied after running any 'ng' command (ng --version). I googled for a while and tried clearing npm cache npm cache verify, uninstalling my global angular cli (npm uninstall -g @angular/cli) and reinstalling Angular/cli (npm install -g @angular/cli) etc.. but it would give an error say its already installed. but the node_modules folder here wouldn't have any angular folder.. reinstalled node even then restarted my computer.

ANSWER: Finally I found that the ng.cmd and ng.ps1 files in C:\Users\JaGoodwin\AppData\Roaming\npm\ here were still there (in npm folder).. even though I did npm uninstall -g @angular/cli. those files were causing ng (angular/cli) to think it was still installed. i deleted those files then npm install -g @angular/[email protected] (version i need) I then removed my projects node_modules and then ran npm install and now can run my angular project using ng serve.

enter image description here

C:\Users\JaGoodwin\AppData\Roaming\npm\

Find this by folder searching %APPDATA% in your windows search bar.

What is the default boolean value in C#?

The default value for bool is false. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.

How to give ASP.NET access to a private key in a certificate in the certificate store?

  1. Create / Purchase certificate. Make sure it has a private key.
  2. Import the certificate into the "Local Computer" account. Best to use Certificates MMC. Make sure to check "Allow private key to be exported"
  3. Based upon which, IIS 7.5 Application Pool's identity use one of the following.

    • IIS 7.5 Website is running under ApplicationPoolIdentity. Open MMC => Add Certificates (Local computer) snap-in => Certificates (Local Computer) => Personal => Certificates => Right click the certificate of interest => All tasks => Manage private key => Add IIS AppPool\AppPoolName and grant it Full control. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS)
    • IIS 7.5 Website is running under NETWORK SERVICE. Using Certificates MMC, added "NETWORK SERVICE" to Full Trust on certificate in "Local Computer\Personal".
    • IIS 7.5 Website is running under "MyIISUser" local computer user account. Using Certificates MMC, added "MyIISUser" (a new local computer user account) to Full Trust on certificate in "Local Computer\Personal".

Update based upon @Phil Hale comment:

Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.

How to read the value of a private field from a different class in Java?

Using the Reflection in Java you can access all the private/public fields and methods of one class to another .But as per the Oracle documentation in the section drawbacks they recommended that :

"Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform"

here is following code snapts to demonstrate basic concepts of Reflection

Reflection1.java

public class Reflection1{

    private int i = 10;

    public void methoda()
    {

        System.out.println("method1");
    }
    public void methodb()
    {

        System.out.println("method2");
    }
    public void methodc()
    {

        System.out.println("method3");
    }

}

Reflection2.java

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class Reflection2{

    public static void main(String ar[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        Method[] mthd = Reflection1.class.getMethods(); // for axis the methods 

        Field[] fld = Reflection1.class.getDeclaredFields();  // for axis the fields  

        // Loop for get all the methods in class
        for(Method mthd1:mthd)
        {

            System.out.println("method :"+mthd1.getName());
            System.out.println("parametes :"+mthd1.getReturnType());
        }

        // Loop for get all the Field in class
        for(Field fld1:fld)
        {
            fld1.setAccessible(true);
            System.out.println("field :"+fld1.getName());
            System.out.println("type :"+fld1.getType());
            System.out.println("value :"+fld1.getInt(new Reflaction1()));
        }
    }

}

Hope it will help.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

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

Accurate way to measure execution times of php scripts

$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
    // do something
}
$total = microtime(true) - $start;
echo $total;

Android toolbar center title and custom font

I solved this solution , And this is a following codes:

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Order History"
            android:layout_gravity="center"
            android:id="@+id/toolbar_title"
            android:textSize="17sp"
            android:textStyle="bold"
            android:textColor="@color/colorWhite"
            />

    </android.support.v7.widget.Toolbar>

And you can change title/label , in Activity, write a below codes:

Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);

TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title); mTitle.setText("@string/....");

How do you remove an invalid remote branch reference from Git?

I didn't know about git branch -rd, so the way I have solved issues like this for myself is to treat my repo as a remote repo and do a remote delete. git push . :refs/remotes/public/master. If the other ways don't work and you have some weird reference you want to get rid of, this raw way is surefire. It gives you the exact precision to remove (or create!) any kind of reference.

How do I get a substring of a string in Python?

Using hardcoded indexes itself can be a mess.

In order to avoid that, Python offers a built-in object slice().

string = "my company has 1000$ on profit, but I lost 500$ gambling."

If we want to know how many money I got left.

Normal solution:

final = int(string[15:19]) - int(string[43:46])
print(final)
>>>500

Using slices:

EARNINGS = slice(15, 19)
LOSSES = slice(43, 46)
final = int(string[EARNINGS]) - int(string[LOSSES])
print(final)
>>>500

Using slice you gain readability.

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

NUnit is probably the most supported by the 3rd party tools. It's also been around longer than the other three.

I personally don't care much about unit test frameworks, mocking libraries are IMHO much more important (and lock you in much more). Just pick one and stick with it.

What exactly is the 'react-scripts start' command?

"start" is a name of a script, in npm you run scripts like this npm run scriptName, npm start is also a short for npm run start

As for "react-scripts" this is a script related specifically to create-react-app

Sorting string array in C#

This code snippet is working properly enter image description here

How do you use global variables or constant values in Ruby?

I think it's local to the file you declared offset. Consider every file to be a method itself.

Maybe put the whole thing into a class and then make offset a class variable with @@offset = Point.new(100, 200);?

how to implement login auth in node.js

Here's how I do it with Express.js:

1) Check if the user is authenticated: I have a middleware function named CheckAuth which I use on every route that needs the user to be authenticated:

function checkAuth(req, res, next) {
  if (!req.session.user_id) {
    res.send('You are not authorized to view this page');
  } else {
    next();
  }
}

I use this function in my routes like this:

app.get('/my_secret_page', checkAuth, function (req, res) {
  res.send('if you are viewing this page it means you are logged in');
});

2) The login route:

app.post('/login', function (req, res) {
  var post = req.body;
  if (post.user === 'john' && post.password === 'johnspassword') {
    req.session.user_id = johns_user_id_here;
    res.redirect('/my_secret_page');
  } else {
    res.send('Bad user/pass');
  }
});

3) The logout route:

app.get('/logout', function (req, res) {
  delete req.session.user_id;
  res.redirect('/login');
});      

If you want to learn more about Express.js check their site here: expressjs.com/en/guide/routing.html If there's need for more complex stuff, checkout everyauth (it has a lot of auth methods available, for facebook, twitter etc; good tutorial on it here).

MAC addresses in JavaScript

The quick and simple answer is No.

Javascript is quite a high level language and does not have access to this sort of information.

How to convert BigInteger to String in java

Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.

Java code To convert byte to Hexadecimal

You can use the method from Bouncy Castle Provider library:

org.bouncycastle.util.encoders.Hex.toHexString(byteArray);

The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms. This jar contains JCE provider and lightweight API for the Bouncy Castle Cryptography APIs for JDK 1.5 to JDK 1.8.

Maven dependency:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.60</version>
</dependency>

or from Apache Commons Codec:

org.apache.commons.codec.binary.Hex.encodeHexString(byteArray);

The Apache Commons Codec package contains simple encoder and decoders for various formats such as Base64 and Hexadecimal. In addition to these widely used encoders and decoders, the codec package also maintains a collection of phonetic encoding utilities.

Maven dependency:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>

Groovy executing shell commands

"ls".execute() returns a Process object which is why "ls".execute().text works. You should be able to just read the error stream to determine if there were any errors.

There is a extra method on Process that allow you to pass a StringBuffer to retrieve the text: consumeProcessErrorStream(StringBuffer error).

Example:

def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)

println proc.text
println b.toString()

Pass all variables from one shell script to another?

In Bash if you export the variable within a subshell, using parentheses as shown, you avoid leaking the exported variables:

#!/bin/bash

TESTVARIABLE=hellohelloheloo
(
export TESTVARIABLE    
source ./test2.sh
)

The advantage here is that after you run the script from the command line, you won't see a $TESTVARIABLE leaked into your environment:

$ ./test.sh
hellohelloheloo
$ echo $TESTVARIABLE
                            #empty! no leak
$

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

stdlib and colored output in C

Because you can't print a character with string formating. You can also think of adding a format with something like this

#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)

f is format as in printf

PRINTC (4, "%s\n", "bar")

will print blue bar

PRINTC (1, "%d", 'a')

will print red 97

Are duplicate keys allowed in the definition of binary search trees?

Many algorithms will specify that duplicates are excluded. For example, the example algorithms in the MIT Algorithms book usually present examples without duplicates. It is fairly trivial to implement duplicates (either as a list at the node, or in one particular direction.)

Most (that I've seen) specify left children as <= and right children as >. Practically speaking, a BST which allows either of the right or left children to be equal to the root node, will require extra computational steps to finish a search where duplicate nodes are allowed.

It is best to utilize a list at the node to store duplicates, as inserting an '=' value to one side of a node requires rewriting the tree on that side to place the node as the child, or the node is placed as a grand-child, at some point below, which eliminates some of the search efficiency.

You have to remember, most of the classroom examples are simplified to portray and deliver the concept. They aren't worth squat in many real-world situations. But the statement, "every element has a key and no two elements have the same key", is not violated by the use of a list at the element node.

So go with what your data structures book said!

Edit:

Universal Definition of a Binary Search Tree involves storing and search for a key based on traversing a data structure in one of two directions. In the pragmatic sense, that means if the value is <>, you traverse the data structure in one of two 'directions'. So, in that sense, duplicate values don't make any sense at all.

This is different from BSP, or binary search partition, but not all that different. The algorithm to search has one of two directions for 'travel', or it is done (successfully or not.) So I apologize that my original answer didn't address the concept of a 'universal definition', as duplicates are really a distinct topic (something you deal with after a successful search, not as part of the binary search.)

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

How to save a data frame as CSV to a user selected location using tcltk

write.csv([enter name of dataframe here],file = file.choose(new = T))

After running above script this window will open :

enter image description here

Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.

How to return value from function which has Observable subscription inside?

This is not exactly correct idea of using Observable

In the component you have to declare class member which will hold an object (something you are going to use in your component)

export class MyComponent {
  name: string = "";
}

Then a Service will be returning you an Observable:

getValueFromObservable():Observable<string> {
    return this.store.map(res => res.json());
}

Component should prepare itself to be able to retrieve a value from it:

OnInit(){
  this.yourServiceName.getValueFromObservable()
    .subscribe(res => this.name = res.name)
}

You have to assign a value from an Observable to a variable:

And your template will be consuming variable name:

<div> {{ name }} </div>

Another way of using Observable is through async pipe http://briantroncone.com/?p=623

Note: If it's not what you are asking, please update your question with more details

How to fit Windows Form to any screen resolution?

Probably a maximized Form helps, or you can do this manually upon form load:

Code Block

this.Location = new Point(0, 0);

this.Size = Screen.PrimaryScreen.WorkingArea.Size;

And then, play with anchoring, so the child controls inside your form automatically fit in your form's new size.

Hope this helps,

Difference in months between two dates

This is from my own library, will return the difference of months between two dates.

public static int MonthDiff(DateTime d1, DateTime d2)
{
    int retVal = 0;

    // Calculate the number of years represented and multiply by 12
    // Substract the month number from the total
    // Substract the difference of the second month and 12 from the total
    retVal = (d1.Year - d2.Year) * 12;
    retVal = retVal - d1.Month;
    retVal = retVal - (12 - d2.Month);

    return retVal;
}

Change size of axes title and labels in ggplot2

You can change axis text and label size with arguments axis.text= and axis.title= in function theme(). If you need, for example, change only x axis title size, then use axis.title.x=.

g+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"))

There is good examples about setting of different theme() parameters in ggplot2 page.

android get real path by Uri.getPath()

EDIT: Use this Solution here: https://stackoverflow.com/a/20559175/2033223 Works perfect!

First of, thank for your solution @luizfelipetx

I changed your solution a little bit. This works for me:

public static String getRealPathFromDocumentUri(Context context, Uri uri){
    String filePath = "";

    Pattern p = Pattern.compile("(\\d+)$");
    Matcher m = p.matcher(uri.toString());
    if (!m.find()) {
        Log.e(ImageConverter.class.getSimpleName(), "ID for requested image not found: " + uri.toString());
        return filePath;
    }
    String imgId = m.group();

    String[] column = { MediaStore.Images.Media.DATA };
    String sel = MediaStore.Images.Media._ID + "=?";

    Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            column, sel, new String[]{ imgId }, null);

    int columnIndex = cursor.getColumnIndex(column[0]);

    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }
    cursor.close();

    return filePath;
}

Note: So we got documents and image, depending, if the image comes from 'recents', 'gallery' or what ever. So I extract the image ID first before looking it up.

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

Passing variable number of arguments around

Ross' solution cleaned-up a bit. Only works if all args are pointers. Also language implementation must support eliding of previous comma if __VA_ARGS__ is empty (both Visual Studio C++ and GCC do).

// pass number of arguments version
 #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__}; _actualFunction(args+1,sizeof(args) / sizeof(*args) - 1);}


// NULL terminated array version
 #define callVardicMethodSafely(...) {value_t *args[] = {NULL, __VA_ARGS__, NULL}; _actualFunction(args+1);}

Add line break to 'git commit -m' from the command line

Sadly, git doesn't seem to allow for any newline character in its message. There are various reasonable solutions already above, but when scripting, those are annoying. Here documents also work, but may also a bit too annoying to deal with (think yaml files)

Here is what I did:

git commit \
    --message "Subject" \
    --message "First line$(echo)Second line$(echo)Third Line"

While this is also still ugly, it allows for 'one-liners' which may be useful still. As usually the strings are variables or combined with variables, the uglynes may be kept to a minimum.

Difference between null and empty ("") Java String

String s = "";
s.length();

String s = null;
s.length();

A reference to an empty string "" points to an object in the heap - so you can call methods on it.

But a reference pointing to null has no object to point in the heap and thus you'll get a NullPointerException.

Get list of certificates from the certificate store in C#

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

Creating multiline strings in JavaScript

If you're willing to use the escaped newlines, they can be used nicely. It looks like a document with a page border.

enter image description here

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

How do you perform address validation?

For US addresses you can require a valid state, and verify that the zip is valid. You could even check that the zip code is in the right state, but beyond that I don't think there are many tests you could run that wouldn't provide a lot of false negatives.

What are you trying to do -- prevent simple mistakes or enforcing some kind of identity check?

How to iterate using ngFor loop Map containing key as string and values as map iteration

As people have mentioned in the comments keyvalue pipe does not retain the order of insertion (which is the primary purpose of Map).

Anyhow, looks like if you have a Map object and want to preserve the order, the cleanest way to do so is entries() function:

<ul>
    <li *ngFor="let item of map.entries()">
        <span>key: {{item[0]}}</span>
        <span>value: {{item[1]}}</span>
    </li>
</ul>

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

Django optional url parameters

Django = 2.2

urlpatterns = [
    re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]

How to set up googleTest as a shared library on Linux

I was similarly underwhelmed by this situation and ended up making my own Ubuntu source packages for this. These source packages allow you to easily produce a binary package. They are based on the latest gtest & gmock source as of this post.

Google Test DEB Source Package

Google Mock DEB Source Package

To build the binary package do this:

tar -xzvf gtest-1.7.0.tar.gz
cd gtest-1.7.0
dpkg-source -x gtest_1.7.0-1.dsc
cd gtest-1.7.0
dpkg-buildpackage

It may tell you that you need some pre-requisite packages in which case you just need to apt-get install them. Apart from that, the built .deb binary packages should then be sitting in the parent directory.

For GMock, the process is the same.

As a side note, while not specific to my source packages, when linking gtest to your unit test, ensure that gtest is included first (https://bbs.archlinux.org/viewtopic.php?id=156639) This seems like a common gotcha.

Unzip files programmatically in .net

Until now, I was using cmd processes in order to extract an .iso file, copy it into a temporary path from server and extracted on a usb stick. Recently I've found that this is working perfectly with .iso's that are less than 10Gb. For a iso like 29Gb this method gets stuck somehow.

    public void ExtractArchive()
    {
        try
        {

            try
            {
                Directory.Delete(copyISOLocation.OutputPath, true); 
            }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
            {
            }

            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            //stackoverflow
            cmd.StartInfo.Arguments = "-R";

            cmd.Disposed += (sender, args) => {
                Console.WriteLine("CMD Process disposed");
            };
            cmd.Exited += (sender, args) => {
                Console.WriteLine("CMD Process exited");
            };
            cmd.ErrorDataReceived += (sender, args) => {
                Console.WriteLine("CMD Process error data received");
                Console.WriteLine(args.Data);
            };
            cmd.OutputDataReceived += (sender, args) => {
                Console.WriteLine("CMD Process Output data received");
                Console.WriteLine(args.Data);
            };

            //stackoverflow


            cmd.Start();

            cmd.StandardInput.WriteLine("C:");
            //Console.WriteLine(cmd.StandardOutput.Read());
            cmd.StandardInput.Flush();

            cmd.StandardInput.WriteLine("cd C:\\\"Program Files (x86)\"\\7-Zip\\");
            //Console.WriteLine(cmd.StandardOutput.ReadToEnd());
            cmd.StandardInput.Flush();

            cmd.StandardInput.WriteLine(string.Format("7z.exe x -o{0} {1}", copyISOLocation.OutputPath, copyISOLocation.TempIsoPath));
            //Console.WriteLine(cmd.StandardOutput.ReadToEnd());
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();
            Console.WriteLine(cmd.StandardOutput.ReadToEnd());
            Console.WriteLine(cmd.StandardError.ReadToEnd());

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

Representing null in JSON

I would pick "default" for data type of variable (null for strings/objects, 0 for numbers), but indeed check what code that will consume the object expects. Don't forget there there is sometimes distinction between null/default vs. "not present".

Check out null object pattern - sometimes it is better to pass some special object instead of null (i.e. [] array instead of null for arrays or "" for strings).

Permission denied error on Github Push

  • click fork button on original github project page
  • clone your forked repository instead original
  • push to it
  • press Pull Requests button on your repository
  • create it
  • wait for original author to accept it

Convert String to Double - VB

The international versions:

    Public Shared Function GetDouble(ByVal doublestring As String) As Double
        Dim retval As Double
        Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

        Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval)
        Return retval
    End Function

    ' NULLABLE VERSION:
    Public Shared Function GetDoubleNullable(ByVal doublestring As String) As Double?
        Dim retval As Double
        Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

        If Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval) Then
            Return retval
        Else
            Return Nothing
        End If
    End Function

Results:

        ' HUNGARIAN REGIONAL SETTINGS (NumberDecimalSeparator: ,)

        ' Clean Double.TryParse
        ' -------------------------------------------------
        Double.TryParse("1.12", d1)     ' Type: DOUBLE     Value: d1 = 0.0
        Double.TryParse("1,12", d2)     ' Type: DOUBLE     Value: d2 = 1.12
        Double.TryParse("abcd", d3)     ' Type: DOUBLE     Value: d3 = 0.0

        ' GetDouble() method
        ' -------------------------------------------------
        d1 = GetDouble("1.12")          ' Type: DOUBLE     Value: d1 = 1.12
        d2 = GetDouble("1,12")          ' Type: DOUBLE     Value: d2 = 1.12
        d3 = GetDouble("abcd")          ' Type: DOUBLE     Value: d3 = 0.0

        ' Nullable version - GetDoubleNullable() method
        ' -------------------------------------------------
        d1n = GetDoubleNullable("1.12") ' Type: DOUBLE?    Value: d1n = 1.12
        d2n = GetDoubleNullable("1,12") ' Type: DOUBLE?    Value: d2n = 1.12
        d3n = GetDoubleNullable("abcd") ' Type: DOUBLE?    Value: d3n = Nothing

do <something> N times (declarative syntax)

If you can't use Underscorejs, you can implement it yourself. By attaching new methods to the Number and String prototypes, you could do it like this (using ES6 arrow functions):

// With String
"5".times( (i) => console.log("number "+i) );

// With number variable
var five = 5;
five.times( (i) => console.log("number "+i) );

// With number literal (parentheses required)
(5).times( (i) => console.log("number "+i) );

You simply have to create a function expression (of whatever name) and assign it to whatever property name (on the prototypes) you would like to access it as:

var timesFunction = function(callback) {
  if (typeof callback !== "function" ) {
    throw new TypeError("Callback is not a function");
  } else if( isNaN(parseInt(Number(this.valueOf()))) ) {
    throw new TypeError("Object is not a valid number");
  }
  for (var i = 0; i < Number(this.valueOf()); i++) {
    callback(i);
  }
};

String.prototype.times = timesFunction;
Number.prototype.times = timesFunction;

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

SQL How to replace values of select return?

I saying that the case statement is wrong but this can be a good solution instead. If you choose to use the CASE statement, you have to make sure that at least one of the CASE condition is matched. Otherwise, you need to define an error handler to catch the error. Recall that you don’t have to do this with the IF statement.

SELECT if(hide = 0,FALSE,TRUE) col FROM tbl; #for BOOLEAN Value return

or

SELECT if(hide = 0,'FALSE','TRUE') col FROM tbl; #for string Value return

How to change the status bar color in Android?

Place this is your values-v21/styles.xml, to enable this on Lollipop:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_secondary</item>
        <item name="colorAccent">@color/color_accent</item>
        <item name="android:statusBarColor">@color/color_primary</item>
    </style>
</resources>

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

How to run python script with elevated privilege on windows

I found a very easy solution to this problem.

  1. Create a shortcut for python.exe
  2. Change the shortcut target into something like C:\xxx\...\python.exe your_script.py
  3. Click "advance..." in the property panel of the shortcut, and click the option "run as administrator"

I'm not sure whether the spells of these options are right, since I'm using Chinese version of Windows.

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();

How to change HTML Object element data attribute value in javascript

The behavior of host objects <object> is due to ECMA262 implementation dependent and set attribute by setAttribute() method may fail.

I see two solutions:

  1. soft: element.data = "http://www.google.com";

  2. hard: remove object from DOM tree and create new one with changed data attribute.

Validating IPv4 addresses with regexp

You've already got a working answer but just in case you are curious what was wrong with your original approach, the answer is that you need parentheses around your alternation otherwise the (\.|$) is only required if the number is less than 200.

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
    ^                                    ^

Remove last characters from a string in C#. An elegant way?

You can actually just use the Remove overload that takes one parameter:

str = str.Remove(str.Length - 3);

However, if you're trying to avoid hard coding the length, you can use:

str = str.Remove(str.IndexOf(','));

Java : How to determine the correct charset encoding of a stream

Can you pick the appropriate char set in the Constructor:

new InputStreamReader(new FileInputStream(in), "ISO8859_1");

How can I remove an SSH key?

I opened "Passwords and Keys" application in my Unity and removed unwanted keys from Secure Keys -> OpenSSH keys And they automatically had been removed from ssh-agent -l as well.

How to use log levels in java

Those are the levels. You'd consider the severity of the message you're logging, and use the appropriate levels.

It's basically a watermark; the higher the level, the more likely you want to retain the information in the log entry. FINEST would be for messages that are of very little importance, so you'd use it for things you usually don't care about but might want to see in some rare circumstance.

"use database_name" command in PostgreSQL

Use this commad when first connect to psql

=# psql <databaseName> <usernamePostgresql>

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

Check whether IIS is installed or not?

For Windows 7:
Control Panel > Programs > Programs and Features > Turn Windows Features On or Off > to turn on IIS click on Check box.

Javascript Date: next month

If you are able to get your hands on date-fns library v2+, you can import the function addMonths, and use that to get the next month

_x000D_
_x000D_
<script type="module">
  import { addMonths } from 'https://cdn.jsdelivr.net/npm/date-fns/+esm'; 
  
  const current = new Date();
  const nextMonth = addMonths(current, 1);
  console.log(`Next month is ${nextMonth}`);
</script>
_x000D_
_x000D_
_x000D_

Comparing Class Types in Java

As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).

In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.

public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
  // TODO handle nulls maybe?
  return c1.getCanonicalName().equals(c2.getCanonicalName());
}

Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.

Change location of log4j.properties

This is my class : Path is fine and properties is loaded.

package com.fiserv.dl.idp.logging;

import java.io.File;
import java.io.FileInputStream;
import java.util.MissingResourceException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class LoggingCapsule {

    private static Logger logger = Logger.getLogger(LoggingCapsule.class);

    public static void info(String message) {


        try {

            String configDir = System.getProperty("config.path");
            if (configDir == null) {
                throw new MissingResourceException("System property: config.path not set", "", "");
            }
            Properties properties = new Properties();
            properties.load(new FileInputStream(configDir + File.separator + "log4j" + ".properties"));
            PropertyConfigurator.configure(properties);
        } catch (Exception e) {
            e.printStackTrace();

        }
        logger.info(message);
    }
    public static void error(String message){
        System.out.println(message);
    }

}

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You have to include one more jar.

xmlbeans-2.3.0.jar

Add this and try.

Note: It is required for the files with .xlsx formats only, not for just .xls formats.

What parameters should I use in a Google Maps URL to go to a lat-lon?

http://maps.google.com/maps?q=58%2041.881N%20152%2031.324W

Just use the coordinates as q-parameter. Strip the z and t prameters. While z should actually just be the zoom level, it seems that it won't work if you set any.

t is the map type. Having that said, it's not obvious how those parameters would affect the result in the shown way. But they do.

Maybe you should try the ll-parameter, but only decimal format will be accepted.

You can find a quick overview of all the parameters here.

JPA getSingleResult() or null

Here's a good option for doing this:

public static <T> T getSingleResult(TypedQuery<T> query) {
    query.setMaxResults(1);
    List<T> list = query.getResultList();
    if (list == null || list.isEmpty()) {
        return null;
    }

    return list.get(0);
}

Easy way to export multiple data.frame to multiple Excel worksheets

You can write to multiple sheets with the xlsx package. You just need to use a different sheetName for each data frame and you need to add append=TRUE:

library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:

wb = createWorkbook()

sheet = createSheet(wb, "Sheet 1")

addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)

sheet = createSheet(wb, "Sheet 2")

addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)

saveWorkbook(wb, "My_File.xlsx")

In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx: http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software

How to target the href to div

Try this code in jquery

$(document).ready(function(){
  $("a").click(function(){
  var id=$(this).attr('href');
  var value=$(id).text();
  $(".target").text(value);
  });
});

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

I've made a category from @Abizern answer

@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
    NSError *error;
    NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
    return (!json ? nil : json);
}
@end

Use it like this,

NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);

PHP how to get the base domain/url?

This works fine if you want the http protocol also since it could be http or https. $domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];

Use of 'const' for function parameters

I say const your value parameters.

Consider this buggy function:

bool isZero(int number)
{
  if (number = 0)  // whoops, should be number == 0
    return true;
  else
    return false;
}

If the number parameter was const, the compiler would stop and warn us of the bug.

What is the proper way to comment functions in Python?

The correct way to do it is to provide a docstring. That way, help(add) will also spit out your comment.

def add(self):
    """Create a new user.
    Line 2 of comment...
    And so on... 
    """

That's three double quotes to open the comment and another three double quotes to end it. You can also use any valid Python string. It doesn't need to be multiline and double quotes can be replaced by single quotes.

See: PEP 257

Eclipse Indigo - Cannot install Android ADT Plugin

I had the same problem. This helped for me:

  1. Go to Help->Install Software
  2. Click on "Available Software Sites"
  3. Click on Add: Name: "Helios" Location: "http://download.eclipse.org/releases/helios"
  4. Try to install Android Development Tools

Read large files in Java

First, if your file contains binary data, then using BufferedReader would be a big mistake (because you would be converting the data to String, which is unnecessary and could easily corrupt the data); you should use a BufferedInputStream instead. If it's text data and you need to split it along linebreaks, then using BufferedReader is OK (assuming the file contains lines of a sensible length).

Regarding memory, there shouldn't be any problem if you use a decently sized buffer (I'd use at least 1MB to make sure the HD is doing mostly sequential reading and writing).

If speed turns out to be a problem, you could have a look at the java.nio packages - those are supposedly faster than java.io,

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

Increment variable value by 1 ( shell programming)

The way to use expr:

i=0
i=`expr $i + 1`

the way to use i++

((i++)); echo $i;

Tested in gnu bash

How to convert a double to long without casting?

If you have a strong suspicion that the DOUBLE is actually a LONG, and you want to

1) get a handle on its EXACT value as a LONG

2) throw an error when its not a LONG

you can try something like this:

public class NumberUtils {

    /**
    * Convert a {@link Double} to a {@link Long}.
    * Method is for {@link Double}s that are actually {@link Long}s and we just
    * want to get a handle on it as one.
    */
    public static long getDoubleAsLong(double specifiedNumber) {
        Assert.isTrue(NumberUtils.isWhole(specifiedNumber));
        Assert.isTrue(specifiedNumber <= Long.MAX_VALUE && specifiedNumber >= Long.MIN_VALUE);
        // we already know its whole and in the Long range
        return Double.valueOf(specifiedNumber).longValue();
    }

    public static boolean isWhole(double specifiedNumber) {
        // http://stackoverflow.com/questions/15963895/how-to-check-if-a-double-value-has-no-decimal-part
        return (specifiedNumber % 1 == 0);
    }
}

Long is a subset of Double, so you might get some strange results if you unknowingly try to convert a Double that is outside of Long's range:

@Test
public void test() throws Exception {
    // Confirm that LONG is a subset of DOUBLE, so numbers outside of the range can be problematic
    Assert.isTrue(Long.MAX_VALUE < Double.MAX_VALUE);
    Assert.isTrue(Long.MIN_VALUE > -Double.MAX_VALUE); // Not Double.MIN_VALUE => read the Javadocs, Double.MIN_VALUE is the smallest POSITIVE double, not the bottom of the range of values that Double can possible be

    // Double.longValue() failure due to being out of range => results are the same even though I minus ten
    System.out.println("Double.valueOf(Double.MAX_VALUE).longValue(): " + Double.valueOf(Double.MAX_VALUE).longValue());
    System.out.println("Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + Double.valueOf(Double.MAX_VALUE - 10).longValue());

    // casting failure due to being out of range => results are the same even though I minus ten
    System.out.println("(long) Double.valueOf(Double.MAX_VALUE): " + (long) Double.valueOf(Double.MAX_VALUE).doubleValue());
    System.out.println("(long) Double.valueOf(Double.MAX_VALUE - 10).longValue(): " + (long) Double.valueOf(Double.MAX_VALUE - 10).doubleValue());
}

Make a phone call programmatically

'openURL:' is deprecated: first deprecated in iOS 10.0 - Please use openURL:options:completionHandler: instead

in Objective-c iOS 10+ use :

NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber] options:@{} completionHandler:nil];

What exactly is Python's file.flush() doing?

Basically, flush() cleans out your RAM buffer, its real power is that it lets you continue to write to it afterwards - but it shouldn't be thought of as the best/safest write to file feature. It's flushing your RAM for more data to come, that is all. If you want to ensure data gets written to file safely then use close() instead.

TypeError: $(...).DataTable is not a function

There can be two reasons for that error:

First

You are loding jQuery.DataTables.js before jquery.js so for that :-

You need to load jQuery.js before you load jQuery.DataTables.js

Second

You are using two versions of jQuery.js on the same page so for that :-

Try to use the higher version and make sure both links have same version of jQuery

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Integrating CSS star rating into an HTML form

Here is the solution.

The HTML:

<div class="rating">
<span>?</span><span>?</span><span>?</span><span>?</span><span>?</span>
</div>

The CSS:

.rating {
  unicode-bidi: bidi-override;
  direction: rtl;
}
.rating > span {
  display: inline-block;
  position: relative;
  width: 1.1em;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
   content: "\2605";
   position: absolute;
}

Hope this helps.

Source

How to create an Observable from static data similar to http one in Angular?

Perhaps you could try to use the of method of the Observable class:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

JavaScript: undefined !== undefined?

I'd like to post some important information about undefined, which beginners might not know.

Look at the following code:

 /* 
  * Consider there is no code above. 
  * The browser runs these lines only.
  */

   // var a;  
   // --- commented out to point that we've forgotten to declare `a` variable 

   if ( a === undefined ) {
       alert('Not defined');
   } else {
       alert('Defined: ' + a);
   }

   alert('Doing important job below');

If you run this code, where variable a HAS NEVER BEEN DECLARED using var, you will get an ERROR EXCEPTION and surprisingly see no alerts at all.

Instead of 'Doing important job below', your script will TERMINATE UNEXPECTEDLY, throwing unhandled exception on the very first line.


Here is the only bulletproof way to check for undefined using typeof keyword, which was designed just for such purpose:

   /* 
    * Correct and safe way of checking for `undefined`: 
    */

   if ( typeof a === 'undefined' ) {
       alert(
           'The variable is not declared in this scope, \n' +
           'or you are pointing to unexisting property, \n' +
           'or no value has been set yet to the variable, \n' + 
           'or the value set was `undefined`. \n' +
           '(two last cases are equivalent, don\'t worry if it blows out your mind.'
           );
   }

   /* 
    *  Use `typeof` for checking things like that
    */

This method works in all possible cases.

The last argument to use it is that undefined can be potentially overwritten in earlier versions of Javascript:

     /* @ Trollface @ */
        undefined = 2;
     /* Happy debuging! */  

Hope I was clear enough.

Maven – Always download sources and javadocs

To follow up on the answer from kevinarpe this does both sources and Javadocs:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.1.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>sources</goal>
                            <goal>resolve</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <classifier>javadoc</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>

Run .jar from batch-file

inside .bat file format

SET CLASSPATH=%Path%;

-------set java classpath and give jar location-------- set classpath=%CLASSPATH%;../lib/MoveFiles.jar;

---------mention your fully classified name of java class to run, which was given in jar------ Java com.mits.MoveFiles pause

Looking for a 'cmake clean' command to clear up CMake output

A solution that I found recently is to combine the out-of-source build concept with a Makefile wrapper.

In my top-level CMakeLists.txt file, I include the following to prevent in-source builds:

if ( ${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR} )
    message( FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there. You may need to remove CMakeCache.txt." )
endif()

Then, I create a top-level Makefile, and include the following:

# -----------------------------------------------------------------------------
# CMake project wrapper Makefile ----------------------------------------------
# -----------------------------------------------------------------------------

SHELL := /bin/bash
RM    := rm -rf
MKDIR := mkdir -p

all: ./build/Makefile
    @ $(MAKE) -C build

./build/Makefile:
    @  ($(MKDIR) build > /dev/null)
    @  (cd build > /dev/null 2>&1 && cmake ..)

distclean:
    @  ($(MKDIR) build > /dev/null)
    @  (cd build > /dev/null 2>&1 && cmake .. > /dev/null 2>&1)
    @- $(MAKE) --silent -C build clean || true
    @- $(RM) ./build/Makefile
    @- $(RM) ./build/src
    @- $(RM) ./build/test
    @- $(RM) ./build/CMake*
    @- $(RM) ./build/cmake.*
    @- $(RM) ./build/*.cmake
    @- $(RM) ./build/*.txt

ifeq ($(findstring distclean,$(MAKECMDGOALS)),)
    $(MAKECMDGOALS): ./build/Makefile
    @ $(MAKE) -C build $(MAKECMDGOALS)
endif

The default target all is called by typing make, and invokes the target ./build/Makefile.

The first thing the target ./build/Makefile does is to create the build directory using $(MKDIR), which is a variable for mkdir -p. The directory build is where we will perform our out-of-source build. We provide the argument -p to ensure that mkdir does not scream at us for trying to create a directory that may already exist.

The second thing the target ./build/Makefile does is to change directories to the build directory and invoke cmake.

Back to the all target, we invoke $(MAKE) -C build, where $(MAKE) is a Makefile variable automatically generated for make. make -C changes the directory before doing anything. Therefore, using $(MAKE) -C build is equivalent to doing cd build; make.

To summarize, calling this Makefile wrapper with make all or make is equivalent to doing:

mkdir build
cd build
cmake ..
make 

The target distclean invokes cmake .., then make -C build clean, and finally, removes all contents from the build directory. I believe this is exactly what you requested in your question.

The last piece of the Makefile evaluates if the user-provided target is or is not distclean. If not, it will change directories to build before invoking it. This is very powerful because the user can type, for example, make clean, and the Makefile will transform that into an equivalent of cd build; make clean.

In conclusion, this Makefile wrapper, in combination with a mandatory out-of-source build CMake configuration, make it so that the user never has to interact with the command cmake. This solution also provides an elegant method to remove all CMake output files from the build directory.

P.S. In the Makefile, we use the prefix @ to suppress the output from a shell command, and the prefix @- to ignore errors from a shell command. When using rm as part of the distclean target, the command will return an error if the files do not exist (they may have been deleted already using the command line with rm -rf build, or they were never generated in the first place). This return error will force our Makefile to exit. We use the prefix @- to prevent that. It is acceptable if a file was removed already; we want our Makefile to keep going and remove the rest.

Another thing to note: This Makefile may not work if you use a variable number of CMake variables to build your project, for example, cmake .. -DSOMEBUILDSUSETHIS:STRING="foo" -DSOMEOTHERBUILDSUSETHISTOO:STRING="bar". This Makefile assumes you invoke CMake in a consistent way, either by typing cmake .. or by providing cmake a consistent number of arguments (that you can include in your Makefile).

Finally, credit where credit is due. This Makefile wrapper was adapted from the Makefile provided by the C++ Application Project Template.

Android EditText for password with android:hint

Actually, I found that if you put the the android:gravity="center" at the end of your xml line, the hint text shows up fine with the android:inputType="textVisiblePassword"

How can I create and style a div using JavaScript?

You can create like this

board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"

document.getElementById("main").appendChild(board);

Complete Runnable Snippet:

_x000D_
_x000D_
var board;_x000D_
board= document.createElement("div");_x000D_
board.id = "mainBoard";_x000D_
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"_x000D_
    _x000D_
document.getElementById("main").appendChild(board);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Get the current date in java.sql.Date format

These are all too long.

Just use:

new Date(System.currentTimeMillis())

Check if a parameter is null or empty in a stored procedure

To check if variable is null or empty use this:

IF LEN(ISNULL(@var, '')) = 0

Breaking out of nested loops

You can also refactor your code to use a generator. But this may not be a solution for all types of nested loops.

How to allow only a number (digits and decimal point) to be typed in an input?

First of all Big thanks to Adam thomas I used the same Adam's logic for this with a small modification to accept the decimal values.

Note: This will allow digits with only 2 decimal values

Here is my Working Example

HTML

<input type="text" ng-model="salary" valid-number />

Javascript

    var app = angular.module('myApp', []);

    app.controller('MainCtrl', function($scope) {
    });

    app.directive('validNumber', function() {
      return {
        require: '?ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
          if(!ngModelCtrl) {
            return; 
          }

          ngModelCtrl.$parsers.push(function(val) {
            if (angular.isUndefined(val)) {
                var val = '';
            }
            var clean = val.replace(/[^0-9\.]/g, '');
            var decimalCheck = clean.split('.');

            if(!angular.isUndefined(decimalCheck[1])) {
                decimalCheck[1] = decimalCheck[1].slice(0,2);
                clean =decimalCheck[0] + '.' + decimalCheck[1];
            }

            if (val !== clean) {
              ngModelCtrl.$setViewValue(clean);
              ngModelCtrl.$render();
            }
            return clean;
          });

          element.bind('keypress', function(event) {
            if(event.keyCode === 32) {
              event.preventDefault();
            }
          });
        }
      };
    });

How to import a csv file using python with headers intact, where first column is a non-numerical

For Python 3

Remove the rb argument and use either r or don't pass argument (default read mode).

with open( <path-to-file>, 'r' ) as theFile:
    reader = csv.DictReader(theFile)
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'
        print(line)

For Python 2

import csv
with open( <path-to-file>, "rb" ) as theFile:
    reader = csv.DictReader( theFile )
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'

Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.

Detect if device is iOS

After iOS 13 you should detect iOS devices like this, since iPad will not be detected as iOS devices by old ways (due to new "desktop" options, enabled by default):

let isIOS = /iPad|iPhone|iPod/.test(navigator.platform)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)

The first condition for iOS < 13 or iPhone or iPad with disabled Desktop mode, the second condition for iPadOS 13 in the default configuration, since it position itself like Macintosh Intel, but actually is the only Macintosh with multi-touch.

Rather a hack than a real solution, but work reliably for me

P.S. As being said earlier, you probably should add IE checkup

let isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream

Find all elements with a certain attribute value in jquery

Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:

$("*[attr-name]")

Hope that helps somebody who happens to land on this page looking for the same thing that I was :).

Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):

$("[attr-name]")

How to list the files in current directory?

I used this answer with my local directory ( for example E:// ) it is worked fine for the first directory and for the seconde directory the output made a java null pointer exception, after searching for the reason i discover that the problem was created by the hidden directory, and this directory was created by windows to avoid this problem just use this

public void recursiveSearch(File file ) {
 File[] filesList = file.listFiles();
    for (File f : filesList) {
        if (f.isDirectory() && !f.isHidden()) {
            System.out.println("Directoy name is  -------------->" + f.getName());
            recursiveSearch(f);
        }
        if( f.isFile() ){
            System.out.println("File name is  -------------->" + f.getName());
        }
    }
}

How to document a method with parameter(s)?

The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

That being said, I personally go with inline comment style occasionally.

def complex(  # Form a complex number
        real=0.0,  # the real part (default 0.0)
        imag=0.0  # the imaginary part (default 0.0)
        ):  # Returns a complex number.
    """Form a complex number.

    I may still use the mainstream docstring notation,
    if I foresee a need to use some other tools
    to generate an HTML online doc later
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    other_code()

One more example here, with some tiny details documented inline:

def foo(  # Note that how I use the parenthesis rather than backslash "\"
          # to natually break the function definition into multiple lines.
        a_very_long_parameter_name,
            # The "inline" text does not really have to be at same line,
            # when your parameter name is very long.
            # Besides, you can use this way to have multiple lines doc too.
            # The one extra level indentation here natually matches the
            # original Python indentation style.
            #
            # This parameter represents blah blah
            # blah blah
            # blah blah
        param_b,  # Some description about parameter B.
            # Some more description about parameter B.
            # As you probably noticed, the vertical alignment of pound sign
            # is less a concern IMHO, as long as your docs are intuitively
            # readable.
        last_param,  # As a side note, you can use an optional comma for
                     # your last parameter, as you can do in multi-line list
                     # or dict declaration.
        ):  # So this ending parenthesis occupying its own line provides a
            # perfect chance to use inline doc to document the return value,
            # despite of its unhappy face appearance. :)
    pass

The benefits (as @mark-horvath already pointed out in another comment) are:

  • Most importantly, parameters and their doc always stay together, which brings the following benefits:
  • Less typing (no need to repeat variable name)
  • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
  • and easier to find missing comment.

Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh

Git push existing repo to a new and different remote repo server?

  1. Create a new repo at github.
  2. Clone the repo from fedorahosted to your local machine.
  3. git remote rename origin upstream
  4. git remote add origin URL_TO_GITHUB_REPO
  5. git push origin master

Now you can work with it just like any other github repo. To pull in patches from upstream, simply run git pull upstream master && git push origin master.

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:

^\d{1,45}$

where \d is the same like [0-9].

How to re-index all subarray elements of a multidimensional array?

Here you can see the difference between the way that deceze offered comparing to the simple array_values approach:

The Array:

$array['a'][0] = array('x' => 1, 'y' => 2, 'z' => 3);
$array['a'][5] = array('x' => 4, 'y' => 5, 'z' => 6);

$array['b'][1] = array('x' => 7, 'y' => 8, 'z' => 9);
$array['b'][7] = array('x' => 10, 'y' => 11, 'z' => 12);

In deceze way, here is your output:

$array = array_map('array_values', $array);
print_r($array);

/* Output */

Array
(
    [a] => Array
        (
            [0] => Array
                (
                    [x] => 1
                    [y] => 2
                    [z] => 3
                )
            [1] => Array
                (
                    [x] => 4
                    [y] => 5
                    [z] => 6
                )
        )
    [b] => Array
        (
            [0] => Array
                (
                    [x] => 7
                    [y] => 8
                    [z] => 9
                )

            [1] => Array
                (
                    [x] => 10
                    [y] => 11
                    [z] => 12
                )
        )
)

And here is your output if you only use array_values function:

$array = array_values($array);
print_r($array);

/* Output */

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [x] => 1
                    [y] => 2
                    [z] => 3
                )
            [5] => Array
                (
                    [x] => 4
                    [y] => 5
                    [z] => 6
                )
        )
    [1] => Array
        (
            [1] => Array
                (
                    [x] => 7
                    [y] => 8
                    [z] => 9
                )
            [7] => Array
                (
                    [x] => 10
                    [y] => 11
                    [z] => 12
                )
        )
)

Connect to mysql in a docker container from the host

  • docker run -e MYSQL_ROOT_PASSWORD=pass --name sql-db -p 3306:3306 mysql

  • docker exec -it sql-db bash

  • mysql -u root -p

Get source jar files attached to Eclipse for Maven-managed dependencies

Right click on project -> maven -> download sources

c#: getter/setter

With the release of C# 6, you can now do something like this for private properties.

public constructor()
{
   myProp = "some value";
}

public string myProp { get; }

How do I use NSTimer?

#import "MyViewController.h"

@interface MyViewController ()

@property (strong, nonatomic) NSTimer *timer;

@end

@implementation MyViewController

double timerInterval = 1.0f;

- (NSTimer *) timer {
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)onTick:(NSTimer*)timer
{
    NSLog(@"Tick...");
}

@end

How to trigger a file download when clicking an HTML button or JavaScript

you can add tag without any text but with link. and when you click the button like you have in code , just run the $("yourlinkclass").click() function.