Programs & Examples On #Glassfish

GlassFish is the reference Java EE application server.

How to return a PNG image from Jersey REST service method to the browser

in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream

@Path("/picture")
public class ProfilePicture {
  @GET
  @Path("/thumbnail")
  @Produces("image/png")
  public StreamingOutput getThumbNail() {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException, WebApplicationException {
        //... read your stream and write into os
      }
    };
  }
}

How do I specify the JDK for a GlassFish domain?

According to the GF Administration Guide:

For a valid JVM installation, locations are checked in the following order: a. domain.xml (java-home inside java-config) b. asenv.conf (setting AS_JAVA="path to java home")

I had to add both these settings to make it work. Otherwise 'asadmin stop-domain domain1' wouldn't work. I guess that GF uses a. and asadmin uses b.

(On Windows: b. asenv.bat)

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

Your description is a little bit strange because the GlassFish server can even start if port 1527 is occupied, because the Java Derby database is a separate java process. So one option could be to just ignore the message in case that the real GlassFish server is indeed starting correctly (NetBeans displays the output for the GlassFish server and the Derby server in different tabs).

Nevertheless you can try to disable starting the registered Derby server for your GlassFish instance.

Make sure that the Derby server is shut down, it can even still run if you have closed NetBeans. If you are not sure kill every java process via the task manager and restart NetBeans.

Right-click your GlassFish instance in the Services tab and choose Properties.

disable derby server start

If instead the real problem is that either port 8080 or 443 (if you activated the HTTPS listener) is in use (which would really prevent GlassFish from starting), you have to find out which application is using this port (maybe Tomcat or something similar) and shut it down.

The error message

'Could not start GlassFish Server 4.1: HTTP or HTTPS listener port is occupied while server is not running'

just points a little bit more in this direction...

Where should I put the log4j.properties file?

Your standard project setup will have a project structure something like:

src/main/java
src/main/resources

You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist

How to configure Glassfish Server in Eclipse manually

For Eclipse Luna

Go to Help>Eclipse MarketPlace> Search for GlassFish Tools and install it.

Restart Eclipse.

Now go to servers>new>server and you will find Glassfish server.

Location of GlassFish Server Logs

In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/.

In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".

If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs

If the server is already running you should see an Output tab in NetBeans which is named similar to GlassFish Server x.x.x

You can also use cat or tail -F on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log. If you are using a different domain then domain1 you have to adjust the path for that.

Could not open ServletContext resource

Try to use classpath*: prefix instead.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-classpath-wildcards

Also please try to deploy exploded war, to ensure that all files are there.

Address already in use: JVM_Bind

Your local port 443 / 8181 / 3820 is used.

If you are on linux/unix:

  • use netstat -an and lsof -n to check who is using this port

If you are on windows

  • use netstat -an and tcpview to check.

What does 'URI has an authority component' mean?

An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.

From RFC3986 on URIs:

The following is an example URI and its component parts:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \
     urn:example:animal:ferret:nose

So there are two formats, one with an authority and one not. Regarding slashes:

"When authority is not present, the path cannot begin with two slash
characters ("//")."

Source: https://tools.ietf.org/rfc/rfc3986.txt (search for text 'authority is not present, the path cannot begin with two slash')

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

The jersey-container-servlet actually uses the jersey-container-servlet-core dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet usage, it will automatically download the dependency as well.

But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer class is actually part of the core dependency.

What is the difference between Tomcat, JBoss and Glassfish?

You should use GlassFish for Java EE enterprise applications. Some things to consider:

A web Server means: Handling HTTP requests (usually from browsers).

A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.

An Application Server (e.g. GlassFish) means: *It can manage Java EE applications (usually both servlet/JSP and EJBs).


Tomcat - is run by Apache community - Open source and has two flavors:

  1. Tomcat - Web profile - lightweight which is only servlet container and does not support Java EE features like EJB, JMS etc.
  2. Tomcat EE - This is a certified Java EE container, this supports all Java EE technologies.

No commercial support available (only community support)

JBoss - Run by RedHat This is a full-stack support for JavaEE and it is a certified Java EE container. This includes Tomcat as web container internally. This also has two flavors:

  1. Community version called Application Server (AS) - this will have only community support.
  2. Enterprise Application Server (EAP) - For this, you can have a subscription-based license (It's based on the number of Cores you have on your servers.)

Glassfish - Run by Oracle This is also a full stack certified Java EE Container. This has its own web container (not Tomcat). This comes from Oracle itself, so all new specs will be tested and implemented with Glassfish first. So, always it would support the latest spec. I am not aware of its support models.

Global npm install location on windows?

These are typical npm paths if you install a package globally:

Windows XP -             %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or -                     %AppData%\roaming\npm\node_modules

jQuery select all except first

$("div.test:not(:first)").hide();

or:

$("div.test:not(:eq(0))").hide();

or:

$("div.test").not(":eq(0)").hide();

or:

$("div.test:gt(0)").hide();

or: (as per @Jordan Lev's comment):

$("div.test").slice(1).hide();

and so on.

See:

Get clicked element using jQuery on event?

The conventional way of handling this doesn't play well with ES6. You can do this instead:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);

  this.delete(clickedElement.data('id'));
});

Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);
  const targetElement = clickedElement.closest('.delete');

  this.delete(targetElement.data('id'));
});

how to convert image to byte array in java?

Here is a complete version of code for doing this. I have tested it. The BufferedImage and Base64 class do the trick mainly. Also some parameter needs to be set correctly.

public class SimpleConvertImage {
    public static void main(String[] args) throws IOException{
        String dirName="C:\\";
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
        BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
        ImageIO.write(img, "jpg", baos);
        baos.flush();

        String base64String=Base64.encode(baos.toByteArray());
        baos.close();

        byte[] bytearray = Base64.decode(base64String);

        BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
        ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    }
}

Reference link

Python functions call by reference

Python is neither pass-by-value nor pass-by-reference. It's more of "object references are passed by value" as described here:

  1. Here's why it's not pass-by-value. Because

    def append(list):
        list.append(1)
    
    list = [0]
    reassign(list)
    append(list)
    

returns [0,1] showing that some kind of reference was clearly passed as pass-by-value does not allow a function to alter the parent scope at all.

Looks like pass-by-reference then, hu? Nope.

  1. Here's why it's not pass-by-reference. Because

    def reassign(list):
      list = [0, 1]
    
    list = [0]
    reassign(list)
    print list
    

returns [0] showing that the original reference was destroyed when list was reassigned. pass-by-reference would have returned [0,1].

For more information look here:

If you want your function to not manipulate outside scope, you need to make a copy of the input parameters that creates a new object.

from copy import copy

def append(list):
  list2 = copy(list)
  list2.append(1)
  print list2

list = [0]
append(list)
print list

Visual Studio 2008 Product Key in Registry?

Just delete key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

Or run in command line:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

With Java 6 form I think is better to check it is closed or not before close (for example if some connection pooler evict the connection in other thread) - for example some network problem - the statement and resultset state can be come closed. (it is not often happens, but I had this problem with Oracle and DBCP). My pattern is for that (in older Java syntax) is:

try {
    //...   
    return resp;
} finally {
    if (rs != null && !rs.isClosed()) {
        try {
            rs.close();
        } catch (Exception e2) { 
            log.warn("Cannot close resultset: " + e2.getMessage());
        }
    }
    if (stmt != null && !stmt.isClosed()) {
        try {
            stmt.close();
        } catch (Exception e2) {
            log.warn("Cannot close statement " + e2.getMessage()); 
        }
    }
    if (con != null && !conn.isClosed()) {
        try {
            con.close();
        } catch (Exception e2) {
            log.warn("Cannot close connection: " + e2.getMessage());
        }
    }
}

In theory it is not 100% perfect because between the the checking the close state and the close itself there is a little room for the change for state. In the worst case you will get a warning in long. - but it is lesser than the possibility of state change in long run queries. We are using this pattern in production with an "avarage" load (150 simultanous user) and we had no problem with it - so never see that warning message.

How can I query for null values in entity framework?

var result = from entry in table    
             where entry.something == value||entry.something == null                   
              select entry;

use that

Upgrading PHP on CentOS 6.5 (Final)

IUS offers an installation script for subscribing to their repository and importing associated GPG keys. Make sure you’re in your home directory, and retrieve the script using curl:

curl 'https://setup.ius.io/' -o setup-ius.sh
sudo bash setup-ius.sh

Install Required Packages-:

sudo yum install -y mod_php70u php70u-cli php70u-mysqlnd php70u-json php70u-gd php70u-dom php70u-simplexml php70u-mcrypt php70u-intl

SQL Server ORDER BY date and nulls last

smalldatetime has range up to June 6, 2079 so you can use

ORDER BY ISNULL(Next_Contact_Date, '2079-06-05T23:59:00')

If no legitimate records will have that date.

If this is not an assumption you fancy relying on a more robust option is sorting on two columns.

ORDER BY CASE WHEN Next_Contact_Date IS NULL THEN 1 ELSE 0 END, Next_Contact_Date

Both of the above suggestions are not able to use an index to avoid a sort however and give similar looking plans.

enter image description here

One other possibility if such an index exists is

SELECT 1 AS Grp, Next_Contact_Date 
FROM T 
WHERE Next_Contact_Date IS NOT NULL
UNION ALL
SELECT 2 AS Grp, Next_Contact_Date 
FROM T 
WHERE Next_Contact_Date IS NULL
ORDER BY Grp, Next_Contact_Date

Plan

