Programs & Examples On #Axiom

Axiom is a Java library developed by Apache that provides an XML object model implementation.

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

Accessing elements by type in javascript

var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
    var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
    for (;i<l;i++) {
        if (elems[i].type.toLowerCase() === "text") {
            ret.push(elems[i]);
        }
    }

    return ret;
}());

Decimal to Hexadecimal Converter in Java

Simple:

  public static String decToHex(int dec)
  {
        return Integer.toHexString(dec);
  }

As mentioned here: Java Convert integer to hex integer

How to fix 'Notice: Undefined index:' in PHP form action

short way, you can use Ternary Operators

$filename = !empty($_POST['filename'])?$_POST['filename']:'-';

How would you count occurrences of a string (actually a char) within a string?

For anyone wanting a ready to use String extension method,

here is what I use which was based on the best of the posted answers:

public static class StringExtension
{    
    /// <summary> Returns the number of occurences of a string within a string, optional comparison allows case and culture control. </summary>
    public static int Occurrences(this System.String input, string value, StringComparison stringComparisonType = StringComparison.Ordinal)
    {
        if (String.IsNullOrEmpty(value)) return 0;

        int count    = 0;
        int position = 0;

        while ((position = input.IndexOf(value, position, stringComparisonType)) != -1)
        {
            position += value.Length;
            count    += 1;
        }

        return count;
    }

    /// <summary> Returns the number of occurences of a single character within a string. </summary>
    public static int Occurrences(this System.String input, char value)
    {
        int count = 0;
        foreach (char c in input) if (c == value) count += 1;
        return count;
    }
}

How to load all modules in a folder?

This is the best way i've found so far:

from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
    if not x.startswith('__'):
        __import__(basename(x)[:-3], globals(), locals())

Can I make a <button> not submit a form?

Yes, you can make a button not submit a form by adding an attribute of type of value button: <button type="button"><button>

No String-argument constructor/factory method to deserialize from String value ('')

Had this when I accidentally was calling

mapper.convertValue(...)

instead of

mapper.readValue(...)

So, just make sure you call correct method, since argument are same and IDE can find many things

Why use def main()?

if the content of foo.py

print __name__
if __name__ == '__main__':
    print 'XXXX'

A file foo.py can be used in two ways.

  • imported in another file : import foo

In this case __name__ is foo, the code section does not get executed and does not print XXXX.

  • executed directly : python foo.py

When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX

One of the use of this functionality to write various kind of unit tests within the same module.

How to do an Integer.parseInt() for a decimal number?

One more solution is possible.

int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))  

Example:

Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))  

Output

10

How to parse float with two decimal places in javascript?

Please use below function if you don't want to round off.

function ConvertToDecimal(num) {
    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
   alert('M : ' +  Number(num)); //If you need it back as a Number    
}

What is the most accurate way to retrieve a user's correct IP address in PHP?

I know this is too late to answer. But you may try these options:

Option 1: (Using curl)

$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://ifconfig.me/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// grab URL and pass it to the browser
$ip = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

return $ip;

Option 2: (Works good on mac)

return trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));

Option 3: (Just used a trick)

return str_replace('Current IP CheckCurrent IP Address: ', '', strip_tags(file_get_contents('http://checkip.dyndns.com')));

Might be a reference: https://www.tecmint.com/find-linux-server-public-ip-address/

Regex: Remove lines containing "help", etc

You can do this using sed: sed '/help/ d' < inputFile > outputFile

How may I sort a list alphabetically using jQuery?

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I had the same problem but it only occurred on the published website on Godaddy. It was no problem in my local host.

The error came from an aspx.cs (code behind file) where I tried to assign a value to a label. It appeared that from within the code behind, that the label Text appears to be null. So all I did with change all my Label Text properties in the ASPX file from Text="" to Text=" ".

The problem disappeared. I don’t know why the error happens from the hosted version but not on my localhost and don’t have time to figure out why. But it works fine now.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

SQL Server 2008- Get table constraints

You Can Get With This Query

Unique Constraint,

Default Constraint With Value,

Foreign Key With referenced Table And Column

And Primary Key Constraint.

Select C.*, (Select definition From sys.default_constraints Where object_id = C.object_id) As dk_definition,
(Select definition From sys.check_constraints Where object_id = C.object_id) As ck_definition,
(Select name From sys.objects Where object_id = D.referenced_object_id) As fk_table,
(Select name From sys.columns Where column_id = D.parent_column_id And object_id = D.parent_object_id) As fk_col
From sys.objects As C
Left Join (Select * From sys.foreign_key_columns) As D On D.constraint_object_id = C.object_id 
Where C.parent_object_id = (Select object_id From sys.objects Where type = 'U'
And name = 'Table Name Here');

Should a RESTful 'PUT' operation return something

I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)

If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.

How to build minified and uncompressed bundle with webpack?

Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.

Installation

npm install --save-dev unminified-webpack-plugin

Usage

var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'library.min.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^

How to convert a string or integer to binary in Ruby?

You have Integer#to_s(base) and String#to_i(base) available to you.

Integer#to_s(base) converts a decimal number to a string representing the number in the base specified:

9.to_s(2) #=> "1001"

while the reverse is obtained with String#to_i(base):

"1001".to_i(2) #=> 9

How do I create a URL shortener?

Very good answer, I have created a Golang implementation of the bjf:

package bjf

import (
    "math"
    "strings"
    "strconv"
)

const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func Encode(num string) string {
    n, _ := strconv.ParseUint(num, 10, 64)
    t := make([]byte, 0)

    /* Special case */
    if n == 0 {
        return string(alphabet[0])
    }

    /* Map */
    for n > 0 {
        r := n % uint64(len(alphabet))
        t = append(t, alphabet[r])
        n = n / uint64(len(alphabet))
    }

    /* Reverse */
    for i, j := 0, len(t) - 1; i < j; i, j = i + 1, j - 1 {
        t[i], t[j] = t[j], t[i]
    }

    return string(t)
}

func Decode(token string) int {
    r := int(0)
    p := float64(len(token)) - 1

    for i := 0; i < len(token); i++ {
        r += strings.Index(alphabet, string(token[i])) * int(math.Pow(float64(len(alphabet)), p))
        p--
    }

    return r
}

Hosted at github: https://github.com/xor-gate/go-bjf

What does "Object reference not set to an instance of an object" mean?

Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur. Please check this link.

for the sake of self learning, you can put some check condition. like

if (myObj== null)
Console.Write("myObj is NULL");

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

here is the proxy setting

git config --global http.proxy http://<username>:<pass>@<ip>:<port>
git config --global https.proxy http://<username>:<pass>@<ip>:<port>

Escape sequence \f - form feed - what exactly is it?

Although recently its use is undefined, a common and useful use for the form feed is to separate sections of code vertically, like so: enter image description here (from http://ergoemacs.org/emacs/emacs_form_feed_section_paging.html)

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

Those extensions aren't really new, they are old. :-)

When C++ was new, some people wanted to have a .c++ extension for the source files, but that didn't work on most file systems. So they tried something close to that, like .cxx, or .cpp instead.

Others thought about the language name, and "incrementing" .c to get .cc or even .C in some cases. Didn't catch on that much.

Some believed that if the source is .cpp, the headers ought to be .hpp to match. Moderately successful.

Javascript to stop HTML5 video playback on modal window close

I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.

$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});

How to make Java work with SQL Server?

The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.

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

sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.

I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).

