Programs & Examples On #Carrierwave

A modern ruby gem for file uploads in Rails and other frameworks, similar to paperclip and attachment_fu

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

**

bundle install --no-deployment

**

$ jekyll help

jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby

How to replace spaces in file names using a bash script

you can use this:

    find . -name '* *' | while read fname 

do
        new_fname=`echo $fname | tr " " "_"`

        if [ -e $new_fname ]
        then
                echo "File $new_fname already exists. Not replacing $fname"
        else
                echo "Creating new file $new_fname to replace $fname"
                mv "$fname" $new_fname
        fi
done

Can you delete data from influxdb?

With influx, you can only delete by time

For example, the following are invalid:

#Wrong
DELETE FROM foo WHERE time < '2014-06-30' and duration > 1000 #Can't delete if where clause has non time entity

This is how I was able to delete the data

DELETE FROM foo WHERE time > '2014-06-30' and time < '2014-06-30 15:16:01'

Update: this worked on influx 8. Supposedly it doesn't work on influx 9

webpack: Module not found: Error: Can't resolve (with relative path)

changing templateUrl: '' to template: '' fixed it

Bash syntax error: unexpected end of file

Apparently, some versions of the shell can also emit this message when the final line of your script lacks a newline.

How to select the row with the maximum value in each group

Another data.table solution:

library(data.table)
setDT(group)[, head(.SD[order(-pt)], 1), by = .(Subject)]

How should I remove all the leading spaces from a string? - swift

For swift 3.0

import Foundation

var str = " Hear me calling"

extension String {
    var stringByRemovingWhitespaces: String {
        return components(separatedBy: .whitespaces).joined()
    }
}

str.stringByRemovingWhitespaces  // Hearmecalling

How do I force make/GCC to show me the commands?

Depending on your automake version, you can also use this:

make AM_DEFAULT_VERBOSITY=1

Reference: AM_DEFAULT_VERBOSITY

Note: I added this answer since V=1 did not work for me.

UTF-8 byte[] to String

Here's a simplified function that will read in bytes and create a string. It assumes you probably already know what encoding the file is in (and otherwise defaults).

static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";

public static String readFileToString(String filePath, String encoding) throws IOException {

    if (encoding == null || encoding.length() == 0)
        encoding = DEFAULT_ENCODING;

    StringBuffer content = new StringBuffer();

    FileInputStream fis = new FileInputStream(new File(filePath));
    byte[] buffer = new byte[BUFF_SIZE];

    int bytesRead = 0;
    while ((bytesRead = fis.read(buffer)) != -1)
        content.append(new String(buffer, 0, bytesRead, encoding));

    fis.close();        
    return content.toString();
}

How long do browsers cache HTTP 301s?

I will post answer that helped me:

go to url:

chrome://settings/clearBrowserData

it should invoke popup and then..

  • select only: cached images and files.
  • select time box : from beginning

Better way to represent array in java properties file

Didn't exactly get your intent. Do check Apache Commons configuration library http://commons.apache.org/configuration/

You can have multiple values against a key as in key=value1,value2 and you can read this into an array as configuration.getAsStringArray("key")

R legend placement in a plot

Edit 2017:

use ggplot and theme(legend.position = ""):

library(ggplot2)
library(reshape2)

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

df = data.frame(number = 1:5,a,b,c)
df_long <- melt(df,id.vars = "number")
ggplot(data=df_long,aes(x = number,y=value, colour=variable)) +geom_line() +
theme(legend.position="bottom")

Original answer 2012: Put the legend on the bottom:

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

dev.off()

layout(rbind(1,2), heights=c(7,1))  # put legend on bottom 1/8th of the chart

plot(a,type='l',ylim=c(min(c(a,b,c)),max(c(a,b,c))))
lines(b,lty=2)
lines(c,lty=3,col='blue')

# setup for no margins on the legend
par(mar=c(0, 0, 0, 0))
# c(bottom, left, top, right)
plot.new()
legend('center','groups',c("A","B","C"), lty = c(1,2,3),
       col=c('black','black','blue'),ncol=3,bty ="n")

enter image description here

SQL Statement with multiple SETs and WHEREs

Best option is multiple updates.

Alternatively you can do the following but is NOT recommended:

UPDATE table
SET ID = CASE WHEN ID = 2555 THEN 111111259 
              WHEN ID = 2724 THEN 111111261
              WHEN ID = 2021 THEN 111111263
              WHEN ID = 2017 THEN 111111264
         END
WHERE ID IN (2555,2724,2021,2017)

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

I am sure what Artem Bilan has explained here might be one of the reasons for this error:

Caused by: com.rabbitmq.client.AuthenticationFailureException: 
ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. 
For details see the

but the solution for me was that I logged in to rabbitMQ admin page (http://localhost:15672/#/users) with the default user name and password which is guest/guest then added a new user and for that new user I enabled the permission to access it from virtual host and then used the new user name and password instead of default guest and that cleared the error.

enter image description here

Change the bullet color of list

I would recommend you to use background-image instead of default list.

.listStyle {
    list-style: none;
    background: url(image_path.jpg) no-repeat left center;
    padding-left: 30px;
    width: 20px;
    height: 20px;
}

Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:

.liststyle{
    list-style: none;
    margin: 0;
    padding: 0;
}
.liststyle:before {
    content: "• ";
    color: red; /* or whatever color you prefer */
    font-size: 20px;/* or whatever the bullet size you prefer */
}

Spring Boot and multiple external configuration files

this is one simple approach using spring boot

TestClass.java

@Configuration
@Profile("one")
@PropertySource("file:/{selected location}/app.properties")
public class TestClass {

    @Autowired
    Environment env;

    @Bean
    public boolean test() {
        System.out.println(env.getProperty("test.one"));
        return true;
    }
}

the app.properties context, in your selected location

test.one = 1234

your spring boot application

@SpringBootApplication

public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(testApplication.class, args);
    }
}

and the predefined application.properties context

spring.profiles.active = one

you can write as many configuration class as you like and enable/disable them just by setting spring.profiles.active = the profile name/names {separated by commas}

as you can see spring boot is great it just needs sometime to get familiar with, it's worth mentioning that you may use @Value on your fields as well

@Value("${test.one}")
String str;

oracle plsql: how to parse XML and insert into table

select *  
FROM XMLTABLE('/person/row'  
         PASSING   
            xmltype('
                <person>
                   <row>
                       <name>Tom</name>
                       <Address>
                           <State>California</State>
                           <City>Los angeles</City>
                       </Address>
                   </row>
                   <row>
                       <name>Jim</name>
                       <Address>
                           <State>California</State>
                           <City>Los angeles</City>
                       </Address>
                   </row>
                </person>
            ')
         COLUMNS  
            --describe columns and path to them:  
            name  varchar2(20)    PATH './name',  
            state varchar2(20)    PATH './Address/State',  
            city  varchar2(20)    PATH './Address/City'
     ) xmlt  
;  

Copy / Put text on the clipboard with FireFox, Safari and Chrome

For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around available using Flash.

function copyIntoClipboard(text) {

    var flashId = 'flashId-HKxmj5';

    /* Replace this with your clipboard.swf location */
    var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';

    if(!document.getElementById(flashId)) {
        var div = document.createElement('div');
        div.id = flashId;
        document.body.appendChild(div);
    }
    document.getElementById(flashId).innerHTML = '';
    var content = '<embed src="' + 
        clipboardSWF +
        '" FlashVars="clipboard=' + encodeURIComponent(text) +
        '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashId).innerHTML = content;
}

The only disadvantage is that this requires Flash to be enabled.

source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is it's Google cache)

C# Lambda expressions: Why should I use them?

This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:

List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");

strings.Find(s => s == "hello");

This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this:

List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");

private static bool FindHello(String s)
{
    return s == "hello";
}

strings.Find(FindHello);

EDIT:

In C# 2.0, this could be done using the anonymous delegate syntax:

  strings.Find(delegate(String s) { return s == "hello"; });

Lambda's significantly cleaned up that syntax.

How to set image in circle in swift

For Swift 4:

import UIKit

extension UIImageView {

func makeRounded() {
    let radius = self.frame.width/2.0
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = true
   }
}

Pandas "Can only compare identically-labeled DataFrame objects" error

Here's a small example to demonstrate this (which only applied to DataFrames, not Series, until Pandas 0.19 where it applies to both):

In [1]: df1 = pd.DataFrame([[1, 2], [3, 4]])

In [2]: df2 = pd.DataFrame([[3, 4], [1, 2]], index=[1, 0])

In [3]: df1 == df2
Exception: Can only compare identically-labeled DataFrame objects

One solution is to sort the index first (Note: some functions require sorted indexes):

In [4]: df2.sort_index(inplace=True)

In [5]: df1 == df2
Out[5]: 
      0     1
0  True  True
1  True  True

Note: == is also sensitive to the order of columns, so you may have to use sort_index(axis=1):

In [11]: df1.sort_index().sort_index(axis=1) == df2.sort_index().sort_index(axis=1)
Out[11]: 
      0     1
0  True  True
1  True  True

Note: This can still raise (if the index/columns aren't identically labelled after sorting).

What are App Domains in Facebook Apps?

In this example:

http://www.example.com:80/somepage?parameter1="hello"&parameter2="world"

the bold part is the Domainname. 80 is rarely included. I post it since many people may wonder if 3000 or some other port is part of the domain if their not staging their app for production yet. Normally you don't specify it since 80 is the default, but if you just want to specify localhost just do it without the port number, it works just as fine. The adress, though, should be http://localhost:3000 (if you have it on that port).

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

Javascript Array.sort implementation?

I've just had a look at the WebKit (Chrome, Safari …) source. Depending on the type of array, different sort methods are used:

Numeric arrays (or arrays of primitive type) are sorted using the C++ standard library function std::qsort which implements some variation of quicksort (usually introsort).

Contiguous arrays of non-numeric type are stringified and sorted using mergesort, if available (to obtain a stable sorting) or qsort if no merge sort is available.

For other types (non-contiguous arrays and presumably for associative arrays) WebKit uses either selection sort (which they call “min” sort) or, in some cases, it sorts via an AVL tree. Unfortunately, the documentation here is rather vague so you’d have to trace the code paths to actually see for which types which sort method is used.

And then there are gems like this comment:

// FIXME: Since we sort by string value, a fast algorithm might be to use a
// radix sort. That would be O(N) rather than O(N log N).

– Let’s just hope that whoever actually “fixes” this has a better understanding of asymptotic runtime than the writer of this comment, and realises that radix sort has a slightly more complex runtime description than simply O(N).

(Thanks to phsource for pointing out the error in the original answer.)

How do you run a single query through mysql from the command line?

mysql -u <user> -p -e "select * from schema.table"

Android WebView, how to handle redirects in app instead of opening a browser

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
    super.onPageStarted(view, url, favicon);
    if (url.equals("your url")) {
        
            Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
            startActivity(intent);
        
    }
}

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

View a file in a different Git branch without changing branches

A simple, newbie friendly way for looking into a file: git gui browser <branch> which lets you explore the contents of any file.

It's also there in the File menu of git gui. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Reduce git repository size

git gc --aggressive is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now). You have other commands to clean the repo too. Don't forget though, sometimes git gc alone can increase the size of the repo!