Spring boot Security Disable security

The only thing that worked for me:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }

and

security.ignored=/**

Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.

How can I get the SQL of a PreparedStatement?

Code Snippet to convert SQL PreparedStaments with the list of arguments. It works for me

  /**
         * 
         * formatQuery Utility function which will convert SQL
         * 
         * @param sql
         * @param arguments
         * @return
         */
        public static String formatQuery(final String sql, Object... arguments) {
            if (arguments != null && arguments.length <= 0) {
                return sql;
            }
            String query = sql;
            int count = 0;
            while (query.matches("(.*)\\?(.*)")) {
                query = query.replaceFirst("\\?", "{" + count + "}");
                count++;
            }
            String formatedString = java.text.MessageFormat.format(query, arguments);
            return formatedString;
        }

How do I import a .bak file into Microsoft SQL Server 2012?

For SQL Server 2008, I would imagine the procedure is similar...?

  • open SQL Server Management Studio
  • log in to a SQL Server instance, right click on "Databases", select "Restore Database"
  • wizard appears, you want "from device" which allows you to select a .bak file

drag drop files into standard html file input

I made a solution for this.

_x000D_
_x000D_
$(function () {_x000D_
    var dropZoneId = "drop-zone";_x000D_
    var buttonId = "clickHere";_x000D_
    var mouseOverClass = "mouse-over";_x000D_
_x000D_
    var dropZone = $("#" + dropZoneId);_x000D_
    var ooleft = dropZone.offset().left;_x000D_
    var ooright = dropZone.outerWidth() + ooleft;_x000D_
    var ootop = dropZone.offset().top;_x000D_
    var oobottom = dropZone.outerHeight() + ootop;_x000D_
    var inputFile = dropZone.find("input");_x000D_
    document.getElementById(dropZoneId).addEventListener("dragover", function (e) {_x000D_
        e.preventDefault();_x000D_
        e.stopPropagation();_x000D_
        dropZone.addClass(mouseOverClass);_x000D_
        var x = e.pageX;_x000D_
        var y = e.pageY;_x000D_
_x000D_
        if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {_x000D_
            inputFile.offset({ top: y - 15, left: x - 100 });_x000D_
        } else {_x000D_
            inputFile.offset({ top: -400, left: -400 });_x000D_
        }_x000D_
_x000D_
    }, true);_x000D_
_x000D_
    if (buttonId != "") {_x000D_
        var clickZone = $("#" + buttonId);_x000D_
_x000D_
        var oleft = clickZone.offset().left;_x000D_
        var oright = clickZone.outerWidth() + oleft;_x000D_
        var otop = clickZone.offset().top;_x000D_
        var obottom = clickZone.outerHeight() + otop;_x000D_
_x000D_
        $("#" + buttonId).mousemove(function (e) {_x000D_
            var x = e.pageX;_x000D_
            var y = e.pageY;_x000D_
            if (!(x < oleft || x > oright || y < otop || y > obottom)) {_x000D_
                inputFile.offset({ top: y - 15, left: x - 160 });_x000D_
            } else {_x000D_
                inputFile.offset({ top: -400, left: -400 });_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
_x000D_
    document.getElementById(dropZoneId).addEventListener("drop", function (e) {_x000D_
        $("#" + dropZoneId).removeClass(mouseOverClass);_x000D_
    }, true);_x000D_
_x000D_
})
_x000D_
#drop-zone {_x000D_
    /*Sort of important*/_x000D_
    width: 300px;_x000D_
    /*Sort of important*/_x000D_
    height: 200px;_x000D_
    position:absolute;_x000D_
    left:50%;_x000D_
    top:100px;_x000D_
    margin-left:-150px;_x000D_
    border: 2px dashed rgba(0,0,0,.3);_x000D_
    border-radius: 20px;_x000D_
    font-family: Arial;_x000D_
    text-align: center;_x000D_
    position: relative;_x000D_
    line-height: 180px;_x000D_
    font-size: 20px;_x000D_
    color: rgba(0,0,0,.3);_x000D_
}_x000D_
_x000D_
    #drop-zone input {_x000D_
        /*Important*/_x000D_
        position: absolute;_x000D_
        /*Important*/_x000D_
        cursor: pointer;_x000D_
        left: 0px;_x000D_
        top: 0px;_x000D_
        /*Important This is only comment out for demonstration purposes._x000D_
        opacity:0; */_x000D_
    }_x000D_
_x000D_
    /*Important*/_x000D_
    #drop-zone.mouse-over {_x000D_
        border: 2px dashed rgba(0,0,0,.5);_x000D_
        color: rgba(0,0,0,.5);_x000D_
    }_x000D_
_x000D_
_x000D_
/*If you dont want the button*/_x000D_
#clickHere {_x000D_
    position: absolute;_x000D_
    cursor: pointer;_x000D_
    left: 50%;_x000D_
    top: 50%;_x000D_
    margin-left: -50px;_x000D_
    margin-top: 20px;_x000D_
    line-height: 26px;_x000D_
    color: white;_x000D_
    font-size: 12px;_x000D_
    width: 100px;_x000D_
    height: 26px;_x000D_
    border-radius: 4px;_x000D_
    background-color: #3b85c3;_x000D_
_x000D_
}_x000D_
_x000D_
    #clickHere:hover {_x000D_
        background-color: #4499DD;_x000D_