jsPDF multi page PDF with HTML renderer

         html2canvas(element[0], {
                    onrendered: function (canvas) {
                        pages = Math.ceil(element[0].clientHeight / 1450);
                        for (i = 0; i <= pages; i += 1) {
                            if (i > 0) {
                                pdf.addPage();
                            }
                            srcImg = canvas;
                            sX = 0;
                            sY = 1450 * i;
                            sWidth = 1100;
                            sHeight = 1450;
                            dX = 0;
                            dY = 0;
                            dWidth = 1100;
                            dHeight = 1450;
                            window.onePageCanvas = document.createElement("canvas");
                            onePageCanvas.setAttribute('width', 1100);
                            onePageCanvas.setAttribute('height', 1450);
                            ctx = onePageCanvas.getContext('2d');
                            ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
                            canvasDataURL = onePageCanvas.toDataURL("image/png");
                            width = onePageCanvas.width;
                            height = onePageCanvas.clientHeight;
                            pdf.setPage(i + 1);
                            pdf.addImage(canvasDataURL, 'PNG', 35, 30, (width * 0.5), (height * 0.5));
                        }
                        pdf.save('testfilename.pdf');
                    }
                });

Open multiple Projects/Folders in Visual Studio Code

On Windows it's possible to use mklink to create directory symbolic links to the needed folders. Then keep them together in a folder, and VSCode will list the content of these.

    c:\>mklink /D c:\dev\MyWork\scripts c:\ProjA\scripts
    symbolic link created for c:\dev\MyWork\scripts <<===>> c:\ProjA\scripts

    c:\>mklink /D c:\dev\MyWork\styles c:\ProjB\styles
    symbolic link created for c:\dev\MyWork\styles <<===>> c:\dev\ProjB\styles

This is very similar to @NeilShen's idea, I guess.

How can I solve ORA-00911: invalid character error?

Remove the semicolon (;), backtick (``) etc. from inside a query

Remove Project from Android Studio

  1. Go to your Android project directory

    C:\Users\HP\AndroidStudioProjects
    

    Screenshot

  2. Delete which one you need to delete

  3. Restart Android Studio

Javadoc link to method in other class

For the Javadoc tag @see, you don't need to use @link; Javadoc will create a link for you. Try

@see com.my.package.Class#method()

Here's more info about @see.

What is the difference between XML and XSD?

Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML could be used for some particular purposes. The XML is only containing data in suitable format and structure.

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

INSERT IF NOT EXISTS ELSE UPDATE?

Firstly update it. If affected row count = 0 then insert it. Its the easiest and suitable for all RDBMS.

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

Using env variable in Spring Boot's application.properties

If the properties files are externalized as environment variables following run configuration can be added into IDE:

--spring.config.additional-location={PATH_OF_EXTERNAL_PROP}

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!


Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Finalize vs Dispose

The main difference between Dispose and Finalize is that:

Dispose is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {} statement is invented. When your program finishes the execution of the code inside the {}, it will call Dispose method automatically.

Finalize is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.

I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.

How to declare a global variable in C++

You declare the variable as extern in a common header:

//globals.h
extern int x;

And define it in an implementation file.

//globals.cpp
int x = 1337;

You can then include the header everywhere you need access to it.

I suggest you also wrap the variable inside a namespace.

Split comma-separated input box values into array in jquery, and loop through it

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

Making an image act like a button

It sounds like you want an image button:

<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />

Alternatively, you can use CSS to make the existing submit button use your image as its background.

In any case, you don't want a separate <img /> element on the page.

Writing handler for UIAlertAction

create alert, tested in xcode 9

let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)

and the function

func finishAlert(alert: UIAlertAction!)
{
}

Setting different color for each series in scatter plot on matplotlib

A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time


# a generic set of data with associated colors
nsamples=1000
x=np.random.uniform(0,10,nsamples)
y=np.random.uniform(0,10,nsamples)
colors={0:'r',1:'g',2:'b',3:'k'}
c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]

plt.close('all')

# "Fast" Scatter plotting
starttime=time.time()
# 1) make a dataframe
df=pd.DataFrame()
df['x']=x
df['y']=y
df['c']=c
plt.figure()
# 2) group the dataframe by color and loop
for g,b in df.groupby(by='c'):
    plt.scatter(b['x'],b['y'],color=g)
print('Fast execution time:', time.time()-starttime)

# "Slow" Scatter plotting
starttime=time.time()
plt.figure()
# 2) group the dataframe by color and loop
for i in range(len(x)):
    plt.scatter(x[i],y[i],color=c[i])
print('Slow execution time:', time.time()-starttime)

plt.show()

phonegap open link in browser

As suggested in a similar question, use JavaScript to call window.open with the target argument set to _system, as per the InAppBrowser documentation:

<a href="#" onclick="window.open('http://www.kidzout.com', '_system'); return false;">www.kidzout.com</a>

This should work, though a better and more flexible solution would be to intercept all links' click events, and call window.open with arguments read from the link's attributes.

Remember you must install the InAppBrowser plugin for this to work:

cordova plugin add cordova-plugin-inappbrowser

How to set border on jPanel?

BorderLayout(int Gap, int Gap) or GridLayout(int Gap, int Gap, int Gap, int Gap)

why paint Border() inside paintComponent( ...)

    Border line, raisedbevel, loweredbevel, title, empty;
    line = BorderFactory.createLineBorder(Color.black);
    raisedbevel = BorderFactory.createRaisedBevelBorder();
    loweredbevel = BorderFactory.createLoweredBevelBorder();
    title = BorderFactory.createTitledBorder("");
    empty = BorderFactory.createEmptyBorder(4, 4, 4, 4);
    Border compound = BorderFactory.createCompoundBorder(empty, xxx);
    Color crl = (Color.blue);
    Border compound1 = BorderFactory.createCompoundBorder(empty, xxx);

Is it possible to use pip to install a package from a private GitHub repository?

If you have your own library/package on GitHub, GitLab, etc., you have to add a tag to commit with a concrete version of the library, for example, v2.0, and then you can install your package:

pip install git+ssh://link/name/[email protected]

This works for me. Other solutions haven't worked for me.

Copy Paste Values only( xlPasteValues )

you may use this:

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

How to use CURL via a proxy?

I have explained use of various CURL options required for CURL PROXY.

$url = 'http://dynupdate.no-ip.com/ip.php';
$proxy = '127.0.0.1:8888';
$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);         // URL for CURL call
curl_setopt($ch, CURLOPT_PROXY, $proxy);     // PROXY details with port
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);   // Use if proxy have username and password
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); // If expected to call with specific PROXY type
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  // If url has redirects then go to the final redirected URL.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);  // Do not outputting it out directly on screen.
curl_setopt($ch, CURLOPT_HEADER, 1);   // If you want Header information of response else make 0
$curl_scraped_page = curl_exec($ch);
curl_close($ch);

echo $curl_scraped_page;

How to check for changes on remote (origin) Git repository

A good way to have a synthetic view of what's going on "origin" is:

git remote show origin

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

How is a JavaScript hash map implemented?

every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

How to vertically align an image inside a div

A pure CSS solution:

_x000D_
_x000D_
.frame {_x000D_
  margin: 1em 0;_x000D_
  height: 35px;_x000D_
  width: 160px;_x000D_
  border: 1px solid red;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-height: 25px;_x000D_
  max-width: 160px;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  margin: auto;_x000D_
  background: #3A6F9A;_x000D_
}
_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=250 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=25 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=23 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=21 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=19 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=17 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=15 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=13 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=11 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=9 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=7 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=5 />_x000D_
</div>_x000D_
<div class=frame>_x000D_
  <img src="http://jsfiddle.net/img/logo.png" height=3 />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Key stuff

// position: relative; - in .frame holds the absolute element within the frame
// top: 0; bottom: 0; left: 0; right: 0; - this is key for centering a component
// margin: auto; - centers the image horizontally & vertically

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

Copy a table from one database to another in Postgres

You have to use DbLink to copy one table data into another table at different database. You have to install and configure DbLink extension to execute cross database query.

