Programs & Examples On #Password confirmation

Write / add data in JSON file using Node.js

I agree with above answers, Here is a complete read and write sample for anyone who needs it.

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  

What is an abstract class in PHP?

An abstract class is like the normal class it contains variables it contains protected variables functions it contains constructor only one thing is different it contains abstract method.

The abstract method means an empty method without definition so only one difference in abstract class we can not create an object of abstract class

Abstract must contains the abstract method and those methods must be defined in its inheriting class.

How to set a value of a variable inside a template code?

Perhaps the default template filter wasn't an option back in 2009...

<html>
<div>Hello {{name|default:"World"}}!</div>
</html>

Set time to 00:00:00

You would better to primarily set time zone to the DateFormat component like this:

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Then you can get "00:00:00" time by passing 0 milliseconds to formatter:

String time = dateFormat.format(0);

or you can create Date object:

Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);

or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);

dateFormat.format(calendar.getTime());

Resolving require paths with webpack

I have resolve it with Webpack 2 like this:

module.exports = {
  resolve: {
    modules: ["mydir", "node_modules"]    
  }
}

You can add more directories to array...

Get most recent row for given ID

Select [insert your fields here]
from tablename 
where signin = (select max(signin) from tablename where ID = 1)

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

Convert Json String to C# Object List

The variables/parameters within the class definition requires { get; set; } I was using like a variable declaration (stupid of me, because it was working for other scenarios) without

{ get; set; }

Because of which, whatever I send from the JavaScript, it was not being received in the Action method. It was always getting null or empty model.

Once the {get; set;} is added, it worked like charm.

I hope it helps someone who is coming from VB6 style of programming line.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

You can suppress basic auth popup with request url looking like this:

https://username:[email protected]/admin/...

If you get 401 error (wrong username or password) it will be correctly handled with jquery error callback. It can cause some security issues (in case of http protocol instead of https), but it's works.

UPD: This solution support will be removed in Chrome 59

Using Python's os.path, how do I go up one directory?

Go up a level from the work directory

import os
os.path.dirname(os.getcwd())

or from the current directory

import os
os.path.dirname('current path')

Git asks for username every time I push

In addition to user701648's answer, you can store your credentials in your home folder (global for all projects), instead of project folder using the following command

$ git config --global credential.helper store
$ git push http://example.com/repo.git
Username: <type your username>
Password: <type your password>

JavaScript function in href vs. onclick

it worked for me using this line of code:

<a id="LinkTest" title="Any Title"  href="#" onclick="Function(); return false; ">text</a>

How do I draw a shadow under a UIView?

Sketch Shadow Using IBDesignable and IBInspectable in Swift 4

HOW TO USE IT

DEMO

SKETCH AND XCODE SIDE BY SIDE

Shadow Exampl

CODE

@IBDesignable class ShadowView: UIView {

    @IBInspectable var shadowColor: UIColor? {
        get {
            if let color = layer.shadowColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.shadowColor = color.cgColor
            } else {
                layer.shadowColor = nil
            }
        }
    }

    @IBInspectable var shadowOpacity: Float {
        get {
            return layer.shadowOpacity
        }
        set {
            layer.shadowOpacity = newValue
        }
    }

    @IBInspectable var shadowOffset: CGPoint {
        get {
            return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
        }
        set {
            layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
        }

     }

    @IBInspectable var shadowBlur: CGFloat {
        get {
            return layer.shadowRadius
        }
        set {
            layer.shadowRadius = newValue / 2.0
        }
    }

    @IBInspectable var shadowSpread: CGFloat = 0 {
        didSet {
            if shadowSpread == 0 {
                layer.shadowPath = nil
            } else {
                let dx = -shadowSpread
                let rect = bounds.insetBy(dx: dx, dy: dx)
                layer.shadowPath = UIBezierPath(rect: rect).cgPath
            }
        }
    }
}

OUTPUT

DEMO OUTPUT

How to connect to LocalDb

I am totally unable to connect to localdb with any tool including MSSMA, sqlcmd, etc. You would think Microsoft would document this, but I find nothing on MSDN. I have v12 and tried (localdb)\v12.0 and that didn't work. Issuing the command sqllocaldb i MSSQLLocalDB shows that the local instance is running, but there is no way to connect to it.

c:\> sqllocaldb i MSSQLLocalDB
Name:               MSSQLLocalDB
Version:            12.0.2000.8
Shared name:
Owner:              CWOLF-PC\cwolf
Auto-create:        Yes
State:              Running
Last start time:    6/12/2014 8:34:11 AM
Instance pipe name: np:\\.\pipe\LOCALDB#C86052DD\tsql\query
c:\>
c:\> sqlcmd -L

Servers:
    ;UID:Login ID=?;PWD:Password=?;Trusted_Connection:Use Integrated Security=?;
*APP:AppName=?;*WSID:WorkStation ID=?;

I finally figured it out!! the connect string is (localdb)\MSSQLLocalDB, e.g.:

$ sqlcmd -S \(localdb\)\\MSSQLLocalDB
1> select 'hello!'
2> go

------
hello!

(1 rows affected)    

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().

Android customized button; changing text color

ok very simple first go to 1. res-valuse and open colors.xml 2.copy 1 of the defined text their for example #FF4081 and change name for instance i changed to white and change its value for instance i changed to #FFFFFF for white value like this

<color name="White">#FFFFFF</color>

then inside your button add this line

 b3.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.White));

ok b3 is the name of my button so changed of the name of ur button all others will be same if u use white color if you change different color then change white to the name of your color but first you have define that color in colors.xml like i explained in pont 2

How to see log files in MySQL?

In addition to the answers above you can pass in command line parameters to the mysqld process for logging options instead of manually editing your conf file. For example, to enable general logging and specifiy a file:

mysqld --general-log --general-log-file=/var/log/mysql.general.log

Confirming other answers above, mysqld --help --verbose gives you the values from the conf file (so running with command line options general-log is FALSE); whereas mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log gives:

general_log     ON
general_log_file        /var/log/mysql.general.log

Use slightly more compact syntax for the error log:

mysqld --general-log --general-log-file=/var/log/mysql.general.log --log-error=/var/log/mysql.error.log

Vertically align text to top within a UILabel

What I did in my app was to set the UILabel's line property to 0 as well as to create a bottom constraint of the UILabel and make sure it is being set to >= 0 as shown in the image below. enter image description here

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

Calculate cosine similarity given 2 sentence strings

A simple pure-Python implementation would be:

import math
import re
from collections import Counter

WORD = re.compile(r"\w+")


def get_cosine(vec1, vec2):
    intersection = set(vec1.keys()) & set(vec2.keys())
    numerator = sum([vec1[x] * vec2[x] for x in intersection])

    sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
    sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
    denominator = math.sqrt(sum1) * math.sqrt(sum2)

    if not denominator:
        return 0.0
    else:
        return float(numerator) / denominator


def text_to_vector(text):
    words = WORD.findall(text)
    return Counter(words)


text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."

vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)

cosine = get_cosine(vector1, vector2)

print("Cosine:", cosine)

Prints:

Cosine: 0.861640436855

The cosine formula used here is described here.

This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.

You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.

How do I get formatted JSON in .NET using C#?

You are going to have a hard time accomplishing this with JavaScriptSerializer.

Try JSON.Net.

With minor modifications from JSON.Net example

using System;
using Newtonsoft.Json;

namespace JsonPrettyPrint
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Product product = new Product
                {
                    Name = "Apple",
                    Expiry = new DateTime(2008, 12, 28),
                    Price = 3.99M,
                    Sizes = new[] { "Small", "Medium", "Large" }
                };

            string json = JsonConvert.SerializeObject(product, Formatting.Indented);
            Console.WriteLine(json);

            Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
        }
    }

    internal class Product
    {
        public String[] Sizes { get; set; }
        public decimal Price { get; set; }
        public DateTime Expiry { get; set; }
        public string Name { get; set; }
    }
}

Results

{
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ],
  "Price": 3.99,
  "Expiry": "\/Date(1230447600000-0700)\/",
  "Name": "Apple"
}

Documentation: Serialize an Object

JBoss AS 7: How to clean up tmp?

As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time

Before

jboss-as-7
 |
 |---> standalone
 |      |----> lib
 |      |----> configuration
 |      |----> deployments
 |      
 |---> domain
 |....

After

jboss-as-7
     |
     |---> standalone
     |      |----> lib
     |      |----> configuration
     |      |----> deployments
     |      |----> tmp
     |      |----> data
     |      |----> log
     |      
     |---> domain
     |....

As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.

For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.

Good luck!

Convert pandas Series to DataFrame

to_frame():

Starting with the following Series, df:

email
[email protected]    A
[email protected]    B
[email protected]    C
dtype: int64

I use to_frame to convert the series to DataFrame:

df = df.to_frame().reset_index()

    email               0
0   [email protected]    A
1   [email protected]    B
2   [email protected]    C
3   [email protected]    D

Now all you need is to rename the column name and name the index column:

df = df.rename(columns= {0: 'list'})
df.index.name = 'index'

Your DataFrame is ready for further analysis.

Update: I just came across this link where the answers are surprisingly similar to mine here.

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

How do I initialise all entries of a matrix with a specific value?

Given a predefined m-by-n matrix size and the target value val, in your example:

m = 1;
n = 10;
val = 5;

there are currently 7 different approaches that come to my mind:


1) Using the repmat function (0.094066 seconds)

A = repmat(val,m,n)

2) Indexing on the undefined matrix with assignment (0.091561 seconds)

A(1:m,1:n) = val

3) Indexing on the target value using the ones function (0.151357 seconds)

A = val(ones(m,n))

4) Default initialization with full assignment (0.104292 seconds)

A = zeros(m,n);
A(:) = val

5) Using the ones function with multiplication (0.069601 seconds)

A = ones(m,n) * val

6) Using the zeros function with addition (0.057883 seconds)

A = zeros(m,n) + val

7) Using the repelem function (0.168396 seconds)

A = repelem(val,m,n)

After the description of each approach, between parentheses, its corresponding benchmark performed under Matlab 2017a and with 100000 iterations. The winner is the 6th approach, and this doesn't surprise me.

The explaination is simple: allocation generally produces zero-filled slots of memory... hence no other operations are performed except the addition of val to every member of the matrix, and on the top of that, input arguments sanitization is very short.

The same cannot be said for the 5th approach, which is the second fastest one because, despite the input arguments sanitization process being basically the same, on memory side three operations are being performed instead of two:

  • the initial allocation
  • the transformation of every element into 1
  • the multiplication by val

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

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

This examples waits 1 second after each request before sending the next one.

Angular 2 change event - model changes

If this helps you,

<input type="checkbox"  (ngModelChange)="mychange($event)" [ngModel]="mymodel">

mychange(val)
{
   console.log(val); // updated value
}

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

How can I use different certificates on specific connections?

If creating a SSLSocketFactory is not an option, just import the key into the JVM

  1. Retrieve the public key: $openssl s_client -connect dev-server:443, then create a file dev-server.pem that looks like

    -----BEGIN CERTIFICATE----- 
    lklkkkllklklklklllkllklkl
    lklkkkllklklklklllkllklkl
    lklkkkllklk....
    -----END CERTIFICATE-----
    
  2. Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem. Password: changeit

  3. Restart JVM

Source: How to solve javax.net.ssl.SSLHandshakeException?

Writing to a file in a for loop

It's preferable to use context managers to close the files automatically

with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
    for line in textfile:
        var1, var2 = line.split(",");
        myfile.writelines(var1)

No assembly found containing an OwinStartupAttribute Error

just paste this code <add key="owin:AutomaticAppStartup" value="false" /> in Web.config Not In web.config there is two webconfig so be sure that it will been paste in Web.Config

How do I automatically scroll to the bottom of a multiline text box?

This only worked for me...

txtSerialLogging->Text = "";

txtSerialLogging->AppendText(s);