_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="drop-zone">_x000D_
    Drop files here..._x000D_
    <div id="clickHere">_x000D_
        or click here.._x000D_
        <input type="file" name="file" id="file" />_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The Drag and Drop functionality for this method only works with Chrome, Firefox and Safari. (Don't know if it works with IE10), but for other browsers, the "Or click here" button works fine.

The input field simply follow your mouse when dragging a file over an area, and I've added a button as well..

Uncomment opacity:0; the file input is only visible so you can see what's going on.

How to convert hex to ASCII characters in the Linux shell?

You can use this command (python script) for larger inputs:

echo 58595a | python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"

The result will be:

XYZ

And for more simplicity, define an alias:

alias hexdecoder='python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"'

echo 58595a | hexdecoder

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

How to 'grep' a continuous stream?

Use awk(another great bash utility) instead of grep where you dont have the line buffered option! It will continuously stream your data from tail.

this is how you use grep

tail -f <file> | grep pattern

This is how you would use awk

tail -f <file> | awk '/pattern/{print $0}'

Disable future dates after today in Jquery Ui Datepicker

This worked for me endDate: "today"

  $('#datepicker').datepicker({
        format: "dd/mm/yyyy",
        autoclose: true,
        orientation: "top",
        endDate: "today"

  });

SOURCE

Centering the pagination in bootstrap

This css works for me:

.dataTables_paginate {
   float: none !important;
   text-align: center !important;
}

How to import data from text file to mysql database

You should set the option:

local-infile=1

into your [mysql] entry of my.cnf file or call mysql client with the --local-infile option:

mysql --local-infile -uroot -pyourpwd yourdbname

You have to be sure that the same parameter is defined into your [mysqld] section too to enable the "local infile" feature server side.

It's a security restriction.

LOAD DATA LOCAL INFILE '/softwares/data/data.csv' INTO TABLE tableName;

Reload content in modal (twitter bootstrap)

I made a small change to Softlion answer, so all my modals won't refresh on hide. The modals with data-refresh='true' attribute are only refreshed, others work as usual. Here is the modified version.

$(document).on('hidden.bs.modal', function (e) {
    if ($(e.target).attr('data-refresh') == 'true') {
        // Remove modal data
        $(e.target).removeData('bs.modal');
        // Empty the HTML of modal
        $(e.target).html('');
    }
});

Now use the attribute as shown below,

<div class="modal fade" data-refresh="true" id="#modal" tabindex="-1" role="dialog" aria-labelledby="#modal-label" aria-hidden="true"></div>

This will make sure only the modals with data-refresh='true' are refreshed. And i'm also resetting the modal html because the old values are shown until new ones get loaded, making html empty fixes that one.

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

How do I adb pull ALL files of a folder present in SD Card

If you want to pull a directory with restricted access from a rooted device you need to restart adb as root: type adb root before pull. Otherwise you'll get an error saying remote object '/data/data/xxx.example.app' does not exist

How to disassemble a binary executable in Linux to get the assembly code?

You might find ODA useful. It's a web-based disassembler that supports tons of architectures.

http://onlinedisassembler.com/

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

As the accepted answer suggests you can add "using" to all views by adding to section of config file.

But for a single view you could just use

@using SomeNamespace.Extensions

Python: Best way to add to sys.path relative to the current running script

When we try to run python file with path from terminal.

import sys
#For file name
file_name=sys.argv[0]
#For first argument
dir= sys.argv[1]
print("File Name: {}, argument dir: {}".format(file_name, dir)

Save the file (test.py).

Runing system.

Open terminal and go the that dir where is save file. then write

python test.py "/home/saiful/Desktop/bird.jpg"

Hit enter

Output:

File Name: test, Argument dir: /home/saiful/Desktop/bird.jpg

How to read and write to a text file in C++?

Default c++ mechanism for file IO is called streams. Streams can be of three flavors: input, output and inputoutput. Input streams act like sources of data. To read data from an input stream you use >> operator:

istream >> my_variable; //This code will read a value from stream into your variable.

Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc. You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.

Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.

ostream << my_variable; //This code will write a value from your variable into stream.

As with input streams, you can write several values to the stream by writing something like this:

ostream << a << b << c;

Obviously inputoutput streams can act as both.

In your code sample you use cout and cin stream objects. cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.

To interact with files, you need to use ifstream and ofstream types. Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.

Your code might look like this:

#include <iostream>
#include <fstream>

using namespace std;

int start()
{
    cout << "Welcome...";

    // do fancy stuff

    return 0;
}

int main ()
{
    string usreq, usr, yn, usrenter;

    cout << "Is this your first time using TEST" << endl;
    cin >> yn;
    if (yn == "y")
    {
        ifstream iusrfile;
        ofstream ousrfile;
        iusrfile.open("usrfile.txt");
        iusrfile >> usr;
        cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
        iusrfile.close();
        cout << "Please type your Username. \n";
        cin >> usrenter;
        if (usrenter == usr)
        {
            start ();
        }
    }
    else
    {
        cout << "THAT IS NOT A REGISTERED USERNAME.";
    }

    return 0;
}

For further reading you might want to look at c++ I/O reference

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

What are the differences between git remote prune, git prune, git fetch --prune, etc

In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.

If you guys see any issues with this please let me know and I'll fix it (etc. etc.)

Save it in a file called git-rm-ntb (call it whatever) on PATH and run:

git-rm-ntb <remote1:optional> <remote2:optional> ...

clean()
{
  REMOTES="$@";
  if [ -z "$REMOTES" ]; then
    REMOTES=$(git remote);
  fi
  REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
  RBRANCHES=()
  while read REMOTE; do
    CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
    RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
  done < <(echo "$REMOTES" )
  [[ $RBRANCHES ]] || exit
  LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
  for i in "${LBRANCHES[@]}"; do
    skip=
    for j in "${RBRANCHES[@]}"; do
      [[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
    done
    [[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
  done
}

clean $@

JavaScript - onClick to get the ID of the clicked button

Button 1 Button 2 Button 3

var reply_click = function() { 
     alert("Button clicked, id "+this.id+", text"+this.innerHTML); 
} 
document.getElementById('1').onclick = reply_click; 
document.getElementById('2').onclick = reply_click; 
document.getElementById('3').onclick = reply_click;

PowerShell Connect to FTP server and get files

Invoke-WebRequest can download HTTP, HTTPS, and FTP links.

$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password

# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing

Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.

Class is not abstract and does not override abstract method

Both classes Rectangle and Ellipse need to override both of the abstract methods.

To work around this, you have 3 options:

  • Add the two methods
  • Make each class that extends Shape abstract
  • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

    abstract class Shape {
        // ...
        void draw(Graphics g);
    }
    

And

    class Rectangle extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

Finally

    class Ellipse extends Shape {
        void draw(Graphics g) {
            // ...
        }
    }

And you can switch in between them, like so:

    Shape shape = new Ellipse();
    shape.draw(/* ... */);

    shape = new Rectangle();
    shape.draw(/* ... */);

Again, just an example.

What is HTML5 ARIA?

I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them

What is ARIA?

If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.

ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.

And see this you tube video for ARIA live.

Stopping a thread after a certain amount of time

If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.

If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).

Is there a way to make numbers in an ordered list bold?

JSFiddle:

ol {
    counter-reset: item;
}
ol li { display: block }

ol li:before {
    content: counter(item) ". ";
    counter-increment: item;
    font-weight: bold;
}

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

Detect and exclude outliers in Pandas data frame

If you have multiple columns in your dataframe and would like to remove all rows that have outliers in at least one column, the following expression would do that in one shot.

df = pd.DataFrame(np.random.randn(100, 3))

from scipy import stats
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]

description:

  • For each column, first it computes the Z-score of each value in the column, relative to the column mean and standard deviation.
  • Then is takes the absolute of Z-score because the direction does not matter, only if it is below the threshold.
  • all(axis=1) ensures that for each row, all column satisfy the constraint.
  • Finally, result of this condition is used to index the dataframe.

Filter other columns based on a single column

  • Specify a column for the zscore, df[0] for example, and remove .all(axis=1).
df[(np.abs(stats.zscore(df[0])) < 3)]

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

How do I do a multi-line string in node.js?

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

What's the syntax for mod in java

Also, mod can be used like this:

int a = 7;
b = a % 2;

b would equal 1. Because 7 % 2 = 1.

"Could not find or load main class" Error while running java program using cmd prompt

I used IntelliJ to create my .jar, which included some unpacked jars from my libraries. One of these other jars had some signed stuff in the MANIFEST which prevented the .jar from being loaded. No warnings, or anything, just didn't work. Could not find or load main class

Removing the unpacked jar which contained the manifest fixed it.

Hide text within HTML?

This will keep its space, but not show anything;

opacity: 0.0;

This will hide the object fully, plus its (reserved) space;

display: none;

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

This is possible using this cross browser javascript implementation of the HTML5 saveAs function: https://github.com/koffsyrup/FileSaver.js

If all you want to do is save text then the above script works in all browsers(including all versions of IE), using nothing but JS.

Removing packages installed with go get

You can delete the archive files and executable binaries that go install (or go get) produces for a package with go clean -i importpath.... These normally reside under $GOPATH/pkg and $GOPATH/bin, respectively.

Be sure to include ... on the importpath, since it appears that, if a package includes an executable, go clean -i will only remove that and not archive files for subpackages, like gore/gocode in the example below.

Source code then needs to be removed manually from $GOPATH/src.

go clean has an -n flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean). It also has a tempting -r flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!

A complete example, which you could base a script on if you like:

$ go get -u github.com/motemen/gore

$ which gore
/Users/ches/src/go/bin/gore

$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a

$ go clean -i github.com/motemen/gore...

$ which gore

$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore

0 directories, 0 files

# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore

$ rm -rf $GOPATH/src/github.com/motemen/gore

Note that this information is based on the go tool in Go version 1.5.1.

Android Studio: Add jar as library?

I don' know why but my Android Studio 0.8.14 goes crazy when I try to implement these solutions using Gradle. I admit my poor knowledge of this great build tool but what does Studio mutilate my project for? I manage to get it working this way: put android-support-v13.jar into 'libs' directory, then F4 on my project and add File dependency where I pointed android-support-v13.jar.

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

Concept behind putting wait(),notify() methods in Object class

These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.

The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.

For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html

Using Spring RestTemplate in generic method with generic parameter

As the code below shows it, it works.

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

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

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

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

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

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

}

Running a command in a new Mac OS X Terminal window

I've been trying to do this for a while. Here is a script that changes to the same working directory, runs the command, and closes the terminal window.

#!/bin/sh 
osascript <<END 
tell application "Terminal"
    do script "cd \"`pwd`\";$1;exit"
end tell
END

Is it possible to use jQuery .on and hover?

The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.

The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.

Usage example:

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )

Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Difference between Visibility.Collapsed and Visibility.Hidden

Even though a bit old thread, for those who still looking for the differences:

Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.

If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.

As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.

Update just one gem with bundler

You simply need to specify the gem name on the command line:

bundle update gem-name

Getting all documents from one collection in Firestore

I prefer to hide all code complexity in my services... so, I generally use something like this:

In my events.service.ts

    async getEvents() {
        const snapchot = await this.db.collection('events').ref.get();
        return new Promise <Event[]> (resolve => {
            const v = snapchot.docs.map(x => {
                const obj = x.data();
                obj.id = x.id;
                return obj as Event;
            });
            resolve(v);
        });
    }

In my sth.page.ts

   myList: Event[];

   construct(private service: EventsService){}

   async ngOnInit() {
      this.myList = await this.service.getEvents();
   }

Enjoy :)

Good tutorial for using HTML5 History API (Pushstate?)

You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/

How can I use "." as the delimiter with String.split() in java

You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

FFmpeg: How to split video efficiently?

does the later approach save computation time and memory?

There is no big difference between those two examples that you provided. The first example cuts the video sequentially, in 2 steps, while the second example does it at the same time (using threads). No particular speed-up will be noticeable. You can read more about creating multiple outputs with FFmpeg

Further more, what you can use (in recent FFmpeg) is the stream segmenter muxer which can:

output streams to a number of separate files of nearly fixed duration. Output filename pattern can be set in a fashion similar to image2.

Apache won't start in wamp

That is what I did and it helped me to find out what my Apache-PHP needed:

C:\Users\Admin>cd C:\wamp\bin\apache\apache2.4.9\bin

C:\wamp\bin\apache\apache2.4.9\bin>httpd -t
Syntax OK

C:\wamp\bin\apache\apache2.4.9\bin>httpd -k start
[Thu Apr 23 14:14:52.150189 2015] [mpm_winnt:error] [pid 3184:tid 112] 
(OS 2)The system cannot find the file specified.  : AH00436: 
No installed service named "Apache2.4".

C:\wamp\bin\apache\apache2.4.9\bin>

The most simple solution:

Uninstall and reinstall WAMP (do not even try to set it up on top of existing installation - it would not help)

P.S.

If you wonder how did I get to this situation, here is the answer: I was trying to install WAMP and it throws me an error in the middle of installation saying:

httpd.exe - System Error

The program can't start because MSVCR110.dll is missing from your computer. 
Try reinstalling the program to fix this problem.

OK

I got and installed Microsoft Visual C++ 2012 Redistributable from here http://www.microsoft.com/en-us/download/details.aspx?id=30679#

And it gave me the "dll" and the MYSQL started working, but not Apache. To make Apache to work I uninstalled and reinstalled WAMP.

Best way to do multi-row insert in Oracle?

Use SQL*Loader. It takes a little setting up, but if this isn't a one off, its worth it.

Create Table