I have already created detailed post on this topic. Please visit this link

java.lang.OutOfMemoryError: GC overhead limit exceeded

For the record, we had the same problem today. We fixed it by using this option:

-XX:-UseConcMarkSweepGC

Apparently, this modified the strategy used for garbage collection, which made the issue disappear.

What are alternatives to document.write?

The reason that your HTML is replaced is because of an evil JavaScript function: document.write().

It is most definitely "bad form." It only works with webpages if you use it on the page load; and if you use it during runtime, it will replace your entire document with the input. And if you're applying it as strict XHTML structure it's not even valid code.


the problem:

document.write writes to the document stream. Calling document.write on a closed (or loaded) document automatically calls document.open which will clear the document.

-- quote from the MDN

document.write() has two henchmen, document.open(), and document.close(). When the HTML document is loading, the document is "open". When the document has finished loading, the document has "closed". Using document.write() at this point will erase your entire (closed) HTML document and replace it with a new (open) document. This means your webpage has erased itself and started writing a new page - from scratch.

I believe document.write() causes the browser to have a performance decrease as well (correct me if I am wrong).


an example:

This example writes output to the HTML document after the page has loaded. Watch document.write()'s evil powers clear the entire document when you press the "exterminate" button:

_x000D_
_x000D_
I am an ordinary HTML page.  I am innocent, and purely for informational purposes. Please do not <input type="button" onclick="document.write('This HTML page has been succesfully exterminated.')" value="exterminate"/>_x000D_
me!
_x000D_
_x000D_
_x000D_


the alternatives:

  • .innerHTML This is a wonderful alternative, but this attribute has to be attached to the element where you want to put the text.

Example: document.getElementById('output1').innerHTML = 'Some text!';

  • .createTextNode() is the alternative recommended by the W3C.

Example: var para = document.createElement('p'); para.appendChild(document.createTextNode('Hello, '));

NOTE: This is known to have some performance decreases (slower than .innerHTML). I recommend using .innerHTML instead.


the example with the .innerHTML alternative:

_x000D_
_x000D_
I am an ordinary HTML page. _x000D_
I am innocent, and purely for informational purposes. _x000D_
Please do not _x000D_
<input type="button" onclick="document.getElementById('output1').innerHTML = 'There was an error exterminating this page. Please replace <code>.innerHTML</code> with <code>document.write()</code> to complete extermination.';" value="exterminate"/>_x000D_
 me!_x000D_
<p id="output1"></p>
_x000D_
_x000D_
_x000D_

git replacing LF with CRLF

I don't know much about git on Windows, but...

Appears to me that git is converting the return format to match that of the running platform (Windows). CRLF is the default return format in Windows, while LF is the default return format for most other OSes.

Chances are, the return format will be adjusted properly when the code is moved to another system. I also reckon git is smart enough to keep binary files intact rather than trying to convert LFs to CRLFs in, say, JPEGs.

In summary, you probably don't need to fret too much over this conversion. However, if you go to archive your project as a tarball, fellow coders would probably appreciate having LF line terminators rather than CRLF. Depending on how much you care (and depending on you not using Notepad), you might want to set git to use LF returns if you can :)

Appendix: CR is ASCII code 13, LF is ASCII code 10. Thus, CRLF is two bytes, while LF is one.

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

New Array from Index Range Swift

subscript

extension Array where Element : Equatable {
  public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
    if bounds.lowerBound > count { return [] }
    let lower = Swift.max(0, bounds.lowerBound)
    let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
    return self[lower..<upper]
  }
  
  public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
    let lower = lower ?? 0
    let upper = upper ?? count
    if lower > upper { return [] }
    return self[safe: lower..<upper]
  }
}

returns a copy of this range clamped to the given limiting range.

var arr = [1, 2, 3]
    
arr[safe: 0..<1]    // returns [1]  assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100]  // returns [3]  assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns []   assert(arr[safe: -100..<0] == [])

arr[safe: 0, 1]     // returns [1]  assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100]   // returns [3]  assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0]  // returns []   assert(arr[safe: -100, 0] == [])

Password Protect a SQLite DB. Is it possible?

You can password protect a SQLite3 DB. Before doing any operations, set the password as follows.

SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();

then next time you can access it like

conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();

This wont allow any GUI editor to view your data. Some editors can decrypt the DB if you provide the password. The algorithm used is RSA.

Later if you wish to change the password, use

conn.ChangePassword("new_password");

To reset or remove password, use

conn.ChangePassword(String.Empty);

What does "select 1 from" do?

select 1 from table

will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:

if exists(select 1 from table where some_column = 'some_value')

What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:

1) performance & you might retrieve more data than you actually need.

2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.

What is the difference between Bower and npm?

For many people working with node.js, a major benefit of bower is for managing dependencies that are not javascript at all. If they are working with languages that compile to javascript, npm can be used to manage some of their dependencies. however, not all their dependencies are going to be node.js modules. Some of those that compile to javascript may have weird source language specific mangling that makes passing them around compiled to javascript an inelegant option when users are expecting source code.

Not everything in an npm package needs to be user-facing javascript, but for npm library packages, at least some of it should be.

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Can't install nuget package because of "Failed to initialize the PowerShell host"

By default the PowerShell script execution is very limited for security reasons. For use within NuGet we need to open the doors.

1. Step

Open Windows PowerShell, run as Administrator

2. Step

NuGet is using the 32 bit console, so it wont be affected by changes to the 64 bit console. Run the following script to make sure you are configuring the 32 bit console.

start-job { Set-ExecutionPolicy RemoteSigned } -RunAs32 | wait-job | Receive-Job

3. Step

Restart Visual Studio

how to concat two columns into one with the existing column name in mysql?

Remove the * from your query and use individual column names, like this:

SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;

Using * means, in your results you want all the columns of the table. In your case * will also include FIRSTNAME. You are then concatenating some columns and using alias of FIRSTNAME. This creates 2 columns with same name.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

Error "The connection to adb is down, and a severe error has occurred."

I had the same problem

  1. I entered Task manager -> find adb.exe -> end process
  2. Go to the Android SDK tools directory in Command Prompt double click adb.exe

That's all

How can I install a .ipa file to my iPhone simulator

Copy From Here:
- Run the application in the Xcode. - Select Finder go to Go and click on select Library Library/Application Support/iPhone Simulator/7.0.3-64/Applications - Select 32 bit folder Copy your application.

Paste To Here:
- /Applications/Xcode-Beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhone Simulator. SDK/Applications
- Paste here and run the simulator.

Drawable image on a canvas

also you can use this way. it will change your big drawble fit to your canvas:

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

Java client certificates over HTTPS/SSL

If you are dealing with a web service call using the Axis framework, there is a much simpler answer. If all want is for your client to be able to call the SSL web service and ignore SSL certificate errors, just put this statement before you invoke any web services:

System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");

The usual disclaimers about this being a Very Bad Thing to do in a production environment apply.

I found this at the Axis wiki.

How to escape a JSON string containing newline characters using JavaScript?

this is an old post. but it may still be helpful for those using angular.fromJson, and JSON.stringify. escape() is deprecated. use this instead,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I just solved this error for myself, but it was a bit silly on my part. Still worth checking if the above doesn't help you.

In my case, I was editing the config files in /etc/phpmyadmin, my install was located in /usr/share/phpmyadmin, and my install was not actually opening the /etc/phpmyadmin config files, as I thought it would. So I just did this command:

ln -s /etc/phpmyadmin/conf* /usr/share/phpmyadmin

For those not in the know, ln -s makes a soft link (basically a shortcut). So that command just makes shortcuts from the config files in /etc to the /usr/share install.

By the way, I figured this out after using the program opensnoop, which shows you what files are being opened (technically, traces open() syscalls and the pid of the process, as they happen), which you can install on Ubuntu with apt-get install perf-tools-unstable, or you can get it here.

