Programs & Examples On #Setrlimit

system call included in POSIX which allows setting of limits on operating system resources like CPU, memory, files and possibly others

How to change the height of a div dynamically based on another div using css?

By specifying the positions we can achieve this,

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  position:relative;
  overflow:auto;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  
  float:left;
}
.div3 {
  width:150px;
  height:100%;
  position:absolute;
  right:0px;
  background-color: #FFFFE0;  
  float:right;
}

but it is not possible to achieve this using float.

Download/Stream file from URL - asp.net

If you are looking for a .NET Core version of @Dallas's answer, use the below.

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

Why doesn't Java support unsigned ints?

Java does have unsigned types, or at least one: char is an unsigned short. So whatever excuse Gosling throws up it's really just his ignorance why there are no other unsigned types.

Also Short types: shorts are used all the time for multimedia. The reason is you can fit 2 samples in a single 32-bit unsigned long and vectorize many operations. Same thing with 8-bit data and unsigned byte. You can fit 4 or 8 samples in a register for vectorizing.

Clear android application user data

Afaik the Browser application data is NOT clearable for other apps, since it is store in private_mode. So executing this command could probalby only work on rooted devices. Otherwise you should try another approach.

php_network_getaddresses: getaddrinfo failed: Name or service not known

$url = "http://user:[email protected]/abc.php?var1=def";
$contents = file_get_contents($url);
echo $contents;

How do I Set Background image in Flutter?

I'm not sure I understand your question, but if you want the image to fill the entire screen you can use a DecorationImage with a fit of BoxFit.cover.

class BaseLayout extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/bulb.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        child: null /* add child content here */,
      ),
    );
  }
}

For your second question, here is a link to the documentation on how to embed resolution-dependent asset images into your app.

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

if you are using maven:

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

How do I force git pull to overwrite everything on every pull?

To pull a copy of the branch and force overwrite of local files from the origin use:

git reset --hard origin/current_branch

All current work will be lost and it will then be the same as the origin branch

How to find out when a particular table was created in Oracle?

SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'

error::make_unique is not a member of ‘std’

This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:

set(CMAKE_CXX_STANDARD 14).

Example:

cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)

# Rest of your declarations...

Why call super() in a constructor?

It simply calls the default constructor of the superclass.

Find all packages installed with easy_install/pip?

pip.get_installed_distributions() will give a list of installed packages

import pip
from os.path import join

for package in pip.get_installed_distributions():
    print(package.location) # you can exclude packages that's in /usr/XXX
    print(join(package.location, package._get_metadata("top_level.txt"))) # root directory of this package

How do I get the XML SOAP request of an WCF Web service request?

I am using below solution for IIS hosting in ASP.NET compatibility mode. Credits to Rodney Viana's MSDN blog.

Add following to your web.config under appSettings:

<add key="LogPath" value="C:\\logpath" />
<add key="LogRequestResponse" value="true" />

Replace your global.asax.cs with below (also fix namespace name):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Text;
using System.IO;
using System.Configuration;

namespace Yournamespace
{
    public class Global : System.Web.HttpApplication
    {
        protected static bool LogFlag;
        protected static string fileNameBase;
        protected static string ext = "log";

        // One file name per day
        protected string FileName
        {
            get
            {
                return String.Format("{0}{1}.{2}", fileNameBase, DateTime.Now.ToString("yyyy-MM-dd"), ext);
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            LogFlag = bool.Parse(ConfigurationManager.AppSettings["LogRequestResponse"].ToString());
            fileNameBase = ConfigurationManager.AppSettings["LogPath"].ToString() + @"\C5API-";   
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (LogFlag) 
            {                
                // Creates a unique id to match Rquests with Responses
                string id = String.Format("Id: {0} Uri: {1}", Guid.NewGuid(), Request.Url);
                FilterSaveLog input = new FilterSaveLog(HttpContext.Current, Request.Filter, FileName, id);
                Request.Filter = input;
                input.SetFilter(false);
                FilterSaveLog output = new FilterSaveLog(HttpContext.Current, Response.Filter, FileName, id);
                output.SetFilter(true);
                Response.Filter = output;
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }

    class FilterSaveLog : Stream
    {

        protected static string fileNameGlobal = null;
        protected string fileName = null;

        protected static object writeLock = null;
        protected Stream sinkStream;
        protected bool inDisk;
        protected bool isClosed;
        protected string id;
        protected bool isResponse;
        protected HttpContext context;

        public FilterSaveLog(HttpContext Context, Stream Sink, string FileName, string Id)
        {
            // One lock per file name
            if (String.IsNullOrWhiteSpace(fileNameGlobal) || fileNameGlobal.ToUpper() != fileNameGlobal.ToUpper())
            {
                fileNameGlobal = FileName;
                writeLock = new object();
            }
            context = Context;
            fileName = FileName;
            id = Id;
            sinkStream = Sink;
            inDisk = false;
            isClosed = false;
        }

        public void SetFilter(bool IsResponse)
        {


            isResponse = IsResponse;
            id = (isResponse ? "Reponse " : "Request ") + id;

            //
            // For Request only read the incoming stream and log it as it will not be "filtered" for a WCF request
            //
            if (!IsResponse)
            {
                AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
                AppendToFile(id);

                if (context.Request.InputStream.Length > 0)
                {
                    context.Request.InputStream.Position = 0;
                    byte[] rawBytes = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(rawBytes, 0, rawBytes.Length);
                    context.Request.InputStream.Position = 0;

                    AppendToFile(rawBytes);
                }
                else
                {
                    AppendToFile("(no body)");
                }
            }

        }

        public void AppendToFile(string Text)
        {
            byte[] strArray = Encoding.UTF8.GetBytes(Text);
            AppendToFile(strArray);

        }

        public void AppendToFile(byte[] RawBytes)
        {
            bool myLock = System.Threading.Monitor.TryEnter(writeLock, 100);


            if (myLock)
            {
                try
                {

                    using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        stream.Position = stream.Length;
                        stream.Write(RawBytes, 0, RawBytes.Length);
                        stream.WriteByte(13);
                        stream.WriteByte(10);

                    }

                }
                catch (Exception ex)
                {
                    string str = string.Format("Unable to create log. Type: {0} Message: {1}\nStack:{2}", ex, ex.Message, ex.StackTrace);
                    System.Diagnostics.Debug.WriteLine(str);
                    System.Diagnostics.Debug.Flush();


                }
                finally
                {
                    System.Threading.Monitor.Exit(writeLock);


                }
            }


        }


        public override bool CanRead
        {
            get { return sinkStream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return sinkStream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return sinkStream.CanWrite; }
        }

        public override long Length
        {
            get
            {
                return sinkStream.Length;
            }
        }

        public override long Position
        {
            get { return sinkStream.Position; }
            set { sinkStream.Position = value; }
        }

        //
        // For WCF this code will never be reached
        //
        public override int Read(byte[] buffer, int offset, int count)
        {
            int c = sinkStream.Read(buffer, offset, count);
            return c;
        }

        public override long Seek(long offset, System.IO.SeekOrigin direction)
        {
            return sinkStream.Seek(offset, direction);
        }

        public override void SetLength(long length)
        {
            sinkStream.SetLength(length);
        }

        public override void Close()
        {

            sinkStream.Close();
            isClosed = true;
        }

        public override void Flush()
        {

            sinkStream.Flush();
        }

        // For streamed responses (i.e. not buffered) there will be more than one Response (but the id will match the Request)
        public override void Write(byte[] buffer, int offset, int count)
        {
            sinkStream.Write(buffer, offset, count);
            AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
            AppendToFile(id);
            AppendToFile(buffer);
        }

    }
}

It should create log file in the folder LogPath with request and response XML.

How do I force Robocopy to overwrite files?

This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).

This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG

I did a small test for you .. and here is the result:

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :      1028      1028         0         0         0       169
   Files :      8053      8053         0         0         0         1
   Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
   Times :   2:46:53   0:41:43                       0:00:00   0:41:44


   Speed :           278653398 Bytes/sec.
   Speed :           15944.675 MegaBytes/min.
   Ended : Friday, August 21, 2020 7:34:33 AM

Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

Some performance tips from my history with it and so many tests & troubles!:

. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

For very large files:

  1. Use Only "One" thread "/MT:1" | Impact: BIG
  2. Must use "/J" to disable buffering. | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

For regular big files:

  1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
  2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
  3. & 4 same as above.

For thousands of tiny files:

  1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
  2. Don't use "/J" | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

Java 8: Lambda-Streams, Filter by Method with Exception

If you want to handled the exception within the stream and continue processing the additional ones, there is an excellent article in DZone by Brian Vermeer using the concept of an Either. It shows an excellent way of handling this situation. The only thing missing is sample code. This is a sample of my exploration using the concepts from that article.

@Test
public void whenValuePrinted_thenPrintValue() {

    List<Integer> intStream = Arrays.asList(0, 1, 2, 3, 4, 5, 6);
    intStream.stream().map(Either.liftWithValue(item -> doSomething(item)))
             .map(item -> item.isLeft() ? item.getLeft() : item.getRight())
             .flatMap(o -> {
                 System.out.println(o);
                 return o.isPresent() ? Stream.of(o.get()) : Stream.empty();
             })
             .forEach(System.out::println);
}

private Object doSomething(Integer item) throws Exception {

    if (item == 0) {
        throw new Exception("Zero ain't a number!");
    } else if (item == 4) {
        return Optional.empty();
    }

    return item;
}

Installing PDO driver on MySQL Linux server

  1. PDO stands for PHP Data Object.
  2. PDO_MYSQL is the driver that will implement the interface between the dataobject(database) and the user input (a layer under the user interface called "code behind") accessing your data object, the MySQL database.

The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)

But there are a few nuances to this which you might not be aware of.

First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.

You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.

And:

By implementing best practices while writing your code you will be much happier with the outcome.

Additional sources:

Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php

Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/

Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028

Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.

>

If we knew what the terminology really meant we wouldn't need to learn anything.

>

How to test the `Mosquitto` server?

If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto server

just visit http://www.hivemq.com/demos/websocket-client/ and enter server connection details.

If you got connected means your server is configured properly.

You can also test publish and subscribe of messages using this mqtt web socket

Bold words in a string of strings.xml in Android

Use html tag inside string resources :-

<resources>
<string name="string_resource_name"><![CDATA[<b> Your text </b>]]> </string>
</resources>

And get bold text from string resources like :-

private Spanned getSpannedText(String text) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT);
        } else {
            return Html.fromHtml(text);
        }
    }


 String s = format(context.getResources().getString(R.string.string_resource_name));
 textView.setText(getSpannedText(s));

Android Call an method from another class

And, if you don't want to instantiate Class2, declare UpdateEmployee as static and call it like this:

Class2.UpdateEmployee();

However, you'll normally want to do what @parag said.

Reference list item by index within Django template?

@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.

Retain precision with double in Java

Doubles are approximations of the decimal numbers in your Java source. You're seeing the consequence of the mismatch between the double (which is a binary-coded value) and your source (which is decimal-coded).

Java's producing the closest binary approximation. You can use the java.text.DecimalFormat to display a better-looking decimal value.

Case insensitive string compare in LINQ-to-SQL

The following 2-stage approach works for me (VS2010, ASP.NET MVC3, SQL Server 2008, Linq to SQL):

result = entRepos.FindAllEntities()
    .Where(e => e.EntitySearchText.Contains(item));

if (caseSensitive)
{
    result = result
        .Where(e => e.EntitySearchText.IndexOf(item, System.StringComparison.CurrentCulture) >= 0);
}

Re-order columns of table in Oracle

Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.

As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):

  • Group related columns together.
  • Not NULL columns before null-able columns.
  • Frequently searched un-indexed columns first.
  • Rarely filled null-able columns last.
  • Static columns first.
  • Updateable varchar columns later.
  • Indexed columns after other searchable columns.

These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.

How to expire a cookie in 30 minutes using jQuery?

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

How to add display:inline-block in a jQuery show() function?

Setting the CSS property after you have used .show() should work. Maybe you are targeting the wrong element on your HTML page.

 $('#foo').css('display', 'inline-block');

But if you are not using any effects of .show(), .hide() why don't you set those CSS properties manually like:

$('#foo').css('display','none'); 
$('#foo').css('display','inline-block');

Array functions in jQuery

Look into the jQuery functions .grep() and .map()

message box in jquery

Try this plugin JQuery UI Message box. He uses jQuery UI Dialog.

jQuery removeClass wildcard

A regex splitting on word boundary \b isn't the best solution for this:

var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
    return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ");

or as a jQuery mixin:

$.fn.removeClassPrefix = function(prefix) {
    this.each(function(i, el) {
        var classes = el.className.split(" ").filter(function(c) {
            return c.lastIndexOf(prefix, 0) !== 0;
        });
        el.className = classes.join(" ");
    });
    return this;
};

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

Call and receive output from Python script in Java?

Jep is anther option. It embeds CPython in Java through JNI.

import jep.Jep;
//...
    try(Jep jep = new Jep(false)) {
        jep.eval("s = 'hello world'");
        jep.eval("print(s)");
        jep.eval("a = 1 + 2");
        Long a = (Long) jep.getValue("a");
    }

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

How to set null value to int in c#?

Use Null.NullInteger ex: private int _ReservationID = Null.NullInteger;

How can I import Swift code to Objective-C?