SQL> create table ldr_test (id number(10) primary key, description varchar2(20));
Table created.
SQL>

Create CSV

oracle-2% cat ldr_test.csv
1,Apple
2,Orange
3,Pear
oracle-2% 

Create Loader Control File

oracle-2% cat ldr_test.ctl 
load data

 infile 'ldr_test.csv'
 into table ldr_test
 fields terminated by "," optionally enclosed by '"'              
 ( id, description )

oracle-2% 

Run SQL*Loader command

oracle-2% sqlldr <username> control=ldr_test.ctl
Password:

SQL*Loader: Release 9.2.0.5.0 - Production on Wed Sep 3 12:26:46 2008

Copyright (c) 1982, 2002, Oracle Corporation.  All rights reserved.

Commit point reached - logical record count 3

Confirm insert

SQL> select * from ldr_test;

        ID DESCRIPTION
---------- --------------------
         1 Apple
         2 Orange
         3 Pear

SQL>

SQL*Loader has alot of options, and can take pretty much any text file as its input. You can even inline the data in your control file if you want.

Here is a page with some more details -> SQL*Loader

Python integer division yields float

According to Python3 documentation,python when divided by integer,will generate float despite expected to be integer.

For exclusively printing integer,use floor division method. Floor division is rounding off zero and removing decimal point. Represented by //

Hence,instead of 2/2 ,use 2//2

You can also import division from __future__ irrespective of using python2 or python3.

Hope it helps!

java.lang.IllegalStateException: Fragment not attached to Activity

Sometimes this exception is caused by a bug in the support library implementation. Recently I had to downgrade from 26.1.0 to 25.4.0 to get rid of it.

Storing and Retrieving ArrayList values from hashmap

You can use like this(Though the random number generator logic is not upto the mark)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);
    test.displayData();

}
public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
        }
        System.out.println();
    }
}
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
        fruit.add(rndData.nextInt(10));
    }
    map.put(name, fruit);
}
}

OUTPUT

grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

How does Python's super() work with multiple inheritance?

I would like to add to what @Visionscaper says at the top:

Third --> First --> object --> Second --> object

In this case the interpreter doesnt filter out the object class because its duplicated, rather its because Second appears in a head position and doesnt appear in the tail position in a hierarchy subset. While object only appears in tail positions and is not considered a strong position in C3 algorithm to determine priority.

The linearisation(mro) of a class C, L(C), is the

  • the Class C
  • plus the merge of
    • linearisation of its parents P1, P2, .. = L(P1, P2, ...) and
    • the list of its parents P1, P2, ..

Linearised Merge is done by selecting the common classes that appears as the head of lists and not the tail since order matters(will become clear below)

The linearisation of Third can be computed as follows:

    L(O)  := [O]  // the linearization(mro) of O(object), because O has no parents

    L(First)  :=  [First] + merge(L(O), [O])
               =  [First] + merge([O], [O])
               =  [First, O]

    // Similarly, 
    L(Second)  := [Second, O]

    L(Third)   := [Third] + merge(L(First), L(Second), [First, Second])
                = [Third] + merge([First, O], [Second, O], [First, Second])
// class First is a good candidate for the first merge step, because it only appears as the head of the first and last lists
// class O is not a good candidate for the next merge step, because it also appears in the tails of list 1 and 2, 
                = [Third, First] + merge([O], [Second, O], [Second])
// class Second is a good candidate for the second merge step, because it appears as the head of the list 2 and 3
                = [Third, First, Second] + merge([O], [O])            
                = [Third, First, Second, O]

Thus for a super() implementation in the following code:

class First(object):
  def __init__(self):
    super(First, self).__init__()
    print "first"

class Second(object):
  def __init__(self):
    super(Second, self).__init__()
    print "second"

class Third(First, Second):
  def __init__(self):
    super(Third, self).__init__()
    print "that's it"

it becomes obvious how this method will be resolved

Third.__init__() ---> First.__init__() ---> Second.__init__() ---> 
Object.__init__() ---> returns ---> Second.__init__() -
prints "second" - returns ---> First.__init__() -
prints "first" - returns ---> Third.__init__() - prints "that's it"

How to set ANDROID_HOME path in ubuntu?

I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:

Install Android SDK

sudo apt-get install android-sdk

Export environmental variables

export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"

rsync error: failed to set times on "/foo/bar": Operation not permitted

I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.

What is your target filesystem?

How to delete duplicate lines in a file without sorting it in Unix?

cat filename | sort | uniq -c | awk -F" " '$1<2 {print $2}'

Deletes the duplicate lines using awk.

How do you rename a MongoDB database?

NOTE: Hopefully this changed in the latest version.

You cannot copy data between a MongoDB 4.0 mongod instance (regardless of the FCV value) and a MongoDB 3.4 and earlier mongod instance. https://docs.mongodb.com/v4.0/reference/method/db.copyDatabase/

ALERT: Hey folks just be careful while copying the database, if you don't want to mess up the different collections under single database.

The following shows you how to rename

> show dbs;
testing
games
movies

To rename you use the following syntax

db.copyDatabase("old db name","new db name")

Example:

db.copyDatabase('testing','newTesting')

Now you can safely delete the old db by the following way

use testing;

db.dropDatabase(); //Here the db **testing** is deleted successfully

Now just think what happens if you try renaming the new database name with existing database name

Example:

db.copyDatabase('testing','movies'); 

So in this context all the collections (tables) of testing will be copied to movies database.

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I had a similar problem and solved it using list...not sure if this will help or not

classes = list(unique_labels(y_true, y_pred))

How do I lowercase a string in Python?

Use .lower() - For example:

s = "Kilometer"
print(s.lower())

The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()

How do I check if a number is positive or negative in C#?

This code takes advantage of SIMD instructions to improve performance.

public static bool IsPositive(int n)
{
  var v = new Vector<int>(n);
  var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
  return result;
}

How to overload __init__ method based on argument type?

Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:

Here's a sample (this is a read method and not a constructor, but the idea is the same):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:

obj.read(filename="blob.txt")

And to read it from a string, I say:

obj.read(str="\x34\x55")

This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex

iFrame onload JavaScript event

Use the iFrame's .onload function of JavaScript:

<iframe id="my_iframe" src="http://www.test.tld/">
    <script type="text/javascript">
        document.getElementById('my_iframe').onload = function() {
            __doPostBack('ctl00$ctl00$bLogout','');
        }
    </script>
    <!--OTHER STUFF-->
</iframe>

Compiling C++ on remote Linux machine - "clock skew detected" warning

type in the terminal and it will solve the issue:

find . -type f | xargs -n 5 touch

make clean

clean

How to Update Multiple Array Elements in mongodb

The thread is very old, but I came looking for answer here hence providing new solution.

With MongoDB version 3.6+, it is now possible to use the positional operator to update all items in an array. See official documentation here.

Following query would work for the question asked here. I have also verified with Java-MongoDB driver and it works successfully.

.update(   // or updateMany directly, removing the flag for 'multi'
   {"events.profile":10},
   {$set:{"events.$[].handled":0}},  // notice the empty brackets after '$' opearor
   false,
   true
)

Hope this helps someone like me.

static files with express.js

const path = require('path');

const express = require('express');

const app = new express();
app.use(express.static('/media'));

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});

app.listen(4000, () => {
    console.log('App listening on port 4000')
})

CLEAR SCREEN - Oracle SQL Developer shortcut?

SQL>Clear Screen (It is used the Clear The Screen FUlly in SQL Plus Window)

How to Code Double Quotes via HTML Codes

There really aren't any differences.

&quot; is processed as &#34; which is the decimal equivalent of &x22; which is the ISO 8859-1 equivalent of ".

The only reason you may be against using &quot; is because it was mistakenly omitted from the HTML 3.2 specification.

Otherwise it all boils down to personal preference.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

My solution is similar to Payam's, except I am using

//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());

If you hit the "3 dots" on the folder and click "Edit"

enter image description here

Then set Pre-Request Scripts for the all calls, so the global variable is always available.

enter image description here

Rollback transaction after @Test

In addition to adding @Transactional on @Test method, you also need to add @Rollback(false)

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

Function stoi not declared

Add this option: -std=c++11 while compiling your code

g++ -std=c++11 my_cpp_code.cpp

How do I get AWS_ACCESS_KEY_ID for Amazon?

It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.

How do I parse JSON into an int?

You may use parseInt :

int id = Integer.parseInt(jsonObj.get("id"));

or better and more directly the getInt method :

int id = jsonObj.getInt("id");

Access 2013 - Cannot open a database created with a previous version of your application

Google Drive has an extension to open MDB files.

enter image description here

I'm not sure how well BLOBs work because I couldn't get my images to display but all the text came up.

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

Get latitude and longitude based on location name with Google Autocomplete API

I hope this can help someone in the future.

You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
        <script type="text/javascript">
        function initialize() {
        var address = (document.getElementById('my-address'));
        var autocomplete = new google.maps.places.Autocomplete(address);
        autocomplete.setTypes(['geocode']);
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }

        var address = '';
        if (place.address_components) {
            address = [
                (place.address_components[0] && place.address_components[0].short_name || ''),
                (place.address_components[1] && place.address_components[1].short_name || ''),
                (place.address_components[2] && place.address_components[2].short_name || '')
                ].join(' ');
        }
      });
}
function codeAddress() {
    geocoder = new google.maps.Geocoder();
    var address = document.getElementById("my-address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {

      alert("Latitude: "+results[0].geometry.location.lat());
      alert("Longitude: "+results[0].geometry.location.lng());
      } 

      else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
google.maps.event.addDomListener(window, 'load', initialize);

        </script>
    </head>
    <body>
        <input type="text" id="my-address">
        <button id="getCords" onClick="codeAddress();">getLat&Long</button>
    </body>
</html>

Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.

Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).