CSS3 Spin Animation

The only answer which gives the correct 359deg:

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}

&.active {
  animation: spin 1s linear infinite;
}

Here's a useful gradient so you can prove it is spinning (if its a circle):

background: linear-gradient(to bottom, #000000 0%,#ffffff 100%);

Detect click event inside iframe

I solved it by doing like this:

$('#filecontainer').load(function(){

        var iframe = $('#filecontainer').contents();

        iframe.find("#choose_pics").click(function(){
               alert("test");
        });
});

Converting byte array to String (Java)

The previous answer from Andreas_D is good. I'm just going to add that wherever you are displaying the output there will be a font and a character encoding and it may not support some characters.

To work out whether it is Java or your display that is a problem, do this:

    for(int i=0;i<str.length();i++) {
        char ch = str.charAt(i);
        System.out.println(i+" : "+ch+" "+Integer.toHexString(ch)+((ch=='\ufffd') ? " Unknown character" : ""));
    }

Java will have mapped any characters it cannot understand to 0xfffd the official character for unknown characters. If you see a '?' in the output, but it is not mapped to 0xfffd, it is your display font or encoding that is the problem, not Java.

SQL query to find third highest salary in company

you can find the third most salary with this query:

SELECT min(salary) 
FROM tblEmployee 
WHERE salary IN (SELECT TOP(3) salary 
                 FROM tblEmployee 
                 ORDER BY salary DESC)

Convert the first element of an array to a string in PHP

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8

Dart/Flutter : Converting timestamp

Just make sure to multiply by the right factor:

Micro: multiply by 1000000 (which is 10 power 6)

Milli: multiply by 1000 (which is 10 power 3)

This is what it should look like in Dart:

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);

Or

var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

Check that a variable is a number in UNIX shell

if echo $var | egrep -q '^[0-9]+$'

Actually this does not work if var is multiline.

ie

var="123
qwer"

Especially if var comes from a file :

var=`cat var.txt`

This is the simplest :

if [ "$var" -eq "$var" ] 2> /dev/null
then echo yes
else echo no
fi

Jquery, Clear / Empty all contents of tbody element?

        <table id="table_id" class="table table-hover">
          <thead>
            <tr>
             ...
             ...
            </tr>
          </thead>
        </table>

use this command to clear the body of that table: $("#table_id tbody").empty()

I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.

hope this helps you.

jQuery post() with serialize and extra data

In new version of jquery, could done it via following steps:

  • get param array via serializeArray()
  • call push() or similar methods to add additional params to the array,
  • call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.

Example code:

var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
    // ...
}

What is a CSRF token? What is its importance and how does it work?

The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.

Change/Get check state of CheckBox

I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

Inserting records into a MySQL table using Java

this can also be done like this if you don't want to use prepared statements.

String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"

Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.

Does a favicon have to be 32x32 or 16x16?

I don't see any up to date info listed here, so here goes:

To answer this question now, 2 favicons will not do it if you want your icon to look great everywhere. See the sizes below:

16 x 16 – Standard size for browsers
24 x 24 – IE9 pinned site size for user interface
32 x 32 – IE new page tab, Windows 7+ taskbar button, Safari Reading List sidebar
48 x 48 – Windows site
57 x 57 – iPod touch, iPhone up to 3G
60 x 60 – iPhone touch up to iOS7
64 x 64 – Windows site, Safari Reader List sidebar in HiDPI/Retina
70 x 70 – Win 8.1 Metro tile
72 x 72 – iPad touch up to iOS6
76 x 76 – iOS7
96 x 96 – GoogleTV
114 x 114 – iPhone retina touch up to iOS6
120 x 120 – iPhone retina touch iOS7
128 x 128 – Chrome Web Store app, Android
144 x 144 – IE10 Metro tile for pinned site, iPad retina up to iOS6
150 x 150 – Win 8.1 Metro tile
152 x 152 – iPad retina touch iOS7
196 x 196 – Android Chrome
310 x 150 – Win 8.1 wide Metro tile
310 x 310 – Win 8.1 Metro tile

What is meant by Ems? (Android TextView)

To add to the other answers in Android, Ems size, can, by default, vary in each language and input.

It means that if you want to set a minimum width to a text field, defined by number of chars, you have to calculate the Ems properly and set it, according to your typeface and font size with the Ems attribute.

To those of you struggle with this, you can calculate the hint size yourself to avoid messing with Ems:

val tf = TextField()
val layout = TextInputLayout()
val hint = "Hint"

val measureText = tf.paint.measureText(hint).toInt()
tf.width = tf.paddingLeft + tf.paddingRight + measureText.toInt()
layout.hint = hint

How to get the clicked link's href with jquery?

You're looking for $(this).attr("href");

How to grant all privileges to root user in MySQL 8.0

My Specs:

mysql --version
mysql  Ver 8.0.16 for Linux on x86_64 (MySQL Community Server - GPL)

What worked for me:

mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'desired_password';
mysql> GRANT ALL PRIVILEGES ON db_name.* TO 'username'@'localhost' WITH GRANT OPTION;

Response in both queries:

Query OK, O rows affected (0.10 sec*)

N.B: I created a database (db_name) earlier and was creating a user credential with all privileges granted to all tables in the DB in place of using the default root user which I read somewhere is a best practice.

Multi value Dictionary

Just create a Pair<TFirst, TSecond> type and use that as your value.

I have an example of one in my C# in Depth source code. Reproduced here for simplicity:

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
    : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first;
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second)
    {
        this.first = first;
        this.second = second;
    }

    public TFirst First
    {
        get { return first; }
    }

    public TSecond Second
    {
        get { return second; }
    }

    public bool Equals(Pair<TFirst, TSecond> other)
    {
        if (other == null)
        {
            return false;
        }
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
               EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

    public override bool Equals(object o)
    {
        return Equals(o as Pair<TFirst, TSecond>);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
               EqualityComparer<TSecond>.Default.GetHashCode(second);
    }
}

How to dynamically create a class?

You can also dynamically create a class by using DynamicObject.

public class DynamicClass : DynamicObject
{
    private Dictionary<string, KeyValuePair<Type, object>> _fields;

    public DynamicClass(List<Field> fields)
    {
        _fields = new Dictionary<string, KeyValuePair<Type, object>>();
        fields.ForEach(x => _fields.Add(x.FieldName,
            new KeyValuePair<Type, object>(x.FieldType, null)));
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_fields.ContainsKey(binder.Name))
        {
            var type = _fields[binder.Name].Key;
            if (value.GetType() == type)
            {
                _fields[binder.Name] = new KeyValuePair<Type, object>(type, value);
                return true;
            }
            else throw new Exception("Value " + value + " is not of type " + type.Name);
        }
        return false;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _fields[binder.Name].Value;
        return true;
    }
}

I store all class fields in a dictionary _fields together with their types and values. The both methods are to can get or set value to some of the properties. You must use the dynamic keyword to create an instance of this class.

The usage with your example:

var fields = new List<Field>() { 
    new Field("EmployeeID", typeof(int)),
    new Field("EmployeeName", typeof(string)),
    new Field("Designation", typeof(string)) 
};

dynamic obj = new DynamicClass(fields);

//set
obj.EmployeeID = 123456;
obj.EmployeeName = "John";
obj.Designation = "Tech Lead";

obj.Age = 25;             //Exception: DynamicClass does not contain a definition for 'Age'
obj.EmployeeName = 666;   //Exception: Value 666 is not of type String

//get
Console.WriteLine(obj.EmployeeID);     //123456
Console.WriteLine(obj.EmployeeName);   //John
Console.WriteLine(obj.Designation);    //Tech Lead