Here's what to do:

  1. Create a new Project in Objective-C

  2. Create a new .swift file  

    • A popup window will appear and ask "Would You like to configure an Objective-C bridging Header".
    • Choose Yes.
  3. Click on your Xcode Project file

  4. Click on Build Settings

  5. Find the Search bar and search for Defines Module.

  6. Change value to Yes.

  7. Search Product Module Name.

  8. Change the value to the name of your project.

  9. In App delegate, add the following : #import "YourProjectName-Swift.h"


Note: Whenever you want to use your Swift file you must be import following line :

#import "YourProjectName-Swift.h"

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

How to convert all text to lowercase in Vim

I assume you want lowercase the text. Solution is pretty simple:

ggVGu

Explanation:

  1. gg - goes to first line of text
  2. V - turns on Visual selection, in line mode
  3. G - goes to end of file (at the moment you have whole text selected)
  4. u - lowercase selected area

SQLite - getting number of rows in a database

In SQL, NULL = NULL is false, you usually have to use IS NULL:

SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words

But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

what is Array.any? for javascript

I believe this to be the cleanest and readable option:

var empty = [];
empty.some(x => x); //returns false

How to get the absolute path to the public_html folder?

Let's asume that show_images.php is in folder images and the site root is public_html, so:

echo dirname(__DIR__); // prints '/home/public_html/'
echo dirname(__FILE__); // prints '/home/public_html/images'

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

How to open Atom editor from command line in OS X?

On macOS you can add it to your ~/.bash_profile

as

alias atom='open -a "Atom"'

and from terminal just call

atom filename.whatever

Add a space (" ") after an element using :after

Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.

The solution:

h2:after {
    content: "\00a0";
}

Android Studio - Failed to notify project evaluation listener error

In my case, I was missing the target SDK platform installed. I remember this error was straightforward and prompted you to install it automatically. Worth checking that as well.

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

pyplot axes labels for subplots

# list loss and acc are your data
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.plot(iteration1, loss)
ax2.plot(iteration2, acc)

ax1.set_title('Training Loss')
ax2.set_title('Training Accuracy')

ax1.set_xlabel('Iteration')
ax1.set_ylabel('Loss')

ax2.set_xlabel('Iteration')
ax2.set_ylabel('Accuracy')

Import data into Google Colaboratory

The simplest way I've made is :

  1. Make repository on github with your dataset
  2. Clone Your repository with ! git clone --recursive [GITHUB LINK REPO]
  3. Find where is your data ( !ls command )
  4. Open file with pandas as You do it in normal jupyter notebook.

Fatal error: Class 'ZipArchive' not found in

Try to write \ZIPARCHIVE instead of ZIPARCHIVE.

How to add a RequiredFieldValidator to DropDownList control?

If you are using a data source, here's another way to do it without code behind.

Note the following key points:

  • The ListItem of Value="0" is on the source page, not added in code
  • The ListItem in the source will be overwritten if you don't include AppendDataBoundItems="true" in the DropDownList
  • InitialValue="0" tells the validator that this is the value that should fire that validator (as pointed out in other answers)

Example:

<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
                  DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType" 
                            InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server" 
                   ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
                   SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>

program cant start because php5.dll is missing

I just now faced this issue while trying to restart XAMPP Apache.

What you can do to solve this is:

  1. download PHP5.dll from http://originaldll.com/file/php5.dll/30704.html
  2. Copy the downloaded php5.dll to C:\xampp\php
  3. Start APACHE and MySql from XAMPP control panel

Hope my solution solves your problem.

Thank You!

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

LINQ Aggregate algorithm explained

In addition to all the great answers here already, I've also used it to walk an item through a series of transformation steps.

If a transformation is implemented as a Func<T,T>, you can add several transformations to a List<Func<T,T>> and use Aggregate to walk an instance of T through each step.

A more concrete example

You want to take a string value, and walk it through a series of text transformations that could be built programatically.

var transformationPipeLine = new List<Func<string, string>>();
transformationPipeLine.Add((input) => input.Trim());
transformationPipeLine.Add((input) => input.Substring(1));
transformationPipeLine.Add((input) => input.Substring(0, input.Length - 1));
transformationPipeLine.Add((input) => input.ToUpper());

var text = "    cat   ";
var output = transformationPipeLine.Aggregate(text, (input, transform)=> transform(input));
Console.WriteLine(output);

This will create a chain of transformations: Remove leading and trailing spaces -> remove first character -> remove last character -> convert to upper-case. Steps in this chain can be added, removed, or reordered as needed, to create whatever kind of transformation pipeline is required.

The end result of this specific pipeline, is that " cat " becomes "A".


This can become very powerful once you realize that T can be anything. This could be used for image transformations, like filters, using BitMap as an example;

Java character array initializer

you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.

or even simpler just use String.charAt() in the loop to populate array like below:

String ini="Hi there";
  char[] array=new  char[ini.length()];

  for(int count=0;count<array.length;count++){
         array[count] = ini.charAt(count);
  System.out.print(" "+array[count]);
  }

or one liner would be

  String ini="Hi there";
  char[] array=ini.toCharArray();

Inline <style> tags vs. inline css properties

It depends.

The main point is to avoid repeated code.

If the same code need to be re-used 2 times or more, and should be in sync when change, use external style sheet.

If you only use it once, I think inline is ok.

Java POI : How to read Excel cell value and not the formula computing it?

There is an alternative command where you can get the raw value of a cell where formula is put on. It's returns type is String. Use:

cell.getRawValue();

ImportError: numpy.core.multiarray failed to import

I had the same error after installing python and opencv in my D: drive (C: runs on a SSD). The problem seemed to be that my execution path was inside the numpy folder. You can check if that's the issue with this code :

import numpy
numpy.version.version

In case it retrieves any error related to the execution path, execute your original code from elsewhere. That solved the could not load numpy.core.multiarray error for me

SQL Server, How to set auto increment after creating a table without data loss?

Changing the IDENTITY property is really a metadata only change. But to update the metadata directly requires starting the instance in single user mode and messing around with some columns in sys.syscolpars and is undocumented/unsupported and not something I would recommend or will give any additional details about.

For people coming across this answer on SQL Server 2012+ by far the easiest way of achieving this result of an auto incrementing column would be to create a SEQUENCE object and set the next value for seq as the column default.

Alternatively, or for previous versions (from 2005 onwards), the workaround posted on this connect item shows a completely supported way of doing this without any need for size of data operations using ALTER TABLE...SWITCH. Also blogged about on MSDN here. Though the code to achieve this is not very simple and there are restrictions - such as the table being changed can't be the target of a foreign key constraint.

Example code.

Set up test table with no identity column.

CREATE TABLE dbo.tblFoo 
(
bar INT PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)


INSERT INTO dbo.tblFoo (bar)
SELECT TOP (10000) ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM master..spt_values v1, master..spt_values v2

Alter it to have an identity column (more or less instant).