Hope this helps, and read the documentation for more information, cheers.

Edit #1: Fiddle

Method List in Visual Studio Code

Yes, there is the workbench.action.gotoSymbol command. On Windows and Linux it's set to CTRL+Shift+O by default.

If this command isn't available for the file types you are working with then you should take a look at the VSCode extensions. Not all languages support this feature.

REST API Best practices: Where to put parameters?

Here is my opinion.

Query params are used as meta data to a request. They act as filter or modifier to an existing resource call.

Example:

/calendar/2014-08-08/events

should give calendar events for that day.

If you want events for a specific category

/calendar/2014-08-08/events?category=appointments

or if you need events of longer than 30 mins

/calendar/2014-08-08/events?duration=30

A litmus test would be to check if the request can still be served without an query params.

How to Add Stacktrace or debug Option when Building Android Studio Project

In Android Studios 2.1.1, the command-line Options is under "Build, Execution, Deployment">"Compiler"

enter image description here

How to generate .env file for laravel?

If the .env a file is missing, then there is another way to generate a .env file

You can download env.example, rename it to .env and edit it. Just set up correct DB credentials etc.

Don't forget to When you use the php artisan key:generate it will generate the new key to your .env file

Opening the Settings app from another app

You can use this on iOS 5.0 and later: This no longer works.

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]];

How can I initialize an ArrayList with all zeroes in Java?

The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).

To initialize an list with 60 zeros you do:

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));

If you want to create a list with 60 different objects, you could use the Stream API with a Supplier as follows:

List<Person> persons = Stream.generate(Person::new)
                             .limit(60)
                             .collect(Collectors.toList());

gcc error: wrong ELF class: ELFCLASS64

sudo apt-get install ia32-libs 

Using Pairs or 2-tuples in Java

I will start from a general point of view about tuples in Java and finish with an implication for your concrete problem.

1) The way tuples are used in non-generic languages is avoided in Java because they are not type-safe (e.g. in Python: tuple = (4, 7.9, 'python')). If you still want to use something like a general purpose tuple (which is not recommended), you should use Object[] or List<Object> and cast the elements after a check with instanceof to assure type-safety.

Usually, tuples in a certain setting are always used the same way with containing the same structure. In Java, you have to define this structure explicitly in a class to provide well-defined, type-safe values and methods. This seems annoying and unnecessairy at first but prevents errors already at compile-time.

2) If you need a tuple containing the same (super-)classes Foo, use Foo[], List<Foo>, or List<? extends Foo> (or the lists's immutable counterparts). Since a tuple is not of a defined length, this solution is equivalent.

3) In your case, you seem to need a Pair (i.e. a tuple of well-defined length 2). This renders maerics's answer or one of the supplementary answers the most efficient since you can reuse the code in the future.

The declared package does not match the expected package ""

This problem got resolved by mentioning the package name

I moved my file Test_Steps.java which was under package stepDefinition

enter image description here

by just adding the package stepDefinition the problem got resolved

So this problem can occur when you have a package and you are not using in your class file.

Adding it has resolved the problem and the error was no longer appearing.

enter image description here

How to tell which disk Windows Used to Boot

There is no boot.ini on a machine with just Vista installed.

How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:) or by how its hardware signature (which bus, etc).

For the simple case check out GetSystemDirectory

Getting Git to work with a proxy server - fails with "Request timed out"

If you have tsocks or proxychains installed and configured, you can

$ tsocks git clone <you_repository>

or

$ proxychains git clone <you_repository>

to make it shorter, I created a symbol link /usr/bin/p for proxychains, so I can use it like this

p git clone <you_repository>

and I can use it to proxy any command,

p <cmd-need-be-proxied>

by the way, proxychains is not updated for a long time, you may wanna try proxychians-ng

AngularJS How to dynamically add HTML and bind to controller

For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.

After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope if there is no $scope for that element)

/**
 * AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
 */
var AngularHelper = (function () {
    var AngularHelper = function () { };

    /**
     * ApplicationName : Default application name for the helper
     */
    var defaultApplicationName = "myApplicationName";

    /**
     * Compile : Compile html with the rootScope of an application
     *  and replace the content of a target element with the compiled html
     * @$targetDom : The dom in which the compiled html should be placed
     * @htmlToCompile : The html to compile using angular
     * @applicationName : (Optionnal) The name of the application (use the default one if empty)
     */
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
        var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);

        $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
            //Get the scope of the target, use the rootScope if it does not exists
            var $scope = $targetDom.html(htmlToCompile).scope();
            $compile($targetDom)($scope || $rootScope);
            $rootScope.$digest();
        }]);
    }

    return AngularHelper;
})();

It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.

Hope it will help.

How do I concatenate two text files in PowerShell?

You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.

gc .\file2.txt| Add-Content -Path .\file1.txt

"%%" and "%/%" for the remainder and the quotient

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> 
> # Integer Division:
> 5%/%2
[1] 2
> 
> # Remainder:
> 5%%2
[1] 1

How to write a Unit Test?

Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x

Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.

How to read a PEM RSA private key from .NET

For people who don't want to use Bouncy, and are trying some of the code included in other answers, I've found that the code works MOST of the time, but trips up on some RSA private strings, such as the one I've included below. By looking at the bouncy code, I tweaked the code provided by wprl to

    RSAparams.D = ConvertRSAParametersField(D, MODULUS.Length);
    RSAparams.DP = ConvertRSAParametersField(DP, P.Length);
    RSAparams.DQ = ConvertRSAParametersField(DQ, Q.Length);
    RSAparams.InverseQ = ConvertRSAParametersField(IQ, Q.Length);

    private static byte[] ConvertRSAParametersField(byte[] bs, int size)
    {
        if (bs.Length == size)
            return bs;

        if (bs.Length > size)
            throw new ArgumentException("Specified size too small", "size");

        byte[] padded = new byte[size];
        Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
        return padded;
    }

-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAxCgWAYJtfKBVa6Px1Blrj+3Wq7LVXDzx+MiQFrLCHnou2Fvb
fxuDeRmd6ERhDWnsY6dxxm981vTlXukvYKpIZQYpiSzL5pyUutoi3yh0+/dVlsHZ
UHheVGZjSMgUagUCLX1p/augXltAjgblUsj8GFBoKJBr3TMKuR5TwF7lBNYZlaiR
k9MDZTROk6MBGiHEgD5RaPKA/ot02j3CnSGbGNNubN2tyXXAgk8/wBmZ4avT0U4y
5oiO9iwCF/Hj9gK/S/8Q2lRsSppgUSsCioSg1CpdleYzIlCB0li1T0flB51zRIpg
JhWRfmK1uTLklU33xfzR8zO2kkfaXoPTHSdOGQIDAQABAoIBAAkhfzoSwttKRgT8
sgUYKdRJU0oqyO5s59aXf3LkX0+L4HexzvCGbK2hGPihi42poJdYSV4zUlxZ31N2
XKjjRFDE41S/Vmklthv8i3hX1G+Q09XGBZekAsAVrrQfRtP957FhD83/GeKf3MwV
Bhe/GKezwSV3k43NvRy2N1p9EFa+i7eq1e5i7MyDxgKmja5YgADHb8izGLx8Smdd
+v8EhWkFOcaPnQRj/LhSi30v/CjYh9MkxHMdi0pHMMCXleiUK0Du6tnsB8ewoHR3
oBzL4F5WKyNHPvesYplgTlpMiT0uUuN8+9Pq6qsdUiXs0wdFYbs693mUMekLQ4a+
1FOWvQECgYEA7R+uI1r4oP82sTCOCPqPi+fXMTIOGkN0x/1vyMXUVvTH5zbwPp9E
0lG6XmJ95alMRhjvFGMiCONQiSNOQ9Pec5TZfVn3M/w7QTMZ6QcWd6mjghc+dGGE
URmCx8xaJb847vACir7M08AhPEt+s2C7ZokafPCoGe0qw/OD1fLt3NMCgYEA08WK
S+G7dbCvFMrBP8SlmrnK4f5CRE3pV4VGneWp/EqJgNnWwaBCvUTIegDlqS955yVp
q7nVpolAJCmlUVmwDt4gHJsWXSQLMXy3pwQ25vdnoPe97y3xXsi0KQqEuRjD1vmw
K7SXoQqQeSf4z74pFal4CP38U3pivvoE4MQmJeMCfyJFceWqQEUEneL+IYkqrZSK
7Y8urNse5MIC3yUlcose1cWVKyPh4RCEv2rk0U1gKqX29Jb9vO2L7RflAmrLNFuA
J+72EcRxsB68RAJqA9VHr1oeAejQL0+JYF2AK4dJG/FsvvFOokv4eNU+FBHY6Tzo
k+t63NDidkvb5jIF6lsCgYEAlnQ08f5Y8Z9qdCosq8JpKYkwM+kxaVe1HUIJzqpZ
X24RTOL3aa8TW2afy9YRVGbvg6IX9jJcMSo30Llpw2cl5xo21Dv24ot2DF2gGN+s
peFF1Z3Naj1Iy99p5/KaIusOUBAq8pImW/qmc/1LD0T56XLyXekcuK4ts6Lrjkit
FaMCgYAusOLTsRgKdgdDNI8nMQB9iSliwHAG1TqzB56S11pl+fdv9Mkbo8vrx6g0
NM4DluCGNEqLZb3IkasXXdok9e8kmX1en1lb5GjyPbc/zFda6eZrwIqMX9Y68eNR
IWDUM3ckwpw3rcuFXjFfa+w44JZVIsgdoGHiXAdrhtlG/i98Rw==
-----END RSA PRIVATE KEY-----