I tried all the cases above, but the problem is in my case text s can decrease, increase and can also remain static for a long time. static means , static length(lines) but content is different.

So, I was facing one line jumping situation at the end when the length(lines) remains same for some times...

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

How do I execute a command and get the output of the command within C++ using POSIX?

C++ stream implemention of waqas's answer:

#include <istream>
#include <streambuf>
#include <cstdio>
#include <cstring>
#include <memory>
#include <stdexcept>
#include <string>

class execbuf : public std::streambuf {
    protected:
        std::string output;
        int_type underflow(int_type character) {
            if (gptr() < egptr()) return traits_type::to_int_type(*gptr());
            return traits_type::eof();
        }
    public:
        execbuf(const char* command) {
            std::array<char, 128> buffer;
            std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command, "r"), pclose);
            if (!pipe) {
                throw std::runtime_error("popen() failed!");
            }
            while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
                this->output += buffer.data();
            }
            setg((char*)this->output.data(), (char*)this->output.data(), (char*)(this->output.data() + this->output.size()));
        }
};

class exec : public std::istream {
    protected:
        execbuf buffer;
    public:
        exec(char* command) : std::istream(nullptr), buffer(command, fd) {
            this->rdbuf(&buffer);
        }
};

This code catches all output through stdout . If you want to catch only stderr then pass your command like this:

sh -c '<your-command>' 2>&1 > /dev/null

If you want to catch both stdout and stderr then the command should be like this:

sh -c '<your-command>' 2>&1

What are Java command line options to set to allow JVM to be remotely debugged?

For java 1.5 or greater:

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.4:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.3:

java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

Here is output from a simple program:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled
Listening for transport dt_socket at address: 1044
Hello whirled

Multiple select statements in Single query

SELECT t1.credit, 
       t2.debit 
FROM   (SELECT Sum(c.total_amount) AS credit 
        FROM   credit c 
        WHERE  c.status = "a") AS t1, 
       (SELECT Sum(d.total_amount) AS debit 
        FROM   debit d 
        WHERE  d.status = "a") AS t2 

TypeError: ObjectId('') is not JSON serializable

I would like to provide an additional solution that improves the accepted answer. I have previously provided the answers in another thread here.

from flask import Flask
from flask.json import JSONEncoder

from bson import json_util

from . import resources

# define a custom encoder point to the json_util provided by pymongo (or its dependency bson)
class CustomJSONEncoder(JSONEncoder):
    def default(self, obj): return json_util.default(obj)

application = Flask(__name__)
application.json_encoder = CustomJSONEncoder

if __name__ == "__main__":
    application.run()

How do you display JavaScript datetime in 12 hour AM/PM format?

_x000D_
_x000D_
function formatTime( d = new Date(), ampm = true ) 
{
    var hour = d.getHours();
    
    if ( ampm )
    {
        var a = ( hour >= 12 ) ? 'PM' : 'AM';
        hour = hour % 12;
        hour = hour ? hour : 12; // the hour '0' should be '12'  
    }

    var hour    = checkDigit(hour);  
    var minute  = checkDigit(d.getMinutes());
    var second  = checkDigit(d.getSeconds());
  
    // https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
    return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}

function checkDigit(t)
{
  return ( t < 10 ) ? `0${t}` : t;
}

document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
_x000D_
<p>ampm true:   <span id="time1"></span> (default)</p>
<p>ampm false:  <span id="time2"></span></p>
_x000D_
_x000D_
_x000D_

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Count frequency of words in a list and sort by frequency

use this

from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})

"End of script output before headers" error in Apache

For future reference:

This is typically an error that occurs when you are unable to view or execute the file, the reason for which is generally a permissions error. I would start by following @Renning 's suggestion and running chmod 755 test.cgi (obviously replace test.cgi with the name of your cgi script here).

If that doesn't work there are a couple other things you can try. I once got this error when I created test.cgi as root in another user's home. The fix there was to run chmod user:user test.cgi where user is the name of the user who's home you're in.

The last thing I can think of is making sure that your cgi script is returning the proper headers. In my ruby script I did it by putting puts "Content-type: text/html" before I actually outputted anything to the page.

Happy coding!

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Getting key with maximum value in dictionary?

I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:

def keywithmaxval(d):
     """ a) create a list of the dict's keys and values; 
         b) return the key with the max value"""  
     v=list(d.values())
     k=list(d.keys())
     return k[v.index(max(v))]

To give you an idea, here are some candidate methods:

def f1():  
     v=list(d1.values())
     k=list(d1.keys())
     return k[v.index(max(v))]

def f2():
    d3={v:k for k,v in d1.items()}
    return d3[max(d3)]

def f3():
    return list(filter(lambda t: t[1]==max(d1.values()), d1.items()))[0][0]    

def f3b():
    # same as f3 but remove the call to max from the lambda
    m=max(d1.values())
    return list(filter(lambda t: t[1]==m, d1.items()))[0][0]        

def f4():
    return [k for k,v in d1.items() if v==max(d1.values())][0]    

def f4b():
    # same as f4 but remove the max from the comprehension
    m=max(d1.values())
    return [k for k,v in d1.items() if v==m][0]        

def f5():
    return max(d1.items(), key=operator.itemgetter(1))[0]    

def f6():
    return max(d1,key=d1.get)     

def f7():
     """ a) create a list of the dict's keys and values; 
         b) return the key with the max value"""    
     v=list(d1.values())
     return list(d1.keys())[v.index(max(v))]    

def f8():
     return max(d1, key=lambda k: d1[k])     

tl=[f1,f2, f3b, f4b, f5, f6, f7, f8, f4,f3]     
cmpthese.cmpthese(tl,c=100) 

The test dictionary:

d1={1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, 
    12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, 
    21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, 
    30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22, 
    39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12, 
    49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33, 
    58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28, 
    68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23, 
    78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31, 
    88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35, 
    98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63, 
    2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21, 
    124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16, 
    142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11, 
    161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32, 
    182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89, 
    208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84, 
    238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30, 
    263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118, 
    296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25, 
    55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108, 
    377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103, 
    1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23, 
    6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119, 
    592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41, 
    700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78, 
    1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99, 
    976: 24, 166: 112}

And the test results under Python 3.2:

    rate/sec       f4      f3    f3b     f8     f5     f2    f4b     f6     f7     f1
f4       454       --   -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0%
f3       466     2.6%      -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0%
f3b   14,715  3138.9% 3057.4%     -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4%
f8    18,070  3877.3% 3777.3%  22.8%     -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2%
f5    33,091  7183.7% 7000.5% 124.9%  83.1%     --  -1.0%  -2.0%  -6.3% -18.6% -29.0%
f2    33,423  7256.8% 7071.8% 127.1%  85.0%   1.0%     --  -1.0%  -5.3% -17.7% -28.3%
f4b   33,762  7331.4% 7144.6% 129.4%  86.8%   2.0%   1.0%     --  -4.4% -16.9% -27.5%
f6    35,300  7669.8% 7474.4% 139.9%  95.4%   6.7%   5.6%   4.6%     -- -13.1% -24.2%
f7    40,631  8843.2% 8618.3% 176.1% 124.9%  22.8%  21.6%  20.3%  15.1%     -- -12.8%
f1    46,598 10156.7% 9898.8% 216.7% 157.9%  40.8%  39.4%  38.0%  32.0%  14.7%     --

And under Python 2.7:

    rate/sec       f3       f4     f8    f3b     f6     f5     f2    f4b     f7     f1
f3       384       --    -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2%
f4       394     2.6%       -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1%
f8    13,079  3303.3%  3216.1%     --  -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2%
f3b   13,852  3504.5%  3412.1%   5.9%     -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5%
f6    18,325  4668.4%  4546.2%  40.1%  32.3%     --  -1.8%  -5.9% -13.5% -29.5% -59.6%
f5    18,664  4756.5%  4632.0%  42.7%  34.7%   1.8%     --  -4.1% -11.9% -28.2% -58.8%
f2    19,470  4966.4%  4836.5%  48.9%  40.6%   6.2%   4.3%     --  -8.1% -25.1% -57.1%
f4b   21,187  5413.0%  5271.7%  62.0%  52.9%  15.6%  13.5%   8.8%     -- -18.5% -53.3%
f7    26,002  6665.8%  6492.4%  98.8%  87.7%  41.9%  39.3%  33.5%  22.7%     -- -42.7%
f1    45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1%  74.4%     -- 

You can see that f1 is the fastest under Python 3.2 and 2.7 (or, more completely, keywithmaxval at the top of this post)

How to stop INFO messages displaying on spark console?

Use below command to change log level while submitting application using spark-submit or spark-sql:

spark-submit \
--conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=file:<file path>/log4j.xml" \
--conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=file:<file path>/log4j.xml"

Note: replace <file path> where log4j config file is stored.

Log4j.properties:

log4j.rootLogger=ERROR, console

# set the log level for these components
log4j.logger.com.test=DEBUG
log4j.logger.org=ERROR
log4j.logger.org.apache.spark=ERROR
log4j.logger.org.spark-project=ERROR
log4j.logger.org.apache.hadoop=ERROR
log4j.logger.io.netty=ERROR
log4j.logger.org.apache.zookeeper=ERROR

# add a ConsoleAppender to the logger stdout to write to the console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# use a simple message format
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

log4j.xml

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8" ?>_x000D_
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">_x000D_
_x000D_
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">_x000D_
   <appender name="console" class="org.apache.log4j.ConsoleAppender">_x000D_
    <param name="Target" value="System.out"/>_x000D_
    <layout class="org.apache.log4j.PatternLayout">_x000D_
    <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />_x000D_
    </layout>_x000D_
  </appender>_x000D_
    <logger name="org.apache.spark">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="org.spark-project">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="org.apache.hadoop">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="io.netty">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <logger name="org.apache.zookeeper">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
   <logger name="org">_x000D_
        <level value="error" />_x000D_
    </logger>_x000D_
    <root>_x000D_
        <priority value ="ERROR" />_x000D_
        <appender-ref ref="console" />_x000D_
    </root>_x000D_
</log4j:configuration>
_x000D_
_x000D_
_x000D_

Switch to FileAppender in log4j.xml if you want to write logs to file instead of console. LOG_DIR is a variable for logs directory which you can supply using spark-submit --conf "spark.driver.extraJavaOptions=-D.

_x000D_
_x000D_
<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">_x000D_
        <param name="file" value="${LOG_DIR}"/>_x000D_
        <param name="datePattern" value="'.'yyyy-MM-dd"/>_x000D_
        <layout class="org.apache.log4j.PatternLayout">_x000D_
            <param name="ConversionPattern" value="%d [%t] %-5p %c %x - %m%n"/>_x000D_
        </layout>_x000D_
    </appender>
_x000D_
_x000D_
_x000D_

Another important thing to understand here is, when job is launched in distributed mode ( deploy-mode cluster and master as yarn or mesos) the log4j configuration file should exist on driver and worker nodes (log4j.configuration=file:<file path>/log4j.xml) else log4j init will complain-

log4j:ERROR Could not read configuration file [log4j.properties]. java.io.FileNotFoundException: log4j.properties (No such file or directory)

Hint on solving this problem-

Keep log4j config file in distributed file system(HDFS or mesos) and add external configuration using log4j PropertyConfigurator. or use sparkContext addFile to make it available on each node then use log4j PropertyConfigurator to reload configuration.

HTML5 input type range show range value

version with editable input:

<form>
    <input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
    <input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>

http://jsfiddle.net/Xjxe6/

gpg decryption fails with no secret key error

I was trying to use aws-vault which uses pass and gnugp2 (gpg2). I'm on Ubuntu 20.04 running in WSL2.

I tried all the solutions above, and eventually, I had to do one more thing -

$ rm ~/.gnupg/S.*                    # remove cache
$ gpg-connect-agent reloadagent /bye # restart gpg agent
$ export GPG_TTY=$(tty)              # prompt for password
# ^ This last line should be added to your ~/.bashrc file