BEGIN TRY;
    BEGIN TRANSACTION;

    /*Using DBCC CHECKIDENT('dbo.tblFoo') is slow so use dynamic SQL to
      set the correct seed in the table definition instead*/
    DECLARE @TableScript nvarchar(max)
    SELECT @TableScript = 
    '
    CREATE TABLE dbo.Destination(
        bar INT IDENTITY(' + 
                     CAST(ISNULL(MAX(bar),0)+1 AS VARCHAR) + ',1)  PRIMARY KEY,
        filler CHAR(8000),
        filler2 CHAR(49)
        )

        ALTER TABLE dbo.tblFoo SWITCH TO dbo.Destination;
    '       
    FROM dbo.tblFoo
    WITH (TABLOCKX,HOLDLOCK)

    EXEC(@TableScript)


    DROP TABLE dbo.tblFoo;

    EXECUTE sp_rename N'dbo.Destination', N'tblFoo', 'OBJECT';


    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    PRINT ERROR_MESSAGE();
END CATCH;

Test the result.

INSERT INTO dbo.tblFoo (filler,filler2) 
OUTPUT inserted.*
VALUES ('foo','bar')

Gives

bar         filler    filler2
----------- --------- ---------
10001       foo       bar      

Clean up

DROP TABLE dbo.tblFoo

How to write URLs in Latex?

You can use \url

\usepackage{hyperref}
\url{http://stackoverflow.com/}

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

LinearLayout not expanding inside a ScrollView

In my case i haven't given the

orientation of LinearLayout(ScrollView's Child)

So by default it takes horizontal, but scrollview scrols vertically, so please check if 'android:orientation="vertical"' is set to your ScrollView's Child(In the case of LinearLayout).

This was my case hopes it helps somebody

.

Why do we use $rootScope.$broadcast in AngularJS?

$rootScope basically functions as an event listener and dispatcher.

To answer the question of how it is used, it used in conjunction with rootScope.$on;

$rootScope.$broadcast("hi");

$rootScope.$on("hi", function(){
    //do something
});

However, it is a bad practice to use $rootScope as your own app's general event service, since you will quickly end up in a situation where every app depends on $rootScope, and you do not know what components are listening to what events.

The best practice is to create a service for each custom event you want to listen to or broadcast.

.service("hiEventService",function($rootScope) {
    this.broadcast = function() {$rootScope.$broadcast("hi")}
    this.listen = function(callback) {$rootScope.$on("hi",callback)}
})

Xcode warning: "Multiple build commands for output file"

This is not an Xcode bug, though the warning message is not helpful enough to describe the real cause.

This error message occurs when you have several files in your project that have the same name. You just have to delete or rename the files with duplicate names and the problem is solved.

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

How to get the last day of the month?

Using dateutil.relativedelta you would get last date of month like this:

from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)

The idea is to get the first day of the month and use relativedelta to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.

Regex: match word that ends with "Id"

This may do the trick:

\b\p{L}*Id\b

Where \p{L} matches any (Unicode) letter and \b matches a word boundary.

How to correctly save instance state of Fragments in back stack?

On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

Here is an example:

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

    if (savedInstanceState == null) {
        myFragment = MyFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
                .commit();
    } else {
        myFragment = (MyFragment) getSupportFragmentManager()
                .findFragmentByTag(MY_FRAGMENT_TAG);
    }
...
}

Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

Getting the application's directory from a WPF application

String exePath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
 string dir = Path.GetDirectoryName(exePath);

Try this!

How to navigate back to the last cursor position in Visual Studio Code?

Mac OS (MacBook Pro):

Back: CTRL(control) + - (Hyphen)

Back Forward: CTRL + Shift + - (Hyphen)

Listing contents of a bucket with boto3

This is similar to an 'ls' but it does not take into account the prefix folder convention and will list the objects in the bucket. It's left up to the reader to filter out prefixes which are part of the Key name.

In Python 2:

from boto.s3.connection import S3Connection

conn = S3Connection() # assumes boto.cfg setup
bucket = conn.get_bucket('bucket_name')
for obj in bucket.get_all_keys():
    print(obj.key)

In Python 3:

from boto3 import client

conn = client('s3')  # again assumes boto.cfg setup, assume AWS S3
for key in conn.list_objects(Bucket='bucket_name')['Contents']:
    print(key['Key'])

How to restrict UITextField to take only numbers in Swift?

func isValidNumber(str:String) -> Bool{
    if str.isEmpty {
        return false
    }
    let newChar = NSCharacterSet(charactersInString: str)
    let boolValid = NSCharacterSet.decimalDigitCharacterSet().isSupersetOfSet(newChar)
    if boolValid{
        return true
    }else{
        let lst = str.componentsSeparatedByString(".")
        let newStr = lst.joinWithSeparator("")
        let currentChar = NSCharacterSet(charactersInString: newStr)
        if lst.count == 2 && !lst.contains("") && NSCharacterSet.decimalDigitCharacterSet().isSupersetOfSet(currentChar){
            return true
        }
        return false
    }
}

Put this function in your "Submit" or "Save" method if there is one.

Convert Difference between 2 times into Milliseconds?

Many of the above mentioned solutions might suite different people.
I would like to suggest a slightly modified code than most accepted solution by "MusiGenesis".

DateTime firstTime = DateTime.Parse( TextBox1.Text );
DateTime secondTime = DateTime.Parse( TextBox2.Text );
double milDiff = secondTime.Subtract(firstTime).TotalMilliseconds;

Considerations:
- earlierTime.Subtract(laterTime) you will get a negative value.
- use int milDiff = (int)DateTime.Now.Subtract(StartTime).TotalMilliseconds; if you need integer value instead of double
- Same code can be used to get difference between two Date values and you may get .TotalDays or .TotalHours insteaf of .TotalMilliseconds

Is there a way to create interfaces in ES6 / Node 4?

This is my solution for the problem. You can 'implement' multiple interfaces by overriding one Interface with another.

class MyInterface {
    // Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance
    /**
     * Gives the sum of the given Numbers
     * @param {Number} a The first Number
     * @param {Number} b The second Number
     * @return {Number} The sum of the Numbers
     */
    sum(a, b) { this._WARNING('sum(a, b)'); }


    // delcare a warning generator to notice if a method of the interface is not overridden
    // Needs the function name of the Interface method or any String that gives you a hint ;)
    _WARNING(fName='unknown method') {
        console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
    }
}

class MultipleInterfaces extends MyInterface {
    // this is used for "implement" multiple Interfaces at once
    /**
     * Gives the square of the given Number
     * @param {Number} a The Number
     * @return {Number} The square of the Numbers
     */
    square(a) { this._WARNING('square(a)'); }
}

class MyCorrectUsedClass extends MyInterface {
    // You can easy use the JS doc declared in the interface
    /** @inheritdoc */
    sum(a, b) {
        return a+b;
    }
}
class MyIncorrectUsedClass extends MyInterface {
    // not overriding the method sum(a, b)
}

class MyMultipleInterfacesClass extends MultipleInterfaces {
    // nothing overriden to show, that it still works
}


let working = new MyCorrectUsedClass();

let notWorking = new MyIncorrectUsedClass();

let multipleInterfacesInstance = new MyMultipleInterfacesClass();

// TEST IT

console.log('working.sum(1, 2) =', working.sum(1, 2));
// output: 'working.sum(1, 2) = 3'

console.log('notWorking.sum(1, 2) =', notWorking.sum(1, 2));
// output: 'notWorking.sum(1, 2) = undefined'
// but also sends a warn to the console with 'WARNING! Function "sum(a, b)" is not overridden in MyIncorrectUsedClass'

console.log('multipleInterfacesInstance.sum(1, 2) =', multipleInterfacesInstance.sum(1, 2));
// output: 'multipleInterfacesInstance.sum(1, 2) = undefined'
// console warn: 'WARNING! Function "sum(a, b)" is not overridden in MyMultipleInterfacesClass'

console.log('multipleInterfacesInstance.square(2) =', multipleInterfacesInstance.square(2));
// output: 'multipleInterfacesInstance.square(2) = undefined'
// console warn: 'WARNING! Function "square(a)" is not overridden in MyMultipleInterfacesClass'

EDIT:

I improved the code so you now can simply use implement(baseClass, interface1, interface2, ...) in the extend.

/**
* Implements any number of interfaces to a given class.
* @param cls The class you want to use
* @param interfaces Any amount of interfaces separated by comma
* @return The class cls exteded with all methods of all implemented interfaces
*/
function implement(cls, ...interfaces) {
    let clsPrototype = Object.getPrototypeOf(cls).prototype;
    for (let i = 0; i < interfaces.length; i++) {
        let proto = interfaces[i].prototype;
        for (let methodName of Object.getOwnPropertyNames(proto)) {
            if (methodName!== 'constructor')
                if (typeof proto[methodName] === 'function')
                    if (!clsPrototype[methodName]) {
                        console.warn('WARNING! "'+methodName+'" of Interface "'+interfaces[i].name+'" is not declared in class "'+cls.name+'"');
                        clsPrototype[methodName] = proto[methodName];
                    }
        }
    }
    return cls;
}

// Basic Interface to warn, whenever an not overridden method is used
class MyBaseInterface {
    // declare a warning generator to notice if a method of the interface is not overridden
    // Needs the function name of the Interface method or any String that gives you a hint ;)
    _WARNING(fName='unknown method') {
        console.warn('WARNING! Function "'+fName+'" is not overridden in '+this.constructor.name);
    }
}


// create a custom class
/* This is the simplest example but you could also use
*
*   class MyCustomClass1 extends implement(MyBaseInterface) {
*       foo() {return 66;}
*   }
*
*/
class MyCustomClass1 extends MyBaseInterface {
    foo() {return 66;}
}

// create a custom interface
class MyCustomInterface1 {
     // Declare your JS doc in the Interface to make it acceable while writing the Class and for later inheritance

    /**
     * Gives the sum of the given Numbers
     * @param {Number} a The first Number
     * @param {Number} b The second Number
     * @return {Number} The sum of the Numbers
     */
    sum(a, b) { this._WARNING('sum(a, b)'); }
}

// and another custom interface
class MyCustomInterface2 {
    /**
     * Gives the square of the given Number
     * @param {Number} a The Number
     * @return {Number} The square of the Numbers
     */
    square(a) { this._WARNING('square(a)'); }
}

// Extend your custom class even more and implement the custom interfaces
class AllInterfacesImplemented extends implement(MyCustomClass1, MyCustomInterface1, MyCustomInterface2) {
    /**
    * @inheritdoc
    */
    sum(a, b) { return a+b; }

    /**
    * Multiplies two Numbers
    * @param {Number} a The first Number
    * @param {Number} b The second Number
    * @return {Number}
    */
    multiply(a, b) {return a*b;}
}


// TEST IT

let x = new AllInterfacesImplemented();

console.log("x.foo() =", x.foo());
//output: 'x.foo() = 66'

console.log("x.square(2) =", x.square(2));
// output: 'x.square(2) = undefined
// console warn: 'WARNING! Function "square(a)" is not overridden in AllInterfacesImplemented'

console.log("x.sum(1, 2) =", x.sum(1, 2));
// output: 'x.sum(1, 2) = 3'

console.log("x.multiply(4, 5) =", x.multiply(4, 5));
// output: 'x.multiply(4, 5) = 20'

Environment variable to control java.io.tmpdir?

we can change the default tomcat file upload location, as

we have to set the environment variable like : CATALINA_TEMPDIR = YOUR FILE UPLOAD LOCATION. this location will change the path here: java -Djava.io.tmpdir=/path/to/tmpdir

How to increase the vertical split window size in Vim

I have these mapped in my .gvimrc to let me hit command-[arrow] to move the height and width of my current window around:

" resize current buffer by +/- 5 
nnoremap <D-left> :vertical resize -5<cr>
nnoremap <D-down> :resize +5<cr>
nnoremap <D-up> :resize -5<cr>
nnoremap <D-right> :vertical resize +5<cr>

For MacVim, you have to put them in your .gvimrc (and not your .vimrc) as they'll otherwise get overwritten by the system .gvimrc

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Why use Optional.of over Optional.ofNullable?

In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElseThrow(NullPointerException::new);
                   // .orElseThrow(CustomException::new);

How to compare two tables column by column in oracle

It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.

The query will return all rows that

  • Exists in table1 but not in table2
  • Exists in table2 but not in table1
  • Exists in both tables, but have at least one column with a different value

(common identical rows will be excluded).

"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.

select pk
      ,decode(a.rowid, null, null, 'A') as a
      ,decode(b.rowid, null, null, 'B') as b
      ,a.col1, b.col1
      ,a.col2, b.col2
      ,a.col3, b.col3
      ,...
  from table1 a 
  full outer 
  join table2 b using(pk)
 where decode(a.col1, b.col1, 1, 0) = 0
    or decode(a.col2, b.col2, 1, 0) = 0
    or decode(a.col3, b.col3, 1, 0) = 0
    or ...;

Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.

with a as(
   select 0    as col1 from dual union all
   select 1    as col1 from dual union all
   select null as col1 from dual
)
,b as(
   select 1    as col1 from dual union all
   select 2    as col1 from dual union all
   select null as col1 from dual
)   
select a.col1
      ,b.col1
      ,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
      ,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2       
  from a,b
 order 
    by a.col1
      ,b.col1;    




col1   col1_1   approach_1  approach_2
====   ======   ==========  ==========
  0        1    Different   Different  
  0        2    Different   Different  
  0      null   Different   Same         <--- 
  1        1    Same        Same       
  1        2    Different   Different  
  1      null   Different   Same         <---
null       1    Different   Same         <---
null       2    Different   Same         <---
null     null   Same        Same       

Find integer index of rows with NaN in pandas dataframe

I was looking for all indexes of rows with NaN values.
My working solution:

def get_nan_indexes(data_frame):
    indexes = []
    print(data_frame)
    for column in data_frame:
        index = data_frame[column].index[data_frame[column].apply(np.isnan)]
        if len(index):
            indexes.append(index[0])
    df_index = data_frame.index.values.tolist()
    return [df_index.index(i) for i in set(indexes)]

Reference alias (calculated in SELECT) in WHERE clause

You can do this using cross apply

SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;

Load arrayList data into JTable

"The problem is that i cant find a way to set a fixed number of rows"

You don't need to set the number of rows. Use a TableModel. A DefaultTableModel in particular.

String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};

DefaultTableModel tableModel = new DefaultTableModel(col, 0);
                                            // The 0 argument is number rows.

JTable table = new JTable(tableModel);

Then you can add rows to the tableModel with an Object[]

Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};

tableModel.addRow(objs);

You can loop to add your Object[] arrays.

Note: JTable does not currently allow instantiation with the input data as an ArrayList. It must be a Vector or an array.

See JTable and DefaultTableModel. Also, How to Use JTable tutorial

"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."

You can do something like this to add the data

ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();

originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));

for (int i = 0; i < originalLeagueList.size(); i++){
   int position = originalLeagueList.get(i).getPosition();
   String name = originalLeagueList.get(i).getName();
   int points = originalLeagueList.get(i).getPoinst();
   int wins = originalLeagueList.get(i).getWins();
   int defeats = originalLeagueList.get(i).getDefeats();
   int draws = originalLeagueList.get(i).getDraws();
   int totalMatches = originalLeagueList.get(i).getTotalMathces();
   int goalF = originalLeagueList.get(i).getGoalF();
   int goalA = originalLeagueList.get(i).getGoalA();
   in ttgoalD = originalLeagueList.get(i).getTtgoalD();

   Object[] data = {position, name, points, wins, defeats, draws, 
                               totalMatches, goalF, goalA, ttgoalD};

   tableModel.add(data);

}

HTML5 canvas ctx.fillText won't do line breaks?

Canvas element doesn't support such characters as newline '\n', tab '\t' or < br /> tag.

Try it:

var newrow = mheight + 30;
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "bold 24px 'Verdana'";
ctx.textAlign = "center";
ctx.fillText("Game Over", mwidth, mheight); //first line
ctx.fillText("play again", mwidth, newrow); //second line 

or perhaps multiple lines:

var textArray = new Array('line2', 'line3', 'line4', 'line5');
var rows = 98;
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "bold 24px 'Verdana'";
ctx.textAlign = "center";
ctx.fillText("Game Over", mwidth, mheight); //first line

for(var i=0; i < textArray.length; ++i) {
rows += 30;
ctx.fillText(textArray[i], mwidth, rows); 
}  

How to find the users list in oracle 11g db?

I tried this query and it works for me.

SELECT username FROM dba_users 
ORDER BY username;

If you want to get the list of all that users which are created by end-user, then you can try this:

SELECT username FROM dba_users where Default_TableSpace not in ('SYSAUX', 'SYSTEM', 'USERS')
ORDER BY username;

Difference between == and ===

>>> will always put a 0 in the left most bit, while >> will put a 1 or a 0 depending on what the sign of it is.

How to output JavaScript with PHP

An easier way is to use the heredoc syntax of PHP. An example:

<?php

echo <<<EOF
<script type="text/javascript">
    document.write("Hello World!");
</script>
EOF;

?>

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How can I get the status code from an http error in Axios?

You can put the error into an object and log the object, like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

Customizing Bootstrap CSS template

you can start with this tool, https://themestr.app/theme , seeing how it overwrites the scss variables, you would get an idea what variable impacts what. its the simplest way I think.

example scss genearation:

@import url(https://fonts.googleapis.com/css?family=Montserrat:200,300,400,700);
$font-family-base:Montserrat;
@import url(https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,700);
$headings-font-family:Open Sans;

$enable-grid-classes:false;
$primary:#222222;
$secondary:#666666;
$success:#333333;
$danger:#434343;
$info:#515151;
$warning:#5f5f5f;
$light:#eceeec;
$dark:#111111;
@import "bootstrap";

How to cin Space in c++?

Use cin.get() to read the next character.

However, for this problem, it is very inefficient to read a character at a time. Use the istream::read() instead.

int main()
{
   char a[10];
   cin.read(a, sizeof(a));
   for(int i = 0; i < 10; i++)
   {
       if(a[i] == ' ')
          cout<<"It is a space!!!"<<<endl;
   }
   return 0;
}

And use == to check equality, not =.

Pause Console in C++ program

This works for me.

void pause()
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    std::string dummy;
    std::cout << "Press any key to continue . . .";
    std::getline(std::cin, dummy);
}

Regex matching beginning AND end strings

Well, the simple regex is this:

/^dbo\..*_fn$/

It would be better, however, to use the string manipulation functionality of whatever programming language you're using to slice off the first four and the last three characters of the string and check whether they're what you want.

Looking to understand the iOS UIViewController lifecycle

As of iOS 6 and onward. The new diagram is as follows:

enter image description here

Insert a row to pandas dataframe

I put together a short function that allows for a little more flexibility when inserting a row:

def insert_row(idx, df, df_insert):
    dfA = df.iloc[:idx, ]
    dfB = df.iloc[idx:, ]

    df = dfA.append(df_insert).append(dfB).reset_index(drop = True)

    return df

which could be further shortened to:

def insert_row(idx, df, df_insert):
    return df.iloc[:idx, ].append(df_insert).append(df.iloc[idx:, ]).reset_index(drop = True)

Then you could use something like:

df = insert_row(2, df, df_new)

where 2 is the index position in df where you want to insert df_new.

Python spacing and aligning strings

Try %*s and %-*s and prefix each string with the column width:

>>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10           Revision: 1
>>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
District: Tower                 Date: May 16, 2012

Best way to simulate "group by" from bash?

I'd have done it like this:

perl -e 'while (<>) {chop; $h{$_}++;} for $k (keys %h) {print "$k $h{$k}\n";}' ip_addresses

but uniq might work for you.

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

Getting data from Yahoo Finance

Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo

Update built-in vim on Mac OS X