How to do a regular expression replace in MySQL?

we solve this problem without using regex this query replace only exact match string.

update employee set
employee_firstname = 
trim(REPLACE(concat(" ",employee_firstname," "),' jay ',' abc '))

Example:

emp_id employee_firstname

1 jay

2 jay ajay

3 jay

After executing query result:

emp_id employee_firstname

1 abc

2 abc ajay

3 abc

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

PHP salt and hash SHA256 for login password

I think @Flo254 chained $salt to $password1and stored them to $hashed variable. $hashed variable goes inside INSERT query with $salt.

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Threading Example in Android

One of Androids powerful feature is the AsyncTask class.

To work with it, you have to first extend it and override doInBackground(...). doInBackground automatically executes on a worker thread, and you can add some listeners on the UI Thread to get notified about status update, those functions are called: onPreExecute(), onPostExecute() and onProgressUpdate()

You can find a example here.

Refer to below post for other alternatives:

Handler vs AsyncTask vs Thread

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How to get request URI without context path?

With Spring you can do:

String path = new UrlPathHelper().getPathWithinApplication(request);

How can I override inline styles with external CSS?

!important, after your CSS declaration.

div {
   color: blue !important; 

   /* This Is Now Working */
}

Can't start Eclipse - Java was started but returned exit code=13

The best answer here is too long. I cannot comment so I added my answer.

  1. Go here: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Download the latest SDK (of course for x64 if your computer is x64)
  3. Install it
  4. Now the party is finished, and it's time to work with Eclipse ;)

How to implement the Softmax function in Python

Based on all the responses and CS231n notes, allow me to summarise:

def softmax(x, axis):
    x -= np.max(x, axis=axis, keepdims=True)
    return np.exp(x) / np.exp(x).sum(axis=axis, keepdims=True)

Usage:

x = np.array([[1, 0, 2,-1],
              [2, 4, 6, 8], 
              [3, 2, 1, 0]])
softmax(x, axis=1).round(2)

Output:

array([[0.24, 0.09, 0.64, 0.03],
       [0.  , 0.02, 0.12, 0.86],
       [0.64, 0.24, 0.09, 0.03]])

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

How to increase the max upload file size in ASP.NET?

I have a blog post on how to increase the file size for asp upload control.

From the post:

By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution timeout is 110 seconds. These properties can be changed from within the web.config file’s httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The executionTimeout property determines the maximum time for execution.

live output from subprocess command

None of the Pythonic solutions worked for me. It turned out that proc.stdout.read() or similar may block forever.

Therefore, I use tee like this:

subprocess.run('./my_long_running_binary 2>&1 | tee -a my_log_file.txt && exit ${PIPESTATUS}', shell=True, check=True, executable='/bin/bash')

This solution is convenient if you are already using shell=True.

${PIPESTATUS} captures the success status of the entire command chain (only available in Bash). If I omitted the && exit ${PIPESTATUS}, then this would always return zero since tee never fails.

unbuffer might be necessary for printing each line immediately into the terminal, instead of waiting way too long until the "pipe buffer" gets filled. However, unbuffer swallows the exit status of assert (SIG Abort)...

2>&1 also logs stderror to the file.

MySQL Trigger - Storing a SELECT in a variable

Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)

Argument list too long error for rm, cp, mv commands

I ran into this problem a few times. Many of the solutions will run the rm command for each individual file that needs to be deleted. This is very inefficient:

find . -name "*.pdf" -print0 | xargs -0 rm -rf

I ended up writing a python script to delete the files based on the first 4 characters in the file-name:

import os
filedir = '/tmp/' #The directory you wish to run rm on 
filelist = (os.listdir(filedir)) #gets listing of all files in the specified dir
newlist = [] #Makes a blank list named newlist
for i in filelist: 
    if str((i)[:4]) not in newlist: #This makes sure that the elements are unique for newlist
        newlist.append((i)[:4]) #This takes only the first 4 charcters of the folder/filename and appends it to newlist
for i in newlist:
    if 'tmp' in i:  #If statment to look for tmp in the filename/dirname
        print ('Running command rm -rf '+str(filedir)+str(i)+'* : File Count: '+str(len(os.listdir(filedir)))) #Prints the command to be run and a total file count
        os.system('rm -rf '+str(filedir)+str(i)+'*') #Actual shell command
print ('DONE')

This worked very well for me. I was able to clear out over 2 million temp files in a folder in about 15 minutes. I commented the tar out of the little bit of code so anyone with minimal to no python knowledge can manipulate this code.

How to reset AUTO_INCREMENT in MySQL?

Try Run This Query

 ALTER TABLE tablename AUTO_INCREMENT = value;

Or Try This Query For The Reset Auto Increment

 ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;

And Set Auto Increment Then Run This Query

  ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

Formatting MM/DD/YYYY dates in textbox in VBA

For a quick solution, I usually do like this.

This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If TextBox1.Text <> "" Then
        If IsDate(TextBox1.Text) Then
            TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
        Else
            MsgBox "Please enter a valid date!"
            Cancel = True
        End If
    End If
End Sub

However, I think what Sid developed is a much better approach - a full fledged date picker control.

How to add number of days to today's date?

Here is a solution that worked for me.

function calduedate(ndays){

    var newdt = new Date(); var chrday; var chrmnth;
    newdt.setDate(newdt.getDate() + parseInt(ndays));

    var newdate = newdt.getFullYear();
    if(newdt.getMonth() < 10){
        newdate = newdate+'-'+'0'+newdt.getMonth();
    }else{
        newdate = newdate+'-'+newdt.getMonth();
    }
    if(newdt.getDate() < 10){
        newdate = newdate+'-'+'0'+newdt.getDate();
    }else{
        newdate = newdate+'-'+newdt.getDate();
    }

    alert("newdate="+newdate);

}

python 2 instead of python 3 as the (temporary) default python?

Just call the script using something like python2.7 or python2 instead of just python.

So:

python2 myscript.py

instead of:

python myscript.py

What you could alternatively do is to replace the symbolic link "python" in /usr/bin which currently links to python3 with a link to the required python2/2.x executable. Then you could just call it as you would with python 3.

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

Parsing DateTime:

To parse a DateTime, use one of the following methods:

Alternatively, you may use try-parse pattern:

Read more about Custom Date and Time Format Strings.

Converting DateTime to a string:

To return a DateTime as a string in "yyyyMMdd" format, you may use ToString method.

  • Code snippet example: string date = DateTime.ToString("yyyyMMdd");
  • Note upper-cased M's refer to months and lower-cased m's to minutes.

Your case:

In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact:

string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse, 
                                          "yyyyMMdd",
                                          CultureInfo.InvariantCulture);

Get the decimal part from a double

You may remove the dot . from the double you are trying to get the decimals from using the Remove() function after converting the double to string so that you could do the operations required on it

Consider having a double _Double of value of 0.66781, the following code will only show the numbers after the dot . which are 66781

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string _Decimals = _Double.ToString().Remove(0, _Double.ToString().IndexOf(".") + 1); //Remove everything starting with index 0 and ending at the index of ([the dot .] + 1) 

Another Solution

You may use the class Path as well which performs operations on string instances in a cross-platform manner

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string Output = Path.GetExtension(D.ToString()).Replace(".",""); //Get (the dot and the content after the last dot available and replace the dot with nothing) as a new string object Output
//Do something

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

The import javax.servlet can't be resolved

If you get this compilation error, it means that you have not included the servlet jar in the classpath. The correct way to include this jar is to add the Server Runtime jar to your eclipse project. You should follow the steps below to address this issue: You can download the servlet-api.jar from here http://www.java2s.com/Code/Jar/s/Downloadservletapijar.htm

_x000D_
_x000D_
Save it in directory. Right click on project -> go to properties->Buildpath and follow the steps.
_x000D_
_x000D_
_x000D_

Note: The jar which are shown in the screen are not correct jar.

you can follow the step to configure.

enter image description here

enter image description here enter image description here enter image description here

IntelliJ - show where errors are

For those who even yet have the problem, try enabling "Build project automatically" in the Java compiler settings and see if that makes a difference as it worked for me.

Adding Permissions in AndroidManifest.xml in Android Studio?

You can type them manually but the editor will assist you.

http://developer.android.com/reference/android/Manifest.permission.html

You can see the snap sot below.

enter image description here

As soon as you type "a" inside the quotes you get a list of permissions and also hint to move caret up and down to select the same.

enter image description here

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

Difference between DOM parentNode and parentElement

there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

node.js Error: connect ECONNREFUSED; response from server

From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).

The problem might be you have not created server on your local machine which listens to port 8000.

For that you have to set up server on localhost which can serve your request.

  1. Create server.js

    var express = require('express');
    var app = express();
    
    app.get('/', function (req, res) {
      res.send('Hello World!'); // This will serve your request to '/'.
    });
    
    app.listen(8000, function () {
      console.log('Example app listening on port 8000!');
     });
    
  2. Run server.js : node server.js

  3. Run file that contains code to make request.

How to scan a folder in Java?

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