The source of this solution is from some blog-post in Japanese, luckily there's Google Translate :)

How do I center text vertically and horizontally in Flutter?

If you are a intellij IDE user, you can use shortcut key Alt+Enter and then choose Wrap with Center and then add textAlign: TextAlign.center

Referencing value in a closed Excel workbook using INDIRECT?

In Excel 2016 at least, you can use INDIRECT with a full path reference; the entire reference (including sheet name) needs to be enclosed by ' characters.

So this should work for you:

= INDIRECT("'C:\data\[myExcelFile.xlsm]" & C13 & "'!$A$1")

Note the closing ' in the last string (ie '!$A$1 surrounded by "")

Get contentEditable caret index position

function getCaretPosition() {
    var x = 0;
    var y = 0;
    var sel = window.getSelection();
    if(sel.rangeCount) {
        var range = sel.getRangeAt(0).cloneRange();
        if(range.getClientRects()) {
        range.collapse(true);
        var rect = range.getClientRects()[0];
        if(rect) {
            y = rect.top;
            x = rect.left;
        }
        }
    }
    return {
        x: x,
        y: y
    };
}

Java sending and receiving file (byte[]) over sockets

To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];, instead we could do

    byte[] bytearray = new byte[1024*16];
    FileInputStream fis = null;
    try {

        fis = new FileInputStream(file);
        OutputStream output= socket.getOututStream();
        BufferedInputStream bis = new BufferedInputStream(fis);

        int readLength = -1;
        while ((readLength = bis.read(bytearray)) > 0) {
            output.write(bytearray, 0, readLength);

        }
        bis.close();
        output.close();
    }
    catch(Exception ex ){

        ex.printStackTrace();
    } //Excuse the poor exception handling...

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264

and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141

eg:

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES

Open youtube video in Fancybox jquery

Thanx, Alexander!

And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:

'swf': {'allowfullscreen':'true', 'wmode':'transparent'}

no suitable HttpMessageConverter found for response type

A refinement of Vadim Zin4uk's answer is just to use the existing GsonHttpMessageConverter class but invoke the setSupportedMediaTypes() setter.

For spring boot apps, this results into adding to following to your configuration classes:

@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
    GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
    converter.setGson(gson);
    List<MediaType> supportedMediaTypes = converter.getSupportedMediaTypes();
    if (! supportedMediaTypes.contains(TEXT_PLAIN)) {
        supportedMediaTypes = new ArrayList<>(supportedMediaTypes);
        supportedMediaTypes.add(TEXT_PLAIN);
        converter.setSupportedMediaTypes(supportedMediaTypes);
    }
    return converter;
}

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

How to get multiple selected values from select box in JSP?

Something along the lines of (using JSTL):

<p>Selected Values:
<ul>
  <c:forEach items="${paramValues['select2']}" var="selectedValue">
    <li><c:out value="${selectedValue}" /></li>
  </c:forEach>
</ul>
</p>

Why is the parent div height zero when it has floated children

Ordinarily, floats aren't counted in the layout of their parents.

To prevent that, add overflow: hidden to the parent.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowAllS3ActionsInUserFolder",
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::your_bucket_name",
                "arn:aws:s3:::your_bucket_name/*"
            ]
        }
    ]
}

Adding both "arn:aws:s3:::your_bucket_name" and "arn:aws:s3:::your_bucket_name/*" to policy congiguration fixed the issue for me.

How to initialize an array of custom objects

I had to create an array of a predefined type, and I successfully did as follows:

[System.Data.DataColumn[]]$myitems = ([System.Data.DataColumn]("col1"), 
                [System.Data.DataColumn]("col2"),  [System.Data.DataColumn]("col3"))

How to have Android Service communicate with Activity

My method:

Class to manage send and receive message from/to service/activity:

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class MessageManager {

    public interface IOnHandleMessage{
        // Messages
        int MSG_HANDSHAKE = 0x1;

        void onHandleMessage(Message msg);
    }

    private static final String LOGCAT = MessageManager.class.getSimpleName();

    private Messenger mMsgSender;
    private Messenger mMsgReceiver;
    private List<Message> mMessages;

    public MessageManager(IOnHandleMessage callback, IBinder target){
        mMsgReceiver = new Messenger(new MessageHandler(callback, MessageHandler.TYPE_ACTIVITY));
        mMsgSender = new Messenger(target);
        mMessages = new ArrayList<>();
    }

    public MessageManager(IOnHandleMessage callback){
        mMsgReceiver = new Messenger(new MessageHandler(callback, MessageHandler.TYPE_SERVICE));
        mMsgSender = null;
        mMessages = new ArrayList<>();
    }

    /* START Getter & Setter Methods */
    public Messenger getMsgSender() {
        return mMsgSender;
    }

    public void setMsgSender(Messenger sender) {
        this.mMsgSender = sender;
    }

    public Messenger getMsgReceiver() {
        return mMsgReceiver;
    }

    public void setMsgReceiver(Messenger receiver) {
        this.mMsgReceiver = receiver;
    }

    public List<Message> getLastMessages() {
        return mMessages;
    }

    public void addMessage(Message message) {
        this.mMessages.add(message);
    }
    /* END Getter & Setter Methods */

    /* START Public Methods */
    public void sendMessage(int what, int arg1, int arg2, Bundle msgData){
        if(mMsgSender != null && mMsgReceiver != null) {
            try {
                Message msg = Message.obtain(null, what, arg1, arg2);
                msg.replyTo = mMsgReceiver;
                if(msgData != null){
                    msg.setData(msgData);
                }
                mMsgSender.send(msg);
            } catch (RemoteException rE) {
                onException(rE);
            }
        }
    }

    public void sendHandshake(){
        if(mMsgSender != null && mMsgReceiver != null){
            sendMessage(IOnHandleMessage.MSG_HANDSHAKE, 0, 0, null);
        }
    }
    /* END Public Methods */

    /* START Private Methods */
    private void onException(Exception e){
        Log.e(LOGCAT, e.getMessage());
        e.printStackTrace();
    }
    /* END Private Methods */

    /** START Private Classes **/
    private class MessageHandler extends Handler {

        // Types
        final static int TYPE_SERVICE = 0x1;
        final static int TYPE_ACTIVITY = 0x2;

        private IOnHandleMessage mCallback;
        private int mType;

        public MessageHandler(IOnHandleMessage callback, int type){
            mCallback = callback;
            mType = type;
        }

        @Override
        public void handleMessage(Message msg){
            addMessage(msg);
            switch(msg.what){
                case IOnHandleMessage.MSG_HANDSHAKE:
                    switch(mType){
                        case TYPE_SERVICE:
                            setMsgSender(msg.replyTo);
                            sendHandshake();
                            break;
                        case TYPE_ACTIVITY:
                            Log.v(LOGCAT, "HERE");
                            break;
                    }
                    break;
                default:
                    if(mCallback != null){
                        mCallback.onHandleMessage(msg);
                    }
                    break;
            }
        }

    }
    /** END Private Classes **/

}

In Activity Example:

public class activity extends AppCompatActivity
      implements     ServiceConnection,
                     MessageManager.IOnHandleMessage { 

    [....]

    private MessageManager mMessenger;

    private void initMyMessenger(IBinder iBinder){
        mMessenger = new MessageManager(this, iBinder);
        mMessenger.sendHandshake();
    }

    private void bindToService(){
        Intent intent = new Intent(this, TagScanService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        /* START THE SERVICE IF NEEDED */
    }

    private void unbindToService(){
    /* UNBIND when you want (onDestroy, after operation...)
        if(mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }

    /* START Override MessageManager.IOnHandleMessage Methods */
    @Override
    public void onHandleMessage(Message msg) {
        switch(msg.what){
            case Constants.MSG_SYNC_PROGRESS:
                Bundle data = msg.getData();
                String text = data.getString(Constants.KEY_MSG_TEXT);
                setMessageProgress(text);
                break;
            case Constants.MSG_START_SYNC:
                onStartSync();
                break;
            case Constants.MSG_END_SYNC:
                onEndSync(msg.arg1 == Constants.ARG1_SUCCESS);
                mBound = false;
                break;
        }
    }
    /* END Override MessageManager.IOnHandleMessage Methods */

    /** START Override ServiceConnection Methods **/
    private class BLEScanServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            initMyMessenger(iBinder);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mMessenger = null;
            mBound = false;
        }
    }
    /** END Override ServiceConnection Methods **/

In Service Example:

public class Blablabla extends Service
    implements     MessageManager.IOnHandleMessage {

    [...]

    private MessageManager mMessenger;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        super.onBind(intent);
        initMessageManager();
        return mMessenger.getMsgReceiver().getBinder();
    }

    private void initMessageManager(){
        mMessenger = new MessageManager(this);
    }

    /* START Override IOnHandleMessage Methods */
    @Override
    public void onHandleMessage(Message msg) {
    /* Do what you want when u get a message looking the "what" attribute */
    }
    /* END Override IOnHandleMessage Methods */

Send a message from Activity / Service:

mMessenger.sendMessage(what, arg1, arg2, dataBundle);

How this works:

on the activity you start or bind the service. The service "OnBind" methods return the Binder to his MessageManager, the in the Activity through the "Service Connection" interface methods implementation "OnServiceConnected" you get this IBinder and init you MessageManager using it. After the Activity has init his MessageManager the MessageHandler send and Handshake to the service so it can set his "MessageHandler" sender ( the "private Messenger mMsgSender;" in MessageManager ). Doing this the service know to who send his messages.

You can also implement this using a List/Queue of Messenger "sender" in the MessageManager so you can send multiple messages to different Activities/Services or you can use a List/Queue of Messenger "receiver" in the MessageManager so you can receive multiple message from different Activities/Services.

In the "MessageManager" instance you have a list of all messages received.

As you can see the connection between "Activity's Messenger" and "Service Messenger" using this "MessageManager" instance is automatic, it is done through the "OnServiceConnected" method and through the use of the "Handshake".

Hope this is helpful for you :) Thank you very much! Bye :D

What is __init__.py for?

There are 2 main reasons for __init__.py

  1. For convenience: the other users will not need to know your functions' exact location in your package hierarchy.

    your_package/
      __init__.py
      file1.py
      file2.py
        ...
      fileN.py
    
    # in __init__.py
    from file1 import *
    from file2 import *
    ...
    from fileN import *
    
    # in file1.py
    def add():
        pass
    

    then others can call add() by

    from your_package import add
    

    without knowing file1, like

    from your_package.file1 import add
    
  2. If you want something to be initialized; for example, logging (which should be put in the top level):

    import logging.config
    logging.config.dictConfig(Your_logging_config)
    

What does principal end of an association means in 1:1 relationship in Entity framework

This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.

Had a situation where having FK of dependent must be it's PK was not feasible.

E.g., Foo already has one-to-many relationship with Bar.

public class Foo {
   public Guid FooId;
   public virtual ICollection<> Bars; 
}
public class Bar {
   //PK
   public Guid BarId;
   //FK to Foo
   public Guid FooId;
   public virtual Foo Foo;
}

Now, we had to add another one-to-one relationship between Foo and Bar.

public class Foo {
   public Guid FooId;
   public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
   public virtual Bar PrimaryBar;
   public virtual ICollection<> Bars;
}
public class Bar {
   public Guid BarId;
   public Guid FooId;
   public virtual Foo PrimaryBarOfFoo;
   public virtual Foo Foo;
}

Here is how to specify one-to-one relationship using fluent api:

modelBuilder.Entity<Bar>()
            .HasOptional(p => p.PrimaryBarOfFoo)
            .WithOptionalPrincipal(o => o.PrimaryBar)
            .Map(x => x.MapKey("PrimaryBarId"));

Note that while adding PrimaryBarId needs to be removed, as we specifying it through fluent api.