If I understand things correctly, you want to install over your existing Vim, for better or worse :-) This is a bad idea and it is not the "clean" way to do it. Why? Well, OS X expects that nothing will ever change in /usr/bin unbeknownst to it, so any time you overwrite stuff in there you risk breaking some intricate interdependency. And, Let's say you do break something -- there's no way to "undo" that damage. You will be sad and alone. You may have to reinstall OS X.

Part 1: A better idea

The "clean" way is to install in a separate place, and make the new binary higher priority in the $PATH. Here is how I recommend doing that:

$ # Create the directories you need
$ sudo mkdir -p /opt/local/bin
$ # Download, compile, and install the latest Vim
$ cd ~
$ hg clone https://bitbucket.org/vim-mirror/vim or git clone https://github.com/vim/vim.git
$ 
$ cd vim
$ ./configure --prefix=/opt/local
$ make
$ sudo make install
$ # Add the binary to your path, ahead of /usr/bin
$ echo 'PATH=/opt/local/bin:$PATH' >> ~/.bash_profile
$ # Reload bash_profile so the changes take effect in this window
$ source ~/.bash_profile

Voila! Now when we use vim we will be using the new one. But, to get back to our old configuration in the event of huge f*ckups, we can just delete the /opt directory.

$ which vim
/opt/local/bin/vim
$ vim --version | head -n 2
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 27 2011 20:55:46)
MacOS X (unix) version

See how clean this is.

I recommend not to install in /usr/local/bin when you want to override binaries in /usr/bin, because by default OS X puts /usr/bin higher priority in $PATH than /usr/local/bin, and screwing with that opens its own can of worms.... So, that's what you SHOULD do.

Part 2: The "correct" answer (but a bad idea)

Assuming you're set on doing that, you are definitely on track. To install on top of your current installation, you need to set the "prefix" directory. That's done like this:

hg clone https://bitbucket.org/vim-mirror/vim or git clone https://github.com/vim/vim.git
cd vim
./configure --prefix=/usr
make
sudo make install

You can pass "configure" a few other options too, if you want. Do "./configure --help" to see them. I hope you've got a backup before you do it, though, in case something goes wrong....

How to move an element down a litte bit in html

<style>
.row-2 UL LI A
{
  margin-top: 10px;  /* or whatever amount you need it to move down */
}
</style>

How to print a float with 2 decimal places in Java?

small simple program for demonstration:

import java.io.*;
import java.util.Scanner;

public class twovalues {

    public static void main(String args[]) {

        float a,b;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Values For Calculation");

        a=sc.nextFloat();
        b=sc.nextFloat();

        float c=a/b;
        System.out.printf("%.2f",c);
    }
}

Initialize a vector array of strings

If you are using cpp11 (enable with the -std=c++0x flag if needed), then you can simply initialize the vector like this:

// static std::vector<std::string> v;
v = {"haha", "hehe"};

How can I pretty-print JSON using node.js?

I know this is old question. But maybe this can help you

JSON string

var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';

Pretty Print JSON

JSON.stringify(JSON.parse(jsonStr), null, 2);

Minify JSON

JSON.stringify(JSON.parse(jsonStr));

Save PHP variables to a text file

(Sorry I can't comment just yet, otherwise I would)

To add to Christian's answer you might consider using json_encode and json_decode instead of serialize and unserialize to keep you safe. See a warning from the PHP man page:

Warning

Do not pass untrusted user input to unserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

So your final solution might have the following:

$file = '/tmp/file';
$content = json_encode($my_variable);
file_put_contents($file, $content);
$content = json_decode(file_get_contents($file), TRUE);

Plotting categorical data with pandas and matplotlib

To plot multiple categorical features as bar charts on the same plot, I would suggest:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        "colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
        "direction": ["up", "up", "down", "left", "right", "down", "down"],
    }
)

categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
    df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
fig.show()

enter image description here

Cross browser JavaScript (not jQuery...) scroll to top animation

PURE JAVASCRIPT SCROLLER CLASS