Edit: And here is how looks my class Field:

public class Field
{
    public Field(string name, Type type)
    {
        this.FieldName = name;
        this.FieldType = type;
    }

    public string FieldName;

    public Type FieldType;
}

Can I call a constructor from another constructor (do constructor chaining) in C++?

No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:

  • Overload the constructor, using different signatures
  • Use default values on arguments, to make a "simpler" version available

Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.

This is directly from the MSDN docs:

// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false 
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);

Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.

Failed to resolve: com.android.support:appcompat-v7:26.0.0

If you already use jitpack.io or any repository. You can add google repository like this:

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

how to stop Javascript forEach?

Below code will break the foreach loop once the condition is met, below is the sample example

    var array = [1,2,3,4,5];
    var newArray = array.slice(0,array.length);
    array.forEach(function(item,index){
        //your breaking condition goes here example checking for value 2
        if(item == 2){
            array.length = array.indexOf(item);
        }

    })
    array = newArray;

Git for beginners: The definitive practical guide

Push and pull changes

In an simplified way, just do git push and git pull. Changes are merged and if there's a conflict git will let you know and you can resolve it manually.

When you first push to a remote repository you need to do a git push origin master (master being the master branch). From then on you just do the git push.

Push tags with git push --tags.

How to do date/time comparison

Recent protocols prefer usage of RFC3339 per golang time package documentation.

In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs.

cutOffTime, _ := time.Parse(time.RFC3339, "2017-08-30T13:35:00Z")
// POSTDATE is a date time field in DB (datastore)
query := datastore.NewQuery("db").Filter("POSTDATE >=", cutOffTime).

Apache: The requested URL / was not found on this server. Apache

In httpd.conf file you need to remove #

#LoadModule rewrite_module modules/mod_rewrite.so

after removing # line will look like this:

LoadModule rewrite_module modules/mod_rewrite.so

And Apache restart

Ansible playbook shell output

The debug module could really use some love, but at the moment the best you can do is use this:

- hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
      register: ps

    - debug: var=ps.stdout_lines

It gives an output like this:

ok: [host1] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 1.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@notty ",
        " 0.2 root     java",
        " 0.0 root     sort -r -k1"
    ]
}
ok: [host2] => {
    "ps.stdout_lines": [
        "%CPU USER     COMMAND",
        " 4.0 root     /usr/bin/python",
        " 0.6 root     sshd: root@notty ",
        " 0.1 root     java",
        " 0.0 root     sort -r -k1"
    ]
}

How to restart counting from 1 after erasing table in MS Access?

I think the only ways to do this is outlined in this article.

The article explains several methods. Here is one example:

To do this in Microsoft Office Access 2007, follow these steps:

Delete the AutoNumber field from the main table.

  1. Make note of the AutoNumber field name.
  2. Click the Create tab, and then click Query Design in the Other group.
  3. In the Show Table dialog box, select the main table. Click Add, and then click Close.
  4. Double-click the required fields in the table view of the main table to select the fields.
  5. Select the required Sort order.
  6. On the Design tab, click Make Table in the Query Type group. Type the new table name in the Table Name box, and then click OK.
  7. On the Design tab, click Run in the Results group.
  8. The following message appears:

    You are about to paste # row(s) into a new table.

    Click Yes to insert the rows.
  9. Close the query.
  10. Right-click the new table, and then click Design View.
  11. In the Design view for the table, add an AutoNumber field that has the same field name that you deleted in step 1. Add this AutoNumber field to the new table, and then save the table.
  12. Close the Design view window.
  13. Rename the main table name. Rename the new table name to the main table name.

How can I declare a two dimensional string array?

When you are trying to create a multi-dimensional array all you need to do is add a comma to the declaration like so:

string[,] tablero = new string[3,3].

What's the best mock framework for Java?

I've had good success using Mockito.

When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).

I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.

Here's an (abridged) example from the Mockito homepage:

import static org.mockito.Mockito.*;

List mockedList = mock(List.class);
mockedList.clear();
verify(mockedList).clear();

It doesn't get much simpler than that.

The only major downside I can think of is that it won't mock static methods.

Call to a member function on a non-object

you can use 'use' in function like bellow example

function page_properties($objPortal) use($objPage){    
    $objPage->set_page_title($myrow['title']);
}

Chrome desktop notification example

See also ServiceWorkerRegistration.showNotification

It appears that window.webkitNotifications has already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  } else {
    alert(`Permission is ${Notification.permission}`);
  }
}

codepen

How to get xdebug var_dump to show full object/array

I know this is late but it might be of some use:

echo "<pre>";
print_r($array);
echo "</pre>";

Oracle 12c Installation failed to access the temporary location

Install it from CMD using the command

setup.exe -ignorePrereq -J"-Doracle.install.client.validate.clientSupportedOSCheck=false"

Reference

Div with margin-left and width:100% overflowing on the right side

I realise this is an old post but this might benefit somebody who, like me, has come to this page from a google search and is at their wits end.

None of the other answers given here worked for me and I had already given up hope, but today I was searching for a solution to another similar problem with divs, which I found answered multiple times on SO. The accepted answer worked for my div, and I had the sudden notion to try it for my previous textbox issue - and it worked! The solution:

add box-sizing: border-box to the style of the textbox.

To add this to all multi-line textboxes using CSS, add the following to your style sheet:

textarea
{
  box-sizing: border-box;
}

Thanks to thirtydot for the solution at

width: 100%-padding?

and

Content of div is longer then div itself when width is set to 100%?

Does "\d" in regex mean a digit?

\\d{3} matches any sequence of three digits in Java.

CSS3 gradient background set on body doesn't stretch but instead repeats?

instead of 100% i just add some pixxel got this now and it works for whole page without gap:

html {     
height: 1420px; } 
body {     
height: 1400px;     
margin: 0;     
background-repeat: no-repeat; }

How can I get a character in a string by index?

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Observable Finally on Subscribe

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

I think finalize() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

Jan 2019: Updated for RxJS 6

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

Failed to find 'ANDROID_HOME' environment variable

Execute: sudo gedit ~/.bashrc add

JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export JAVA_HOME
PATH=$PATH:$JAVA_HOME
export PATH
export ANDROID_HOME=~/Android/Sdk 
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

and

source ~/.bashrc

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

Reloading .env variables without restarting server (Laravel 5, shared hosting)

It's possible that your configuration variables are cached. Verify your config/app.php as well as your .env file then try

php artisan cache:clear

on the command line.

Is there a library function for Root mean square error (RMSE) in python?

Just in case someone finds this thread in 2019, there is a library called ml_metrics which is available without pre-installation in Kaggle's kernels, pretty lightweighted and accessible through pypi ( it can be installed easily and fast with pip install ml_metrics):

from ml_metrics import rmse
rmse(actual=[0, 1, 2], predicted=[1, 10, 5])
# 5.507570547286102

It has few other interesting metrics which are not available in sklearn, like mapk.

References:

Converting .NET DateTime to JSON

the conversion from 1970,1,1 needs the double rounded to zero decimal places i thinks

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);

on the client side i use

new Date(+data.replace(/\D/g, ''));

install / uninstall APKs programmatically (PackageManager vs Intents)

If you're using Kotlin, API 14+, and just wish to show uninstall dialog for your app:

startActivity(Intent(Intent.ACTION_UNINSTALL_PACKAGE).apply {
    data = Uri.parse("package:$packageName")
})

You can change packageName to any other package name if you want to prompt the user to uninstall another app on the device

Counting null and non-null values in a single query

Number of elements where a is null:

select count(a) from us where a is null;

Number of elements where a is not null:

select count(a) from us where a is not null;

Reading an Excel file in python using pandas

Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:

import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])

Since .sheet_names returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).

How do I concatenate strings in Swift?