Also note that method name [WithOptionalPrincipal()][1] is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.

How to localise a string inside the iOS info.plist file?

All the above did not work for me (XCode 7.3) so I read Apple reference on how to do, and it is much simpler than described above. According to Apple:

Localized values are not stored in the Info.plist file itself. Instead, you store the values for a particular localization in a strings file with the name InfoPlist.strings. You place this file in the same language-specific project directory that you use to store other resources for the same localization.

Accordingly, I created a string file named InfoPlist.strings and placed it in the xx.lproj folder of the "xx" language (and added it to the project using File->Add Files to ...). That's it. No need for the key "Localized resources can be mixed" = YES, and no need for InfoPlist.strings in base.lproj or en.lproj.

The application uses the Info.plist key-value as the default value if it can not find a key in the language specific file. Thus, I put my English value in the Info.plist file and the translated one in the language specific file, tested and everything works.

In particular, there is no need to localize the InfoPlist.strings (which creates a version of the file in the base.lproj, en.lroj, and xx.lproj), and in my case going that way did not work.

What does 'super' do in Python?

When calling super() to resolve to a parent's version of a classmethod, instance method, or staticmethod, we want to pass the current class whose scope we are in as the first argument, to indicate which parent's scope we're trying to resolve to, and as a second argument the object of interest to indicate which object we're trying to apply that scope to.

Consider a class hierarchy A, B, and C where each class is the parent of the one following it, and a, b, and c respective instances of each.

super(B, b) 
# resolves to the scope of B's parent i.e. A 
# and applies that scope to b, as if b was an instance of A

super(C, c) 
# resolves to the scope of C's parent i.e. B
# and applies that scope to c

super(B, c) 
# resolves to the scope of B's parent i.e. A 
# and applies that scope to c

Using super with a staticmethod

e.g. using super() from within the __new__() method

class A(object):
    def __new__(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        return super(A, cls).__new__(cls, *a, **kw)

Explanation:

1- even though it's usual for __new__() to take as its first param a reference to the calling class, it is not implemented in Python as a classmethod, but rather a staticmethod. That is, a reference to a class has to be passed explicitly as the first argument when calling __new__() directly:

# if you defined this
class A(object):
    def __new__(cls):
        pass

# calling this would raise a TypeError due to the missing argument
A.__new__()

# whereas this would be fine
A.__new__(A)

2- when calling super() to get to the parent class we pass the child class A as its first argument, then we pass a reference to the object of interest, in this case it's the class reference that was passed when A.__new__(cls) was called. In most cases it also happens to be a reference to the child class. In some situations it might not be, for instance in the case of multiple generation inheritances.

super(A, cls)

3- since as a general rule __new__() is a staticmethod, super(A, cls).__new__ will also return a staticmethod and needs to be supplied all arguments explicitly, including the reference to the object of insterest, in this case cls.

super(A, cls).__new__(cls, *a, **kw)

4- doing the same thing without super

class A(object):
    def __new__(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        return object.__new__(cls, *a, **kw)

Using super with an instance method

e.g. using super() from within __init__()

class A(object): 
    def __init__(self, *a, **kw):
        # ...
        # you make some changes here
        # ...

        super(A, self).__init__(*a, **kw)

Explanation:

1- __init__ is an instance method, meaning that it takes as its first argument a reference to an instance. When called directly from the instance, the reference is passed implicitly, that is you don't need to specify it:

# you try calling `__init__()` from the class without specifying an instance
# and a TypeError is raised due to the expected but missing reference
A.__init__() # TypeError ...

# you create an instance
a = A()

# you call `__init__()` from that instance and it works
a.__init__()

# you can also call `__init__()` with the class and explicitly pass the instance 
A.__init__(a)

2- when calling super() within __init__() we pass the child class as the first argument and the object of interest as a second argument, which in general is a reference to an instance of the child class.

super(A, self)

3- The call super(A, self) returns a proxy that will resolve the scope and apply it to self as if it's now an instance of the parent class. Let's call that proxy s. Since __init__() is an instance method the call s.__init__(...) will implicitly pass a reference of self as the first argument to the parent's __init__().

4- to do the same without super we need to pass a reference to an instance explicitly to the parent's version of __init__().

class A(object): 
    def __init__(self, *a, **kw):
        # ...
        # you make some changes here
        # ...

        object.__init__(self, *a, **kw)

Using super with a classmethod

class A(object):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        print "A.alternate_constructor called"
        return cls(*a, **kw)

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        return super(B, cls).alternate_constructor(*a, **kw)

Explanation:

1- A classmethod can be called from the class directly and takes as its first parameter a reference to the class.

# calling directly from the class is fine,
# a reference to the class is passed implicitly
a = A.alternate_constructor()
b = B.alternate_constructor()

2- when calling super() within a classmethod to resolve to its parent's version of it, we want to pass the current child class as the first argument to indicate which parent's scope we're trying to resolve to, and the object of interest as the second argument to indicate which object we want to apply that scope to, which in general is a reference to the child class itself or one of its subclasses.

super(B, cls_or_subcls)

3- The call super(B, cls) resolves to the scope of A and applies it to cls. Since alternate_constructor() is a classmethod the call super(B, cls).alternate_constructor(...) will implicitly pass a reference of cls as the first argument to A's version of alternate_constructor()

super(B, cls).alternate_constructor()

4- to do the same without using super() you would need to get a reference to the unbound version of A.alternate_constructor() (i.e. the explicit version of the function). Simply doing this would not work:

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        return A.alternate_constructor(cls, *a, **kw)

The above would not work because the A.alternate_constructor() method takes an implicit reference to A as its first argument. The cls being passed here would be its second argument.

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        # first we get a reference to the unbound 
        # `A.alternate_constructor` function 
        unbound_func = A.alternate_constructor.im_func
        # now we call it and pass our own `cls` as its first argument
        return unbound_func(cls, *a, **kw)

How to fully clean bin and obj folders within Visual Studio?

You can easily find and remove bin and obj folders in Far Manager.

  1. Navigate to you solution and press Alt+F7
  2. In search setting dialog:

    • Type "bin,obj" in field "A file mask or several file masks"
    • Check option "Search for folders"
    • Press Enter
  3. After the search is done, switch view to "Panel".

  4. Select all files (with Ctrl+A) and delete folders (press "Shift+Del")

Hope it helps someone.

ERROR 1049 (42000): Unknown database

Its a common error which happens when we try to access a database which doesn't exist. So create the database using

CREATE DATABASE blog_development;

The error commonly occours when we have dropped the database using

DROP DATABASE blog_development;

and then try to access the database.

Core Data: Quickest way to delete all instances of an entity

iOS 9 and later:

iOS 9 added a new class called NSBatchDeleteRequest that allows you to easily delete objects matching a predicate without having to load them all in to memory. Here's how you'd use it:

Swift 5

let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Car")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

do {
    try myPersistentStoreCoordinator.execute(deleteRequest, with: myContext)
} catch let error as NSError {
    // TODO: handle the error
}

Objective-C

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];

NSError *deleteError = nil;
[myPersistentStoreCoordinator executeRequest:delete withContext:myContext error:&deleteError];

More information about batch deletions can be found in the "What's New in Core Data" session from WWDC 2015 (starting at ~14:10).

iOS 8 and earlier:

Fetch 'em all and delete 'em all:

NSFetchRequest *allCars = [[NSFetchRequest alloc] init];
[allCars setEntity:[NSEntityDescription entityForName:@"Car" inManagedObjectContext:myContext]];
[allCars setIncludesPropertyValues:NO]; //only fetch the managedObjectID

NSError *error = nil;
NSArray *cars = [myContext executeFetchRequest:allCars error:&error];
[allCars release];
//error handling goes here
for (NSManagedObject *car in cars) {
  [myContext deleteObject:car];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here

IIS Express gives Access Denied error when debugging ASP.NET MVC

I just fixed this exact problem in IIS EXPRESS fixed it by editing the application host .config to the location section specific to the below. I had set Windows Authentication in Visual Studio 2012 but when I went into the XML it looked like this.

the windows auth tag needed to be added below as shown.

<windowsAuthentication enabled="true" />

<location path="MyApplicationbeingDebugged">
        ``<system.webServer>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="false" />
                    <!-- INSERT TAG HERE --> 
                </authentication>
            </security>
        </system.webServer>
</location>

PHP function to build query string from array

As this question is quite old and for PHP, here is a way to do it in the (currently) very popular PHP framework Laravel.

To encode the query string for a path in your application, give your routes names and then use the route() helper function like so:

route('documents.list.', ['foo' => 'bar']);

The result will look something like:

http://localhost/documents/list?foo=bar

Also be aware that if your route has any path segment parameters e.g. /documents/{id}, then make sure you pass an id argument to the route() parameters too, otherwise it will default to using the value of the first parameter.

Flattening a shallow list in Python

Off the top of my head, you can eliminate the lambda:

reduce(list.__add__, map(list, [mi.image_set.all() for mi in list_of_menuitems]))

Or even eliminate the map, since you've already got a list-comp:

reduce(list.__add__, [list(mi.image_set.all()) for mi in list_of_menuitems])

You can also just express this as a sum of lists:

sum([list(mi.image_set.all()) for mi in list_of_menuitems], [])

Lightweight Javascript DB for use in Node.js

Lokijs: A fast, in-memory document-oriented datastore for node.js, browser and cordova.

  • In-memory Javascript Datastore wih Persistence
  • In-Browser NoSQL db with syncing and persisting
  • a Redis-style store an npm install away
  • Persistable NoSQL db for Cordova
  • Embeddable NoSQL db with Persistence for node-webkit

LokiJS to be the ideal solution:

  • Mobile applications - especially HTML5 based (Cordova, Phonegap, etc.)
  • Node.js embedded datastore for small-to-medium apps
  • Embedded in desktop application with Node Webkit

https://github.com/techfort/LokiJS

How to read files and stdout from a running Docker container

The stdout of the process started by the docker container is available through the docker logs $containerid command (use -f to keep it going forever). Another option would be to stream the logs directly through the docker remote API.

For accessing log files (only if you must, consider logging to stdout or other standard solution like syslogd) your only real-time option is to configure a volume (like Marcus Hughes suggests) so the logs are stored outside the container and available for processing from the host or another container.

If you do not need real-time access to the logs, you can export the files (in tar format) with docker export

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

How to analyze information from a Java core dump?

Okay if you've created the core dump with gcore or gdb then you'll need to convert it to something called a HPROF file. These can be used by VisualVM, Netbeans or Eclipse's Memory Analyzer Tool (formerly SAP Memory Analyzer). I'd recommend Eclipse MAT.

To convert the file use the commandline tool jmap.

# jmap -dump:format=b,file=dump.hprof /usr/bin/java core.1234

where:

dump.hprof is the name of the hprof file you wish to create

/usr/bin/java is the path to the version of the java binary that generated the core dump

core.1234 is your regular core file.

How to enable CORS on Firefox?

This Firefox add-on may work for you:

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

It can toggle CORS on and off for development purposes.

Key existence check in HashMap

Do you ever store a null value? If not, you can just do:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // No such key
}

Otherwise, you could just check for existence if you get a null value returned:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // Key might be present...
    if (map.containsKey(key)) {
       // Okay, there's a key but the value is null
    } else {
       // Definitely no such key
    }
}

How to get value of a div using javascript

DIVs do not have a value property.

Technically, according to the DTDs, they shouldn't have a value attribute either, but generally you'll want to use .getAttribute() in this case:

function overlay()
{
    var cookieValue = document.getElementById('demo').getAttribute('value');
    alert(cookieValue);
}

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Maintain the aspect ratio of a div with CSS

You can achieve that by using SVG.

It depends on a case, but in some it is really usefull. As an example - you can set background-image without setting fixed height or use it to embed youtube <iframe> with ratio 16:9 and position:absolute etc.