This is an old question but I thought I could answer with some fancy stuff and some more options to play with if you want to have a bit more control over the animation.

  • Cross-browser
  • Copy/Paste ready solution (You only need CSS and JS)
  • 3 animate modes: ["normal"|"linear"|false]
  • Customize your animation with available settings - make it snappy or fluent
  • Double click to skip animation
  • Every next single click adds initial speed
  • Stop scroll animation by draging down the scroll bar
  • Stop scroll animation by mouse wheel down
  • Animated button fade-in-out on scroll
  • Here it is a pure JS Class to take care of the scrolling for you:

    SEE DEMO AT CODEPEN OR GO TO THE BOTTOM AND RUN THE SINPET

    // ------------------- USE EXAMPLE ---------------------
    // *Set options
    var options = {
      'showButtonAfter': 200, // show button after scroling down this amount of px
      'animate': "linear", // [false|normal|linear] - for false no aditional settings are needed
    
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms
        'steps': 20, // the more steps per loop the slower animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
      'linear': { // applys only if [animate: linear] - set scroll px|ms
        'px': 30, // the more px the quicker your animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
    };
    
    
    // *Create new Scroller and run it.
    var scroll = new Scroller(options);
    scroll.init();
    

    FULL CLASS SCRIPT + USE EXAMPLE:

    _x000D_
    _x000D_
    // PURE JAVASCRIPT (OOP)_x000D_
    _x000D_
    function Scroller(options) {_x000D_
      this.options = options;_x000D_
      this.button = null;_x000D_
      this.stop = false;_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.constructor = Scroller;_x000D_
    _x000D_
    Scroller.prototype.createButton = function() {_x000D_
    _x000D_
      this.button = document.createElement('button');_x000D_
      this.button.classList.add('scroll-button');_x000D_
      this.button.classList.add('scroll-button--hidden');_x000D_
      this.button.textContent = "^";_x000D_
      document.body.appendChild(this.button);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.init = function() {_x000D_
      this.createButton();_x000D_
      this.checkPosition();_x000D_
      this.click();_x000D_
      this.stopListener();_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.scroll = function() {_x000D_
      if (this.options.animate == false || this.options.animate == "false") {_x000D_
        this.scrollNoAnimate();_x000D_
        return;_x000D_
      }_x000D_
      if (this.options.animate == "normal") {_x000D_
        this.scrollAnimate();_x000D_
        return;_x000D_
      }_x000D_
      if (this.options.animate == "linear") {_x000D_
        this.scrollAnimateLinear();_x000D_
        return;_x000D_
      }_x000D_
    }_x000D_
    Scroller.prototype.scrollNoAnimate = function() {_x000D_
      document.body.scrollTop = 0;_x000D_
      document.documentElement.scrollTop = 0;_x000D_
    }_x000D_
    Scroller.prototype.scrollAnimate = function() {_x000D_
      if (this.scrollTop() > 0 && this.stop == false) {_x000D_
        setTimeout(function() {_x000D_
          this.scrollAnimate();_x000D_
          window.scrollBy(0, (-Math.abs(this.scrollTop()) / this.options.normal['steps']));_x000D_
        }.bind(this), (this.options.normal['ms']));_x000D_
      }_x000D_
    }_x000D_
    Scroller.prototype.scrollAnimateLinear = function() {_x000D_
      if (this.scrollTop() > 0 && this.stop == false) {_x000D_
        setTimeout(function() {_x000D_
          this.scrollAnimateLinear();_x000D_
          window.scrollBy(0, -Math.abs(this.options.linear['px']));_x000D_
        }.bind(this), this.options.linear['ms']);_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.click = function() {_x000D_
    _x000D_
      this.button.addEventListener("click", function(e) {_x000D_
        e.stopPropagation();_x000D_
        this.scroll();_x000D_
      }.bind(this), false);_x000D_
    _x000D_
      this.button.addEventListener("dblclick", function(e) {_x000D_
        e.stopPropagation();_x000D_
        this.scrollNoAnimate();_x000D_
      }.bind(this), false);_x000D_
    _x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.hide = function() {_x000D_
      this.button.classList.add("scroll-button--hidden");_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.show = function() {_x000D_
      this.button.classList.remove("scroll-button--hidden");_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.checkPosition = function() {_x000D_
      window.addEventListener("scroll", function(e) {_x000D_
        if (this.scrollTop() > this.options.showButtonAfter) {_x000D_
          this.show();_x000D_
        } else {_x000D_
          this.hide();_x000D_
        }_x000D_
      }.bind(this), false);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.stopListener = function() {_x000D_
    _x000D_
      // stop animation on slider drag_x000D_
      var position = this.scrollTop();_x000D_
      window.addEventListener("scroll", function(e) {_x000D_
        if (this.scrollTop() > position) {_x000D_
          this.stopTimeout(200);_x000D_
        } else {_x000D_
          //..._x000D_
        }_x000D_
        position = this.scrollTop();_x000D_
      }.bind(this, position), false);_x000D_
    _x000D_
      // stop animation on wheel scroll down_x000D_
      window.addEventListener("wheel", function(e) {_x000D_
        if (e.deltaY > 0) this.stopTimeout(200);_x000D_
      }.bind(this), false);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.stopTimeout = function(ms) {_x000D_
      this.stop = true;_x000D_
      // console.log(this.stop); //_x000D_
      setTimeout(function() {_x000D_
        this.stop = false;_x000D_
        console.log(this.stop); //_x000D_
      }.bind(this), ms);_x000D_
    }_x000D_
    _x000D_
    Scroller.prototype.scrollTop = function() {_x000D_
      var curentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;_x000D_
      return curentScrollTop;_x000D_
    }_x000D_
    _x000D_
    _x000D_
    _x000D_
    // ------------------- USE EXAMPLE ---------------------_x000D_
    // *Set options_x000D_
    var options = {_x000D_
      'showButtonAfter': 200, // show button after scroling down this amount of px_x000D_
      'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed_x000D_
    _x000D_
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms_x000D_
        'steps': 20, // the more steps per loop the slower animation gets_x000D_
        'ms': 10 // the less ms the quicker your animation gets_x000D_
      },_x000D_
      'linear': { // applys only if [animate: linear] - set scroll px|ms_x000D_
        'px': 30, // the more px the quicker your animation gets_x000D_
        'ms': 10 // the less ms the quicker your animation gets_x000D_
      },_x000D_
    };_x000D_
    // *Create new Scroller and run it._x000D_
    var scroll = new Scroller(options);_x000D_
    scroll.init();
    _x000D_
    /* CSS */_x000D_
    _x000D_
    @import url(https://fonts.googleapis.com/css?family=Open+Sans);_x000D_
     body {_x000D_
      font-family: 'Open Sans', sans-serif;_x000D_
      font-size: 1.2rem;_x000D_
      line-height: 2rem;_x000D_
      height: 100%;_x000D_
      position: relative;_x000D_
      padding: 0 25%;_x000D_
    }_x000D_
    .scroll-button {_x000D_
      font-size: 1.2rem;_x000D_
      line-height: 2rem;_x000D_
      padding: 10px;_x000D_
      width: 50px;_x000D_
      height: 50px;_x000D_
      background: black;_x000D_
      color: white;_x000D_
      border-radius: 50%;_x000D_
      position: fixed;_x000D_
      right: 20px;_x000D_
      bottom: 20px;_x000D_
      visibility: visible;_x000D_
      filter: alpha(opacity=50);_x000D_
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=50);_x000D_
      opacity: 0.5;_x000D_
      cursor: pointer;_x000D_
      transition: all 1.2s;_x000D_
      -webkit-transition: all 1.2s;_x000D_
      -moz-transition: all 1.2s;_x000D_
      -ms-transition: all 1.2s;_x000D_
      -o-transition: all 1.2s;_x000D_
    }_x000D_
    .scroll-button:hover {_x000D_
      filter: alpha(opacity=100);_x000D_
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);_x000D_
      opacity: 1;_x000D_
    }_x000D_
    .scroll-button--hidden {_x000D_
      filter: alpha(opacity=0);_x000D_
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);_x000D_
      opacity: 0;_x000D_
      visibility: hidden;_x000D_
    }
    _x000D_
    <!-- HTML -->_x000D_
    _x000D_
    <h1>Scroll down by 200px for button to appear</h1>_x000D_
    <ul>_x000D_
      <li>Cross-browser</li>_x000D_
      <li>Copy/Paste solution</li>_x000D_
      <li>3 animate modes: <b>["normal"|"linear"|false]</b></li>_x000D_
      <li>Customize your aniamtion with aveilable settings - make it snapy or fluent</li>_x000D_
      <li>Double click to skip animation</li>_x000D_
      <li>Every next single click adds initial speed</li>_x000D_
      <li>Stop scroll animation by draging down the scroll bar</li>_x000D_
      <li>Stop scroll animation by mouse wheel down</li>_x000D_
      <li>Animated button fade-in-out on scroll</li>_x000D_
    </ul>_x000D_
    _x000D_
    <br />_x000D_
    <br />_x000D_
    <pre>_x000D_
    // ------------------- USE EXAMPLE ---------------------_x000D_
    // *Set options_x000D_
    var options = {_x000D_
      'showButtonAfter': 200, // show button after scroling down this amount of px_x000D_
      'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed_x000D_
      _x000D_
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms_x000D_
        'steps': 20, // the more steps the slower animation gets_x000D_
        'ms': 20 // the less ms the quicker your animation gets_x000D_
      }, _x000D_
      'linear': { // applys only if [animate: linear] - set scroll px|ms_x000D_
        'px': 55, // the more px the quicker your animation gets_x000D_
        'ms': 10 // the less ms the quicker your animation gets_x000D_
      }, _x000D_
    };_x000D_
    _x000D_
    // *Create new Scroller and run it._x000D_
    var scroll = new Scroller(options);_x000D_
    scroll.init();_x000D_
    </pre>_x000D_
    <br />_x000D_
    <br />_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae illo nobis quo autem molestias voluptatum quam, amet ipsum debitis, iure animi illum soluta eaque qui perspiciatis harum, sequi nesciunt.</span><span>Quisquam nesciunt aspernatur a possimus pariatur enim architecto. Hic aperiam sit repellat doloremque vel est soluta et assumenda dolore, sint sapiente porro, quam impedit. Sint praesentium quas excepturi, voluptatem dicta!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate, porro nisi molestias minima corrupti tempore, dolorum fugiat ipsam dicta doloremque accusamus atque consequatur iusto natus, mollitia distinctio odit dolor tempora.</span><span>Perferendis a in laudantium accusantium, dolorum eius placeat velit porro similique, eum cumque veniam neque aspernatur architecto suscipit rem laboriosam voluptates laborum? Voluptates tempora necessitatibus animi nostrum quod, maxime odio.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil accusantium, itaque corporis repellat pariatur soluta officia perspiciatis in reprehenderit facere, incidunt saepe excepturi. Inventore atque ex illo, ipsam at deserunt.</span><span>Laborum inventore officia, perspiciatis cumque magni consequatur iste accusantium soluta, nesciunt blanditiis voluptatibus adipisci laudantium mollitia minus quia necessitatibus voluptates. Minima unde quos impedit necessitatibus aspernatur minus maiores ipsa eligendi!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate nesciunt, explicabo similique, quo maxime modi, aliquid, voluptatibus repellendus dolorum placeat mollitia ea dicta quia laboriosam alias dignissimos ipsam tenetur. Nulla.</span><span>Vel maiores necessitatibus odio voluptate debitis, error in accusamus nulla, eum, nemo et ea commodi. Autem numquam at, consequatur temporibus. Mollitia placeat nobis blanditiis impedit distinctio! Ad, incidunt fugiat sed.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam voluptatum, odio quam omnis iste laudantium, itaque architecto, eos ullam debitis delectus sapiente nemo autem reprehenderit. Dolorem quidem facere ipsam! Nisi.</span><span>Vitae quaerat modi voluptatibus ratione numquam? Sapiente aliquid officia pariatur quibusdam aliquam id expedita non recusandae, cumque deserunt asperiores. Corrupti et doloribus aspernatur ipsum asperiores, ipsa unde corporis commodi reiciendis?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima adipisci minus iste, nesciunt itaque quisquam quidem voluptatum assumenda rerum aliquid, excepturi voluptatem tempora. Possimus ratione alias a error vel, rem.</span><span>Officia esse error accusantium veritatis ad, et sit animi? Recusandae mollitia odit tenetur ad cumque maiores eligendi blanditiis nobis hic tempora obcaecati consequatur commodi totam, debitis, veniam, ducimus molestias ut.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati quibusdam, tempora cupiditate quaerat tempore ullam delectus voluptates optio eum placeat provident consequatur iure reprehenderit vero quae sapiente architecto earum nemo.</span><span>Quis molestias sint fuga doloribus, necessitatibus nulla. Esse ipsa, itaque asperiores. Tempora a sequi nobis cumque incidunt aspernatur, pariatur rem voluptatibus. Atque veniam magnam, ea laudantium ipsum reprehenderit sapiente repellendus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, pariatur at explicabo aliquid repudiandae vero eum quasi totam voluptates iusto unde ad repellendus ipsam et voluptatem hic adipisci! Vero, nobis!</span><span>Consequatur eligendi quo quas omnis architecto dolorum aperiam doloremque labore, explicabo enim incidunt vitae saepe, quod soluta illo odit provident amet beatae quasi animi. Similique nostrum molestiae animi corrupti qui?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias quis, tempora laborum incidunt qui fuga adipisci doloremque iusto commodi vitae est, nemo iure placeat ut sit optio, consequuntur voluptas impedit.</span><span>Eos officiis, hic esse unde eaque, aut tenetur voluptate quam sint vel exercitationem totam dolor odio soluta illo praesentium non corrupti! Consequuntur velit, mollitia excepturi. Minus, veniam accusantium! Aliquam, ea!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit quis reiciendis veritatis expedita velit vitae amet magni sunt rerum in blanditiis aut tempore quia fugiat, voluptates officia quaerat quam id.</span><span>Sapiente tempore repudiandae, quae doloremque ullam odio quia ea! Impedit atque, ipsa consequatur quis obcaecati voluptas necessitatibus, cupiditate sunt amet ab modi illum inventore, a dolor enim similique architecto est!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque non aliquam, sit illo quas deserunt esse nobis reprehenderit quidem fuga beatae eligendi reiciendis omnis qui repellat velit earum blanditiis possimus.</span><span>Provident aspernatur ducimus, illum beatae debitis vitae non dolorum rem officia nostrum natus accusantium perspiciatis ad soluta maiores praesentium eveniet qui hic quis at quaerat ea perferendis. Ut, aut, natus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione corrupti quibusdam, sed hic veniam. Perspiciatis ex, quod architecto natus autem totam at commodi excepturi maxime pariatur corporis, veritatis vero, praesentium.</span><span>Nesciunt suscipit, nobis eos perferendis ex quaerat inventore nihil qui magnam saepe rerum velit reiciendis ipsam deleniti ducimus eligendi odio eius minima vero, nisi voluptates amet eaque, iste, labore laudantium.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, voluptas accusantium ad omnis velit distinctio! Adipisci magnam nihil nostrum molestiae rem dolores, ut ad nemo, dolor quos itaque maiores quaerat!</span><span>Quia ad suscipit reprehenderit vitae inventore eius non culpa maiores omnis sit obcaecati vel placeat quibusdam, ipsa exercitationem nam odit, magni nobis. Quam quas, accusamus expedita molestiae asperiores eaque ex?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum explicabo doloribus nihil iusto quasi vel expedita dignissimos amet mollitia, temporibus aut atque architecto assumenda dolorum nam velit deserunt totam numquam.</span><span>Ab perferendis labore, quae. Quidem architecto quo officia deserunt ea doloribus libero molestias id nisi perferendis eum porro, quibusdam! Odit aliquid placeat rem aut officia minus sit esse eos obcaecati!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi nostrum repellendus placeat, unde aperiam. Fuga, voluptas, minima. Debitis nemo ducimus itaque laboriosam error quaerat reprehenderit quo animi incidunt. Nulla, quis!</span><span>Explicabo assumenda dicta ratione? Tempora commodi asperiores, explicabo doloremque eius quia impedit possimus architecto sit nemo odio eum fuga minima dolor iste mollitia sequi dolorem perspiciatis unde quisquam laborum soluta.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam officia corporis, reiciendis laudantium, voluptate voluptates necessitatibus assumenda, delectus quisquam velit deserunt! Reprehenderit, vel quaerat accusantium nesciunt libero animi. Sequi, eveniet?</span><span>Animi natus pariatur porro, alias, veniam aut est tempora adipisci molestias harum modi cumque assumenda enim! Expedita eveniet autem illum rerum nostrum ipsum alias neque aut, dolorum impedit pariatur non?</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis aliquid rerum, odio veniam ipsam ad officia quos repellat ex aperiam voluptatum optio est animi possimus minus. Sapiente voluptates amet dolorem.</span><span>Illo necessitatibus similique asperiores inventore ut cumque nihil assumenda debitis explicabo rerum, dolorum molestiae culpa accusantium. Nisi doloremque optio provident blanditiis, eum ipsam asperiores, consequatur aliquam vel sit mollitia sunt.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim, totam harum perferendis. Minus ea perferendis laboriosam, iste, qui corrupti, quas veritatis omnis officiis animi fuga perspiciatis impedit! Error, harum, voluptas.</span><span>Omnis laborum, cum mollitia facilis ipsa unde distinctio maxime nesciunt illum perspiciatis ut officiis, eligendi numquam dolorem quod modi ipsam est rerum perferendis repellendus totam. Maxime excepturi culpa alias labore.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit deleniti, odit sit consequatur dolorum omnis repellendus, alias vel ullam numquam. Nostrum obcaecati hic, possimus delectus nam atque aliquid explicabo cum.</span><span>Explicabo tenetur minima consequatur, aliquam, laudantium non consequuntur facilis sint, suscipit debitis ex atque mollitia magni quod repellat ratione dolorum excepturi molestiae cumque iusto eos unde? Voluptatum dolores, porro provident!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At laboriosam fuga aperiam eveniet, obcaecati esse, nulla porro iure molestiae praesentium sint fugiat ea voluptate suscipit voluptates mollitia, voluptatibus. Autem, non.</span><span>Numquam velit culpa tempora ratione ipsum minus modi in? Nisi reiciendis, voluptate voluptatem maxime repellat quae odio, repellendus aliquid laborum dolorem. Labore, fuga ea minima explicabo quae voluptatum necessitatibus, similique.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, rerum dolorum nemo error fugiat ut, modi, architecto libero maxime laborum repellendus doloribus neque aperiam adipisci quaerat obcaecati deserunt consequuntur amet!</span><span>Sint, assumenda nisi obcaecati doloremque iste. Perspiciatis accusantium, distinctio impedit cum esse recusandae sunt. Officiis culpa dolore eius, doloribus natus, dolorum excepturi vitae fugiat ullam provident harum! Suscipit, assumenda, harum.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, nihil tenetur tempore eligendi qui nesciunt consequatur delectus accusantium consectetur ipsa, nulla doloribus dolores rerum corporis, laborum, laboriosam hic mollitia repellat.</span><span>Ab deleniti vitae blanditiis quod tenetur! Voluptatem temporibus ab eaque quis? Quis odio aliquid harum temporibus totam, ipsa eius iusto fugiat enim in, quibusdam molestiae aliquam consequatur nulla, consequuntur sint.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum odit praesentium quos, earum nesciunt laudantium illo tempora eligendi, porro doloremque mollitia neque aperiam inventore nam maxime dolor labore aspernatur molestias.</span><span>Voluptatibus provident hic cupiditate placeat, ut reprehenderit nisi eum, dolores ad sed quis. Doloribus molestiae, quae rem odit expedita soluta, facilis animi corporis velit ut in, recusandae harum laboriosam veritatis.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt repudiandae molestias magnam delectus veritatis labore, corporis dicta officia quos, ad corrupti odit! Ad hic officia maxime eveniet consectetur similique adipisci!</span><span>Quia at, nesciunt aliquid delectus ex alias voluptas maxime hic esse. Incidunt, laborum quos mollitia dolores et! Voluptas commodi asperiores, fugit quidem quis corporis, a eaque, animi, autem deserunt repellendus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi quas, voluptas hic minima inventore optio, id quidem placeat necessitatibus omnis voluptatibus vitae mollitia tempora consequuntur consequatur, illo facilis accusamus illum.</span><span>Voluptates consequuntur ipsam odit. Eius quis ipsam vitae, nihil molestias perferendis corporis recusandae consequatur vero iure blanditiis quas adipisci quos voluptatem rem illo voluptate. Eveniet officiis iure sit laborum veniam.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit a quis cumque nostrum quisquam molestiae pariatur, asperiores natus necessitatibus adipisci illum cupiditate nam vero, tempora excepturi laborum, earum. Voluptates, nobis.</span><span>Pariatur suscipit, hic blanditiis libero, iusto, quam cupiditate nam error id asperiores repellat ab consequatur vitae ipsa voluptatem totam magni reiciendis expedita maxime dolor! Minus explicabo quas, laborum ab omnis!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore qui ad assumenda placeat optio illo molestias corporis dolorum cum. Doloribus eius autem obcaecati minima, asperiores iure dignissimos ducimus suscipit dolorem.</span><span>Blanditiis earum accusamus eaque temporibus necessitatibus voluptatum dolorem enim debitis inventore assumenda quae error perspiciatis aut, nulla delectus quam ipsa sapiente ea aliquam laboriosam repudiandae. Nesciunt praesentium, beatae eos quasi!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate dicta voluptate impedit? Ad voluptatum dicta earum perferendis asperiores. Dolore distinctio modi expedita consequatur provident perspiciatis neque totam rerum placeat quas.</span><span>Eveniet optio est possimus iste accusantium ipsum illum. Maiores saepe repudiandae facere, delectus iure dolorem vitae nihil pariatur minima, reprehenderit eligendi dolore impedit, nisi doloribus quidem similique. Optio, delectus, minus.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste ex molestiae architecto enim nihil tempore, atque consequuntur doloribus recusandae sed consequatur veniam quos, in consectetur perspiciatis magni nostrum ab voluptates.</span><span>Nisi quos mollitia quis in maiores asperiores labore deserunt! Voluptate voluptas adipisci qui hic officia molestias, laborum necessitatibus sint nam vel minus incidunt perspiciatis recusandae sunt, rerum suscipit doloremque possimus!</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At nihil perferendis quae quidem facilis aliquid pariatur possimus hic asperiores, recusandae exercitationem adipisci atque laborum, delectus, odit ab reprehenderit distinctio dolor.</span><span>Non excepturi quos aspernatur repudiandae laboriosam, unde molestias, totam, sapiente harum accusamus delectus laborum ipsam velit amet nisi! Consectetur aliquam provident voluptatibus saepe repudiandae eveniet laborum beatae, animi, voluptate dolores.</span></p>_x000D_
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque magni, eum ipsa, veritatis facere voluptatem dolorum nobis neque minus debitis asperiores iste. Pariatur sequi quam, tempora. Dignissimos, esse similique tempora.</span><span>Ex delectus excepturi autem sunt, nemo repudiandae, recusandae nostrum accusantium nobis temporibus magnam eligendi similique veritatis deleniti, eaque blanditiis possimus at! Repellat alias laboriosam ipsum commodi dolorem, corporis dolore suscipit!</span></p>
    _x000D_
    _x000D_
    _x000D_

    How can I center an image in Bootstrap?

    Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

    <div class="container">
        <div class="row">
            <div class="col-4">
                <img class="mx-auto d-block" src="...">  
            </div>
        </div>
    </div>
    

    Or leave it as inline-block and wrapped it in a div with .text-center:

    <div class="container">
        <div class="row">
            <div class="col-4">
              <div class="text-center">
                <img src="..."> 
              </div>     
            </div>
        </div>
    </div>
    

    I made a fiddle showing both ways. They are documented here as well.

    Detecting Windows or Linux?

    Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0

    public class OSValidator {
    
        private static String OS = System.getProperty("os.name").toLowerCase();
    
        public static void main(String[] args) {
    
            System.out.println(OS);
    
            if (isWindows()) {
                System.out.println("This is Windows");
            } else if (isMac()) {
                System.out.println("This is Mac");
            } else if (isUnix()) {
                System.out.println("This is Unix or Linux");
            } else if (isSolaris()) {
                System.out.println("This is Solaris");
            } else {
                System.out.println("Your OS is not support!!");
            }
        }
    
        public static boolean isWindows() {
            return OS.contains("win");
        }
    
        public static boolean isMac() {
            return OS.contains("mac");
        }
    
        public static boolean isUnix() {
            return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
        }
    
        public static boolean isSolaris() {
            return OS.contains("sunos");
        }
        public static String getOS(){
            if (isWindows()) {
                return "win";
            } else if (isMac()) {
                return "osx";
            } else if (isUnix()) {
                return "uni";
            } else if (isSolaris()) {
                return "sol";
            } else {
                return "err";
            }
        }
    
    }
    

    Structs in Javascript

    It's more work to set up, but if maintainability beats one-time effort then this may be your case.

    /**
     * @class
     */
    class Reference {
    
        /**
         * @constructs Reference
         * @param {Object} p The properties.
         * @param {String} p.class The class name.
         * @param {String} p.field The field name.
         */
        constructor(p={}) {
            this.class = p.class;
            this.field = p.field;
        }
    }
    

    Advantages:

    • not bound to argument order
    • easily extendable
    • type script support:

    enter image description here

    Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

    I've just had the same problem (with Python 2.7 and PIL for this versions, but the solution should work also for 2.6) and the way to solve it is to copy all the registry keys from:

    HKEY_LOCAL_MACHINE\SOFTWARE\Python
    

    to

    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python
    

    Worked for me

    solution found at the address below so credits should go there: http://effbot.slinkset.com/items/Adding_Python_Information_to_the_Windows_Registry

    What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

    LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).

    RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.

    WebView : to load html, static or dynamic pages.

    For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html

    Procedure expects parameter which was not supplied

    First - why is that an EXEC? Shouldn't that just be

    AS
    SELECT Column_Name, ...
    FROM ...
    WHERE TABLE_NAME = @template
    

    The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name', it would search WHERE TABLE_NAME = Column_Name, which is very rare (to have table and column named the same).

    Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL (keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.

    Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...

    Can I style an image's ALT text with CSS?

    You can use img[alt] {styles} to style only the alternative text.

    UIButton title text color

    swift 5 version:

    By using default inbuilt color:

    1. button.setTitleColor(UIColor.green, for: .normal)

    OR

    You can use your custom color by using RGB method:

    1. button.setTitleColor(UIColor(displayP3Red: 0.0/255.0, green: 180.0/255.0, blue: 2.0/255.0, alpha: 1.0), for: .normal)

    Using an index to get an item, Python

    You can use _ _getitem__(key) function.

    >>> iterable = ('A', 'B', 'C', 'D', 'E')
    >>> key = 4
    >>> iterable.__getitem__(key)
    'E'
    

    Closing JFrame with button click

    It appears to me that you have two issues here. One is that JFrame does not have a close method, which has been addressed in the other answers.

    The other is that you're having trouble referencing your JFrame. Within actionPerformed, super refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super instead (you should also be able to use MyExtendedJFrame.this, as I see no reason why you'd want to override the behaviour of dispose or setVisible).

    cordova run with ios error .. Error code 65 for command: xcodebuild with args:

    In my case it was the app icon PNG file... I mean, it took 1 day to go from the provided error

    Error code 65 for command: xcodebuild with args:

    to the human-readable one:

    "the PNG file icon is no good for the picky Apple Xcode"

    Lost httpd.conf file located apache

    Get the path of running Apache

    $ ps -ef | grep apache
    apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2
    

    Append -V argument to the path

    $ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
    -D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"
    

    Reference:
    http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

    How to run a class from Jar which is not the Main-Class in its Manifest file

    Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.

    MyJar1.jar\META-INF\MANIFEST.MF

    Manifest-Version: 1.0
    Main-Class: com.mycomp.myproj.dir1.MainClass1
    Class-Path: MyJar.jar
    

    MyJar2.jar\META-INF\MANIFEST.MF

    Manifest-Version: 1.0
    Main-Class: com.mycomp.myproj.dir2.MainClass2
    Class-Path: MyJar.jar
    

    etc. Then just run it with java -jar MyJar2.jar

    Calculating the angle between the line defined by two points

    with pygame:

    dy = p1.y - p2.y
    dX = p2.x - p1.x
    
    rads = atan2(dy,dx)
    degs = degrees(rads)
    if degs < 0 :
       degs +=90
    

    it work for me

    How to enable GZIP compression in IIS 7.5

    Global Gzip in HttpModule

    If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

    HttpContext context = HttpContext.Current;
    context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
    HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
    HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
    

    Run chrome in fullscreen mode on Windows

    I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...

    • Start chrome and navigate to page (www.youtube.com/tv)
    • Drag the address from the address bar (the lock icon) to the desktop. It will create a shortcut.
    • From chrome, open Apps (the icon with the multiple coloured dots)
    • From desktop, drag the shortcut into the Apps space
    • Right click on the new icon in Apps and select "Open fullscreen"
    • Right click again on the icon in Apps and select "Create shortcuts..."
    • Select for example Desktop and Create. A new shortcut will be created on desktop.

    Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.

    HTML table with fixed headers and a fixed column?

    YUI DataTable

    I don't know if YUI DT has this feature but I won't be surprised if it does.

    ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

    Update your web.config

      <system.webServer>
        <modules>
          <remove name="WebDAVModule"/>
        </modules>
        <handlers>
          <remove name="WebDAV" />
          <remove name="ExtensionlessUrl-Integrated-4.0" />
          <add name="ExtensionlessUrl-Integrated-4.0"
               path="*."
               verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
               type="System.Web.Handlers.TransferRequestHandler"
               preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
      </system.webServer>
    

    http://odetocode.com/blogs/scott/archive/2012/08/07/configuration-tips-for-asp-net-mvc-4-on-a-windows.aspx

    Removes the need to modify your host configs.

    what is the difference between XSD and WSDL

    XSD is schema for WSDL file. XSD contain datatypes for WSDL. Element declared in XSD is valid to use in WSDL file. We can Check WSDL against XSD to check out web service WSDL is valid or not.

    Get name of current script in Python

    If you're doing an unusual import (e.g., it's an options file), try:

    import inspect
    print (inspect.getfile(inspect.currentframe()))
    

    Note that this will return the absolute path to the file.

    Asynchronous shell exec in PHP

    In Linux, you can start a process in a new independent thread by appending an ampersand at the end of the command

    mycommand -someparam somevalue &
    

    In Windows, you can use the "start" DOS command

    start mycommand -someparam somevalue
    

    Can I use DIV class and ID together in CSS?

    Of course you can.

    Your HTML there is just fine. To style the elements with css you can use the following approaches:

    #y {
        ...
    }
    
    .x {
        ...
    }
    
    #y.x {
        ...
    }
    

    Also you can add as many classes as you wish to your element

    <div id="id" class="classA classB classC ...">
    </div>
    

    And you can style that element using a selector with any combination of the classes and id. For example:

    #id.classA.classB.classC {
         ...
    }
    
    #id.classC {
    }
    

    How to start up spring-boot application via command line?

    To run the spring-boot application, need to follow some step.

    1. Maven setup (ignore if already setup):

      a. Install maven from https://maven.apache.org/download.cgi

      b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).

      c. Set MAVEN_HOME in system variable. enter image description here

      d. Set path for maven

    enter image description here

    1. Add Maven Plugin to POM.XML

      <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

    2. Build Spring Boot Project with Maven

         maven package
      

      or

           mvn install / mvn clean install
      
    3. Run Spring Boot app using Maven:

          mvn spring-boot:run
      
    4. [optional] Run Spring Boot app with java -jar command

           java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
      

    Java: How to check if object is null?

    I use this approach:

    if (null == drawable) {
      //do stuff
    } else {
      //other things
    }
    

    This way I find improves the readability of the line - as I read quickly through a source file I can see it's a null check.

    With regards to why you can't call .equals() on an object which may be null; if the object reference you have (namely 'drawable') is in fact null, it doesn't point to an object on the heap. This means there's no object on the heap on which the call to equals() can succeed.

    Best of luck!

    setImmediate vs. nextTick

    I recommend you to check docs section dedicated for Loop to get better understanding. Some snippet taken from there:

    We have two calls that are similar as far as users are concerned, but their names are confusing.

    • process.nextTick() fires immediately on the same phase

    • setImmediate() fires on the following iteration or 'tick' of the
      event loop

    In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change.

    How to "inverse match" with regex?

    In perl you can do

    process($line) if ($line =~ !/Andrea/);

    Secure random token in Node.js

    The npm module anyid provides flexible API to generate various kinds of string ID / code.

    To generate random string in A-Za-z0-9 using 48 random bytes:

    const id = anyid().encode('Aa0').bits(48 * 8).random().id();
    // G4NtiI9OYbSgVl3EAkkoxHKyxBAWzcTI7aH13yIUNggIaNqPQoSS7SpcalIqX0qGZ
    

    To generate fixed length alphabet only string filled by random bytes:

    const id = anyid().encode('Aa').length(20).random().id();
    // qgQBBtDwGMuFHXeoVLpt
    

    Internally it uses crypto.randomBytes() to generate random.

    How would I create a UIAlertView in Swift?

    Click of View

    @IBAction func testClick(sender: UIButton) {
    
      var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
      self.presentViewController(uiAlert, animated: true, completion: nil)
    
      uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
       println("Click of default button")
      }))
    
      uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
       println("Click of cancel button")
      }))
    
    }
    

    Done with two buttons OK & Cancel

    How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

    After further reading, and confirmation from Linus G Thiel above, I found I simply had to,

    • Downgrade to Node.js 0.6.12
    • And either,
      • Install Mocha as global
      • Add ./node_modules/.bin to my PATH

    Best way to check if a Data Table has a null value in it

    You can null/blank/space Etc value using LinQ Use Following Query

       var BlankValueRows = (from dr1 in Dt.AsEnumerable()
                                      where dr1["Columnname"].ToString() == ""
                                      || dr1["Columnname"].ToString() == ""
                                       || dr1["Columnname"].ToString() == ""
                                      select Columnname);
    

    Here Replace Columnname with table column name and "" your search item in above code we looking null value.

    Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

    To get this working for Calabash automated tests

    There is a pull request up to fix the issue of xcode 12 not working with calabash https://github.com/calabash/run_loop/pull/757

    A temporary solution is to use this WIP branch, although it is not great to have to use this as it is a draft PR. Xcode 12 support for Calabash will hopefully come in the future.

    Change in your Gemfile

    gem "run_loop"
    

    to

    gem 'run_loop', git: 'https://github.com/calabash/run_loop.git', branch: 'xcode_14_support'
    

    How do I concatenate two strings in Java?

    Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:

    1. The simplest way

    You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and

    1. In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
    2. In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).

    Example with a non null object:

    Integer theNumber = 42;
    System.out.println("Your number is " + theNumber + "!");
    

    Output:

    Your number is 42!
    

    Example with a null object:

    Integer theNumber = null;
    System.out.println("Your number is " + theNumber + "!");
    

    Output:

    Your number is null!
    

    Example with a primitive type:

    int theNumber = 42;
    System.out.println("Your number is " + theNumber + "!");
    

    Output:

    Your number is 42!
    

    2. The explicit way and potentially the most efficient one

    You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.

    Example:

    int theNumber = 42;
    StringBuilder buffer = new StringBuilder()
        .append("Your number is ").append(theNumber).append('!');
    System.out.println(buffer.toString()); // or simply System.out.println(buffer)
    

    Output:

    Your number is 42!
    

    Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.

    Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.

    So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:

    Example optimized :

    int theNumber = 42;
    StringBuilder buffer = new StringBuilder(18)
        .append("Your number is ").append(theNumber).append('!');
    System.out.println(buffer)
    

    Output:

    Your number is 42!
    

    3. The most readable way

    You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.

    Example:

    int theNumber = 42;
    System.out.println(String.format("Your number is %d!", theNumber));
    // Or if we need to print only we can use printf
    System.out.printf("Your number is still %d with printf!%n", theNumber);
    

    Output:

    Your number is 42!
    Your number is still 42 with printf!
    

    The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.

    AttributeError: 'module' object has no attribute

    SoLvEd

    Python is looking for the a object within your a.py module.

    Either RENAME that file to something else or use

    from __future__ import absolute_import 
    

    at the top of your a.py module.

    Valid characters in a Java class name

    Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

    • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

    • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

    • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

    From the official Java Tutorial.

    How do I pre-populate a jQuery Datepicker textbox with today's date?

    $(function()
    {
    $('.date-pick').datePicker().val(new Date().asString()).trigger('change');
    });
    

    Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html

    How to change int into int64?

    i := 23
    i64 := int64(i)
    fmt.Printf("%T %T", i, i64) // to print the data types of i and i64
    

    How To Use DateTimePicker In WPF?

    There is a DateTimePicker available in the Extended Toolkit.

    source of historical stock data

    I'd crawl finance.google.com (for the quotes) - or finance.yahoo.com.

    Both these will return html pages for most exchanges around the world, including historical. Then, it's just a matter of parsing the HTML to extract what you need.

    I've done this in the past, with great success. Alternatively, if you don't mind using Perl - there are several modules on CPAN that have done this work for you - i.e. extracting quotes from Google/Yahoo.

    For more, see Quote History

    How to get Url Hash (#) from server side

    Possible solution for GET requests:

    New Link format: http://example.com/yourDirectory?hash=video01

    Call this function toward top of controller or http://example.com/yourDirectory/index.php:

    function redirect()
    {
        if (!empty($_GET['hash'])) {
            /** Sanitize & Validate $_GET['hash']
                   If valid return string
                   If invalid: return empty or false
            ******************************************************/
            $validHash = sanitizeAndValidateHashFunction($_GET['hash']);
            if (!empty($validHash)) {
                $url = './#' . $validHash;
            } else {
                $url = '/your404page.php';
            }
            header("Location: $url");
        }
    }
    

    Calling UserForm_Initialize() in a Module

    From a module:

    UserFormName.UserForm_Initialize
    

    Just make sure that in your userform, you update the sub like so:

    Public Sub UserForm_Initialize() so it can be called from outside the form.

    Alternately, if the Userform hasn't been loaded:

    UserFormName.Show will end up calling UserForm_Initialize because it loads the form.

    In AngularJS, what's the difference between ng-pristine and ng-dirty?

    As already stated in earlier answers, ng-pristine is for indicating that the field has not been modified, whereas ng-dirty is for telling it has been modified. Why need both?

    Let's say we've got a form with phone and e-mail address among the fields. Either phone or e-mail is required, and you also have to notify the user when they've got invalid data in each field. This can be accomplished by using ng-dirty and ng-pristine together:

    <form name="myForm">
        <input name="email" ng-model="data.email" ng-required="!data.phone">
        <div class="error" 
             ng-show="myForm.email.$invalid && 
                      myForm.email.$pristine &&
                      myForm.phone.$pristine">Phone or e-mail required</div>
        <div class="error" 
             ng-show="myForm.email.$invalid && myForm.email.$dirty">
            E-mail is invalid
        </div>
    
        <input name="phone" ng-model="data.phone" ng-required="!data.email">
        <div class="error" 
             ng-show="myForm.phone.$invalid && 
                      myForm.email.$pristine &&
                      myForm.phone.$pristine">Phone or e-mail required</div>
        <div class="error" 
             ng-show="myForm.phone.$invalid && myForm.phone.$dirty">
            Phone is invalid
        </div>
    </form>
    

    Set size on background image with CSS?

    Not too hard, if you're not afraid of going a little more in depth :)

    There's one forgotten argument:

    background-size: contain;
    

    This won't stretch your background-image as it would do with cover. It would stretch until the longer side reaches the width or height of the outer container and therefore preserving the image.

    Edit: There's also -webkit-background-size and -moz-background-size.

    The background-size property is supported in IE9+, Firefox 4+, Opera, Chrome, and Safari 5+.

    - Source: W3 Schools

    Make sure that the controller has a parameterless public constructor error

    I had the same problem. I googled it for two days. At last I accidentally noticed that the problem was access modifier of the constructor of the Controller. I didn’t put the public key word behind the Controller’s constructor.

    public class MyController : ApiController
        {
            private readonly IMyClass _myClass;
    
            public MyController(IMyClass myClass)
            {
                _myClass = myClass;
            }
        }
    

    I add this experience as another answer maybe someone else made a similar mistake.

    Switch on ranges of integers in JavaScript

    This does not require a switch statement. It is clearer, more concise, faster, and optimises better, to use if else statements...

    var d = this.dealer;
    if (1 <= d && d <= 11) { // making sure in range 1..11
        if (d <= 4) {
            alert("1 to 4");
        } else if (d <= 8) {
            alert("5 to 8");
        } else {
            alert("9 to 11");
        }
    } else {
        alert("not in range");
    }
    

    Speed test

    I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/

    • Chrome: switch was around 70% slower than if else

    • Firefox: switch was around 5% slower than if else

    • IE: switch was around 5% slower than if else

    • Safari: switch was around 95% slower than if else

    Notes:

    Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.

    For numeric ranges, I like to use this kind of construction...

    if (1 <= d && d <= 11) {...}
    

    ... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".

    Clearer

    A few people don't think this is clearer. I'd say it is not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense.

    My concern, with "switch (true)", is that it can appear to be a meaningless line of code. Many coders, reading that will not know what to make of it.

    For my own code, I'm more willing to use obscure structures from time to time, but if anyone else will look at it, I try to use clearer constructs. I think it is better to use the constructs for what they are intended.

    Optimisation

    In a modern environment, code is often going to be minified for production, so you can write clear concise code, with readable variable names and helpful comments. There's no clear reason to use switch in this way.

    I also tried putting both constructs through a minifier. The if/else structure compresses well, becoming a single short expression using nested ternary operators. The switch statement when minified remains a switch, complete with "switch", "case" and "break" tokens, and as a result is considerably longer in code.

    How switch(true) works

    I think "switch(true) is obscure, but it seems some people just want to use it, so here's an explanation of why it works...

    A switch/case statement works by matching the part in the switch with each case, and then executing the code on the first match. In most use cases, we have a variable or non-constant expression in the switch, and then match it.

    With "switch(true), we will find the first expression in the case statements that is true. If you read "switch (true)" as "find the first expression that is true", the code feels more readable.

    jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

    Exclusions and provided dependencies will not work in child projects.

    If you are using inheritance in Maven projects you must include this configuration on the parent pom.xml file. You will have a <parent>...</parent> section in your pom.xml if you are using inheritance. So you will have something like this in your parent pom.xml:

    <groupId>some.groupId</groupId>
    <version>1.0</version>
    <artifactId>someArtifactId</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>child-module-1</module>
        <module>child-module-2</module>
    </modules>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    

    How do I insert an image in an activity with android studio?

    I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

    enter image description here


    Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

    enter image description here

    It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

    enter image description here

    Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

    <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/homepage"
            tools:layout_editor_absoluteX="55dp"
            tools:layout_editor_absoluteY="130dp" />
    

    You need to give image location using

    app:srcCompat="@drawable/imagename"
    

    Difference between string and text in rails?

    If the attribute is matching f.text_field in form use string, if it is matching f.text_area use text.

    How can I make the browser wait to display the page until it's fully loaded?

    Although this is not always a good idea, you're free to decide if you really want to do that. There are some different ways to do it, and I found a simple example here:

    http://www.reconn.us/content/view/37/47/

    Probably not the best one, but it should help you develop your own solution. Good luck.

    Get individual query parameters from Uri

    You can use:

    var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
    System.Web.HttpUtility.ParseQueryString(queryString)
    

    MSDN

    How to compare two NSDates: Which is more recent?

    Late to the party, but another easy way of comparing NSDate objects is to convert them into primitive types which allows for easy use of '>' '<' '==' etc

    eg.

    if ([dateA timeIntervalSinceReferenceDate] > [dateB timeIntervalSinceReferenceDate]) {
        //do stuff
    }
    

    timeIntervalSinceReferenceDate converts the date into seconds since the reference date (1 January 2001, GMT). As timeIntervalSinceReferenceDate returns a NSTimeInterval (which is a double typedef), we can use primitive comparators.

    How do you strip a character out of a column in SQL Server?

    Use the "REPLACE" string function on the column in question:

    UPDATE (yourTable)
    SET YourColumn = REPLACE(YourColumn, '*', '')
    WHERE (your conditions)
    

    Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.

    Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.

    Marc

    XAMPP - Apache could not start - Attempting to start Apache service

    Try to install x86 version of XAMPP. The default XAMPP version on their website is x64 (maybe because I'm using x64 Windows 7). download link here

    java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

    If you are connecting a remote mysql server from your local machine using java see the below steps. Error : "java.sql.SQLException: Access denied for user 'xxxxx'@'101.123.163.141' (using password: YES) "

    for remote access may be cpanel or others grant the remote access for your local ip address.

    In the above error message: "101.123.163.141" is my local machine ip. So First we have to give remote access in the Cpanel-> Remote MySQL®. Then run your application to connect.

    Class.forName("com.mysql.jdbc.Driver");  
    Connection con=DriverManager.getConnection(  
        "jdbc:mysql://www.xyz.com/abc","def","ghi");  
    //here abc is database name, def is username and ghi        
    Statement stmt=con.createStatement();  
    ResultSet rs=stmt.executeQuery("select * from employee");  
        while(rs.next())  
            System.out.println(rs.getInt(1)+" "+rs.getString(2)+"  
                              "+rs.getString(3));  
    con.close();    
    

    Hope it will resolve your issue.

    Thanks

    How to set min-height for bootstrap container

    Have you tried height: auto; on your .container div?

    Here is a fiddle, if you change img height, container height will adjust to it.

    EDIT

    So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

    add to your .containerclass this line

    min-height:0px !important;

    I've updated my fiddle to give you an example.

    PHP random string generator

    IF YOUR ARE USING PHP 7 +

    public function generateRandom(){
    
    $string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
    
    // OR
    
    $string = base64_encode(random_bytes(10)); // ~14 characters, includes /=+
    
    // or
    
    $string = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+
    
    // or
    
    $string = bin2hex(random_bytes(10)); // 20 characters, only 0-9a-f
    
    }
    

    React.js, wait for setState to finish before triggering a function?

    Why not one more answer? setState() and the setState()-triggered render() have both completed executing when you call componentDidMount() (the first time render() is executed) and/or componentDidUpdate() (any time after render() is executed). (Links are to ReactJS.org docs.)

    Example with componentDidUpdate()

    Caller, set reference and set state...

    <Cmp ref={(inst) => {this.parent=inst}}>;
    this.parent.setState({'data':'hello!'});
    

    Render parent...

    componentDidMount() {           // componentDidMount() gets called after first state set
        console.log(this.state.data);   // output: "hello!"
    }
    componentDidUpdate() {          // componentDidUpdate() gets called after all other states set
        console.log(this.state.data);   // output: "hello!"
    }
    

    Example with componentDidMount()

    Caller, set reference and set state...

    <Cmp ref={(inst) => {this.parent=inst}}>
    this.parent.setState({'data':'hello!'});
    

    Render parent...

    render() {              // render() gets called anytime setState() is called
        return (
            <ChildComponent
                state={this.state}
            />
        );
    }
    

    After parent rerenders child, see state in componentDidUpdate().

    componentDidMount() {           // componentDidMount() gets called anytime setState()/render() finish
    console.log(this.props.state.data); // output: "hello!"
    }
    

    How can I get a Unicode character's code?

    Just convert it to int:

    char registered = '®';
    int code = (int) registered;
    

    In fact there's an implicit conversion from char to int so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.

    This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt().

    Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+, e.g. "U+0020" for space.) That's beyond the scope of this question though, as we don't know what the requirements are.

    How to convert XML to java.util.Map and vice versa

    Here the converter for XStream including unmarshall

    public class MapEntryConverter implements Converter{
    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }
    
    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        AbstractMap<String,String> map = (AbstractMap<String,String>) value;
        for (Entry<String,String> entry : map.entrySet()) {
            writer.startNode(entry.getKey().toString());
            writer.setValue(entry.getValue().toString());
            writer.endNode();
        }
    }
    
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Map<String, String> map = new HashMap<String, String>();
    
        while(reader.hasMoreChildren()) {
            reader.moveDown();
            map.put(reader.getNodeName(), reader.getValue());
            reader.moveUp();
        }
        return map;
    }
    

    Creating a List of Lists in C#

    A quick example:

    List<List<string>> myList = new List<List<string>>();
    myList.Add(new List<string> { "a", "b" });
    myList.Add(new List<string> { "c", "d", "e" });
    myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
    myList.Add(new List<string> { "a", "b" });
    
    // To iterate over it.
    foreach (List<string> subList in myList)
    {
        foreach (string item in subList)
        {
            Console.WriteLine(item);
        }
    }
    

    Is that what you were looking for? Or are you trying to create a new class that extends List<T> that has a member that is a `List'?

    HTML5 Canvas vs. SVG vs. div

    While there is still some truth to most of the answers above, I think they deserve an update:

    Over the years the performance of SVG has improved a lot and now there is hardware-accelerated CSS transitions and animations for SVG that do not depend on JavaScript performance at all. Of course JavaScript performance has improved, too and with it the performance of Canvas, but not as much as SVG got improved. Also there is a "new kid" on the block that is available in almost all browsers today and that is WebGL. To use the same words that Simon used above: It beats both Canvas and SVG hands down. This doesn't mean it should be the go-to technology, though, since it's a beast to work with and it is only faster in very specific use-cases.

    IMHO for most use-cases today, SVG gives the best performance/usability ratio. Visualizations need to be really complex (with respect to number of elements) and really simple at the same time (per element) so that Canvas and even more so WebGL really shine.

    In this answer to a similar question I am providing more details, why I think that the combination of all three technologies sometimes is the best option you have.

    Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

    scanf needs to know the size of the data being pointed at by &d to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf is always getting a double.

    How to check if input date is equal to today's date?

    Just use the following code in your javaScript:

    if(new Date(hireDate).getTime() > new Date().getTime())
    {
    //Date greater than today's date 
    }
    

    Change the condition according to your requirement.Here is one link for comparision compare in java script

    Difference between clean, gradlew clean

    1. ./gradlew clean

      Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

    2. ./gradlew clean assembleDebug

      Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

    3. ./gradlew clean :assembleDebug

      Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

    4. Android Studio --> Build --> Clean

      Is essentially the same as ./gradlew clean. See here.

    For more info, I suggest taking the time to read through the Android docs, especially this one.

    How to convert an array of strings to an array of floats in numpy?

    You can use this as well

    import numpy as np
    x=np.array(['1.1', '2.2', '3.3'])
    x=np.asfarray(x,float)
    

    UIView bottom border?

    Implemented in a category as below:

    UIButton+Border.h:

    @interface UIButton (Border)
    
    - (void)addBottomBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    
    - (void)addLeftBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    
    - (void)addRightBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    
    - (void)addTopBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
    
    @end
    

    UIButton+Border.m:

    @implementation UIButton (Border)
    
    - (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
    
        border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
    }
    
    - (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
    
        border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
        [self.layer addSublayer:border];
    }
    
    - (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
    
        border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
    }
    
    - (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
        CALayer *border = [CALayer layer];
        border.backgroundColor = color.CGColor;
    
        border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
        [self.layer addSublayer:border];
    }
    
    @end
    

    SVN 405 Method Not Allowed

    I had a similar problem. I ended up nuking it from orbit, and lost my SVN history in the process. But at least I made that damn error go away.

    This is probably a sub-optimal sequence of commands to execute, but it should fairly closely follow the sequence of commands that I actually did to get things to work:

    cp -rp target ~/other/location/target-20111108
    svn rm target --force
    cp -rp ~/other/location/target-20111108 target-other-name
    cd target-other-name
    find . -name .svn -print | xargs rm -rf
    cd ..
    svn add target-other-name
    svn ci -m "Re-re-re-re-re-re-re-re-re-re import target"
    svn mv target-other-name target
    svn ci -m "Re-re-re-re-re-re-re-re-re-re import target"
    

    Return JSON for ResponseEntity<String>

    The root of the problem is that Spring (via ResponseEntity, RestController, and/or ResponseBody) will use the contents of the string as the raw response value, rather than treating the string as JSON value to be encoded. This is true even when the controller method uses produces = MediaType.APPLICATION_JSON_VALUE, as in the question here.

    It's essentially like the difference between the following:

    // yields: This is a String
    System.out.println("This is a String");
    
    // yields: "This is a String"
    System.out.println("\"This is a String\"");
    

    The first output cannot be parsed as JSON, but the second output can.

    Something like '"'+myString+'"' is probably not a good idea however, as that won't handle proper escaping of double-quotes within the string and will not produce valid JSON for any such string.

    One way to handle this would be to embed your string inside an object or list, so that you're not passing a raw string to Spring. However, that changes the format of your output, and really there's no good reason not to be able to return a properly-encoded JSON string if that's what you want to do. If that's what you want, the best way to handle it is via a JSON formatter such as Json or Google Gson. Here's how it might look with Gson:

    import com.google.gson.Gson;
    
    @RestController
    public class MyController
    
        private static final Gson gson = new Gson();
    
        @RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        ResponseEntity<String> so() {
            return ResponseEntity.ok(gson.toJson("This is a String"));
        }
    }
    

    Bootstrap trying to load map file. How to disable it? Do I need to do it?

    From bootstrap.css remove remove last line /*# sourceMappingURL=bootstrap-theme.css.map */

    Returning an empty array

    return new File[0];
    

    This is better and efficient approach.

    Passing a dictionary to a function as keyword parameters

    Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

    So my example becomes:

    d = dict(p1=1, p2=2)
    def f2(p1,p2):
        print p1, p2
    f2(**d)
    

    CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

    1.copy your --.MDF,--.LDF files to pate this location For 2008 server C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA 2.In sql server 2008 use ATTACH and select same location for add

    Regular expression to match exact number of characters?

    Your solution is correct, but there is some redundancy in your regex.
    The similar result can also be obtained from the following regex:

    ^([A-Z]{3})$
    

    The {3} indicates that the [A-Z] must appear exactly 3 times.

    Types in Objective-C on iOS

    This is a good overview:

    http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

    or run this code:

    32 bit process:

      NSLog(@"Primitive sizes:");
      NSLog(@"The size of a char is: %d.", sizeof(char));
      NSLog(@"The size of short is: %d.", sizeof(short));
      NSLog(@"The size of int is: %d.", sizeof(int));
      NSLog(@"The size of long is: %d.", sizeof(long));
      NSLog(@"The size of long long is: %d.", sizeof(long long));
      NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
      NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
      NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
      NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
      NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
      NSLog(@"The size of a float is: %d.", sizeof(float));
      NSLog(@"The size of a double is %d.", sizeof(double));
    
      NSLog(@"Ranges:");
      NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
      NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
      NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
      NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
      NSLog(@"INT_MIN:    %i",   INT_MIN);
      NSLog(@"INT_MAX:    %i",   INT_MAX);
      NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
      NSLog(@"LONG_MAX:   %li",  LONG_MAX);
      NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
      NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
      NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
      NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int
    

    When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

    Primitive sizes:
    The size of a char is: 1.                
    The size of short is: 2.                 
    The size of int is: 4.                   
    The size of long is: 4.                  
    The size of long long is: 8.             
    The size of a unsigned char is: 1.       
    The size of unsigned short is: 2.        
    The size of unsigned int is: 4.          
    The size of unsigned long is: 4.         
    The size of unsigned long long is: 8.    
    The size of a float is: 4.               
    The size of a double is 8.               
    Ranges:                                  
    CHAR_MIN:   -128                         
    CHAR_MAX:   127                          
    SHRT_MIN:   -32768                       
    SHRT_MAX:   32767                        
    INT_MIN:    -2147483648                  
    INT_MAX:    2147483647                   
    LONG_MIN:   -2147483648                  
    LONG_MAX:   2147483647                   
    ULONG_MAX:  4294967295                   
    LLONG_MIN:  -9223372036854775808         
    LLONG_MAX:  9223372036854775807          
    ULLONG_MAX: 18446744073709551615 
    

    64 bit process:

    The size of a char is: 1.
    The size of short is: 2.
    The size of int is: 4.
    The size of long is: 8.
    The size of long long is: 8.
    The size of a unsigned char is: 1.
    The size of unsigned short is: 2.
    The size of unsigned int is: 4.
    The size of unsigned long is: 8.
    The size of unsigned long long is: 8.
    The size of a float is: 4.
    The size of a double is 8.
    Ranges:
    CHAR_MIN:   -128
    CHAR_MAX:   127
    SHRT_MIN:   -32768
    SHRT_MAX:   32767
    INT_MIN:    -2147483648
    INT_MAX:    2147483647
    LONG_MIN:   -9223372036854775808
    LONG_MAX:   9223372036854775807
    ULONG_MAX:  18446744073709551615
    LLONG_MIN:  -9223372036854775808
    LLONG_MAX:  9223372036854775807
    ULLONG_MAX: 18446744073709551615
    

    Is there a way to avoid null check before the for-each loop iteration starts?

    Another Java 8+ way would be to create a forEach method that does not crash when using a null value:

    public static <T> void forEach(Iterable<T> set, Consumer<T> action) {
        if (set != null) {
            set.forEach(action);
        }
    }
    

    The usage of the own defined foreach is close to the native Java 8 one:

    ArrayList<T> list = null;
    
    //java 8+ (will throw a NullPointerException)
    list.forEach(item -> doSomething(...) );
    
    //own implementation
    forEach(list, item -> doSomething(...) );
    

    How to append text to a text file in C++?

    You could also do it like this

    #include <fstream>
    
    int main(){   
    std::ofstream ost {outputfile, std::ios_base::app};
    
    ost.open(outputfile);
    ost << "something you want to add to your outputfile";
    ost.close();
    return 0;
    }
    

    Permissions for /var/www/html

    log in as root user:

    sudo su
    
    password:
    

    then go and do what you want to do in var/www

    Does it make sense to use Require.js with Angular.js?

    I think that it depends on your project complexity since angular is pretty much modularized. Your controllers can be mapped and you can just import those JavaScript classes in your index.html page.

    But in case your project get bigger. Or you anticipates such scenario, you should integrate angular with requirejs. In this article you can see a demo app for such integration.

    PHP - concatenate or directly insert variables in string

    I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

    In python, what is the difference between random.uniform() and random.random()?

    The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random() just does this. Use random.uniform(a, b) to specify a different range.

    D3 transform scale and translate

    The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

    When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

    How can I use if/else in a dictionary comprehension?

    You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

    { (some_key if condition else default_key):(something_if_true if condition
              else something_if_false) for key, value in dict_.items() }
    

    The final if clause acts as a filter, which is different from having the conditional expression.


    Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

    Laravel whereIn OR whereIn

    You have a orWhereIn function in Laravel. It takes the same parameters as the whereIn function.

    It's not in the documentation but you can find it in the laravel API. http://laravel.com/api/4.1/

    That should give you this:

    $query-> orWhereIn('products.value', $f);
    

    SSL: CERTIFICATE_VERIFY_FAILED with Python3

    In my case, I used the ssl module to "workaround" the certification like so:

    import ssl
    
    ssl._create_default_https_context = ssl._create_unverified_context
    

    Then to read your link content, you can use:

    urllib.request.urlopen(urllink)
    

    How to fix ReferenceError: primordials is not defined in node

    I was getting this error on Windows 10. Turned out to be a corrupted roaming profile.

    npm ERR! node v12.4.0
    npm ERR! npm  v3.3.12
    
    npm ERR! primordials is not defined
    npm ERR!
    npm ERR! If you need help, you may report this error at:
    npm ERR!     <https://github.com/npm/npm/issues>
    
    npm ERR! Please include the following file with any support request:
    

    Deleting the C:\Users\{user}\AppData\Roaming\npm folder fixed my issue.

    Django download a file

    If you hafe upload your file in media than:

    media
    example-input-file.txt

    views.py

    def download_csv(request):    
        file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')    
        if os.path.exists(file_path):    
            with open(file_path, 'rb') as fh:    
                response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")    
                response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)    
                return response
    

    urls.py

    path('download_csv/', views.download_csv, name='download_csv'),
    

    download.html

    a href="{% url 'download_csv' %}" download=""
    

    Sort a list of tuples by 2nd item (integer value)

    For a lambda-avoiding method, first define your own function:

    def MyFn(a):
        return a[1]
    

    then:

    sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=MyFn)
    

    Python: Removing list element while iterating over list

    Why not rewrite it to be

    for element in somelist: 
       do_action(element)  
    
    if check(element): 
        remove_element_from_list
    

    See this question for how to remove from the list, though it looks like you've already seen that Remove items from a list while iterating

    Another option is to do this if you really want to keep this the same

    newlist = [] 
    for element in somelist: 
       do_action(element)  
    
       if not check(element): 
          newlst.append(element)
    

    Running PHP script from the command line

    I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:

    F:\myfolder\php\php.exe -f F:\myfolder\php\script.php
    

    Convert file: Uri to File in Android

    None of this works for me. I found this to be the working solution. But my case is specific to images.

    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();
    

    What is the default font of Sublime Text?

    The default font on windows 10 is Consolas

    How do you use https / SSL on localhost?

    If you have IIS Express (with Visual Studio):

    To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.

    See the steps and pictures at this code project.

    IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.

    From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.

    enter image description here

    Android - Set text to TextView

    In your layout. Your Texto should not contain (android:text=...). I would remove this line. Either keep the Java string OR the (android:text=...)

    What is the C# equivalent of NaN or IsNumeric?

    Actually, Double.NaN is supported in all .NET versions 2.0 and greater.

    Set encoding and fileencoding to utf-8 in Vim

    You can set the variable 'fileencodings' in your .vimrc.

    This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

    See :help filencodings

    If you often work with e.g. cp1252, you can add it there:

    set fileencodings=ucs-bom,utf-8,cp1252,default,latin9
    

    How to declare a constant in Java

    Anything that is static is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.

    Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.

    In your case, when you declared it as static final, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final variable so it cannot be updated).

    In second case, the final int a is also constant , however it is created every time you create an instance of the class where that variable is declared.

    Have a look on this Java tutorial for better understanding ,

    How to get records randomly from the oracle database?

    SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;
    

    This is more efficient as it doesn't need to sort the Table.