Difference between ${} and $() in Bash

  1. $() means: "first evaluate this, and then evaluate the rest of the line".

    Ex :

    echo $(pwd)/myFile.txt
    

    will be interpreted as

    echo /my/path/myFile.txt
    

    On the other hand ${} expands a variable.

    Ex:

    MY_VAR=toto
    echo ${MY_VAR}/myFile.txt
    

    will be interpreted as

    echo toto/myFile.txt
    
  2. Why can't I use it as bash$ while ((i=0;i<10;i++)); do echo $i; done

    I'm afraid the answer is just that the bash syntax for while just isn't the same as the syntax for for.

Recommended method for escaping HTML in Java

There is a newer version of the Apache Commons Lang library and it uses a different package name (org.apache.commons.lang3). The StringEscapeUtils now has different static methods for escaping different types of documents (http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html). So to escape HTML version 4.0 string:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;

String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");

insert a NOT NULL column to an existing table

The error message is quite descriptive, try:

ALTER TABLE MyTable ADD Stage INT NOT NULL DEFAULT '-';

What does += mean in Python?

+= is the in-place addition operator.

It's the same as doing cnt = cnt + 1. For example:

>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44

The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)

There are similar operator for subtraction/multiplication/division/power and others:

i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4

The += operator also works on strings, for example:

>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there

People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:

  1. If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

The str.join() method refers to doing the following:

mysentence = []
for x in range(100):
    mysentence.append("test")
" ".join(mysentence)

..instead of the more obvious:

mysentence = ""
for x in range(100):
    mysentence += " test"

The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)

If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.

jQuery hasAttr checking to see if there is an attribute on an element

You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:

$("#change_password").click(function() {
    var target = $(this).attr("rel");
    if($("#" + target).attr("disabled")) {
        $("#" + target).attr("disabled", false);
    } else {
        $("#" + target).attr("disabled", true);
    }
});

The "rel" attribute stores the id of the target input field.

MySQL: Large VARCHAR vs. TEXT?

  • TEXT and BLOB may by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version.

  • VARCHAR is stored inline with the table. VARCHAR is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a real-world scenario with your data.

How to filter files when using scp to copy dir recursively?

There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:

rsync -av --exclude '*.svn' user@server:/my/dir .

(this line copy rsync from distant folder to current one)

Recent versions of rsync tunnel over an ssh connection automatically by default.

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

How many characters can you store with 1 byte?

1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.

enter image description here value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html

Size of Tiny Int = 1 Byte ( -128 to 127)

Int = 4 Bytes (-2147483648 to 2147483647)

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

try:

Activity parentActivity = this.getParent();
if (parentActivity != null)
{
    View landmarkEditNameView = (EditText) parentActivity.findViewById(R.id. landmark_name_dialog_edit);
}

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.

Some reasons why this might happen:

  • Tomcat may have crashed
  • The web application did not respond in time and the request from Apache timed out
  • The Tomcat threads are timing out
  • A network device is blocking the request, perhaps as some sort of connection timeout or DoS attack prevention system

If the problem is related to timeout settings, you may be able to resolve it by investigating the following:

  • ProxyTimeout directive of Apache's mod_proxy
  • Connector config of Apache Tomcat
  • Your network device's manual

How to trigger a phone call when clicking a link in a web page on mobile phone

Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a> and you should be good to go.

If you want to use it for an image, the <a> tag can handle the <img/> placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>

What data type to use for hashed password field and what length?

You can actually use CHAR(length of hash) to define your datatype for MySQL because each hashing algorithm will always evaluate out to the same number of characters. For example, SHA1 always returns a 40-character hexadecimal number.

Find an element in a list of tuples

[tup for tup in a if tup[0] == 1]

How to append the output to a file?

Use >> to append:

command >> file

django templates: include and extends

You can't pull in blocks from an included file into a child template to override the parent template's blocks. However, you can specify a parent in a variable and have the base template specified in the context.

From the documentation:

{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

Instead of separate "page1.html" and "page2.html", put {% extends base_template %} at the top of "commondata.html". And then in your view, define base_template to be either "base1.html" or "base2.html".

error opening trace file: No such file or directory (2)

I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.

What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).

screenshot of the AVD creation screen

Additional information:

while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:

"/Applications/Android Studio.app/sdk/tools/emulator" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none

WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img

I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.

Box shadow in IE7 and IE8

Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.

It supports box-shadow (except for the inset keyword).

Convert sqlalchemy row object to python dict

Two ways:

1.

for row in session.execute(session.query(User).statement):
    print(dict(row))

2.

selected_columns = User.__table__.columns
rows = session.query(User).with_entities(*selected_columns).all()
for row in rows :
    print(row._asdict())

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

FIFO based Queue implementations?

ArrayDeque is probably the fastest object-based queue in the JDK; Trove has the TIntQueue interface, but I don't know where its implementations live.

Rails: How to reference images in CSS within Rails 4

This should get you there every single time.

background-image: url(<%= asset_data_uri 'transparent_2x2.png'%>);

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

A very short way to do it is just right click on the activity_main.xml design background and select convert view then select Relativealayout. Your code in Xml Text will auto. Change. Goodluck

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

You have not accepted the license agreements of the following SDK components

I have resolve the problem by using the command:

  1. Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the android SDK first, or you can install it from the android studio installation process.)
  2. Shift+Left click and Press W,then Enter to open CMD on the folder path
  3. Type in the cmd: sdkmanager --licenses
  4. Once press enter, you need to accept all the licenses by pressing y

CHECKING THE LICENSES

  1. Go to: C:\Users[PC NAME]\AppData\Local\Android\sdk\
  2. Check the folder named licenses
android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license

WAS TESTED ON CORDOVA USING THE COMMAND:

cordova build android

-- UPDATE NEW FOLDER PATH --

Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)

enter image description here

SDKManager will be store in :

  1. Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin
  2. Type in the cmd: sdkmanager --licenses

Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html

callback to handle completion of pipe

Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish, it should handle writableStream's finish event.

var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });

How to disable button in React.js

You shouldn't be setting the value of the input through refs.

Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components

In a nutshell

<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />

Then you will be able to control the disabled state by using disabled={!this.state.value}

unsigned int vs. size_t

The size_t type is the type returned by the sizeof operator. It is an unsigned integer capable of expressing the size in bytes of any memory range supported on the host machine. It is (typically) related to ptrdiff_t in that ptrdiff_t is a signed integer value such that sizeof(ptrdiff_t) and sizeof(size_t) are equal.

When writing C code you should always use size_t whenever dealing with memory ranges.

The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic. For example, on many older PC type computers the value sizeof(size_t) would be 4 (bytes) but sizeof(int) would be 2 (byte). 16 bit arithmetic was faster than 32 bit arithmetic, though the CPU could handle a (logical) memory space of up to 4 GiB.

Use the int type only when you care about efficiency as its actual precision depends strongly on both compiler options and machine architecture. In particular the C standard specifies the following invariants: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) placing no other limitations on the actual representation of the precision available to the programmer for each of these primitive types.

Note: This is NOT the same as in Java (which actually specifies the bit precision for each of the types 'char', 'byte', 'short', 'int' and 'long').

Play multiple CSS animations at the same time

You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
    50%{_x000D_
        transform: rotate(360deg) scale(2);_x000D_
    }_x000D_
    100% { _x000D_
        transform: rotate(720deg) scale(1);_x000D_
    } _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_

PHP Warning: Unknown: failed to open stream

This isn't a direct answer to the question, but I had the same problem. I installed VSFTPD on my Ubuntu Server VPS. I could upload files, but every file I uploaded didn't have execution permissions (all files had rights "600"). These posts explain explain exactly what you have to do to configure your VSFTPD to set default rights on your files:

How to get the azure account tenant Id?

In the Azure CLI (I use GNU/Linux):

$ azure login  # add "-e AzureChinaCloud" if you're using Azure China

This will ask you to login via https://aka.ms/devicelogin or https://aka.ms/deviceloginchina

$ azure account show
info:    Executing command account show
data:    Name                        : BizSpark Plus
data:    ID                          : aZZZZZZZ-YYYY-HHHH-GGGG-abcdef569123
data:    State                       : Enabled
data:    Tenant ID                   : 0XXXXXXX-YYYY-HHHH-GGGG-123456789123
data:    Is Default                  : true
data:    Environment                 : AzureCloud
data:    Has Certificate             : No
data:    Has Access Token            : Yes
data:    User name                   : [email protected]
data:    
info:    account show command OK

or simply:

azure account show --json | jq -r '.[0].tenantId'

or the new az:

az account show --subscription a... | jq -r '.tenantId'
az account list | jq -r '.[].tenantId'

I hope it helps

jQuery click event on radio button doesn't get fired

It fires. Check demo http://jsfiddle.net/yeyene/kbAk3/

$("#inline_content input[name='type']").click(function(){
    alert('You clicked radio!');
    if($('input:radio[name=type]:checked').val() == "walk_in"){
        alert($('input:radio[name=type]:checked').val());
        //$('#select-table > .roomNumber').attr('enabled',false);
    }
});

Char array to hex string C++

The simplest:

int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}

Avoid synchronized(this) in Java?

  1. Make your data immutable if it is possible ( final variables)
  2. If you can't avoid mutation of shared data across multiple threads, use high level programming constructs [e.g. granular Lock API ]

A Lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first.

Sample code to use ReentrantLock which implements Lock interface

 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }

Advantages of Lock over Synchronized(this)

  1. The use of synchronized methods or statements forces all lock acquisition and release to occur in a block-structured way.

  2. Lock implementations provide additional functionality over the use of synchronized methods and statements by providing

    1. A non-blocking attempt to acquire a lock (tryLock())
    2. An attempt to acquire the lock that can be interrupted (lockInterruptibly())
    3. An attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
  3. A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as

    1. guaranteed ordering
    2. non-re entrant usage
    3. Deadlock detection

Have a look at this SE question regarding various type of Locks:

Synchronization vs Lock

You can achieve thread safety by using advanced concurrency API instead of Synchronied blocks. This documentation page provides good programming constructs to achieve thread safety.

Lock Objects support locking idioms that simplify many concurrent applications.

Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.

ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.

Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.

Here is the example for asp.net :

https://www.madskristensen.net/blog/javascript-alertshow(e2809dmessagee2809d)-from-aspnet-code-behind/

Wait until ActiveWorkbook.RefreshAll finishes - VBA

This worked for me:

ActiveWorkbook.refreshall
ActiveWorkbook.Save

When you save the workbook it's necessary to complete the refresh.

React passing parameter via onclick event using ES6 syntax

onClick={this.handleRemove.bind(this, id)}

Oracle's default date format is YYYY-MM-DD, WHY?

reason: if you are looking at a column of data with a time stamp, the _MOST_IMPORTANT_ bit of information is the year. If data has been in the db for ten years, that's important to know. so year comes first.

it makes sense that month would come next, then day, hour, minute. Objectively, these are the most logical sequence for time data to be displayed.

it also makes sense that if you are going to display the data by default, you should display only the most significant portion of the data, so by default, only Y-M-D. everything else CAN be displayed, but it does not clutter your sql report by default.

Ordering by date is logical if you display Y-M-D because it is sequential. Computers are good at sequential, and it looks logical.

finally. Your bias to want M-D-Y is your bias. Not everyone even in the US uses this format. So use the most logical format and don't be outraged when others decide to be logical by default.

(I am US born, and I do not represent Oracle. I can, however, think for myself)

Count number of occurences for each unique value

This works for me. Take your vector v

length(summary(as.factor(v),maxsum=50000))

Comment: set maxsum to be large enough to capture the number of unique values

or with the magrittr package

v %>% as.factor %>% summary(maxsum=50000) %>% length

setting y-axis limit in matplotlib

One thing you can do is to set your axis range by yourself by using matplotlib.pyplot.axis.

matplotlib.pyplot.axis

from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])

0,10 is for x axis range. 0,20 is for y axis range.

or you can also use matplotlib.pyplot.xlim or matplotlib.pyplot.ylim

matplotlib.pyplot.ylim

plt.ylim(-2, 2)
plt.xlim(0,10)

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank">
  <img width="220" height="250" border="0" align="center"  src=""/>
</a>

Bundling data files with PyInstaller (--onefile)

If you are still trying to put files relative to your executable instead of in the temp directory, you need to copy it yourself. This is how I ended up getting it done.

https://stackoverflow.com/a/59415662/999943

You add a step in the spec file that does a filesystem copy to the DISTPATH variable.

Hope that helps.

How to upgrade Angular CLI to the latest version

To update Angular CLI to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g @angular/cli
npm cache clean
# if npm version is > 5 then use `npm cache verify` to avoid errors (or to avoid using --force)
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install

Source: Github

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

What can I use for good quality code coverage for C#/.NET?

We've released EAP to dotCover and will be releasing the beta version soon.

How to set a cron job to run every 3 hours

The unix setup should be like the following:

 0 */3 * * * sh cron/update_old_citations.sh

good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/

Use of "this" keyword in C++

this points to the object in whose member function it is reffered, so it is optional.

Read remote file with node.js (http.get)

function(url,callback){
    request(url).on('data',(data) => {
        try{
            var json = JSON.parse(data);    
        }
        catch(error){
            callback("");
        }
        callback(json);
    })
}

You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .

Automatically open Chrome developer tools when new tab/new window is opened

You can open Dev Tools (F12 in Chrome) in new window by clicking three, vertical dots on the right bottom corner, and choose Open as Separate Window.

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.

After that you can just easily get the wanted prop:

for employee in employees:
    print(employee.eng_name)

Or in the template:

{% for employee in employees %}

    <p>{{ employee.eng_name }}</p>

{% endfor %}

In android how to set navigation drawer header image and name programmatically in class file?

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View hView =  navigationView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.nav_name);
nav_user.setText(user);

hope this help!

Pretty git branch graphs

Depends on what they looked like. I use gitx which makes pictures like this one:

simple plot

You can compare git log --graph vs. gitk on a 24-way octopus merge (originally from http://clojure-log.n01se.net/date/2008-12-24.html):

24-way git octopus merge. Original URL was <code>http://lwn.net/images/ns/kernel/gitk-octopus.png</code>

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

Converting from longitude\latitude to Cartesian coordinates

In python3.x it can be done using :

# Converting lat/long to cartesian
import numpy as np

def get_cartesian(lat=None,lon=None):
    lat, lon = np.deg2rad(lat), np.deg2rad(lon)
    R = 6371 # radius of the earth
    x = R * np.cos(lat) * np.cos(lon)
    y = R * np.cos(lat) * np.sin(lon)
    z = R *np.sin(lat)
    return x,y,z

How to check if two words are anagrams

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Algorithms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JOptionPane;

/**
 *
 * @author Mokhtar
 */
public class Anagrams {

    //Write aprogram to check if two words are anagrams
    public static void main(String[] args) {
        Anagrams an=new Anagrams();
        ArrayList<String> l=new ArrayList<String>();
        String result=JOptionPane.showInputDialog("How many words to test anagrams");
        if(Integer.parseInt(result) >1)
        {    
            for(int i=0;i<Integer.parseInt(result);i++)
            {

                String word=JOptionPane.showInputDialog("Enter word #"+i);
                l.add(word);   
            }
            System.out.println(an.isanagrams(l));
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Can not be tested, \nYou can test two words or more");
        }

    }

    private static String sortString( String w )
    {
        char[] ch = w.toCharArray();
        Arrays.sort(ch);
        return new String(ch);
    }

    public boolean isanagrams(ArrayList<String> l)
    {
        boolean isanagrams=true; 
        ArrayList<String> anagrams = null;
        HashMap<String, ArrayList<String>> map =  new HashMap<String, ArrayList<String>>();
        for(int i=0;i<l.size();i++)
            {
        String word = l.get(i);
        String sortedWord = sortString(word);
            anagrams = map.get( sortedWord );
        if( anagrams == null ) anagrams = new ArrayList<String>();
        anagrams.add(word);
        map.put(sortedWord, anagrams);
            }

            for(int h=0;h<l.size();h++)
            {
                if(!anagrams.contains(l.get(h)))
                {
                    isanagrams=false;
                    break;
                }
            }

            return isanagrams;
        //}
        }

}

how to make a cell of table hyperlink

Why not combine the onclick method with the <a> element inside the <td> for backup for non-JS? Seems to work great.

<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>

document.getElementById replacement in angular4 / typescript?

You can just inject the DOCUMENT token into the constructor and use the same functions on it

import { Inject }  from '@angular/core';
import { DOCUMENT } from '@angular/common'; 

@Component({...})
export class AppCmp {
   constructor(@Inject(DOCUMENT) document) {
      document.getElementById('el');
   }
}

Or if the element you want to get is in that component, you can use template references.

How to initialize an array of custom objects

Here is a more concise version of the accepted answer which avoids repeating the NoteProperty identifiers and the [pscustomobject]-cast:

$myItems =  ("Joe",32,"something about him"), ("Sue",29,"something about her")
            | ForEach-Object {[pscustomobject]@{name = $_[0]; age = $_[1]; info = $_[2]}}

Result:

> $myItems

name           age         info
----           ---         ----
Joe            32          something about him
Sue            29          something about her

Convert floats to ints in Pandas?

The columns that needs to be converted to int can be mentioned in a dictionary also as below

df = df.astype({'col1': 'int', 'col2': 'int', 'col3': 'int'})

Create Git branch with current changes

If you hadn't made any commit yet, only (1: branch) and (3: checkout) would be enough.
Or, in one command: git checkout -b newBranch

As mentioned in the git reset man page:

$ git branch topic/wip     # (1)
$ git reset --hard HEAD~3  # (2)  NOTE: use $git reset --soft HEAD~3 (explanation below)
$ git checkout topic/wip   # (3)
  1. You have made some commits, but realize they were premature to be in the "master" branch. You want to continue polishing them in a topic branch, so create "topic/wip" branch off of the current HEAD.
  2. Rewind the master branch to get rid of those three commits.
  3. Switch to "topic/wip" branch and keep working.

Note: due to the "destructive" effect of a git reset --hard command (it does resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded), I would rather go with:

$ git reset --soft HEAD~3  # (2)

This would make sure I'm not losing any private file (not added to the index).
The --soft option won't touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do).


With Git 2.23+, the new command git switch would create the branch in one line (with the same kind of reset --hard, so beware of its effect):

git switch -f -c topic/wip HEAD~3

How to display images from a folder using php - PHP

You have two ways to do that:

METHOD 1. The secure way.

Put the images on /www/htdocs/

<?php
    $www_root = 'http://localhost/images';
    $dir = '/var/www/images';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

METHOD 2. Unsecure but more flexible.

Put the images on any directory (apache must have permission to read the file).

<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

And create another script to read the image file.

<?php
    $filename = base64_decode($_GET['file']);
    // Check the folder location to avoid exploit
    if (dirname($filename) == '/home/user/Pictures')
        echo file_get_contents($filename);
?>