For 3:2 ratio set viewBox="0 0 3 2" and so on.

Example:

_x000D_
_x000D_
div{_x000D_
    background-color:red_x000D_
}_x000D_
svg{_x000D_
    width:100%;_x000D_
    display:block;_x000D_
    visibility:hidden_x000D_
}_x000D_
_x000D_
.demo-1{width:35%}_x000D_
.demo-2{width:20%}
_x000D_
<div class="demo-1">_x000D_
  <svg viewBox="0 0 3 2"></svg>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<div class="demo-2">_x000D_
  <svg viewBox="0 0 3 2"></svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to solve PHP error 'Notice: Array to string conversion in...'

You are using <input name='C[]' in your HTML. This creates an array in PHP when the form is sent.

You are using echo $_POST['C']; to echo that array - this will not work, but instead emit that notice and the word "Array".

Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];

How to recover closed output window in netbeans?

Easy way, just write some wrong code and Run > Build it will show the error in output window.

I tried all of the above but no success, just this one worked.

How do I supply an initial value to a text field?

This can be achieved using TextEditingController.

To have an initial value you can add

TextEditingController _controller = TextEditingController(text: 'initial value');

or

If you are using TextFormField you have a initialValue property there. Which basically provides this initialValue to the controller automatically.

TextEditingController _controller = TextEditingController();
TextFormField(
  controller: _controller,
  initialValue: 'initial value'
)

To clear the text you can use _controller.clear() method.

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

In my case and while installing VS 2015 on Windows7 64x SP1, I experienced the same so tried to cancel and download/install the KBKB2999226 separately and for some reason the standalone update installer also get stuck searching for updates.

enter image description here

Here what I did:

  1. When the VS installer stuck at the KB2999226 update I clicked cancel.
  2. Installer took me back to confirm cancellation, waited for a while then opened the windows task manager and ended the process of wuse.exe (windows standalone update installer)
  3. On the VS installer clicked "No" to return to installation process. The process was completed without errors.

Filter Java Stream to 1 and only 1 element

Using reduce

This is the simpler and flexible way I found (based on @prunge answer)

Optional<User> user = users.stream()
        .filter(user -> user.getId() == 1)
        .reduce((a, b) -> {
            throw new IllegalStateException("Multiple elements: " + a + ", " + b);
        })

This way you obtain:

  • the Optional - as always with your object or Optional.empty() if not present
  • the Exception (with eventually YOUR custom type/message) if there's more than one element

How to resize images proportionally / keeping the aspect ratio?

In order to determine the aspect ratio, you need to have a ratio to aim for.

Height

function getHeight(length, ratio) {
  var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
  return Math.round(height);
}

Width

function getWidth(length, ratio) {
  var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
  return Math.round(width);
}

In this example I use 16:10 since this the typical monitor aspect ratio.

var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);

console.log(height);
console.log(width);

Results from above would be 147 and 300

Make view 80% width of parent in React Native

If you are simply looking to make the input relative to the screen width, an easy way would be to use Dimensions:

// De structure Dimensions from React
var React = require('react-native');
var {
  ...
  Dimensions
} = React; 

// Store width in variable
var width = Dimensions.get('window').width; 

// Use width variable in style declaration
<TextInput style={{ width: width * .8 }} />

I've set up a working project here. Code is also below.

https://rnplay.org/apps/rqQPCQ

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  Dimensions
} = React;

var width = Dimensions.get('window').width;

var SampleApp = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={{fontSize:22}}>Percentage Width In React Native</Text>
        <View style={{marginTop:100, flexDirection: 'row',justifyContent: 'center'}}>
            <TextInput style={{backgroundColor: '#dddddd', height: 60, width: width*.8 }} />
          </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:100
  },

});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Converting between datetime, Timestamp and datetime64

You can just use the pd.Timestamp constructor. The following diagram may be useful for this and related questions.

Conversions between time representations

How to clear the entire array?

[your Array name] = Empty

Then the array will be without content and can be filled again.

Javascript: console.log to html

Slight improvement on @arun-p-johny answer:

In html,

<pre id="log"></pre>

In js,

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function () {
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
        } else {
            logger.innerHTML += arguments[i] + '<br />';
        }
      }
    }
})();

Start using:

console.log('How', true, new Date());

Angular 1.6.0: "Possibly unhandled rejection" error

Try adding this code to your config. I had a similar issue once, and this workaround did the trick.

app.config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
}]);

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

Change background color of selected item on a ListView

Define variable

private ListView mListView;

Initialize variable

mListView = (ListView)findViewById(R.id.list_view);

OnItemClickListener of listview

   mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adpterView, View view, int position,
                long id) {
            for (int i = 0; i < mListView.getChildCount(); i++) {
                if(position == i ){
                    mListView.getChildAt(i).setBackgroundColor(Color.BLUE);     
                }else{
                    mListView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
                }
            }
        }
    });

Build and run the project - Done

Programmatically navigate to another view controller/scene

I Give you my code to make a transition. In this example the action is connecting to an UIButton. So don't forget to set it. Don't forget to set the name of your ViewController in the transition method.

Don't forget to set your storyboard too. Your need to have one view per viewController. Connect each ViewController to each view in storyBoard. You can see on the screenshoot bellow

enter image description here enter image description here

class PresentationViewController: UIViewController {
    override func viewDidLoad() {
         super.viewDidLoad()

         var playButton   = UIButton.buttonWithType(UIButtonType.System) as UIButton

         let image = UIImage(named: "YourPlayButton") as UIImage?

         playButton.frame = CGRectMake(0, 0, 100, 100)
         playButton.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2)
         playButton.addTarget(self, action: "transition:", forControlEvents:  UIControlEvents.TouchUpInside)
         playButton.setBackgroundImage(image, forState: UIControlState.Normal)

         self.view.addSubview(playButton)
    }


func transition(sender:UIButton!)
{
    println("transition")
    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("YourSecondViewController") as UIViewController

    let window = UIApplication.sharedApplication().windows[0] as UIWindow
    UIView.transitionFromView(
        window.rootViewController!.view,
        toView: secondViewController.view,
        duration: 0.65,
        options: .TransitionCrossDissolve,
        completion: {
            finished in window.rootViewController = secondViewController
    })
}
}

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

In Visual Studio 2012 +/-, the property page for "Configuration Properties'.Linker."Command Line" contains a box labeled "Additional Options". If you're building x64, make sure that box doesn't contain /MACHINE:I386. My projects did and it generated the error in question.

Develop Android app using C#

I have used the Unity 3D game engine for developing games for the PC and mobile phone. We use C# in this development.

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Getting activity from context in android

This method should be helpful..!

public Activity getActivityByContext(Context context){

if(context == null){
    return null;
    }

else if((context instanceof ContextWrapper) && (context instanceof Activity)){
        return (Activity) context;
    }

else if(context instanceof ContextWrapper){
        return getActivity(((ContextWrapper) context).getBaseContext());
    }

return null;

    }

I hope this helps.. Merry coding!

Multiple files upload (Array) with CodeIgniter 2.0

    public function imageupload() 
    {

      $count = count($_FILES['userfile']['size']);

  $config['upload_path'] = './uploads/';
  $config['allowed_types'] = 'gif|jpg|png|bmp';
  $config['max_size']   = '0';
  $config['max_width']  = '0';
  $config['max_height']  = '0';

  $config['image_library'] = 'gd2';
  $config['create_thumb'] = TRUE;
  $config['maintain_ratio'] = FALSE;
  $config['width'] = 50;
  $config['height'] = 50;

  foreach($_FILES as $key=>$value)
  { 
     for($s=0; $s<=$count-1; $s++)
     {
     $_FILES['userfile']['name']=$value['name'][$s];
     $_FILES['userfile']['type']    = $value['type'][$s];
     $_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s]; 
     $_FILES['userfile']['error']       = $value['error'][$s];
     $_FILES['userfile']['size']    = $value['size'][$s];  

         $this->load->library('upload', $config);

         if ($this->upload->do_upload('userfile'))
         {
           $data['userfile'][$i] = $this->upload->data();
       $full_path = $data['userfile']['full_path'];


           $config['source_image'] = $full_path;
           $config['new_image'] = './uploads/resiezedImage';

           $this->load->library('image_lib', $config);
           $this->image_lib->resize(); 
           $this->image_lib->clear();

         }
         else
         {
           $data['upload_errors'][$i] = $this->upload->display_errors();
         } 
     }
  }
}

How to check ASP.NET Version loaded on a system?

Here is some code that will return the installed .NET details:

<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<% 
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String

winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)

For filndx As Integer = 0 To 2
  aspNETfil(0) = "ngen.exe"
  aspNETfil(1) = "clr.dll"
  aspNETfil(2) = "KernelBase.dll"

  If filndx = 2   
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
  Else
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
  End If

  If File.Exists(aspNETpth(filndx)) Then
    aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
    aspNETtxt(filndx) = aspNETver.FileVersion.ToString
    aspNETdiv = aspNETtxt(filndx).Split(" ")
    aspNETfix(filndx) = aspNETdiv(0)
  Else
    aspNETfix(filndx) = "Path not found... No version found..."
  End If
Next

Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>

Here is the new output, cleaner code, more output:

Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Your import has a subtle error:

import java.awt.List;

It should be:

import java.util.List;

The problem is that both awt and Java's util package provide a class called List. The former is a display element, the latter is a generic type used with collections. Furthermore, java.util.ArrayList extends java.util.List, not java.awt.List so if it wasn't for the generics, it would have still been a problem.

Edit: (to address further questions given by OP) As an answer to your comment, it seems that there is anther subtle import issue.

import org.omg.DynamicAny.NameValuePair;

should be

import org.apache.http.NameValuePair

nameValuePairs now uses the correct generic type parameter, the generic argument for new UrlEncodedFormEntity, which is List<? extends NameValuePair>, becomes valid, since your NameValuePair is now the same as their NameValuePair. Before, org.omg.DynamicAny.NameValuePair did not extend org.apache.http.NameValuePair and the shortened type name NameValuePair evaluated to org.omg... in your file, but org.apache... in their code.

Specify sudo password for Ansible

After five years, I can see this is still a very relevant subject. Somewhat mirroring leucos's answer which I find the best in my case, using ansible tools only (without any centralised authentication, tokens or whatever). This assumes you have the same username and the same public key on all servers. If you don't, of course you'd need to be more specific and add the corresponding variables next to the hosts:

[all:vars]
ansible_ssh_user=ansible
ansible_ssh_private_key_file=home/user/.ssh/mykey
[group]
192.168.0.50 ansible_sudo_pass='{{ myserver_sudo }}'

ansible-vault create mypasswd.yml
ansible-vault edit mypasswd.yml

Add:

myserver_sudo: mysecretpassword

Then:

ansible-playbook -i inv.ini my_role.yml --ask-vault --extra-vars '@passwd.yml'

At least this way you don't have to write more the variables which point to the passwords.

Angular 5 - Copy to clipboard

Copy using angular cdk,

Module.ts

import {ClipboardModule} from '@angular/cdk/clipboard';

Programmatically copy a string: MyComponent.ts,

class MyComponent {
  constructor(private clipboard: Clipboard) {}

  copyHeroName() {
    this.clipboard.copy('Alphonso');
  }
}

Click an element to copy via HTML:

<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="2">Copy text</button>

Reference: https://material.angular.io/cdk/clipboard/overview

How to set TextView textStyle such as bold, italic

try this to set your TextView style by java code

txt1.setTypeface(null,Typeface.BOLD_ITALIC);

How and where are Annotations used in Java?

Java EE 5 favors the use of annotations over XML configuration. For example, in EJB3 the transaction attributes on an EJB method are specified using annotations. They even use annotations to mark POJOs as EJBs and to specify particular methods as lifecycle methods instead of requiring that implementation of an interface.

Passing enum or object through an intent (the best solution)

This is an old question, but everybody fails to mention that Enums are actually Serializable and therefore can perfectly be added to an Intent as an extra. Like this:

public enum AwesomeEnum {
  SOMETHING, OTHER;
}

intent.putExtra("AwesomeEnum", AwesomeEnum.SOMETHING);

AwesomeEnum result = (AwesomeEnum) intent.getSerializableExtra("AwesomeEnum");

The suggestion to use static or application-wide variables is a really bad idea. This really couples your activities to a state managing system, and it is hard to maintain, debug and problem bound.


ALTERNATIVES:

A good point was noted by tedzyc about the fact that the solution provided by Oderik gives you an error. However, the alternative offered is a bit cumbersome to use (even using generics).

If you are really worried about the performance of adding the enum to an Intent I propose these alternatives instead:

OPTION 1:

public enum AwesomeEnum {
  SOMETHING, OTHER;
  private static final String name = AwesomeEnum.class.getName();
  public void attachTo(Intent intent) {
    intent.putExtra(name, ordinal());
  }
  public static AwesomeEnum detachFrom(Intent intent) {
    if(!intent.hasExtra(name)) throw new IllegalStateException();
    return values()[intent.getIntExtra(name, -1)];
  }
}

Usage:

// Sender usage
AwesomeEnum.SOMETHING.attachTo(intent);
// Receiver usage
AwesomeEnum result = AwesomeEnum.detachFrom(intent);

OPTION 2: (generic, reusable and decoupled from the enum)

public final class EnumUtil {
    public static class Serializer<T extends Enum<T>> extends Deserializer<T> {
        private T victim;
        @SuppressWarnings("unchecked") 
        public Serializer(T victim) {
            super((Class<T>) victim.getClass());
            this.victim = victim;
        }
        public void to(Intent intent) {
            intent.putExtra(name, victim.ordinal());
        }
    }
    public static class Deserializer<T extends Enum<T>> {
        protected Class<T> victimType;
        protected String name;
        public Deserializer(Class<T> victimType) {
            this.victimType = victimType;
            this.name = victimType.getName();
        }
        public T from(Intent intent) {
            if (!intent.hasExtra(name)) throw new IllegalStateException();
            return victimType.getEnumConstants()[intent.getIntExtra(name, -1)];
        }
    }
    public static <T extends Enum<T>> Deserializer<T> deserialize(Class<T> victim) {
        return new Deserializer<T>(victim);
    }
    public static <T extends Enum<T>> Serializer<T> serialize(T victim) {
        return new Serializer<T>(victim);
    }
}

Usage:

// Sender usage
EnumUtil.serialize(AwesomeEnum.Something).to(intent);
// Receiver usage
AwesomeEnum result = 
EnumUtil.deserialize(AwesomeEnum.class).from(intent);

OPTION 3 (with Kotlin):

It's been a while, but since now we have Kotlin, I thought I would add another option for the new paradigm. Here we can make use of extension functions and reified types (which retains the type when compiling).

inline fun <reified T : Enum<T>> Intent.putExtra(victim: T): Intent =
    putExtra(T::class.java.name, victim.ordinal)

inline fun <reified T: Enum<T>> Intent.getEnumExtra(): T? =
    getIntExtra(T::class.java.name, -1)
        .takeUnless { it == -1 }
        ?.let { T::class.java.enumConstants[it] }

There are a few benefits of doing it this way.

  • We don't require the "overhead" of an intermediary object to do the serialization as it's all done in place thanks to inline which will replace the calls with the code inside the function.
  • The functions are more familiar as they are similar to the SDK ones.
  • The IDE will autocomplete these functions which means there is no need to have previous knowledge of the utility class.

One of the downsides is that, if we change the order of the Emums, then any old reference will not work. This can be an issue with things like Intents inside pending intents as they may survive updates. However, for the rest of the time, it should be ok.

It's important to note that other solutions, like using the name instead of the position, will also fail if we rename any of the values. Although, in those cases, we get an exception instead of the incorrect Enum value.

Usage:

// Sender usage
intent.putExtra(AwesomeEnum.SOMETHING)
// Receiver usage
val result = intent.getEnumExtra<AwesomeEnum>()

how to remove the first two columns in a file using shell (awk, sed, whatever)

Its pretty straight forward to do it with only shell

while read A B C; do
echo "$C"
done < oldfile >newfile

Why is &#65279; appearing in my HTML?

If you are using Notepad++, "Menu" >> "Encoding" >> "Convert to UTF-8" your "include" files.

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

How do I check to see if a value is an integer in MySQL?

I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do

select field from table where field REGEXP '^-?[0-9]+$';

this is reasonably fast. If your field is numeric, just test for

ceil(field) = field

instead.

Use jQuery to hide a DIV when the user clicks outside of it

Even sleaker:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

Executing <script> injected by innerHTML after AJAX call

Another thing to do is to load the page with a script such as:

<div id="content" onmouseover='myFunction();$(this).prop( 'onmouseover', null );'>
<script type="text/javascript">
function myFunction() {
  //do something
}
myFunction();
</script>
</div>

This will load the page, then run the script and remove the event handler when the function has been run. This will not run immediately after an ajax load, but if you are waiting for the user to enter the div element, this will work just fine.

PS. Requires Jquery

What is the difference between HAVING and WHERE in SQL?

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

Source

Insert data to MySql DB and display if insertion is success or failure

$result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
if($result)
{
echo "Success";

}
else
{
echo "Error";

}

Undefined reference to `pow' and `floor'

To find the point where to add the -lm in Eclipse-IDE is really horrible, so it took me some time.

If someone else also uses Edlipse, here's the way how to add the command:

Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Miscelleaneous -> Linker flags: in this field add the command -lm

What is the `zero` value for time.Time in Go?

The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

How to get GET (query string) variables in Express.js on Node.js?

In Express it's already done for you and you can simply use req.query for that:

var id = req.query.id; // $_GET["id"]

Otherwise, in NodeJS, you can access req.url and the builtin url module to url.parse it manually:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

How can I return an empty IEnumerable?

As for me, most elegant way is yield break

What's the complete range for Chinese characters in Unicode?

The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD].

  1. [\u2e80-\u2fd5]

CJK Radicals Supplement is a Unicode block containing alternative, often positional, forms of the Kangxi radicals. They are used headers in dictionary indices and other CJK ideograph collections organized by radical-stroke.

  1. [\u3190-\u319f]

Kanbun is a Unicode block containing annotation characters used in Japanese copies of classical Chinese texts, to indicate reading order.

  1. [\u3400-\u4DBF]

CJK Unified Ideographs Extension-A is a Unicode block containing rare Han ideographs.

  1. [\u4E00-\u9FCC]

CJK Unified Ideographs is a Unicode block containing the most common CJK ideographs used in modern Chinese and Japanese.

  1. [\uF900-\uFAAD]

CJK Compatibility Ideographs is a Unicode block created to contain Han characters that were encoded in multiple locations in other established character encodings, in addition to their CJK Unified Ideographs assignments, in order to retain round-trip compatibility between Unicode and those encodings.

For the details please refer to here, and the extensions are provided in other answers.

Assign a variable inside a Block to a variable outside a Block

yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

This issue is because you didn't register the data access component with the interface written for it. Try using as follows