It can be also used after a filter-branch, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch can keep backup refs in .git/refs/original, so that directory can be cleaned too.

Finally, as mentioned in this comment and this question; cleaning the reflog can help:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository


Update Feb. 2021, eleven years later: the new git maintenance command (man page) should supersede git gc, and can be scheduled.

(grep) Regex to match non-ASCII characters?

[^\x00-\x7F] and [^[:ascii:]] miss some control bytes so strings can be the better option sometimes. For example cat test.torrent | perl -pe 's/[^[:ascii:]]+/\n/g' will do odd things to your terminal, where as strings test.torrent will behave.

Getting user input

Use the raw_input() function to get input from users (2.x):

print "Enter a file name:",
filename = raw_input()

or just:

filename = raw_input('Enter a file name: ')

or if in Python 3.x:

filename = input('Enter a file name: ')

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

How to Allow Remote Access to PostgreSQL database

A fast shortcut for restarting service on Windows:

1) Press Windows Key + R

2) Type "services.msc"

enter image description here

3) Order by name

4) Find "PostgreSQL" service and restart it.

enter image description here

Duplicate / Copy records in the same MySQL table

I have a similar issue, and this is what I'm doing:

insert into Preguntas  (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` )  select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18

Been Preguntas:

CREATE TABLE IF NOT EXISTS `Preguntas` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `EncuestaID` int(11) DEFAULT NULL,
  `Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Seccion` int(11) DEFAULT NULL,
  `RespuestaID` bigint(11) DEFAULT NULL,
  `Texto` text COLLATE utf8_unicode_ci ,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;

So, the ID is automatically incremented and also I'm using a fixed value ('23') for EncuestaID.

Execute and get the output of a shell command in node.js

Thanks to Renato answer, I have created a really basic example:

const exec = require('child_process').exec

exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))

It will just print your global git username :)

Expand a random range from 1–5 to 1–7

For values 0-7 you have the following:

0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111

From bitwise from left to right Rand5() has p(1) = {2/5, 2/5, 3/5}. So if we complement those probability distributions (~Rand5()) we should be able to use that to produce our number. I'll try to report back later with a solution. Anyone have any thoughts?

R

Oracle select most recent date record

you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)

also you cannot use OVER clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)

select *
from (select
  staff_id, site_id, pay_level, date, 
  max(date) over (partition by staff_id) max_date
  from owner.table
  where end_enrollment_date is null
)
where date = max_date

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Try this - set Ajax call by setting up the header as follows:

var uri = "http://localhost:50869/odata/mydatafeeds"
$.ajax({
    url: uri,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Negotiate");
    },
    async: true,
    success: function (data) {
        alert(JSON.stringify(data));
    },
    error: function (xhr, textStatus, errorMessage) {
        alert(errorMessage);
    }                
});

Then run your code by opening Chrome with the following command line:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

IE8 support for CSS Media Query

Internet Explorer versions before IE9 do not support media queries.

If you are looking for a way of degrading the design for IE8 users, you may find IE's conditional commenting helpful. Using this, you can specify an IE 8/7/6 specific style sheet which over writes the previous rules.

For example:

<link rel="stylesheet" type="text/css" media="all" href="style.css"/>
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ie.css"/>
<![endif]-->

This won't allow for a responsive design in IE8, but could be a simpler and more accessible solution than using a JS plugin.

How to declare a global variable in php?

Add your variables in $GLOBALS super global array like

$GLOBALS['variable'] = 'localhost'; 

and use it globally

or you can use constant which are accessible throughout the script

define('HOSTNAME', 'localhost');  

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

How to block users from closing a window in Javascript?

How about that?

function internalHandler(e) {
    e.preventDefault(); // required in some browsers
    e.returnValue = ""; // required in some browsers
    return "Custom message to show to the user"; // only works in old browsers
}

if (window.addEventListener) {
    window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
    window.attachEvent('onbeforeunload', internalHandler);
}

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Identify "project navigator" or "package explorer" view.
    Right click on your project, select Build Path --> Configure build Path.

  2. In the emerging window, you will find four tabs, select "Libraries".There, under "Web app libraries" (expand it), you will see the libraries added to the project's classpath. Check if all of them are available. If one or more are not (they'll have "missing" beside their name and a red mark on their icon), check if you need them (perhaps you don't); if you don't need them, remove it, if you need them, exit this window, look out for the missing jar and IMPORT it into your project.

SQL Server: how to create a stored procedure

Create this way.

Create procedure dept_count(dept_name varchar(20),d_count integer)
   begin
     select count(*) into d_count
     from instructor
     where instructor.dept_name=dept_count.dept_name
   end

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I solved this issue after changing the "Gradle Version" and "Android Plugin version".

You just goto "File>>Project Structure>>Project>>" and make changes here. I have worked a combination of versions from another working project of mine and added to the Project where I was getting this problem.

How do I undo the most recent local commits in Git?

Undo the last commit:

git reset --soft HEAD^ or git reset --soft HEAD~

This will undo the last commit.

Here --soft means reset into staging.

HEAD~ or HEAD^ means to move to commit before HEAD.

Replace the last commit to new commit:

git commit --amend -m "message"

It will replace the last commit with the new commit.

Use jQuery to get the file input's selected filename without the path

Here is how I do it, it works pretty well.

In your HTML do:

<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />

Then in your js file create a simple function:

function fileSelect(id, e){
    console.log(e.target.files[0].name);
}

If you're doing multiple files, you should also be able to get the list by looping over this:

e.target.files[0].name

What does '&' do in a C++ declaration?

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

This is invalid code on several counts. Running it through g++ gives:

crap.cpp: In function ‘int main()’:
crap.cpp:11: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int*’
crap.cpp:3: error: in passing argument 1 of ‘int add(int&)’
crap.cpp: In function ‘int add(int&)’:
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:20: error: invalid type argument of ‘unary *’

A valid version of the code reads:

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            p=p+100;
            return p;
}

What is happening here is that you are passing a variable "as is" to your function. This is roughly equivalent to:

int add(int *p)
{
      *p=*p+100;
      return *p;
}

However, passing a reference to a function ensures that you cannot do things like pointer arithmetic with the reference. For example:

int add(int &p)
{
            *p=*p+100;
            return p;
}

is invalid.

If you must use a pointer to a reference, that has to be done explicitly:

int add(int &p)
{
                    int* i = &p;
            i=i+100L;
            return *i;
}

Which on a test run gives (as expected) junk output:

The value of the variable number before calling the function : 5
The value of the variable number after the function is returned : 5
The value of result : 1399090792

Add image to left of text via css

.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px;  /* width of the image plus a little extra padding */
display: block;  /* may not need this, but I've found I do */
}

Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).

OpenCV NoneType object has no attribute shape

I had this issue with cap = cv2.VideoCapture(0). I changed this to cap = cv2.VideoCapture(1) and then it worked. Since it wasn't linked to the right webcam it was returning nothing. Maybe this will help good luck.

How do I disable directory browsing?

This is not an answer, just my experience:

On my Ubuntu 12.04 apache2, didn't find Indexes in either apache2.conf or httpd.conf, luckily I found it in sites-available/default. After removing it, now it doesn't see directory listing. May have to do it for sites-available/default-ssl.

What is a C++ delegate?

You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.


Option 1 : functors:

A function object may be created by implementing operator()

struct Functor
{
     // Normal class/struct members

     int operator()(double d) // Arbitrary return types and parameter list
     {
          return (int) d + 1;
     }
};

// Use:
Functor f;
int i = f(3.14);

Option 2: lambda expressions (C++11 only)

// Syntax is roughly: [capture](parameter list) -> return type {block}
// Some shortcuts exist
auto func = [](int i) -> double { return 2*i/1.15; };
double d = func(1);

Option 3: function pointers

int f(double d) { ... }
typedef int (*MyFuncT) (double d);
MyFuncT fp = &f;
int a = fp(3.14);

Option 4: pointer to member functions (fastest solution)

See Fast C++ Delegate (on The Code Project).

struct DelegateList
{
     int f1(double d) { }
     int f2(double d) { }
};

typedef int (DelegateList::* DelegateType)(double d);

DelegateType d = &DelegateList::f1;
DelegateList list;
int a = (list.*d)(3.14);

Option 5: std::function

(or boost::function if your standard library doesn't support it). It is slower, but it is the most flexible.

#include <functional>
std::function<int(double)> f = [can be set to about anything in this answer]
// Usually more useful as a parameter to another functions

Option 6: binding (using std::bind)

Allows setting some parameters in advance, convenient to call a member function for instance.

struct MyClass
{
    int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
};

std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11

Option 7: templates

Accept anything as long as it matches the argument list.

template <class FunctionT>
int DoSomething(FunctionT func)
{
    return func(3.14);
}

Save results to csv file with Python

I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.

import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')

(This answer posted 6 years later, for posterity's sake.)

In a different case similar to what you're asking about, say you have two columns like this:

names = ['Player Name', 'Foo', 'Bar']
scores = ['Score', 250, 500]

You could save it like this:

np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s')

scores.csv would look like this:

Player Name,Score
Foo,250
Bar,500

How to calculate mean, median, mode and range from a set of numbers

Here's the complete clean and optimised code in JAVA 8

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

public class Solution {

public static void main(String[] args) {

    /*Take input from user*/
    Scanner sc = new Scanner(System.in);

    int n =0;
    n = sc.nextInt();
    
    int arr[] = new int[n];
    
    //////////////mean code starts here//////////////////
    int sum = 0;
    for(int i=0;i<n; i++)
    {
         arr[i] = sc.nextInt();
         sum += arr[i]; 
    }
    System.out.println((double)sum/n); 
    //////////////mean code ends here//////////////////


    //////////////median code starts here//////////////////
    Arrays.sort(arr);
    int val = arr.length/2;
    System.out.println((arr[val]+arr[val-1])/2.0); 
    //////////////median code ends here//////////////////


    //////////////mode code starts here//////////////////
    int maxValue=0;
    int maxCount=0;

    for(int i=0; i<n; ++i)
    {
        int count=0;

        for(int j=0; j<n; ++j)
        {
            if(arr[j] == arr[i])
            {
                ++count;
            }

            if(count > maxCount)
            {
                maxCount = count;
                maxValue = arr[i];
            }
        }
    } 
    System.out.println(maxValue);
   //////////////mode code ends here//////////////////

  }

}

Node.js: socket.io close client connection

try this to close the connection:

socket.close();

and if you want to open it again:

socket.connect();

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If you are like me, and are staring at this thread thinking "But I'm not trying to add a component, I am trying to add a guard/service/pipe, etc." then the issue is likely that you have added the wrong type to a routing path. That is what I did. I accidentally added a guard to the component: section of a path instead of the canActivate: section. I love IDE autocomplete but you have to slow down a bit and pay attention. If you absolutely can't find it, do a global search for the name it is complaining about and look at every usage to make sure you didn't slip-up with a name.

why windows 7 task scheduler task fails with error 2147942667

For me it was the "Start In" - I copied the values from an older server, and updated the path to the new .exe location, but I forgot to update the "start in" location - if it doesn't exist, you get this error too

Quoting @hans-passant 's comment from above, because it is valuable to debugging this issue:

Convert the error code to hex to get 0x8007010B. The 7 makes it a Windows error. Which makes 010B error code 267. "The directory name is invalid". Sure, that happens.

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Best way to integrate Python and JavaScript?

You might also want to check out the PyPy project - they have a Python to (anything) compiler, including Python to Javascript, C, and llvm. This allows you to write your code in Python and then compile it into Javascript as you desire.

http://codespeak.net/pypy

Also, check out the informative blog:

http://morepypy.blogspot.com/

Unfortunately though, you can't convert Javascript to Python this way. It seems to work really well overall, they used to have a Javascript (made from compiled Python) version of the Bub'n'Bros game online (though the server has been down for a while).

http://bub-n-bros.sourceforge.net

How to check if all of the following items are in a list?

I would probably use set in the following manner :

set(l).issuperset(set(['a','b'])) 

or the other way round :

set(['a','b']).issubset(set(l)) 

I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...

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

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

JSON string

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

Pretty Print JSON

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

Minify JSON

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

How does OAuth 2 protect against things like replay attacks using the Security Token?

Here is perhaps the simplest explanation of how OAuth2 works for all 4 grant types, i.e., 4 different flows where the app can acquire the access token.

Similarity

All grant type flows have 2 parts:

  • Get access token
  • Use access token

The 2nd part 'use access token' is the same for all flows

Difference

The 1st part of the flow 'get access token' for each grant type varies.

However, in general the 'get access token' part can be summarized as consisting 5 steps:

  1. Pre-register your app (client) with OAuth provider, e.g., Twitter, etc. to get client id/secret
  2. Create a social login button with client id & required scopes/permissions on your page so when clicked user gets redirected to OAuth provider to be authenticated
  3. OAuth provider request user to grant permission to your app (client)
  4. OAuth provider issues code
  5. App (client) acquires access token

Here is a side-by-side diagram comparing how each grant type flow is different based on the 5 steps.

This diagram is from https://blog.oauth.io/introduction-oauth2-flow-diagrams/

enter image description here

Each have different levels of implementation difficulty, security, and uses cases. Depending on your needs and situation, you will have to use one of them. Which to use?

Client Credential: If your app is only serving a single user

Resource Owner Password Crendential: This should be used only as last resort as the user has to hand over his credentials to the app, which means the app can do everything the user can

Authorization Code: The best way to get user authorization

Implicit: If you app is mobile or single-page app

There is more explanation of the choice here: https://blog.oauth.io/choose-oauth2-flow-grant-types-for-app/

Stopping a CSS3 Animation on last frame

If you want to add this behaviour to a shorthand animation property definition, the order of sub-properties is as follows

animation-name - default none

animation-duration - default 0s

animation-timing-function - default ease

animation-delay - default 0s

animation-iteration-count - default 1

animation-direction - default normal

animation-fill-mode - you need to set this to forwards

animation-play-state - default running

Therefore in the most common case, the result will be something like this

animation: colorchange 1s ease 0s 1 normal forwards;

See the MDN documentation here

Spring,Request method 'POST' not supported

I had csrf enabled in my sprint security xml file, so I just added one line in the form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> 

This way I was able to submit the form having the model attribute.

jQuery: load txt file and insert into div

 <script type="text/javascript">     
   $("#textFileID").html("Loading...").load("URL TEXT");
 </script>  

 <div id="textFileID"></div>

Spring Boot - Cannot determine embedded database driver class for database type NONE

Doing below works.

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

But If I wanted to have dataSource, I should not do the above configuration. The below link says that we need to all the properties in application.properties file. All the properties should start with spring.datasource.*

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

What are the ascii values of up down left right?

Gaa! Go to asciitable.com. The arrow keys are the control equivalent of the HJKL keys. I.e., in vi create a big block of text. Note you can move around in that text using the HJKL keys. The arrow keys are going to be ^H, ^J, ^K, ^L.

At asciitable.com find, "K" in the third column. Now, look at the same row in the first column to find the matching control-code ("VT" in this case).

Is it possible to insert HTML content in XML document?

Please see this.

Text inside a CDATA section will be ignored by the parser.

http://www.w3schools.com/xml/dom_cdatasection.asp

This is will help you to understand the basics about XML

Are multiple `.gitignore`s frowned on?

There are many scenarios where you want to commit a directory to your Git repo but without the files in it, for example the logs, cache, uploads directories etc.

So what I always do is to add a .gitignore file in those directories with the following content:

*
!.gitignore

With this .gitignore file, Git will not track any files in those directories yet still allow me to add the .gitignore file and hence the directory itself to the repo.

Bootstrap 3 Navbar with Logo

Well I finally got this same problem working, here is my solution and I tested it on my site in all three major browsers: Chrome, Firefox, and Internet Explorer.

First of all if you are not using a text based logo then remove "navbar-brand" completely as I found this particular class to be the main cause of my collapsed nav menu doubling up.

Shout out to user3137032 for leading me in the right direction.

You have to make a custom responsive image container, I called mine "logo"

Here is the bootstrap HTML mark up:

<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="@Url.Action(" Index ", "Home ")" class="logo"><img src="~/resources/images/Logo_Concept.png" /></a>
    </div>
    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li>
          <a href="@Url.Action(" About ", "Home ")">
            <i class="glyphicon glyphicon-info-sign"></i> About
          </a>
        </li>
        <li>
          <a href="@Url.Action(" Contact ", "Home ")">
            <i class="glyphicon glyphicon-phone"></i> Contact
          </a>
        </li>
        <li>
          <a href="@Url.Action(" Index ", "Products ")">
            <i class="glyphicon glyphicon-tag"></i> Products
          </a>
        </li>
      </ul>
    </div>
  </div>
</div>

And the CSS code:

.logo img {
width: 100% \9; /*Force IE10 and below to size SVG images correctly*/
max-width: 100%;
}

@media (max-width:480px) { 
.logo img {
    width: 70% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 70% !important;
}
}

@media (max-width:400px) { 
.logo img {
    width: 75% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 75%;
}
}

@media (max-width:385px) { 
.logo img {
    width: 70% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 70%;
}
}

@media (max-width:345px) { 
.logo img {
    width: 65% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 65%;
}
}

@media (max-width:335px) { 
.logo img {
    width: 60% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 60%;
}
}

@media (max-width:325px) { 
.logo img {
    width: 55% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 55%;
}
}

@media (max-width:315px) { 
.logo img {
    width: 50% \9; /*Force IE10 and below to size SVG images correctly*/
    max-width: 50%;
}
}

The value in @media (max-width: x) may vary depending on your logo images width, mine is 368px. The percentages may need to be changed as well depending on your logo's size. The first @media query should be your threshold and mine was image width (368px) + collapsed button size (44px) + about 60px and it came out to 480px which is where I start the responsive image scaling.

Please be sure to remove my razor syntax from the HTML portions. Let me know if it fixes your problem, it fixed mine.

Edit: Sorry, I missed your navbar height issue. There are a couple ways to go about it, personally I compile the Bootstrap LESS with the appropriate navbar height, for my purposes I use 70px, and my image height is 68 px. The second way to do it is in the bootstrap.css file itself, search for ".navbar" and change min-height: to the height of your logo.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I know this is quite an old one, but I faced similar issue and resolved it in a different way. The actuator-autoconfigure pom somehow was invalid and so it was throwing IllegalStateException. I removed the actuator* dependencies from my maven repo and did a Maven update in eclipse, which then downloaded the correct/valid dependencies and resolved my issue.

How to get commit history for just one branch?

You can use only git log --oneline

Replace new line/return with space using regex

I found this.

String newString = string.replaceAll("\n", " ");

Although, as you have a double line, you will get a double space. I guess you could then do another replace all to replace double spaces with a single one.

If that doesn't work try doing:

string.replaceAll(System.getProperty("line.separator"), " ");

If I create lines in "string" by using "\n" I had to use "\n" in the regex. If I used System.getProperty() I had to use that.

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

How to hide scrollbar in Firefox?

::-webkit-scrollbar {
  display: none;
}

It will not work in Firefox, as the Firefox abandoned the support for hidden scrollbars with functionality (you can use overflow: -moz-scrollbars-none; in old versions).

C++ cast to derived class

First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast or return NULL pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:

DerivedType m_derivedType = m_baseType;

Here there is no casting. You are creating a new object of type DerivedType and try to initialize it with value of m_baseType variable.

Next line is not much better:

DerivedType m_derivedType = (DerivedType)m_baseType;

Here you are creating a temporary of DerivedType type initialized with m_baseType value.

The last line

DerivedType * m_derivedType = (DerivedType*) & m_baseType;

should compile provided that BaseType is a direct or indirect public base class of DerivedType. It has two flaws anyway:

  1. You use deprecated C-style cast. The proper way for such casts is
    static_cast<DerivedType *>(&m_baseType)
  2. The actual type of casted object is not of DerivedType (as it was defined as BaseType m_baseType; so any use of m_derivedType pointer will result in undefined behaviour.

Android button with icon and text

Try this one.

<Button
    android:id="@+id/bSearch"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:text="Search"
    android:drawableLeft="@android:drawable/ic_menu_search"
    android:textSize="24sp"/>

How do I format a String in an email so Outlook will print the line breaks?

You can force a line break in outlook when attaching one (or two?) tab characters (\t) just before the line break (CRLF).

Example:

This is my heading in the mail\t\n
Just here Outlook is forced to begin a new line.

It seems to work on Outlook 2010. Please test if this works on other versions.

See also Outlook autocleaning my line breaks and screwing up my email format

CSS div 100% height

try setting the body style to:

body { position:relative;}

it worked for me

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

As @user3483203 pointed out, numpy.select is the best approach

Store your conditional statements and the corresponding actions in two lists

conds = [(df['eri_hispanic'] == 1),(df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1)),(df['eri_nat_amer'] == 1),(df['eri_asian'] == 1),(df['eri_afr_amer'] == 1),(df['eri_hawaiian'] == 1),(df['eri_white'] == 1,])

actions = ['Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White']

You can now use np.select using these lists as its arguments

df['label_race'] = np.select(conds,actions,default='Other')

Reference: https://numpy.org/doc/stable/reference/generated/numpy.select.html

When increasing the size of VARCHAR column on a large table could there be any problems?

Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change.

Gradients on UIView and UILabels On iPhone

I realize this is an older thread, but for future reference:

As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer:

 UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
 CAGradientLayer *gradient = [CAGradientLayer layer];
 gradient.frame = view.bounds;
 gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
 [view.layer insertSublayer:gradient atIndex:0];

Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors.

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

Perl: Use s/ (replace) and return new string

If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s/// should be all you need:

#!/usr/bin/perl -w    

use strict;     

   main();   

   sub main{    
      my $foo = "blahblahblah";          
      print '$foo: ' , replace("lah","ar",$foo) , "\n";  #$foo: barbarbar

   }        

   sub replace {
      my ($from,$to,$string) = @_;
      $string =~s/$from/$to/ig;                          #case-insensitive/global (all occurrences)

      return $string;
   }

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

Copy folder recursively in Node.js

Since I'm just building a simple Node.js script, I didn't want the users of the script to need to import a bunch of external modules and dependencies, so I put on my thinking cap and did a search for running commands from the Bash shell.

This Node.js code snippet recursively copies a folder called node-webkit.app to a folder called build:

child = exec("cp -r node-webkit.app build", function(error, stdout, stderr) {
    sys.print("stdout: " + stdout);
    sys.print("stderr: " + stderr);
    if(error !== null) {
        console.log("exec error: " + error);
    } else {

    }
});

Thanks to Lance Pollard at dzone for getting me started.

The above snippet is limited to Unix-based platforms, like macOS and Linux, but a similar technique may work for Windows.

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

Auto increment in MongoDB to store sequence of Unique User ID

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

maxObj = db.CollectionName.aggregate([
  {
    $group : { _id: '$item', maxValue: { $max: '$fieldName' } } 
  }
];
fieldNextValue = maxObj.maxValue + 1;

$fieldName is the name of your field, but without the $ sign.

CollectionName is the name of your collection.

The reason I am not using count() is that the produced value could meet an existing value.

The creation of an enforcing unique index could make it safer:

db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )

Pandas group-by and sum

You can set the groupby column to index then using sum with level

df.set_index(['Fruit','Name']).sum(level=[0,1])
Out[175]: 
               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Oranges Bob        67
        Tom        15
        Mike       57
        Tony        1
Grapes  Bob        35
        Tom        87
        Tony       15

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

Creating a textarea with auto-resize

I created a small (7kb) custom element that deals with all of this resizing logic for you.

It works everywhere, because it's implemented as a custom element. Including: Virtual DOMs (React, Elm, etc.), server-side rendered stuff like PHP and plain boring HTML files.

Apart from listening for the input event, it also has a timer that fires every 100ms to make sure things are still working in case the text content changes by some other means.

Here's how it works:

// At the top of one of your Javascript files
import "autoheight-textarea";

or include as a script tag

<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/main.min.js"></script>

then just wrap your textarea elements like so

HTML File

<autoheight-textarea>
  <textarea rows="4" placeholder="Type something"></textarea>
<autoheight-textarea>

React.js Component

const MyComponent = () => {
  return (
    <autoheight-textarea>
      <textarea rows={4} placeholder="Type something..." />
    </autoheight-textarea>
  );
}

Here's a basic demo on Codesandbox: https://codesandbox.io/s/unruffled-http-2vm4c

And you can grab the package here: https://www.npmjs.com/package/autoheight-textarea

If you're just curious to see the resizing logic, you can take a look at this function: https://github.com/Ahrengot/autoheight-textarea/blob/master/src/index.ts#L74-L85

How can I fill a div with an image while keeping it proportional?

You can use div to achieve this. without img tag :) hope this helps.

_x000D_
_x000D_
.img{_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
 background-image:url('http://www.mandalas.com/mandala/htdocs/images/Lrg_image_Pages/Flowers/Large_Orange_Lotus_8.jpg');_x000D_
 background-repeat:no-repeat;_x000D_
 background-position:center center;_x000D_
 border:1px solid red;_x000D_
 background-size:cover;_x000D_
}_x000D_
.img1{_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
 background-image:url('https://images.freeimages.com/images/large-previews/9a4/large-pumpkin-1387927.jpg');_x000D_
 background-repeat:no-repeat;_x000D_
 background-position:center center;_x000D_
 border:1px solid red;_x000D_
 background-size:cover;_x000D_
}
_x000D_
<div class="img"> _x000D_
</div>_x000D_
<div class="img1"> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Pass all variables from one shell script to another?

Adding to the answer of Fatal Error, There is one more way to pass the variables to another shell script.

The above suggested solution have some drawbacks:

  1. using Export : It will cause the variable to be present out of their scope which is not a good design practice.
  2. using Source : It may cause name collisions or accidental overwriting of a predefined variable in some other shell script file which have sourced another file.

There is another simple solution avaiable for us to use. Considering the example posted by you,

test.sh

#!/bin/bash

TESTVARIABLE=hellohelloheloo
./test2.sh "$TESTVARIABLE"

test2.sh

#!/bin/bash

echo $1

output

hellohelloheloo

Also it is important to note that "" are necessary if we pass multiword strings. Taking one more example

master.sh

#!/bin/bash
echo in master.sh
var1="hello world"
sh slave1.sh $var1
sh slave2.sh "$var1"
echo back to master

slave1.sh

#!/bin/bash
echo in slave1.sh
echo value :$1

slave2.sh

#!/bin/bash
echo in slave2.sh
echo value : $1

output

in master.sh
in slave1.sh
value :"hello
in slave2.sh
value :"hello world"

It happens because of the reasons aptly described in this link

Reverse engineering from an APK file to a project

Below are some of the tools which you can use to perform reverse engineering from an APK file to source code :

  1. Dex2jar
  2. Java decompiler
  3. Apktool
  4. Apk Analyser

Can't connect to localhost on SQL Server Express 2012 / 2016

According to Aaron Bertand:

  1. You need to verify that the SQL Server service is running. You can do this by going to Start > Control Panel > Administrative Tools > Services, and checking that the service SQL Server (SQLEXPRESS) is running. If not, start it.

  2. While you're in the services applet, also make sure that the service SQL Browser is started. If not, start it.

  3. You need to make sure that SQL Server is allowed to use TCP/IP or named pipes. You can turn these on by opening the SQL Server Configuration Manager in Start > Programs > Microsoft SQL Server 2012 > Configuration Tools (or SQL Server Configuration Manager), and make sure that TCP/IP and Named Pipes are enabled. If you don't find the SQL Server Configuration Manager in the Start Menu you can launch the MMC snap-in manually. Check SQL Server Configuration Manager for the path to the snap-in according to your version.

    SQL Server Configuration Manager

  4. Verify your SQL Server connection authentication mode matches your connection string:

    • If you're connecting using a username and password, you need to configure SQL Server to accept "SQL Server Authentication Mode":

      -- YOU MUST RESTART YOUR SQL SERVER AFTER RUNNING THIS!
      USE [master]
      GO
      DECLARE @SqlServerAndWindowsAuthenticationMode INT = 2;
      EXEC xp_instance_regwrite
        N'HKEY_LOCAL_MACHINE',
        N'Software\Microsoft\MSSQLServer\MSSQLServer',
        N'LoginMode',
        REG_DWORD,
        @SqlServerAndWindowsAuthenticationMode;
      GO
      
    • If you're connecting using "Integrated Security=true" (Windows Mode), and this error only comes up when debugging in web applications, then you need to add the ApplicationPoolIdentity as a SQL Server login:
  5. otherwise, run Start -> Run -> Services.msc If so, is it running?

If it's not running then

It sounds like you didn't get everything installed. Launch the install file and chose the option "New installation or add features to an existing installation". From there you should be able to make sure the database engine service gets installed.

PHP json_encode json_decode UTF-8

For me both methods

<?php

header('Content-Type: text/html; charset=utf-8');

echo json_encode($YourData, \JSON_UNESCAPED_UNICODE);

MySQLi prepared statements error reporting

Not sure if this answers your question or not. Sorry if not

To get the error reported from the mysql database about your query you need to use your connection object as the focus.

so:

echo $mysqliDatabaseConnection->error

would echo the error being sent from mysql about your query.

Hope that helps

Create Git branch with current changes

Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.

Just use:

git checkout -b topic/newbranch

Any uncommitted work will be taken along to the new branch.

If you try to push you will get the following message

fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use

git push --set-upstream origin feature/feature/NEWBRANCH

Just do as suggested to create the branch remotely:

git push --set-upstream origin feature/feature/NEWBRANCH

How do you completely remove Ionic and Cordova installation from mac?

These commands worked for me:

npm uninstall -g cordova
npm uninstall -g ionic

Changing the maximum length of a varchar column?

You need

ALTER TABLE YourTable ALTER COLUMN YourColumn <<new_datatype>> [NULL | NOT NULL]

But remember to specify NOT NULL explicitly if desired.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NOT NULL;

If you leave it unspecified as below...

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500);

Then the column will default to allowing nulls even if it was originally defined as NOT NULL. i.e. omitting the specification in an ALTER TABLE ... ALTER COLUMN is always treated as.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NULL;

This behaviour is different from that used for new columns created with ALTER TABLE (or at CREATE TABLE time). There the default nullability depends on the ANSI_NULL_DFLT settings.

How to escape strings in SQL Server using PHP?

function ms_escape_string($data) {
        if ( !isset($data) or empty($data) ) return '';
        if ( is_numeric($data) ) return $data;

        $non_displayables = array(
            '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
            '/%1[0-9a-f]/',             // url encoded 16-31
            '/[\x00-\x08]/',            // 00-08
            '/\x0b/',                   // 11
            '/\x0c/',                   // 12
            '/[\x0e-\x1f]/'             // 14-31
        );
        foreach ( $non_displayables as $regex )
            $data = preg_replace( $regex, '', $data );
        $data = str_replace("'", "''", $data );
        return $data;
    }

Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.

EDIT: There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends: http://php.net/manual/en/pdo.prepared-statements.php

How to filter WooCommerce products by custom attribute

Try WooCommerce Product Filter, plugin developed by Mihajlovicnenad.com. You can filter your products by any criteria. Also, it integrates with your Shop and archive pages perfectly. Here is a screenshot. And this is just one of the layouts, you can customize and make your own. Look at demo site. Thanks! enter image description here

CSS Image size, how to fill, but not stretch?

CSS solution no JS and no background image:

Method 1 "margin auto" ( IE8+ - NOT FF!):

_x000D_
_x000D_
div{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  position:relative;_x000D_
  overflow:hidden;_x000D_
}_x000D_
div img{_x000D_
  position:absolute; _x000D_
  top:0; _x000D_
  bottom:0; _x000D_
  margin: auto;_x000D_
  width:100%;_x000D_
}
_x000D_
<p>Original:</p>_x000D_
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
_x000D_
<p>Wrapped:</p>_x000D_
<div>_x000D_
  <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/

Method 2 "transform" ( IE9+ ):

_x000D_
_x000D_
div{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  position:relative;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
div img{_x000D_
  position:absolute; _x000D_
  width:100%;_x000D_
  top: 50%;_x000D_
  -ms-transform: translateY(-50%);_x000D_
  -webkit-transform: translateY(-50%);_x000D_
  transform: translateY(-50%);_x000D_
}
_x000D_
<p>Original:</p>_x000D_
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
_x000D_
<p>Wrapped:</p>_x000D_
<div>_x000D_
  <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/1/

Method 2 can be used to center an image in a fixed width / height container. Both can overflow - and if the image is smaller than the container it will still be centered.

http://jsfiddle.net/5xjr05dt/3/

Method 3 "double wrapper" ( IE8+ - NOT FF! ):

_x000D_
_x000D_
.outer{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  margin: 200px auto; /* just for example */_x000D_
  border: 1px solid red; /* just for example */_x000D_
  /* overflow: hidden; */ /* TURN THIS ON */_x000D_
  position: relative;_x000D_
}_x000D_
.inner { _x000D_
    border: 1px solid green; /* just for example */_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    margin: auto;_x000D_
    display: table;_x000D_
    left: 50%;_x000D_
}_x000D_
.inner img {_x000D_
    display: block;_x000D_
    border: 1px solid blue; /* just for example */_x000D_
    position: relative;_x000D_
    right: 50%;_x000D_
    opacity: .5; /* just for example */_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
     <img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/5/

Method 4 "double wrapper AND double image" ( IE8+ ):

_x000D_
_x000D_
.outer{_x000D_
  width:150px; _x000D_
  height:100px; _x000D_
  margin: 200px auto; /* just for example */_x000D_
  border: 1px solid red; /* just for example */_x000D_
  /* overflow: hidden; */ /* TURN THIS ON */_x000D_
  position: relative;_x000D_
}_x000D_
.inner { _x000D_
    border: 1px solid green; /* just for example */_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    bottom: 0;_x000D_
    display: table;_x000D_
    left: 50%;_x000D_
}_x000D_
.inner .real_image {_x000D_
    display: block;_x000D_
    border: 1px solid blue; /* just for example */_x000D_
    position: absolute;_x000D_
    bottom: 50%;_x000D_
    right: 50%;_x000D_
    opacity: .5; /* just for example */_x000D_
}_x000D_
_x000D_
.inner .placeholder_image{_x000D_
  opacity: 0.1; /* should be 0 */_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    <img class="real_image" src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
    <img class="placeholder_image"  src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/5xjr05dt/26/

  • Method 1 has slightly better support - you have to set the width OR height of image!
  • With the prefixes method 2 also has decent support ( from ie9 up ) - Method 2 has no support on Opera mini!
  • Method 3 uses two wrappers - can overflow width AND height.
  • Method 4 uses a double image ( one as placeholder ) this gives some extra bandwidth overhead, but even better crossbrowser support.

Method 1 and 3 don't seem to work with Firefox

How do you append rows to a table using jQuery?

You should append to the table and not the rows.

<script type="text/javascript">
$('a').click(function() {
    $('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

How to center a "position: absolute" element

This worked for me:

position: absolute;
left: 50%;
transform: translateX(-50%);

What causes a TCP/IP reset (RST) flag to be sent?

I've just spent quite some time troubleshooting this very problem. None of the proposed solutions worked. Turned out that our sysadmin by mistake assigned the same static IP to two unrelated servers belonging to different groups, but sitting on the same network. The end results were intermittently dropped vnc connections, browser that had to be refreshed several times to fetch the web page, and other strange things.

Check if instance is of a type

bool isValid = c.GetType() == typeof(TForm) ? true : false;

or simpler

bool isValid = c.GetType() == typeof(TForm);

what is the unsigned datatype?

In C and C++

unsigned = unsigned int (Integer type)
signed   = signed int (Integer type)

An unsigned integer containing n bits can have a value between 0 and (2^n-1) , which is 2^n different values.

An unsigned integer is either positive or zero.

Signed integers are stored in a computer using 2's complement.

Regex using javascript to return just numbers

Everything that other solutions have, but with a little validation

// value = '675-805-714'
const validateNumberInput = (value) => { 
    let numberPattern = /\d+/g 
    let numbers = value.match(numberPattern)

    if (numbers === null) {
        return 0
    }  

    return parseInt(numbers.join([]))
}
// 675805714

Is it possible to change a UIButtons background color?

I assume you're talking about a UIButton with UIButtonTypeRoundedRect? You can't change the background color of that. When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear). So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect: method or you create images for the different button states (which is perfectly fine to do).

If you set the background images in Interface Builder you should notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like this:

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];

The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set). You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Do copyright dates need to be updated?

The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.

Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.

Auto code completion on Eclipse

Its simple these are the steps: 1. first go to the following settings Window -> Preferences -> Java -> Editor -> content assist -> advanced 2. there will be two boxes having checkboxes. 3. check everthing in there and click apply. 4. now ofcourse when you'll be coding there will be auto code completion feature automatically.

Correct Semantic tag for copyright info - html5

The <footer> tag seems like a good candidate:

<footer>&copy; 2011 Some copyright message</footer>

How can I URL encode a string in Excel VBA?

I had problem with encoding cyrillic letters to URF-8.

I modified one of the above scripts to match cyrillic char map. Implmented is the cyrrilic section of

https://en.wikipedia.org/wiki/UTF-8 and http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024

Other sections development is sample and need verification with real data and calculate the char map offsets

Here is the script:

Public Function UTF8Encode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim TempChr As Long
  Dim CurChr As Long
  Dim Offset As Long
  Dim TempHex As String
  Dim CharToEncode As Long
  Dim TempAnsShort As String

  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    CharToEncode = Asc(Mid(StringToEncode, CurChr, 1))
' http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024
' as per https://en.wikipedia.org/wiki/UTF-8 specification the engoding is as follows

    Select Case CharToEncode
'   7   U+0000 U+007F 1 0xxxxxxx
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case 0 To &H7F
            TempAns = TempAns + "%" + Hex(CharToEncode And &H7F)
      Case &H80 To &H7FF
'   11  U+0080 U+07FF 2 110xxxxx 10xxxxxx
' The magic is in offset calculation... there are different offsets between UTF-8 and Windows character maps
' offset 192 = &HC0 = 1100 0000 b  added to start of UTF-8 cyrillic char map at &H410
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H1F) Or &HC0), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

'' debug and development version
''          CharToEncode = CharToEncode - 192 + &H410
''          TempChr = (CharToEncode And &H3F) Or &H80
''          TempHex = Hex(TempChr)
''          TempAnsShort = "%" & Right("0" & TempHex, 2)
''          TempChr = ((CharToEncode And &H7C0) / &H40) Or &HC0
''          TempChr = ((CharToEncode \ &H40) And &H1F) Or &HC0
''          TempHex = Hex(TempChr)
''          TempAnsShort = "%" & Right("0" & TempHex, 2) & TempAnsShort
''          TempAns = TempAns + TempAnsShort

      Case &H800 To &HFFFF
'   16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
' not tested . Doesnot match Case condition... very strange
        MsgBox ("Char to encode  matched U+0800 U+FFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
''          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &HF) Or &HE0), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case &H10000 To &H1FFFFF
'   21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
''        MsgBox ("Char to encode  matched &H10000 &H1FFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H7) Or &HF0), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case &H200000 To &H3FFFFFF
'   26  U+200000 U+3FFFFFF 5 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
''        MsgBox ("Char to encode  matched U+200000 U+3FFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3) Or &HF8), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case &H4000000 To &H7FFFFFFF
'   31  U+4000000 U+7FFFFFFF 6 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
''        MsgBox ("Char to encode  matched U+4000000 U+7FFFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
          CharToEncode = CharToEncode - 192 + &H410
          TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3F) Or &H80), 2) & TempAnsShort
          TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000000) And &H1) Or &HFC), 2) & TempAnsShort
          TempAns = TempAns + TempAnsShort

      Case Else
' somethig else
' to be developped
        MsgBox ("Char to encode not matched: " & CharToEncode & " = &H" & Hex(CharToEncode))

    End Select

    CurChr = CurChr + 1
  Loop

  UTF8Encode = TempAns
End Function

Good luck!

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

PostgreSQL: days/months/years between two dates

Almost the same function as you needed (based on atiruz's answer, shortened version of UDF from here)

CREATE OR REPLACE FUNCTION datediff(type VARCHAR, date_from DATE, date_to DATE) RETURNS INTEGER LANGUAGE plpgsql
AS
$$
DECLARE age INTERVAL;
BEGIN
    CASE type
        WHEN 'year' THEN
            RETURN date_part('year', date_to) - date_part('year', date_from);
        WHEN 'month' THEN
            age := age(date_to, date_from);
            RETURN date_part('year', age) * 12 + date_part('month', age);
        ELSE
            RETURN (date_to - date_from)::int;
    END CASE;
END;
$$;

Usage:

/* Get months count between two dates */
SELECT datediff('month', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 10 */

/* Get years count between two dates */
SELECT datediff('year', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 1 */

/* Get days count between two dates */
SELECT datediff('day', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 323 */

/* Get months count between specified and current date */
SELECT datediff('month', '2015-02-14'::date, NOW()::date);
/* Result: 47 */

How to stop event bubbling on checkbox click

Use the stopPropagation method:

event.stopPropagation();

How to edit log message already committed in Subversion?

If your repository enables setting revision properties via the pre-revprop-change hook you can change log messages much easier.

svn propedit --revprop -r 1234 svn:log url://to/repository

Or in TortoiseSVN, AnkhSVN and probably many other subversion clients by right clicking on a log entry and then 'change log message'.

How to get current route in react-router 2.0.0-rc5

For any users having the same issue in 2017, I solved it the following way:

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}

and use it like this:

componentDidMount () {
    console.log(this.context.location.pathname);
}

Convert Swift string to array

Martin R answer is the best approach, and as he said, because String conforms the SquenceType protocol, you can also enumerate a string, getting each character on each iteration.

let characters = "Hello"
var charactersArray: [Character] = []

for (index, character) in enumerate(characters) {
    //do something with the character at index
    charactersArray.append(character)
}

println(charactersArray)

how to run python files in windows command prompt?

First set path of python https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows

and run python file

python filename.py

command line argument with python

python filename.py command-line argument

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

While the top answer (w/ mysqladmin) worked on mac 10.15, then it did not work on ubuntu. Then tried many of the other options including safe start for mysql, none worked. Thus adding a new response.

At least for the version I got 5.7.28-0ubuntu0.18.04.4 answers were lacking IDENTIFIED WITH mysql_native_password. 5.7.28 is the default on the current LTS and thus should be the default for most new new systems (till 20.04 LTS comes out).

Found: https://www.digitalocean.com/community/questions/can-t-set-root-password-mysql-server and now applied

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pass_here';

which does work.

How to dynamically insert a <script> tag via jQuery after page load?

If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.

If the script is static, then Rocket's getScript-suggestion is the way to go.

Generate Json schema from XML schema (XSD)

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

gpg: no valid OpenPGP data found

I had a similar issue.

The command I used was as follows:

wget -qO https://download.jitsi.org/jitsi-key.gpg.key |  apt-key add -

I forgot a hyphen between the flags and the URL, which is why wget threw an error.

This is the command that finally worked for me:

wget -qO - https://download.jitsi.org/jitsi-key.gpg.key |  apt-key add -

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

Eclipse automatically created the appcompat_v7.Because of Kitkat Api launched itself it adds automatically appcompat_v7 and fragment_main.xml.

Best ways to solve these:

  1. Firstly in project,Right click->properties->Android.There you can see the red marked appcompat placed in Reference. Click that and Remove it.Then Tick the right target name in Project Build Target.

  2. Delete fragment_main.xml and Appcompat file created in your Eclipse.

  3. Edit and change your activity_main.xml like these:

    <?xml version="1.0" encoding="utf-8"?>
    
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    
    </RelativeLayout>
    
  4. In res/values/styles.xml:

    <resources>
    
        <style name="AppBaseTheme" parent="android:Theme.Light">
    
        </style>
    
        <!-- Application theme. -->
        <style name="AppTheme" parent="AppBaseTheme">
    
        </style>
    
    </resources>
    
  5. In res/values-v11/styles.xml you have to change like these:

    <resources>
    
        <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
        </style>
    
    </resources>
    
  6. In res/values-v14/styles.xml you have to change like these:

      <resources>
    
        <style name="AppBaseTheme" parent="android:Theme.Light">
        </style>
    
        <style name="AppTheme" parent="AppBaseTheme">
        </style>
    
    </resources>
    
  7. Change your menu/main.xml like these:

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:showAsAction="never"
            android:title="@string/action_settings"/>
    
    </menu>
    
  8. Finally change your MainActivity.java like these:

    import android.app.Activity;
    import android.os.Bundle;
    
    
    public class MainActivity extends Activity {
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    }
    
    }
    

LikeWise you have to do it for creating a new project

Defining a variable with or without export

To illustrate what the other answers are saying:

$ foo="Hello, World"
$ echo $foo
Hello, World
$ bar="Goodbye"
$ export foo
$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar

bash-3.2$ 

Sequel Pro Alternative for Windows

Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).

From the website:

Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.

How to prevent multiple definitions in C?

If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.

Good luck with it

How to change xampp localhost to another folder ( outside xampp folder)?

just in case someone looks for this, the path to the file on Sourav answer (httpd.conf) in linux is /opt/lampp/etc/httpd.conf

JAVA_HOME does not point to the JDK

This is by design. You cannot use ant's java.home (which is a java.lang.System property) interchangeably with how JAVA_HOME is set in the OS environment. You are probably trying to assert the location of the Java compiler with a fundamentally different value from a different property layer -- i.e. java.home (from Ant's Java internals) points to the Java Runtime Environment at <any_installed_java_pointed_to_by_ant>/jre while JDK_HOME (from the OS environment) is usually set to <DOWNLOADED_AND_INSTALLED_JAVA_DEVELOPMENT_KIT>.

See my question and answer here for more details: Where does Ant set its 'java.home' (and is it wrong) and is it supposed to append '/jre'?

The solution is to access the system environment property within Ant by using ${env.JAVA_HOME}. Specify which java to use explicitly in the Javac Task by setting the executable property to the javac path and the fork property to yes (see Ant's Javac Task Documentation). That way, it doesn't matter what Java environment Ant is running inside, the compiler is always clearly specified!

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.

You actually can do this but it's a bit of a bodge.

First off create a new Page class which looks something like the following:

public partial class NoRenderPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Allows for printing
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /*Do nothing*/ }
    }
}

Does not need to have an .ASPX associated with it.

Then in the control you wish to render you can do something like the following.

    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    var page = new NoRenderPage();
    page.DesignerInitialize();
    var form = new HtmlForm();
    page.Controls.Add(form);
    form.Controls.Add(pnl);
    controlToRender.RenderControl(hw);

Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.

How to remove a row from JTable?

A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.

Converting HTML to Excel?

We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.

React: "this" is undefined inside a component function

in my case this was the solution = () => {}

methodName = (params) => {
//your code here with this.something
}

PySpark 2.0 The size or shape of a DataFrame

Add this to the your code:

import pyspark
def spark_shape(self):
    return (self.count(), len(self.columns))
pyspark.sql.dataframe.DataFrame.shape = spark_shape

Then you can do

>>> df.shape()
(10000, 10)

But just remind you that .count() can be very slow for very large table that has not been persisted.

Why does javascript map function return undefined?

My solution would be to use filter after the map.

This should support every JS data type.

example:

const notUndefined = anyValue => typeof anyValue !== 'undefined'    
const noUndefinedList = someList
          .map(// mapping condition)
          .filter(notUndefined); // by doing this, 
                      //you can ensure what's returned is not undefined

Is there a way to use shell_exec without waiting for the command to complete?

If it's off of a web page, I recommend generating a signal of some kind (dropping a file in a directory, perhaps) and having a cron job pick up the work that needs to be done. Otherwise, we're likely to get into the territory of using pcntl_fork() and exec() from inside an Apache process, and that's just bad mojo.

How to select a range of the second row to the last row

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

A JOIN With Additional Conditions Using Query Builder or Eloquent

You can replicate those brackets in the left join:

LEFT JOIN bookings  
               ON rooms.id = bookings.room_type_id
              AND (  bookings.arrival between ? and ?
                  OR bookings.departure between ? and ? )

is

->leftJoin('bookings', function($join){
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(DB::raw('(  bookings.arrival between ? and ? OR bookings.departure between ? and ? )'), DB::raw(''), DB::raw(''));
})

You'll then have to set the bindings later using "setBindings" as described in this SO post: How to bind parameters to a raw DB query in Laravel that's used on a model?

It's not pretty but it works.

2D array values C++

int iArray[2][2] = {{1, 2}, {3, 4}};

Think of a 2D array as an array of arrays.

<Django object > is not JSON serializable

Our js-programmer asked me to return the exact JSON format data instead of a json-encoded string to her.

Below is the solution.(This will return an object that can be used/viewed straightly in the browser)

import json
from xxx.models import alert
from django.core import serializers

def test(request):
    alert_list = alert.objects.all()

    tmpJson = serializers.serialize("json",alert_list)
    tmpObj = json.loads(tmpJson)

    return HttpResponse(json.dumps(tmpObj))

How can I export a GridView.DataSource to a datatable or dataset?

Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable

How to call a php script/function on a html button click

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>

Select the first row by group

now, for dplyr, adding a distinct counter.

df %>%
    group_by(aa, bb) %>%
    summarise(first=head(value,1), count=n_distinct(value))

You create groups, them summarise within groups.

If data is numeric, you can use:
first(value) [there is also last(value)] in place of head(value, 1)

see: http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html

Full:

> df
Source: local data frame [16 x 3]

   aa bb value
1   1  1   GUT
2   1  1   PER
3   1  2   SUT
4   1  2   GUT
5   1  3   SUT
6   1  3   GUT
7   1  3   PER
8   2  1   221
9   2  1   224
10  2  1   239
11  2  2   217
12  2  2   221
13  2  2   224
14  3  1   GUT
15  3  1   HUL
16  3  1   GUT

> library(dplyr)
> df %>%
>   group_by(aa, bb) %>%
>   summarise(first=head(value,1), count=n_distinct(value))

Source: local data frame [6 x 4]
Groups: aa

  aa bb first count
1  1  1   GUT     2
2  1  2   SUT     2
3  1  3   SUT     3
4  2  1   221     3
5  2  2   217     3
6  3  1   GUT     2

Debug JavaScript in Eclipse

In 2015, there are at least six choices for JavaScript debugging in Eclipse:

Adding to the above, here are a couple of videos which focus on "debugging JavaScript using eclipse"

Outdated

Editor does not contain a main type

In Eclipse, make sure you add your source folder in the project properties -> java build path -> source. Otherwise, the main() function may not be included in your project.

Python match a string with regex

r stands for a raw string, so things like \ will be automatically escaped by Python.

Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.

short explanation

In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)

As per re.match vs re.search here's an example that will clarify it for you:

>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>

So search will find a match anywhere, match will only start at the beginning

how to use #ifdef with an OR condition?

OR condition in #ifdef

#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */

or-

#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */

Both above are the same, which one you use simply depends on your taste.


P.S.: #ifdef is simply the short form of #if defined, however, does not support complex condition.


Further-

  • AND: #if defined LINUX && defined ANDROID
  • XOR: #if defined LINUX ^ defined ANDROID

Minimum 6 characters regex expression

This match 6 or more any chars but newline:

/^.{6,}$/

Online code beautifier and formatter

What language?? There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.

Good ol' indent is a nice, customizable, command-line utility to format C and C++ programs.

What is a "thread" (really)?

A thread is nothing more than a memory context (or how Tanenbaum better puts it, resource grouping) with execution rules. It's a software construct. The CPU has no idea what a thread is (some exceptions here, some processors have hardware threads), it just executes instructions.

The kernel introduces the thread and process concept to manage the memory and instructions order in a meaningful way.

Message 'src refspec master does not match any' when pushing commits in Git

What worked for me was simply checkout to the branch that I want my code to push and then simply push your code.

git checkout -b branchname-on-which-i-will-push-my-code

git add .
git commit -m "my commit message"
git push origin branchname-on-which-i-will-push-my-code

git: updates were rejected because the remote contains work that you do not have locally

This usually happens when the repo contains some items that are not there locally. So in order to push our changes, in this case we need to integrate the remote changes and then push.

So create a pull from remote

git pull origin master

Then push changes to that remote

git push origin master

jQuery prevent change for select

In the event someone needs a generic version of mattsven's answer (as I did), here it is:

$('select').each(function() {
    $(this).data('lastSelected', $(this).find('option:selected'));
});

$('select').change(function() {
    if(my_condition) {
        $(this).data('lastSelected').attr('selected', true);
    }
});

$('select').click(function() {
    $(this).data('lastSelected', $(this).find('option:selected'));
});

What exactly is "exit" in PowerShell?

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

Reference

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

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

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

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

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

How to select a dropdown value in Selenium WebDriver using Java

First Import the package as :

import org.openqa.selenium.support.ui.Select;

then write in single line as:

new Select (driver.findElement(By.id("sampleid"))).selectByValue("SampleValue");

Float to String format specifier

Use ToString() with this format:

12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000

Put as much zero as necessary at the end of the format.

Best HTML5 markup for sidebar

The ASIDE has since been modified to include secondary content as well.

HTML5 Doctor has a great writeup on it here: http://html5doctor.com/aside-revisited/

Excerpt:

With the new definition of aside, it’s crucial to remain aware of its context. >When used within an article element, the contents should be specifically related >to that article (e.g., a glossary). When used outside of an article element, the >contents should be related to the site (e.g., a blogroll, groups of additional >navigation, and even advertising if that content is related to the page).

Eliminating duplicate values based on only one column of the table

I solve such queries using this pattern:

SELECT *
FROM t
WHERE t.field=(
  SELECT MAX(t.field) 
  FROM t AS t0 
  WHERE t.group_column1=t0.group_column1
    AND t.group_column2=t0.group_column2 ...)

That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:

WITH site_history AS (
  SELECT sites.siteName, sites.siteIP, history.date
  FROM sites
  JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
  SELECT MAX(date) 
  FROM site_history h0 
  WHERE h.siteName=h0.siteName)
ORDER BY siteName

It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date field should be unique for each siteName, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history table has an unique index for (site, date), this query is also very fast, index range scan on the history table scanning just the first item can be used.

Tomcat 7 "SEVERE: A child container failed during start"

When a servlet 3.0 application starts the container has to scan all the classes for annotations (unless metadata-complete=true). Tomcat uses a fork (no additions, just unused code removed) of Apache Commons BCEL to do this scanning. The web app is failing to start because BCEL has come across something it doesn't understand.

If the applications runs fine on Tomcat 6, adding metadata-complete="true" in your web.xml or declaring your application as a 2.5 application in web.xml will stop the annotation scanning.

At the moment, this looks like a problem in the class being scanned. However, until we know which class is causing the problem and take a closer look we won't know. I'll need to modify Tomcat to log a more useful error message that names the class in question. You can follow progress on this point at: https://issues.apache.org/bugzilla/show_bug.cgi?id=53161

What size should apple-touch-icon.png be for iPad and iPhone?

Yes. If the size does not match, the system will rescale it. But it's better to make 2 versions of the icons.

  • iPad — 72x72.
  • iPhone (=4) — 114x114.
  • iPhone =3GS — 57x57 — If possible.

You could differentiate iPad and iPhone by the user agent on your server. If you don't want to write script on server, you could also change the icon with Javascript by

<link ref="apple-touch-icon" href="iPhone_version.png" />
...

if (... iPad test ...) {
  $('link[rel="apple-touch-icon"]').href = 'iPad_version.png'; // assuming jQuery
}

This works because the icon is queried only when you add the web clip.

(There's no public way to differentiate iPhone =4 from iPhone =3GS in Javascript yet.)

How can I read user input from the console?

string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console

Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.

Console.ReadLine() reads a string (so then you need to change the string to a double)

Java 256-bit AES Password-Based Encryption

Adding to @Wufoo's edits, the following version uses InputStreams rather than files to make working with a variety of files easier. It also stores the IV and Salt in the beginning of the file, making it so only the password needs to be tracked. Since the IV and Salt do not need to be secret, this makes life a little easier.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    public final static int SALT_LEN     = 8;
    static final String     HEXES        = "0123456789ABCDEF";
    String                  mPassword    = null;
    byte[]                  mInitVec     = null;
    byte[]                  mSalt        = new byte[SALT_LEN];
    Cipher                  mEcipher     = null;
    Cipher                  mDecipher    = null;
    private final int       KEYLEN_BITS  = 128;    // see notes below where this is used.
    private final int       ITERATIONS   = 65536;
    private final int       MAX_FILE_BUF = 1024;

    /**
     * create an object with just the passphrase from the user. Don't do anything else yet
     * @param password
     */
    public AES(String password) {
        mPassword = password;
    }

    public static String byteToHex(byte[] raw) {
        if (raw == null) {
            return null;
        }

        final StringBuilder hex = new StringBuilder(2 * raw.length);

        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }

        return hex.toString();
    }

    public static byte[] hexToByte(String hexString) {
        int    len = hexString.length();
        byte[] ba  = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            ba[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                                + Character.digit(hexString.charAt(i + 1), 16));
        }

        return ba;
    }

    /**
     * debug/print messages
     * @param msg
     */
    private void Db(String msg) {
        System.out.println("** Crypt ** " + msg);
    }

    /**
     * This is where we write out the actual encrypted data to disk using the Cipher created in setupEncrypt().
     * Pass two file objects representing the actual input (cleartext) and output file to be encrypted.
     *
     * there may be a way to write a cleartext header to the encrypted file containing the salt, but I ran
     * into uncertain problems with that.
     *
     * @param input - the cleartext file to be encrypted
     * @param output - the encrypted data file
     * @throws IOException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public void WriteEncryptedFile(InputStream inputStream, OutputStream outputStream)
            throws IOException, IllegalBlockSizeException, BadPaddingException {
        try {
            long             totalread = 0;
            int              nread     = 0;
            byte[]           inbuf     = new byte[MAX_FILE_BUF];
            SecretKeyFactory factory   = null;
            SecretKey        tmp       = null;

            // crate secureRandom salt and store  as member var for later use
            mSalt = new byte[SALT_LEN];

            SecureRandom rnd = new SecureRandom();

            rnd.nextBytes(mSalt);
            Db("generated salt :" + byteToHex(mSalt));
            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

            /*
             *  Derive the key, given password and salt.
             *
             * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
             * The end user must also install them (not compiled in) so beware.
             * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
             */
            KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

            tmp = factory.generateSecret(spec);

            SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

            /*
             *  Create the Encryption cipher object and store as a member variable
             */
            mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            mEcipher.init(Cipher.ENCRYPT_MODE, secret);

            AlgorithmParameters params = mEcipher.getParameters();

            // get the initialization vectory and store as member var
            mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();
            Db("mInitVec is :" + byteToHex(mInitVec));
            outputStream.write(mSalt);
            outputStream.write(mInitVec);

            while ((nread = inputStream.read(inbuf)) > 0) {
                Db("read " + nread + " bytes");
                totalread += nread;

                // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
                // and results in full blocks of MAX_FILE_BUF being written.
                byte[] trimbuf = new byte[nread];

                for (int i = 0; i < nread; i++) {
                    trimbuf[i] = inbuf[i];
                }

                // encrypt the buffer using the cipher obtained previosly
                byte[] tmpBuf = mEcipher.update(trimbuf);

                // I don't think this should happen, but just in case..
                if (tmpBuf != null) {
                    outputStream.write(tmpBuf);
                }
            }

            // finalize the encryption since we've done it in blocks of MAX_FILE_BUF
            byte[] finalbuf = mEcipher.doFinal();

            if (finalbuf != null) {
                outputStream.write(finalbuf);
            }

            outputStream.flush();
            inputStream.close();
            outputStream.close();
            outputStream.close();
            Db("wrote " + totalread + " encrypted bytes");
        } catch (InvalidKeyException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidParameterSpecException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
     * to disk as (output) File.
     *
     * I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
     *  and still have a correctly decrypted file in the end. Seems to work so left it in.
     *
     * @param input - File object representing encrypted data on disk
     * @param output - File object of cleartext data to write out after decrypting
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws IOException
     */
    public void ReadEncryptedFile(InputStream inputStream, OutputStream outputStream)
            throws IllegalBlockSizeException, BadPaddingException, IOException {
        try {
            CipherInputStream cin;
            long              totalread = 0;
            int               nread     = 0;
            byte[]            inbuf     = new byte[MAX_FILE_BUF];

            // Read the Salt
            inputStream.read(this.mSalt);
            Db("generated salt :" + byteToHex(mSalt));

            SecretKeyFactory factory = null;
            SecretKey        tmp     = null;
            SecretKey        secret  = null;

            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

            KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

            tmp    = factory.generateSecret(spec);
            secret = new SecretKeySpec(tmp.getEncoded(), "AES");

            /* Decrypt the message, given derived key and initialization vector. */
            mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            // Set the appropriate size for mInitVec by Generating a New One
            AlgorithmParameters params = mDecipher.getParameters();

            mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

            // Read the old IV from the file to mInitVec now that size is set.
            inputStream.read(this.mInitVec);
            Db("mInitVec is :" + byteToHex(mInitVec));
            mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));

            // creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
            cin = new CipherInputStream(inputStream, mDecipher);

            while ((nread = cin.read(inbuf)) > 0) {
                Db("read " + nread + " bytes");
                totalread += nread;

                // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
                byte[] trimbuf = new byte[nread];

                for (int i = 0; i < nread; i++) {
                    trimbuf[i] = inbuf[i];
                }

                // write out the size-adjusted buffer
                outputStream.write(trimbuf);
            }

            outputStream.flush();
            cin.close();
            inputStream.close();
            outputStream.close();
            Db("wrote " + totalread + " encrypted bytes");
        } catch (Exception ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * adding main() for usage demonstration. With member vars, some of the locals would not be needed
     */
    public static void main(String[] args) {

        // create the input.txt file in the current directory before continuing
        File   input   = new File("input.txt");
        File   eoutput = new File("encrypted.aes");
        File   doutput = new File("decrypted.txt");
        String iv      = null;
        String salt    = null;
        AES    en      = new AES("mypassword");

        /*
         * write out encrypted file
         */
        try {
            en.WriteEncryptedFile(new FileInputStream(input), new FileOutputStream(eoutput));
            System.out.printf("File encrypted to " + eoutput.getName() + "\niv:" + iv + "\nsalt:" + salt + "\n\n");
        } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
        }

        /*
         * decrypt file
         */
        AES dc = new AES("mypassword");

        /*
         * write out decrypted file
         */
        try {
            dc.ReadEncryptedFile(new FileInputStream(eoutput), new FileOutputStream(doutput));
            System.out.println("decryption finished to " + doutput.getName());
        } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
        }
    }
}

Capturing TAB key in text box

I'd rather tab indentation not work than breaking tabbing between form items.

If you want to indent to put in code in the Markdown box, use Ctrl+K (or ?K on a Mac).

In terms of actually stopping the action, jQuery (which Stack Overflow uses) will stop an event from bubbling when you return false from an event callback. This makes life easier for working with multiple browsers.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

./gradlew wrapper --gradle-version=5.4.1 --distribution-type=bin

https://gradle.org/install/#manually

To check:

 ./gradlew tasks

To input it without command:

go to-> gradle/wrapper/gradle-wrapper.properties distribution url and change it to the updated zip version

output:

 ./gradlew tasks
Downloading https://services.gradle.org/distributions/gradle-5.4.1-bin.zip
...................................................................................

Welcome to Gradle 5.4.1!

Here are the highlights of this release:
 - Run builds with JDK12
 - New API for Incremental Tasks
 - Updates to native projects, including Swift 5 support

For more details see https://docs.gradle.org/5.4.1/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

> Starting Daemon 

Creating a SearchView that looks like the material design guidelines

To achieve desired look of SearchView, you can use styles.

First, you need to create style for your SearchView, which should look something like this:

<style name="CustomSearchView" parent="Widget.AppCompat.SearchView">
    <item name="searchIcon">@null</item>
    <item name="queryBackground">@null</item>
</style>

Whole list of attributes you can find at this article, under the "SearchView" section.

Secondly, you need to create a style for your Toolbar, which is used as ActionBar:

<style name="ToolbarSearchView" parent="Base.ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="searchViewStyle">@style/CustomSearchView</item>
</style>

And finally you need to update your Toolbar theme attribute this way:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/ToolbarSearchView" />

Result:

enter image description here

NOTE: You need to change your Toolbar theme attribute directly. If you'll just update your main theme searchViewStyle attribute it wouldn't affect your Toolbar.

How to download Javadoc to read offline?

JAVA Fax Api documentation

You could download the mac 2.2 preview release from here and unzip it.

http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html

The javadoc won't quite match 2.1, but it will be close and if you use the preview instead, it will match exactly.

I think this would help you :)

Impersonate tag in Web.Config

You had the identity node as a child of authentication node. That was the issue. As in the example above, authentication and identity nodes must be children of the system.web node

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Proposing brew update && brew upgrade as the solution is not a good answer and, as this error appears in most of the cases due the execution of this...

Switch to the previous version you were using with only: brew switch openssl XXX and that's it.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.

Shuffling a list of objects

As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using sample(a, len(a)) is the solution, using len(a) as the sample size. See https://docs.python.org/3.6/library/random.html#random.sample for the Python documentation.

Here's a simple version using random.sample() that returns the shuffled result as a new list.

import random

a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False

# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))

try:
    random.sample(a, len(a) + 1)
except ValueError as e:
    print "Nope!", e

# print: no duplicates: True
# print: Nope! sample larger than population

getCurrentPosition() and watchPosition() are deprecated on insecure origins

In HTTP the error occurs.

Set permission for localhost in bellow label(Accept requests from these HTTP referrers (web sites)).

It worked for me.

Equivalent of shell 'cd' command to change the working directory?

As already pointed out by others, all the solutions above only change the working directory of the current process. This is lost when you exit back to the Unix shell. If desperate you can change the parent shell directory on Unix with this horrible hack:

def quote_against_shell_expansion(s):
    import pipes
    return pipes.quote(s)

def put_text_back_into_terminal_input_buffer(text):
    # use of this means that it only works in an interactive session
    # (and if the user types while it runs they could insert characters between the characters in 'text'!)
    import fcntl, termios
    for c in text:
        fcntl.ioctl(1, termios.TIOCSTI, c)

def change_parent_process_directory(dest):
    # the horror
    put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")

Compare two folders which has many files inside contents

I used

diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

Can I use Homebrew on Ubuntu?

The following steps worked for me:

  • Clone it from github

    git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew
    
  • Open your .bash_profile file using vi ~/.bash_profile

  • Add these lines

    export PATH="$HOME/.linuxbrew/bin:$PATH"
    export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
    export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
    
  • Then type the following lines in your terminal

    export PATH=$HOME/.linuxbrew/bin:$PATH
    hash -r
    

Yes, it is done. Type brew in your terminal to check its existence.

What does "where T : class, new()" mean?

class & new are 2 constraints on the generic type parameter T.
Respectively they ensure:

class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

new

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

Their combination means that the type T must be a Reference Type (can't be a Value Type), and must have a parameterless constructor.

Example:

struct MyStruct { } // structs are value types

class MyClass1 { } // no constructors defined, so the class implicitly has a parameterless one

class MyClass2 // parameterless constructor explicitly defined
{
    public MyClass2() { }
}

class MyClass3 // only non-parameterless constructor defined
{
    public MyClass3(object parameter) { }
}

class MyClass4 // both parameterless & non-parameterless constructors defined
{
    public MyClass4() { }
    public MyClass4(object parameter) { }
}

interface INewable<T>
    where T : new()
{
}

interface INewableReference<T>
    where T : class, new()
{
}

class Checks
{
    INewable<int> cn1; // ALLOWED: has parameterless ctor
    INewable<string> n2; // NOT ALLOWED: no parameterless ctor
    INewable<MyStruct> n3; // ALLOWED: has parameterless ctor
    INewable<MyClass1> n4; // ALLOWED: has parameterless ctor
    INewable<MyClass2> n5; // ALLOWED: has parameterless ctor
    INewable<MyClass3> n6; // NOT ALLOWED: no parameterless ctor
    INewable<MyClass4> n7; // ALLOWED: has parameterless ctor

    INewableReference<int> nr1; // NOT ALLOWED: not a reference type
    INewableReference<string> nr2; // NOT ALLOWED: no parameterless ctor
    INewableReference<MyStruct> nr3; // NOT ALLOWED: not a reference type
    INewableReference<MyClass1> nr4; // ALLOWED: has parameterless ctor
    INewableReference<MyClass2> nr5; // ALLOWED: has parameterless ctor
    INewableReference<MyClass3> nr6; // NOT ALLOWED: no parameterless ctor
    INewableReference<MyClass4> nr7; // ALLOWED: has parameterless ctor
}

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

Listing all extras of an Intent

Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
    Log.d("KEY", iterator.next());
}

How to find a text inside SQL Server procedures / triggers?

SELECT ROUTINE_TYPE, ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%Your Text%' 

How to add include and lib paths to configure/make cycle?

You want a config.site file. Try:

$ mkdir -p ~/local/share
$ cat << EOF > ~/local/share/config.site
CPPFLAGS=-I$HOME/local/include
LDFLAGS=-L$HOME/local/lib
...
EOF

Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.

MySQL Sum() multiple columns

SELECT student, (SUM(mark1)+SUM(mark2)+SUM(mark3)....+SUM(markn)) AS Total
 FROM your_table
 GROUP BY student

Get String in YYYYMMDD format from JS date object?

Moment.js could be your friend

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');

Window.open and pass parameters by post method

I wanted to do this in React using plain Js and the fetch polyfill. OP didn't say he specifically wanted to create a form and invoke the submit method on it, so I have done it by posting the form values as json:

examplePostData = {
    method: 'POST',
    headers: {
       'Content-type' : 'application/json',
       'Accept' : 'text/html'
    },
    body: JSON.stringify({
        someList: [1,2,3,4],
        someProperty: 'something',
        someObject: {some: 'object'}
    })
}

asyncPostPopup = () => {

    //open a new window and set some text until the fetch completes
    let win=window.open('about:blank')
    writeToWindow(win,'Loading...')

    //async load the data into the window
    fetch('../postUrl', this.examplePostData)
    .then((response) => response.text())
    .then((text) => writeToWindow(win,text))
    .catch((error) => console.log(error))
}

writeToWindow = (win,text) => {
    win.document.open()
    win.document.write(text)
    win.document.close()
}

MySQL Install: ERROR: Failed to build gem native extension

In order to resolve

Gem::Ext::BuildError: ERROR: Failed to build gem native extension error for mysql2,

I think libmysql-ruby got changed with ruby-mysql

Simply try with following commands,

sudo apt-get install ruby-mysql

& then

sudo apt-get install libmysqlclient-dev

Detect Windows version in .net

I used this when I had to determine various Microsoft Operating System versions:

string getOSInfo()
{
   //Get Operating system information.
   OperatingSystem os = Environment.OSVersion;
   //Get version information about the os.
   Version vs = os.Version;

   //Variable to hold our return value
   string operatingSystem = "";

   if (os.Platform == PlatformID.Win32Windows)
   {
       //This is a pre-NT version of Windows
       switch (vs.Minor)
       {
           case 0:
               operatingSystem = "95";
               break;
           case 10:
               if (vs.Revision.ToString() == "2222A")
                   operatingSystem = "98SE";
               else
                   operatingSystem = "98";
               break;
           case 90:
               operatingSystem = "Me";
               break;
           default:
               break;
       }
   }
   else if (os.Platform == PlatformID.Win32NT)
   {
       switch (vs.Major)
       {
           case 3:
               operatingSystem = "NT 3.51";
               break;
           case 4:
               operatingSystem = "NT 4.0";
               break;
           case 5:
               if (vs.Minor == 0)
                   operatingSystem = "2000";
               else
                   operatingSystem = "XP";
               break;
           case 6:
               if (vs.Minor == 0)
                   operatingSystem = "Vista";
               else if (vs.Minor == 1)
                   operatingSystem = "7";
               else if (vs.Minor == 2)
                   operatingSystem = "8";
               else
                   operatingSystem = "8.1";
               break;
           case 10:
               operatingSystem = "10";
               break;
           default:
               break;
       }
   }
   //Make sure we actually got something in our OS check
   //We don't want to just return " Service Pack 2" or " 32-bit"
   //That information is useless without the OS version.
   if (operatingSystem != "")
   {
       //Got something.  Let's prepend "Windows" and get more info.
       operatingSystem = "Windows " + operatingSystem;
       //See if there's a service pack installed.
       if (os.ServicePack != "")
       {
           //Append it to the OS name.  i.e. "Windows XP Service Pack 3"
           operatingSystem += " " + os.ServicePack;
       }
       //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"
       //operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
   }
   //Return the information we've gathered.
   return operatingSystem;
}

Source: here

How to concatenate properties from multiple JavaScript objects

ES6 ++

The question is adding various different objects into one.

let obj = {};
const obj1 = { foo: 'bar' };
const obj2 = { bar: 'foo' };
Object.assign(obj, obj1, obj2);
//output => {foo: 'bar', bar: 'foo'};

lets say you have one object with multiple keys that are objects:

let obj = {
  foo: { bar: 'foo' },
  bar: { foo: 'bar' }
}

this was the solution I found (still have to foreach :/)

let objAll = {};

Object.values(obj).forEach(o => {
  objAll = {...objAll, ...o};
});

By doing this we can dynamically add ALL object keys into one.

// Output => { bar: 'foo', foo: 'bar' }

Maven does not find JUnit tests to run

By default Maven uses the following naming conventions when looking for tests to run:

If your test class doesn't follow these conventions you should rename it or configure Maven Surefire Plugin to use another pattern for test classes.

How to center align the cells of a UICollectionView?

The top solutions here did not work for me out-of-the-box, so I came up with this which should work for any horizontal scrolling collection view with flow layout and only one section:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
    {
    // Add inset to the collection view if there are not enough cells to fill the width.
    CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
    CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
    NSInteger cellCount = [collectionView numberOfItemsInSection:section];
    CGFloat inset = (collectionView.bounds.size.width - (cellCount * cellWidth) - ((cellCount - 1)*cellSpacing)) * 0.5;
    inset = MAX(inset, 0.0);
    return UIEdgeInsetsMake(0.0, inset, 0.0, 0.0);
    }

What is an alternative to execfile in Python 3?

Here's what I had (file is already assigned to the path to the file with the source code in both examples):

execfile(file)

Here's what I replaced it with:

exec(compile(open(file).read(), file, 'exec'))

My favorite part: the second version works just fine in both Python 2 and 3, meaning it's not necessary to add in version dependent logic.