This will work too:

var string = "swift"
var resultStr = string + " is a new Programming Language"

Change selected value of kendo ui dropdownlist

The Simplest way to do this is:

$("#Instrument").data('kendoDropDownList').value("A value");

Here is the JSFiddle example.

"inconsistent use of tabs and spaces in indentation"

Sublime Text 3

In Sublime Text, WHILE editing a Python file:

Sublime Text menu > Preferences > Settings - Syntax Specific :

Python.sublime-settings

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

Use JAXB to create Object from XML String

To pass XML content, you need to wrap the content in a Reader, and unmarshal that instead:

JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);

What does 'corrupted double-linked list' mean

I have found the answer to my question myself:)

So what I didn't understand was how the glibc could differentiate between a Segfault and a corrupted double-linked list, because according to my understanding, from perspective of glibc they should look like the same thing. Because if I implement a double-linked list inside my program, how could the glibc possibly know that this is a double-linked list, instead of any other struct? It probably can't, so thats why i was confused.

Now I've looked at malloc/malloc.c inside the glibc's code, and I see the following:

1543 /* Take a chunk off a bin list */
1544 #define unlink(P, BK, FD) {                                            \
1545   FD = P->fd;                                                          \
1546   BK = P->bk;                                                          \
1547   if (__builtin_expect (FD->bk != P || BK->fd != P, 0))                \
1548     malloc_printerr (check_action, "corrupted double-linked list", P); \
1549   else {                                                               \
1550     FD->bk = BK;                                                       \
1551     BK->fd = FD;                                                       \

So now this suddenly makes sense. The reason why glibc can know that this is a double-linked list is because the list is part of glibc itself. I've been confused because I thought glibc can somehow detect that some programming is building a double-linked list, which I wouldn't understand how that works. But if this double-linked list that it is talking about, is part of glibc itself, of course it can know it's a double-linked list.

I still don't know what has triggered this error. But at least I understand the difference between corrupted double-linked list and a Segfault, and how the glibc can know this struct is supposed to be a double-linked list:)

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

Overlapping Views in Android

Yes, that is possible. The challenge, however, is to do their layout properly. The easiest way to do it would be to have an AbsoluteLayout and then put the two images where you want them to be. You don't need to do anything special for the transparent png except having it added later to the layout.

Nullable type as a generic parameter possible?

Just do two things to your original code – remove the where constraint, and change the last return from return null to return default(T). This way you can return whatever type you want.

By the way, you can avoid the use of is by changing your if statement to if (columnValue != DBNull.Value).

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Give the relative path URL value to the pom.xml file
../parentfoldername/pom.xml

OSError: [Errno 8] Exec format error

I will hijack this thread to point out that this error may also happen when target of Popen is not executable. Learnt it hard way when by accident I have had override a perfectly executable binary file with zip file.

Fast and simple String encrypt/decrypt in JAVA

Java - encrypt / decrypt user name and password from a configuration file

Code from above link

DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........

// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");      

Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it 
......

// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);

Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

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

On Windows 10 - This happened for me after the latest update in 2020.

What solved this issue for me was running the following in PowerShell

C:\>Install-Module -Name MicrosoftPowerBIMgmt

Submit Button Image

<INPUT TYPE="image" SRC="images/submit.gif" HEIGHT="30" WIDTH="173" BORDER="0" ALT="Submit Form">
Where the standard submit button has TYPE="submit", we now have TYPE="image". The image type is by default a form submitting button. More simple

Putting HTML inside Html.ActionLink(), plus No Link Text?

It's very simple.

If you want to have something like a glyphicon icon and then "Wish List",

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")

Eclipse does not start when I run the exe?

re install your java. First check your OS version.

Determining if Swift dictionary contains key and obtaining any of its values

My solution for a cache implementation that stores optional NSAttributedString:

public static var attributedMessageTextCache    = [String: NSAttributedString?]()

    if attributedMessageTextCache.index(forKey: "key") != nil
    {
        if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
        {
            return attributedMessageText
        }
        return nil
    }

    TextChatCache.attributedMessageTextCache["key"] = .some(.none)
    return nil

How to convert string to XML using C#

// using System.Xml;

String rawXml =
      @"<root>
          <person firstname=""Riley"" lastname=""Scott"" />
          <person firstname=""Thomas"" lastname=""Scott"" />
      </root>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);

I think this should work.

Why are C++ inline functions in the header?

The c++ inline keyword is misleading, it doesn't mean "inline this function". If a function is defined as inline, it simply means that it can be defined multiple times as long as all definitions are equal. It's perfectly legal for a function marked inline to be a real function that is called instead of getting code inlined at the point where it's called.

Defining a function in a header file is needed for templates, since e.g. a templated class isn't really a class, it's a template for a class which you can make multiple variations of. In order for the compiler to be able to e.g. make a Foo<int>::bar() function when you use the Foo template to create a Foo class, the actual definition of Foo<T>::bar() must be visible.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

How to print Boolean flag in NSLog?

Note that in Swift, you can just do

let testBool: Bool = true
NSLog("testBool = %@", testBool.description)

This will log testBool = true

Is it possible to use jQuery .on and hover?

Just surfed in from the web and felt I could contribute. I noticed that with the above code posted by @calethebrewer can result in multiple calls over the selector and unexpected behaviour for example: -

$(document).on('mouseover', '.selector', function() {
   //do something
});
$(document).on('mouseout', '.selector', function() {
   //do something
});

This fiddle http://jsfiddle.net/TWskH/12/ illustraits my point. When animating elements such as in plugins I have found that these multiple triggers result in unintended behavior which may result in the animation or code being called more than is necessary.

My suggestion is to simply replace with mouseenter/mouseleave: -

$(document).on('mouseenter', '.selector', function() {
   //do something
});
$(document).on('mouseleave', '.selector', function() {
   //do something
});

Although this prevented multiple instances of my animation from being called, I eventually went with mouseover/mouseleave as I needed to determine when children of the parent were being hovered over.

Perform Button click event when user press Enter key in Textbox

In the aspx page load event, add an onkeypress to the box.

this.TextBox1.Attributes.Add(
    "onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");

Then add this javascript to evaluate the key press, and if it is "enter," click the right button.

<script>
    function button_click(objTextBox,objBtnID)
    {
        if(window.event.keyCode==13)
        {
            document.getElementById(objBtnID).focus();
            document.getElementById(objBtnID).click();
        }
    }
</script>

How to select all textareas and textboxes using jQuery?

$('input[type=text], textarea').css({width: '90%'});

That uses standard CSS selectors, jQuery also has a set of pseudo-selector filters for various form elements, for example:

$(':text').css({width: '90%'});

will match all <input type="text"> elements. See Selectors documentation for more info.

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

The $_post function need the name value like:

<input type="submit" value"Submit" name="example">

Call

$var = strip_tags($_POST['example']);
if (isset($var)){
    // your code here
}

Get cart item name, quantity all details woocommerce

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:

foreach ( WC()->cart->get_cart() as $cart_item ) {
   $item_name = $cart_item['data']->get_title();
   $quantity = $cart_item['quantity'];
   $price = $cart_item['data']->get_price();
   ...

This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

Set width to match constraints in ConstraintLayout

If you want TextView in the center of parent..
Your main layout is Constraint Layout

<androidx.appcompat.widget.AppCompatTextView
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:text="@string/logout"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     android:gravity="center">
</androidx.appcompat.widget.AppCompatTextView>

How to replace ${} placeholders in a text file?

Sed!

Given template.txt:

The number is ${i}
The word is ${word}

we just have to say:

sed -e "s/\${i}/1/" -e "s/\${word}/dog/" template.txt

Thanks to Jonathan Leffler for the tip to pass multiple -e arguments to the same sed invocation.

Http Get using Android HttpURLConnection

URL url = new URL("https://www.google.com");

//if you are using

URLConnection conn =url.openConnection();

//change it to

HttpURLConnection conn =(HttpURLConnection )url.openConnection();

tap gesture recognizer - which object was tapped?

Here is an update for Swift 3 and an addition to Mani's answer. I would suggest using sender.view in combination with tagging UIViews (or other elements, depending on what you are trying to track) for a somewhat more "advanced" approach.

  1. Adding the UITapGestureRecognizer to e.g. an UIButton (you can add this to UIViews etc. as well) Or a whole bunch of items in an array with a for-loop and a second array for the tap gestures.
    let yourTapEvent = UITapGestureRecognizer(target: self, action: #selector(yourController.yourFunction)) 
    yourObject.addGestureRecognizer(yourTapEvent) // adding the gesture to your object
  1. Defining the function in the same testController (that's the name of your View Controller). We are going to use tags here - tags are Int IDs, which you can add to your UIView with yourButton.tag = 1. If you have a dynamic list of elements like an array you can make a for-loop, which iterates through your array and adds a tag, which increases incrementally

    func yourFunction(_ sender: AnyObject) {
        let yourTag = sender.view!.tag // this is the tag of your gesture's object
        // do whatever you want from here :) e.g. if you have an array of buttons instead of just 1:
        for button in buttonsArray {
          if(button.tag == yourTag) {
            // do something with your button
          }
        }
    }
    

The reason for all of this is because you cannot pass further arguments for yourFunction when using it in conjunction with #selector.

If you have an even more complex UI structure and you want to get the parent's tag of the item attached to your tap gesture you can use let yourAdvancedTag = sender.view!.superview?.tag e.g. getting the UIView's tag of a pressed button inside that UIView; can be useful for thumbnail+button lists etc.

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

How to play a sound in C#, .NET

I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();

This is another way to play sound.

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

How to shutdown a Spring Boot Application in a correct way?

SpringApplication implicitly registers a shutdown hook with the JVM to ensure that ApplicationContext is closed gracefully on exit. That will also call all bean methods annotated with @PreDestroy. That means we don't have to explicitly use the registerShutdownHook() method of a ConfigurableApplicationContext in a boot application, like we have to do in spring core application.

@SpringBootConfiguration
public class ExampleMain {
    @Bean
    MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ExampleMain.class, args);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.doSomething();

        //no need to call context.registerShutdownHook();
    }

    private static class MyBean {

        @PostConstruct
        public void init() {
            System.out.println("init");
        }

        public void doSomething() {
            System.out.println("in doSomething()");
        }

        @PreDestroy
        public void destroy() {
            System.out.println("destroy");
        }
    }
}

Rounding SQL DateTime to midnight

This might look cheap but it's working for me

SELECT CONVERT(DATETIME,LEFT(CONVERT(VARCHAR,@dateFieldOrVariable,101),10)+' 00:00:00.000')

How do I instantiate a JAXBElement<String> object?

Here is how I do it. You will need to get the namespace URL and the element name from your generated code.

new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
                new String("").getClass(),testDN);

How to retrieve the current value of an oracle sequence without increment it?

If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual from the backend.

Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...

What is the maximum length of a URL in different browsers?

The URI RFC (of which URLs are a subset) doesn't define a maximum length, however, it does recommend that the hostname part of the URI (if applicable) not exceed 255 characters in length:

URI producers should use names that conform to the DNS syntax, even when use of DNS is not immediately apparent, and should limit these names to no more than 255 characters in length.

As noted in other posts though, some browsers have a practical limitation on the length of a URL.

How set the android:gravity to TextView from Java side in Android

Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");

Filter values only if not null using lambda in Java8

you can use this

List<Car> requiredCars = cars.stream()
    .filter (t->  t!= null && StringUtils.startsWith(t.getName(),"M"))
    .collect(Collectors.toList());

git visual diff between branches

You can also do this easily with gitk.

> gitk branch1 branch2

First click on the tip of branch1. Now right-click on the tip of branch2 and select Diff this->selected.

How to exit an application properly

In a console application, just return from the main program, in a UI-Application Close() all active Forms.

Memory from managed objects will be handled by the .NET Framework, you don't need to care about this.

If you use classes which implement IDisposable (like database connections, for example), you should call Dispose() on them when you no longer need them (preferred way: a using-Statement).

If you use such resources globally (like private members in your form), your form should implement the IDisposable pattern to release these resources on the Close()-call. See this article for details.

Is null check needed before calling instanceof?

No. Java literal null is not an instance of any class. Therefore it can not be an instanceof any class. instanceof will return either false or true therefore the <referenceVariable> instanceof <SomeClass> returns false when referenceVariable value is null.

Preventing an image from being draggable or selectable without using JS

Set the following CSS properties to the image:

user-drag: none; 
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;

How to get config parameters in Symfony2 Twig Templates

Easily, you can define in your config file:

twig:
    globals:
        version: "0.1.0"

And access it in your template with

{{ version }}

Otherwise it must be a way with an Twig extension to expose your parameters.

How to get VM arguments from inside of Java application?

If you want the entire command line of your java process, you can use: JvmArguments.java (uses a combination of JNA + /proc to cover most unix implementations)

Apply vs transform on a group object

Two major differences between apply and transform

There are two major differences between the transform and apply groupby methods.

  • Input:
  • apply implicitly passes all the columns for each group as a DataFrame to the custom function.
  • while transform passes each column for each group individually as a Series to the custom function.
  • Output:
  • The custom function passed to apply can return a scalar, or a Series or DataFrame (or numpy array or even list).
  • The custom function passed to transform must return a sequence (a one dimensional Series, array or list) the same length as the group.

So, transform works on just one Series at a time and apply works on the entire DataFrame at once.

Inspecting the custom function

It can help quite a bit to inspect the input to your custom function passed to apply or transform.

Examples

Let's create some sample data and inspect the groups so that you can see what I am talking about:

import pandas as pd
import numpy as np
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6,10,3,11]})

     State  a   b
0    Texas  4   6
1    Texas  5  10
2  Florida  1   3
3  Florida  3  11

Let's create a simple custom function that prints out the type of the implicitly passed object and then raised an error so that execution can be stopped.

def inspect(x):
    print(type(x))
    raise

Now let's pass this function to both the groupby apply and transform methods to see what object is passed to it:

df.groupby('State').apply(inspect)

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
RuntimeError

As you can see, a DataFrame is passed into the inspect function. You might be wondering why the type, DataFrame, got printed out twice. Pandas runs the first group twice. It does this to determine if there is a fast way to complete the computation or not. This is a minor detail that you shouldn't worry about.

Now, let's do the same thing with transform

df.groupby('State').transform(inspect)
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
RuntimeError

It is passed a Series - a totally different Pandas object.

So, transform is only allowed to work with a single Series at a time. It is impossible for it to act on two columns at the same time. So, if we try and subtract column a from b inside of our custom function we would get an error with transform. See below:

def subtract_two(x):
    return x['a'] - x['b']

df.groupby('State').transform(subtract_two)
KeyError: ('a', 'occurred at index a')

We get a KeyError as pandas is attempting to find the Series index a which does not exist. You can complete this operation with apply as it has the entire DataFrame:

df.groupby('State').apply(subtract_two)

State     
Florida  2   -2
         3   -8
Texas    0   -2
         1   -5
dtype: int64

The output is a Series and a little confusing as the original index is kept, but we have access to all columns.


Displaying the passed pandas object

It can help even more to display the entire pandas object within the custom function, so you can see exactly what you are operating with. You can use print statements by I like to use the display function from the IPython.display module so that the DataFrames get nicely outputted in HTML in a jupyter notebook:

from IPython.display import display
def subtract_two(x):
    display(x)
    return x['a'] - x['b']

Screenshot: enter image description here


Transform must return a single dimensional sequence the same size as the group

The other difference is that transform must return a single dimensional sequence the same size as the group. In this particular instance, each group has two rows, so transform must return a sequence of two rows. If it does not then an error is raised:

def return_three(x):
    return np.array([1, 2, 3])

df.groupby('State').transform(return_three)
ValueError: transform must return a scalar value for each group

The error message is not really descriptive of the problem. You must return a sequence the same length as the group. So, a function like this would work:

def rand_group_len(x):
    return np.random.rand(len(x))

df.groupby('State').transform(rand_group_len)

          a         b
0  0.962070  0.151440
1  0.440956  0.782176
2  0.642218  0.483257
3  0.056047  0.238208

Returning a single scalar object also works for transform

If you return just a single scalar from your custom function, then transform will use it for each of the rows in the group:

def group_sum(x):
    return x.sum()

df.groupby('State').transform(group_sum)

   a   b
0  9  16
1  9  16
2  4  14
3  4  14

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

You can use a lookaround:

^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$

It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.

UPDATE:

Adding modifications suggested by Chris Lutz:

^(?=.*[^\W_])[\w ]*$/

Close all infowindows in Google Maps API v3

You should have to click your map - $('#map-selector').click();

PNG transparency issue in IE8

please try below code.

 background: transparent\0/;
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png');   /* IE7 */      
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */   

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

systemd

sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

sysvinit

sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Android Studio (Preview) sometimes recommends updating to a Gradle Plugin that is not available yet (did Google forget to publish it?). Such as today with

'com.android.tools.build:gradle:3.1.0-beta1'

I found I can see current versions of com.android.tools.build:gradle here, and then I just pick the newest:

https://dl.google.com/dl/android/maven2/index.html

I just found this beta1 gradle bug in the Android Bug Tracker. I also just learned Android Studio > Help Menu > Submit Feedback brought me to the bug tracker.

Found temporary solution at androiddev reddit for the 3.1.0-beta1 problem: Either roll back to Preview Canary 8, or switch to gradle plugin 3.0.1 until Canary 10 is released shortly.

What is username and password when starting Spring Boot with Tomcat?

Addition to accepted answer -

If password not seen in logs, enable "org.springframework.boot.autoconfigure.security" logs.

If you fine-tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO messages, otherwise the default password will not be printed.

https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/htmlsingle/#boot-features-security

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

Generate JSON string from NSDictionary in iOS

Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).

@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end

.

@implementation NSDictionary (BVJSONString)

  -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
     NSError *error;
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                   options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                     error:&error];

     if (! jsonData) {
        NSLog(@"%s: error: %@", __func__, error.localizedDescription);
        return @"{}";
     } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     } 
 }
@end

.

@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end

.

@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                       options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"%s: error: %@", __func__, error.localizedDescription);
        return @"[]";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}
@end

Parse usable Street Address, City, State, Zip from a string

I've been working in the address processing domain for about 5 years now, and there really is no silver bullet. The correct solution is going to depend on the value of the data. If it's not very valuable, throw it through a parser as the other answers suggest. If it's even somewhat valuable you'll definitely need to have a human evaluate/correct all the results of the parser. If you're looking for a fully automated, repeatable solution, you probably want to talk to a address correction vendor like Group1 or Trillium.

Running a script inside a docker container using shell script

Assuming that your docker container is up and running, you can run commands as:

docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"

PHP: If internet explorer 6, 7, 8 , or 9

PHP has a function called get_browser() that will return an object (or array if you so choose) with details about the users' browser and what it can do.

A simple look through gave me this code:

$browser = get_browser( null, true );
if( $browser['name'] == "Firefox" )
    if( $browser['majorversion'] == 4 )
        echo "You're using Firefox version 4!";

This is not a surefire way (as it reads from HTTP_USER_AGENT, which can be spoofed, and will sometimes be analyzed wrong by php), but it's the easiest one that you can find as far as I know.

React: why child component doesn't update when prop changes

I had the same problem. This is my solution, I'm not sure that is the good practice, tell me if not:

state = {
  value: this.props.value
};

componentDidUpdate(prevProps) {
  if(prevProps.value !== this.props.value) {
    this.setState({value: this.props.value});
  }
}

UPD: Now you can do the same thing using React Hooks: (only if component is a function)

const [value, setValue] = useState(propName);
// This will launch only if propName value has chaged.
useEffect(() => { setValue(propName) }, [propName]);

How can I create a progress bar in Excel VBA?

You can add a Form and name it as Form1, add a Frame to it as Frame1 as well as Label1 too. Set Frame1 width to 200, Back Color to Blue. Place the code in the module and check if it helps.

    Sub Main()
    Dim i As Integer
    Dim response
    Form1.Show vbModeless
    Form1.Frame1.Width = 0
    For i = 10 To 10000
        With Form1
            .Label1.Caption = Round(i / 100, 0) & "%"
            .Frame1.Width = Round(i / 100, 0) * 2
             DoEvents
        End With
    Next i

    Application.Wait Now + 0.0000075

    Unload Form1

    response = MsgBox("100% Done", vbOKOnly)

    End Sub

If you want to display on the Status Bar then you can use other way that's simpler:

   Sub Main()
   Dim i As Integer
   Dim response
   For i = 10 To 10000
        Application.StatusBar = Round(i / 100, 0) & "%"
   Next i

   Application.Wait Now + 0.0000075

   response = MsgBox("100% Done", vbOKOnly)

   End Sub

How can I regenerate ios folder in React Native project?

Since react-native eject is depreciated in 60.3 and I was getting diff errors trying to upgrade form 60.1 to 60.3 regenerating the android folder was not working.

I had to

rm -R node_modules

Then update react-native in package.json to 59.1 (remove package-lock.json)

Run

npm install

react-native eject

This will regenerate your android and ios folders Finally upgrade back to 60.3

react-native upgrade

react-native upgrade while back and 59.1 did not regenerate my android folder so the eject was necessary.

Java - Check if input is a positive integer, negative integer, natural number and so on.

If you really have to avoid operators then use Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:

Integer.signum(int i)

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Convert List<DerivedClass> to List<BaseClass>

If you use IEnumerable instead, it will work (at least in C# 4.0, I have not tried previous versions). This is just a cast, of course, it will still be a list.

Instead of -

List<A> listOfA = new List<C>(); // compiler Error

In the original code of the question, use -

IEnumerable<A> listOfA = new List<C>(); // compiler error - no more! :)

How can I use break or continue within for loop in Twig template?

From @NHG comment — works perfectly

{% for post in posts|slice(0,10) %}

Relative Paths in Javascript in an external file

I used pekka's pattern. I think yet another pattern.

<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">

and parsed querystring in myjsfile.js.

Plugins | jQuery Plugins

Android ListView not refreshing after notifyDataSetChanged

Try this

@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
adapter = new ItemAdapter(getActivity(), items);//reload the items from database
adapter.notifyDataSetChanged();
}

How to trigger Jenkins builds remotely and to pass parameters

You can trigger Jenkins builds remotely and to pass parameters by using the following query.

JENKINS_URL/job/job-name/buildWithParameters?token=TOKEN_NAME&param_name1=value&param_name1=value

JENKINS_URL (can be) = https://<your domain name or server address>

TOKE_NAME can be created using configure tab

How to change theme for AlertDialog

 <style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">@color/colorAccent</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">@color/teal</item>
</style>





new AlertDialog.Builder(new ContextThemeWrapper(context,R.style.AlertDialogCustom))
            .setMessage(Html.fromHtml(Msg))
            .setPositiveButton(posBtn, okListener)
            .setNegativeButton(negBtn, null)
            .create()
            .show();

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".