services.AddTransient<IMyDataProvider, MyDataAccess>();`

Bind service to activity in Android

"If you start an android Service with startService(..) that Service will remain running until you explicitly invoke stopService(..). There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder). Usually the IBinder returned is for a complex interface that has been written in AIDL.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the Service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()."

Authorize attribute in ASP.NET MVC

Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

As already said, your socket probably enter in TIME_WAIT state. This issue is well described by Thomas A. Fine here.

To summary, socket closing process follow diagram below:

Socket closing process

Thomas says:

Looking at the diagram above, it is clear that TIME_WAIT can be avoided if the remote end initiates the closure. So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.

Using SO_REUSEADDR is commonly suggested on internet, but Thomas add:

Oddly, using SO_REUSEADDR can actually lead to more difficult "address already in use" errors. SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.

How can I change image tintColor in iOS and WatchKit

Take benefit of Extension in Swift :-

extension UIImageView {
    func changeImageColor( color:UIColor) -> UIImage
    {
        image = image!.withRenderingMode(.alwaysTemplate)
        tintColor = color
        return image!
    }
}

   //Change color of logo 
   logoImage.image =  logoImage.changeImageColor(color: .red)

enter image description here

How to print a dictionary's key?

I'm adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented -- if updated for Python 3 per the suggested workaround in a comment to that answer -- silently fails to return all relevant data.


Background

I have some metabolic data, represented in a graph (nodes, edges, ...). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).

Find keys for given values

The following code correctly finds my keys, given values:

def k4v_edited(my_dict, value):
    values_list = []
    for k, v in my_dict.items():
        if v == value:
            values_list.append(k)
    return values_list

print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]

whereas this code returns only the first (of possibly several matching) keys:

def k4v(my_dict, value):
    for k, v in my_dict.items():
        if v == value:
            return k

print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)

The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.

Forking / Multi-Threaded Processes | Bash

In bash scripts (non-interactive) by default JOB CONTROL is disabled so you can't do the the commands: job, fg, and bg.

Here is what works well for me:

#!/bin/sh

set -m # Enable Job Control

for i in `seq 30`; do # start 30 jobs in parallel
  sleep 3 &
done

# Wait for all parallel jobs to finish
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done

The last line uses "fg" to bring a background job into the foreground. It does this in a loop until fg returns 1 ($? == 1), which it does when there are no longer any more background jobs.

Insert a string at a specific index

If anyone is looking for a way to insert text at multiple indices in a string, try this out:

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};

For example, you can use this to insert <span> tags at certain offsets in a string:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"

Quotation marks inside a string

You can do this using Escape Sequence.

\"

So you will have to write something like this :

String name = "\"john\"";

You can learn about Escape Sequences from here.

How to use GROUP_CONCAT in a CONCAT in MySQL

SELECT ID, GROUP_CONCAT(CONCAT_WS(':', NAME, VALUE) SEPARATOR ',') AS Result 
FROM test GROUP BY ID

@Directive vs @Component in Angular

If you refer the official angular docs

https://angular.io/guide/attribute-directives

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements. e.g *ngIf
  3. Attribute directives—change the appearance or behavior of an element, component, or another directive. e.g [ngClass].

As the Application grows we find difficulty in maintaining all these codes. For reusability purpose, we separate our logic in smart components and dumb components and we use directives (structural or attribute) to make changes in the DOM.

How to compare DateTime without time via LINQ?

It happens that LINQ doesn't like properties such as DateTime.Date. It just can't convert to SQL queries. So I figured out a way of comparing dates using Jon's answer, but without that naughty DateTime.Date. Something like this:

var q = db.Games.Where(t => t.StartDate.CompareTo(DateTime.Today) >= 0).OrderBy(d => d.StartDate);

This way, we're comparing a full database DateTime, with all that date and time stuff, like 2015-03-04 11:49:45.000 or something like this, with a DateTime that represents the actual first millisecond of that day, like 2015-03-04 00:00:00.0000.

Any DateTime we compare to that DateTime.Today will return us safely if that date is later or the same. Unless you want to compare literally the same day, in which case I think you should go for Caesar's answer.

The method DateTime.CompareTo() is just fancy Object-Oriented stuff. It returns -1 if the parameter is earlier than the DateTime you referenced, 0 if it is LITERALLY EQUAL (with all that timey stuff) and 1 if it is later.

Twitter Bootstrap: Print content of modal window

you can download printThis lib from this source https://github.com/jasonday/printThis/blob/0a7f799693af8a8303bf0b8df0efc80c2694af81/printThis.js and include it into your html page

Call the following jquery to print all the content including the content that is not viewable. You may include your css files in an array if you have multiple css files.

$("#modalDiv").printThis({ 
    debug: false,              
    importCSS: true,             
    importStyle: true,         
    printContainer: true,       
    loadCSS: "../css/style.css", 
    pageTitle: "My Modal",             
    removeInline: false,        
    printDelay: 333,            
    header: null,             
    formValues: true          
}); 

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to make Bootstrap carousel slider use mobile left/right swipe

If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.

NOTE: ngx-bootstrap is used.

import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';

@Directive({
  selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
  @Input() swipeThreshold = 50;
  private start: number;
  private stillMoving: boolean;
  private moveListener: Function;

  constructor(
    @Host() @Self() @Optional() private carousel: CarouselComponent,
    private renderer: Renderer2,
    private element: ElementRef
  ) {
  }

  ngOnInit(): void {
    if ('ontouchstart' in document.documentElement) {
      this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
      this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
    }
  }

  private onTouchStart(e: TouchEvent): void {
    if (e.touches.length === 1) {
      this.start = e.touches[0].pageX;
      this.stillMoving = true;
      this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
    }
  }

  private onTouchMove(e: TouchEvent): void {
    if (this.stillMoving) {
      const x = e.touches[0].pageX;
      const difference = this.start - x;
      if (Math.abs(difference) >= this.swipeThreshold) {
        this.cancelTouch();
        if (difference > 0) {
          if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
            this.carousel.activeSlide = this.carousel.activeSlide + 1;
          }
        } else {
          if (this.carousel.activeSlide > 0) {
            this.carousel.activeSlide = this.carousel.activeSlide - 1;
          }
        }
      }
    }
  }

  private onTouchEnd(e: TouchEvent): void {
    this.cancelTouch();
  }

  private cancelTouch() {
    if (this.moveListener) {
      this.moveListener();
      this.moveListener = undefined;
    }
    this.start = null;
    this.stillMoving = false;
  }
}

in html:

<carousel appCarouselSwipe>

    ...

</carousel>

Reference

VLook-Up Match first 3 characters of one column with another column

=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))

Number of lines in a file in Java

How about using the Process class from within Java code? And then reading the output of the command.

Process p = Runtime.getRuntime().exec("wc -l " + yourfilename);
p.waitFor();

BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
int lineCount = 0;
while ((line = b.readLine()) != null) {
    System.out.println(line);
    lineCount = Integer.parseInt(line);
}

Need to try it though. Will post the results.

How to determine the screen width in terms of dp or dip at runtime in Android?

How about using this instead ?

final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels/displayMetrics.density;
final float screenHeightInDp=displayMetrics.heightPixels/displayMetrics.density;

How to send a POST request using volley with string body?

Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();


JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();

StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v("LOG_VOLLEY", response);

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("LOG_VOLLEY", error.toString());
    }
}) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
            return null;
        }
    }

};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);

Where is the visual studio HTML Designer?

The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.

I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.

How to detect the swipe left or Right in Android?

Swipe events are a kind of onTouch events. Simply simplifying @Gal Rom 's answer, just keep track of the vertical an horizontal deltas, and with a little math you can determine what kind of swipe a touchEvent was. (Again, let me stress that this was OBSENELY based to a previous answer, but the simplicity may appeal to novices). The idea is to extend an OnTouchListener, detect what kind of swipe (touch) just happened and call specific methods for each kind.

public class SwipeListener implements View.OnTouchListener {
    private int min_distance = 100;
    private float downX, downY, upX, upY;
    View v;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        this.v = v;
        switch(event.getAction()) { // Check vertical and horizontal touches
            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                return true;
            }
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();

                float deltaX = downX - upX;
                float deltaY = downY - upY;

                //HORIZONTAL SCROLL
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    if (Math.abs(deltaX) > min_distance) {
                        // left or right
                        if (deltaX < 0) {
                            this.onLeftToRightSwipe();
                            return true;
                        }
                        if (deltaX > 0) {
                            this.onRightToLeftSwipe();
                            return true;
                        }
                    } else {
                        //not long enough swipe...
                        return false;
                    }
                }
                //VERTICAL SCROLL
                else {
                    if (Math.abs(deltaY) > min_distance) {
                        // top or down
                        if (deltaY < 0) {
                            this.onTopToBottomSwipe();
                            return true;
                        }
                        if (deltaY > 0) {
                            this.onBottomToTopSwipe();
                            return true;
                        }
                    } else {
                        //not long enough swipe...
                        return false;
                    }
                }
                return false;
            }
        }
        return false;
    }

    public void onLeftToRightSwipe(){
        Toast.makeText(v.getContext(),"left to right",   
                                      Toast.LENGTH_SHORT).show();
    }

    public void onRightToLeftSwipe() {
        Toast.makeText(v.getContext(),"right to left",
                                     Toast.LENGTH_SHORT).show();
    }

    public void onTopToBottomSwipe() {
        Toast.makeText(v.getContext(),"top to bottom", 
                                     Toast.LENGTH_SHORT).show();
    }

    public void onBottomToTopSwipe() {
        Toast.makeText(v.getContext(),"bottom to top", 
                                    Toast.LENGTH_SHORT).show();
    }
}

Can I set a TTL for @Cacheable

Since Spring-boot 1.3.3, you may set expire time in CacheManager by using RedisCacheManager.setExpires or RedisCacheManager.setDefaultExpiration in CacheManagerCustomizer call-back bean.

Load HTML file into WebView

The easiest way would probably be to put your web resources into the assets folder then call:

webView.loadUrl("file:///android_asset/filename.html");

For Complete Communication between Java and Webview See This

Update: The assets folder is usually the following folder: <project>/src/main/assets This can be changed in the asset folder configuration setting in your <app>.iml file as:

<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” /> See Article Where to place the assets folder in Android Studio

How to send an object from one Android Activity to another using Intents?

in your class model (Object) implement Serializable, for Example:

public class MensajesProveedor implements Serializable {

    private int idProveedor;


    public MensajesProveedor() {
    }

    public int getIdProveedor() {
        return idProveedor;
    }

    public void setIdProveedor(int idProveedor) {
        this.idProveedor = idProveedor;
    }


}

and your first Activity

MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
                i.putExtra("mensajes",mp);
                startActivity(i);

and your second Activity (NewActivity)

        MensajesProveedor  mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");

good luck!!

Constructor overloading in Java - best practice

Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.

The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.

For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Un-tick the Prevent saving changes that require table re-creation box from Tools ? Options ? Designers tab.

SQL Server 2012 example:

enter image description here

Find a class somewhere inside dozens of JAR files?

I've always used this on Windows and its worked exceptionally well.

findstr /s /m /c:"package/classname" *.jar, where

findstr.exe comes standard with Windows and the params:

  • /s = recursively
  • /m = print only the filename if there is a match
  • /c = literal string (in this case your package name + class names separated by '/')

Hope this helps someone.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

What is the difference between the | and || or operators?

The single pipe, |, is one of the bitwise operators.

From Wikipedia:

In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes).

Get filename from input [type='file'] using jQuery

Getting the file name is fairly easy. As matsko points out, you cannot get the full file path on the user's computer for security reasons.

var file = $('#image_file')[0].files[0]
if (file){
  console.log(file.name);
}

JQuery addclass to selected div, remove class if another div is selected

**This can be achived easily using two different ways:**

1)We can also do this by using addClass and removeClass of Jquery
2)Toggle class of jQuery

**1)First Way**

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').removeClass('active class or your class name which you want to    remove').addClass('active class or your class name which you want to add');     
});
});

**2) Second Way**

i) Here we need to add the class which we want to show while page get loads.
ii)after clicking on div we we will toggle class i.e. the class is added while loading page gets removed and class which we provide in toggleClss gets added :)

<div id="dvId" class="ActiveClassname ">
</div

$(documnet.ready(function(){
$('#dvId').click(function(){
  $('#dvId').toggleClass('ActiveClassname InActiveClassName');     
});
});


Enjoy.....:)

If you any doubt free to ask any time...

Python Linked List

Here is some list functions based on Martin v. Löwis's representation:

cons   = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length  = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin   = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")

where w = sys.stdout.write

Although doubly linked lists are famously used in Raymond Hettinger's ordered set recipe, singly linked lists have no practical value in Python.

I've never used a singly linked list in Python for any problem except educational.

Thomas Watnedal suggested a good educational resource How to Think Like a Computer Scientist, Chapter 17: Linked lists:

A linked list is either:

  • the empty list, represented by None, or
  • a node that contains a cargo object and a reference to a linked list.

    class Node: 
      def __init__(self, cargo=None, next=None): 
        self.car = cargo 
        self.cdr = next    
      def __str__(self): 
        return str(self.car)
    
    def display(lst):
      if lst:
        w("%s " % lst)
        display(lst.cdr)
      else:
        w("nil\n")
    

"You may need an appropriate loader to handle this file type" with Webpack and Babel

In my case, I had such error since import path was wrong:

Wrong: import Select from "react-select/src/Select"; // it was auto-generated by IDE ;)

Correct: import Select from "react-select";

How to position a div scrollbar on the left hand side?

You could try direction:rtl; in your css. Then reset the text direction in the inner div

#scroll{
    direction:rtl; 
    overflow:auto; 
    height:50px; 
    width:50px;}

#scroll div{
    direction:ltr;
}

Untested.

Spring RestTemplate GET with parameters

    String uri = http://my-rest-url.org/rest/account/{account};

    Map<String, String> uriParam = new HashMap<>();
    uriParam.put("account", "my_account");

    UriComponents builder = UriComponentsBuilder.fromHttpUrl(uri)
                .queryParam("pageSize","2")
                        .queryParam("page","0")
                        .queryParam("name","my_name").build();

    HttpEntity<String> requestEntity = new HttpEntity<>(null, getHeaders());

    ResponseEntity<String> strResponse = restTemplate.exchange(builder.toUriString(),HttpMethod.GET, requestEntity,
                        String.class,uriParam);

    //final URL: http://my-rest-url.org/rest/account/my_account?pageSize=2&page=0&name=my_name

RestTemplate: Build dynamic URI using UriComponents (URI variable and Request parameters)

How can I convert a DateTime to an int?

dateDate.Ticks

should give you what you're looking for.

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

DateTime.Ticks


If you're really looking for the Linux Epoch time (seconds since Jan 1, 1970), the accepted answer for this question should be relevant.


But if you're actually trying to "compress" a string representation of the date into an int, you should ask yourself why aren't you just storing it as a string to begin with. If you still want to do it after that, Stecya's answer is the right one. Keep in mind it won't fit into an int, you'll have to use a long.

JPA - Persisting a One to Many relationship

One way to do that is to set the cascade option on you "One" side of relationship:

class Employee {
   // 

   @OneToMany(cascade = {CascadeType.PERSIST})
   private Set<Vehicles> vehicles = new HashSet<Vehicles>();

   //
}

by this, when you call

Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);

it will save the vehicles too.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.

Just check your code for posible output or you can put the header on top of your method so it will be send first.

Print a string as hex bytes?

Just for convenience, very simple.

def hexlify_byteString(byteString, delim="%"):
    ''' very simple way to hexlify a bytestring using delimiters '''
    retval = ""
    for intval in byteString:
        retval += ( '0123456789ABCDEF'[int(intval / 16)])
        retval += ( '0123456789ABCDEF'[int(intval % 16)])
        retval += delim
    return( retval[:-1])

hexlify_byteString(b'Hello World!', ":")
# Out[439]: '48:65:6C:6C:6F:20:57:6F:72:6C:64:21'

Order by in Inner Join

In SQL, the order of the output is not defined unless you specify it in the ORDER BY clause.

Try this:

SELECT  *
FROM    one
JOIN    two
ON      one.one_name = two.one_name
ORDER BY
        one.id

Find the files that have been changed in last 24 hours

On GNU-compatible systems (i.e. Linux):

find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more

This will list files and directories that have been modified in the last 24 hours (-mtime 0). It will list them with the last modified time in a format that is both sortable and human-readable (%T+), followed by the file size (%s), followed by the full filename (%p), each separated by tabs (\t).

2>/dev/null throws away any stderr output, so that error messages don't muddy the waters; sort -r sorts the results by most recently modified first; and | more lists one page of results at a time.

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

Find out if string ends with another string in C++

bool EndsWith(const std::string& data, const std::string& suffix)
{
    return data.find(suffix, data.size() - suffix.size()) != string::npos;
}

Tests

#include <iostream>
int main()
{
   cout << EndsWith(u8"o!hello!1", u8"o!") << endl; 
   cout << EndsWith(u8"o!hello!", u8"o!") << endl; 
   cout << EndsWith(u8"hello!", u8"o!") << endl; 
   cout << EndsWith(u8"o!hello!o!", u8"o!") << endl; 
   return 0;
}

Output

0 
1 
1 
1 

How can I count text lines inside an DOM element? Can I?

Clone the container object and write 2 letters and calculate the height. This return the real height with all style applied, line height, etc. Now, calculate the height object / the size of a letter. In Jquery, the height excelude the padding, margin and border, it is great to calculate the real height of each line:

other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
lines = obj.height() /  size;

If you use a rare font with different height of each letter, this does not works. But works with all normal fonts, like Arial, mono, comics, Verdana, etc. Test with your font.

Example:

<div id="content" style="width: 100px">hello how are you? hello how are you? hello how are you?</div>
<script type="text/javascript">
$(document).ready(function(){

  calculate = function(obj){
    other = obj.clone();
    other.html('a<br>b').hide().appendTo('body');
    size = other.height() / 2;
    other.remove();
    return obj.height() /  size;
  }

  n = calculate($('#content'));
  alert(n + ' lines');
});
</script>

Result: 6 Lines

Works in all browser without rare functions out of standards.

Check: https://jsfiddle.net/gzceamtr/

How to check if any flags of a flag combination are set?

You could just check if the value is not zero.

if ((Int32)(letter & Letters.AB) != 0) { }

But I would consider it a better solution to introduce a new enumeration value with value zero and compare agains this enumeration value (if possible because you must be able to modify the enumeration).

[Flags]
enum Letters
{
    None = 0,
    A    = 1,
    B    = 2,
    C    = 4,
    AB   =  A | B,
    All  = AB | C
}

if (letter != Letters.None) { }

UPDATE

Missread the question - fixed the first suggestion and just ignore the second suggestion.

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

How do I get the SharedPreferences from a PreferenceActivity in Android?

import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);

Update

According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.

  2. Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.

(1) The recommended way is to use by the default mode, without specifying the file name

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

(2) Here is how you get the instance when you specify the file name

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:

int storedPreference = preferences.getInt("storedInt", 0);

To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also supports methods like remove() and clear() to delete the preference values from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also the same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

To see some more examples check Android's Data Storage post on developers site.

indexOf and lastIndexOf in PHP?

In php:

  • stripos() function is used to find the position of the first occurrence of a case-insensitive substring in a string.

  • strripos() function is used to find the position of the last occurrence of a case-insensitive substring in a string.

Sample code:

$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;

Output: Fist index = 2 Last index = 13

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

How to add leading zeros for for-loop in shell?

From bash 4.0 onward, you can use Brace Expansion with fixed length strings. See below for the original announcement.

It will do just what you need, and does not require anything external to the shell.

$ echo {01..05}
01 02 03 04 05

for num in {01..05}
do
  echo $num
done
01
02
03
04
05

CHANGES, release bash-4.0, section 3

This is a terse description of the new features added to bash-4.0 since the release of bash-3.2.

. . .

z. Brace expansion now allows zero-padding of expanded numeric values and will add the proper number of zeroes to make sure all values contain the same number of digits.

How do I express "if value is not empty" in the VBA language?

Alexphi's suggestion is good. You can also hard code this by first creating a variable as a Variant and then assigning it to Empty. Then do an if/then with to possibly fill it. If it gets filled, it's not empty, if it doesn't, it remains empty. You check this then with IsEmpty.

Sub TestforEmpty()

    Dim dt As Variant
    dt = Empty

    Dim today As Date
    today = Date
    If today = Date Then
        dt = today
    End If

    If IsEmpty(dt) Then
        MsgBox "It not is today"
    Else
        MsgBox "It is today"
    End If

End Sub

How to set image for bar button with swift?

You can use this code for multiple bar button with custom image:

self.navigationItem.leftBarButtonItem = nil

let button = UIButton(type: .custom)
button.setImage(UIImage (named: "ChatTab"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)

let button2 = UIButton(type: .custom)
button2.setImage(UIImage (named: "ActivityTab"), for: .normal)
button2.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)

let barButtonItem2 = UIBarButtonItem(customView: button2)
self.navigationItem.rightBarButtonItems = [barButtonItem, barButtonItem2]

Result will be this:

enter image description here

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

What is the best algorithm for overriding GetHashCode?

In case you want to polyfill HashCode from netstandard2.1

public static class HashCode
{
    public static int Combine(params object[] instances)
    {
        int hash = 17;

        foreach (var i in instances)
        {
            hash = unchecked((hash * 31) + (i?.GetHashCode() ?? 0));
        }

        return hash;
    }
}

Note: If used with struct, it will allocate memory due to boxing

How to create .pfx file from certificate and private key?

I know a few users have talked about installing this and that and adding command lines programmes and downloading...

Personally I am lazy and find all these methods cumbersome and slow, plus I don't want to download anything and find the correct cmd lines if I don't have to.

Best way for me on my personal IIS server is to use RapidSSLOnline. This is a tool that's on a server allows you to upload your certificate and private key and is able to generate a pfx file for you that you can directly import into IIS.

The link is here: https://www.rapidsslonline.com/ssl-tools/ssl-converter.php

Below is the steps used for the scenario requested.

  1. Select Current Type = PEM
  2. Change for = PFX
  3. Upload your certificate
  4. Upload your private key
  5. If you have ROOT CA cert or intermediate certs upload them too
  6. Set a password of your choosing, used in IIS
  7. Click the reCaptcha to prove you're not a bot
  8. Click Convert

And that's it you should have a PFX downloaded and use this in your Import process on IIS.

Hope this helps other like minded, lazy tech people.

Java collections convert a string to a list of characters

Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.

List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar) 
{
    characterList.add(aChar); //  autoboxing 
}

Maven plugin not using Eclipse's proxy settings

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

     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.somewhere.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
        </proxy>
      </proxies>

    </settings>

Window > Preferences > Maven > User Settings

enter image description here

How to clear radio button in Javascript?

YES<input type="radio" name="group1" id="sal" value="YES" >

NO<input type="radio" name="group1" id="sal1" value="NO" >

<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">

string in namespace std does not name a type

Nouns.h doesn't include <string>, but it needs to. You need to add

#include <string>

at the top of that file, otherwise the compiler doesn't know what std::string is when it is encountered for the first time.

Encode URL in JavaScript?

Here is a LIVE DEMO of encodeURIComponent() and decodeURIComponent() JS built in functions:

<!DOCTYPE html>
<html>
  <head>
    <style>
      textarea{
        width:30%;
        height:100px;
      }
    </style>
    <script>
      // encode string to base64
      function encode()
      {
        var txt = document.getElementById("txt1").value;
        var result = btoa(txt);
        document.getElementById("txt2").value = result;
      }
      // decode base64 back to original string
      function decode()
      {
        var txt = document.getElementById("txt3").value;
        var result = atob(txt);
        document.getElementById("txt4").value = result;
      }
    </script>
  </head>
  <body>
    <div>
      <textarea id="txt1">Some text to decode
      </textarea>
    </div>
    <div>
      <input type="button" id="btnencode" value="Encode" onClick="encode()"/>
    </div>
    <div>
      <textarea id="txt2">
      </textarea>
    </div>
    <br/>
    <div>
      <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
      </textarea>
    </div>
    <div>
      <input type="button" id="btndecode" value="Decode" onClick="decode()"/>
    </div>
    <div>
      <textarea id="txt4">
      </textarea>
    </div>
  </body>
</html>

oracle varchar to number

select to_number(exception_value) from exception where to_number(exception_value) = 105

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

Replacing few values in a pandas dataframe column with another value

Just wanted to show that there is no performance difference between the 2 main ways of doing it:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))

def loc():
    df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


def replace():
    df2['A'].replace(
        to_replace=2,
        value=5,
        inplace=True
    )
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

JSON string to JS object

The string you are returning is not valid JSON. The names in the objects needs to be quoted and the whole string needs to be put in { … } to form an object. JSON also cannot contain something like new Date(). JSON is just a small subset of JavaScript that has only strings, numbers, objects, arrays, true, false and null.

See the JSON grammar for more information.

How can I iterate over files in a given directory?

Here's how I iterate through files in Python:

import os

path = 'the/name/of/your/path'

folder = os.fsencode(path)

filenames = []

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...
        filenames.append(filename)

filenames.sort() # now you have the filenames and can do something with them

NONE OF THESE TECHNIQUES GUARANTEE ANY ITERATION ORDERING

Yup, super unpredictable. Notice that I sort the filenames, which is important if the order of the files matters, i.e. for video frames or time dependent data collection. Be sure to put indices in your filenames though!

how to show calendar on text box click in html

try to use jquery-ui

<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>

<script>   
    $(function() {
         $( "#calendar" ).datepicker();   
    }); 
</script>

<p>Calendar: <input type="text" id="calendar" /></p>

more

illegal use of break statement; javascript

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game == 1) {
           return
        }
    }
}

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated

python, sort descending dataframe with pandas

For pandas 0.17 and above, use this :

test = df.sort_values('one', ascending=False)

Since 'one' is a series in the pandas data frame, hence pandas will not accept the arguments in the form of a list.

How can I pass parameters to a partial view in mvc 4

For Asp.Net core you better use

<partial name="_MyPartialView" model="MyModel" />

So for example

@foreach (var item in Model)
{
   <partial name="_MyItemView" model="item" />
}

How can I add an element after another element?

Solved jQuery: Add element after another element

<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>

OR

<script type="text/javascript"> 
jQuery(document).ready(function(){
jQuery ( ".sidebar_cart" ) .append( "<a href='http://#'>Continue Shopping</a>" );
});
</script>

How to change DataTable columns order

If you have more than 2-3 columns, SetOrdinal is not the way to go. A DataView's ToTable method accepts a parameter array of column names. Order your columns there:

DataView dataView = dataTable.DefaultView;
dataTable = dataView.ToTable(true, "Qty", "Unit", "Id");

@viewChild not working - cannot read property nativeElement of undefined

The accepted answer is correct in all means and I stumbled upon this thread after I couldn't get the Google Map render in one of my app components.

Now, if you are on a recent angular version i.e. 7+ of angular then you will have to deal with the following ViewChild declaration i.e.

@ViewChild(selector: string | Function | Type<any>, opts: {
read?: any;
static: boolean;
})

Now, the interesting part is the static value, which by definition says

  • static - True to resolve query results before change detection runs

Now for rendering a map, I used the following ,

@ViewChild('map', { static: true }) mapElement: any;
  map: google.maps.Map;

laravel 5 : Class 'input' not found

Miscall of Class it should be Input not input

How can I multiply all items in a list together with Python?

The simple way is:

import numpy as np
np.exp(np.log(your_array).sum())

How do I kill this tomcat process in Terminal?

just type the below command in terminal

ps -ef |grep 'catalina'

copy the value of process id then type the following command and paste process id

 kill -9 processid

Get Specific Columns Using “With()” Function in Laravel Eloquent

You can try this code . It is tested in laravel 6 version.

Controller code
 public function getSection(Request $request)
{

  Section::with(['sectionType' => function($q) {
      $q->select('id', 'name');
  }])->where('position',1)->orderBy('serial_no', 'asc')->get(['id','name','','description']);
  return response()->json($getSection);
}
Model code
public function sectionType(){
    return $this->belongsTo(Section_Type::class, 'type_id');
}