Programs & Examples On #Authenticity token

AuthenticityToken is a feature of Ruby on Rails used to protect against CSRF

Rails 4 Authenticity Token

Adding the following line into the form worked for me:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Understanding the Rails Authenticity Token

Minimal attack example that would be prevented: CSRF

On my website evil.com I convince you to submit the following form:

<form action="http://bank.com/transfer" method="post">
  <p><input type="hidden" name="to"      value="ciro"></p>
  <p><input type="hidden" name="ammount" value="100"></p>
  <p><button type="submit">CLICK TO GET PRIZE!!!</button></p>
</form>

If you are logged into your bank through session cookies, then the cookies would be sent and the transfer would be made without you even knowing it.

That is were the CSRF token comes into play:

  • with the GET response that that returned the form, Rails sends a very long random hidden parameter
  • when the browser makes the POST request, it will send the parameter along, and the server will only accept it if it matches

So the form on an authentic browser would look like:

<form action="http://bank.com/transfer" method="post">
  <p><input type="hidden" name="authenticity_token" value="j/DcoJ2VZvr7vdf8CHKsvjdlDbmiizaOb5B8DMALg6s=" ></p>
  <p><input type="hidden" name="to"                 value="ciro"></p>
  <p><input type="hidden" name="ammount"            value="100"></p>
  <p><button type="submit">Send 100$ to Ciro.</button></p>
</form>

Thus, my attack would fail, since it was not sending the authenticity_token parameter, and there is no way I could have guessed it since it is a huge random number.

This prevention technique is called Synchronizer Token Pattern.

Same Origin Policy

But what if the attacker made two requests with JavaScript, one to read the token, and the second one to make the transfer?

The synchronizer token pattern alone is not enough to prevent that!

This is where the Same Origin Policy comes to the rescue, as I have explained at: https://security.stackexchange.com/questions/8264/why-is-the-same-origin-policy-so-important/72569#72569

How Rails sends the tokens

Covered at: Rails: How Does csrf_meta_tag Work?

Basically:

  • HTML helpers like form_tag add a hidden field to the form for you if it's not a GET form

  • AJAX is dealt with automatically by jquery-ujs, which reads the token from the meta elements added to your header by csrf_meta_tags (present in the default template), and adds it to any request made.

    uJS also tries to update the token in forms in outdated cached fragments.

Other prevention approaches

MySQL Insert query doesn't work with WHERE clause

correct syntax for mysql insert into statement using post method is:

$sql="insert into ttable(username,password) values('$_POST[username]','$_POST[password]')";

What is the iPad user agent?

I think it is worth mentioning that you don't generally need to use the whole agent string, unless perhaps you find a reason where you need to tailor the website to a specific model.

You can check for iPhone, iPad and iPod in the agent string and cover all your bases.

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
    appleMobileDevice = true;
}
else {
    appleMobileDevice = false;
}

node.js shell command execution

A promisified version of the most-awarded answer:

  runCmd: (cmd, args) => {
    return new Promise((resolve, reject) => {
      var spawn = require('child_process').spawn
      var child = spawn(cmd, args)
      var resp = ''
      child.stdout.on('data', function (buffer) { resp += buffer.toString() })
      child.stdout.on('end', function () { resolve(resp) })
    })
  }

To use:

 runCmd('ls').then(ret => console.log(ret))

Javascript variable access in HTML

<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];

window.onload = function() {
       //when the document is finished loading, replace everything
       //between the <a ...> </a> tags with the value of splitText
   document.getElementById("myLink").innerHTML=splitText;
} 

</script>

<body>
<a id="myLink" href = test.html></a>
</body>
</html>

slideToggle JQuery right to left

I know it's been a year since this was asked, but just for people that are going to visit this page I am posting my solution.

By using what @Aldi Unanto suggested here is a more complete answer:

  jQuery('.show_hide').click(function(e) {
    e.preventDefault();
    if (jQuery('.slidingDiv').is(":visible") ) {
      jQuery('.slidingDiv').stop(true,true).hide("slide", { direction: "left" }, 200);
    } else {
      jQuery('.slidingDiv').stop(true,true).show("slide", { direction: "left" }, 200);
    }
  });

First I prevent the link from doing anything on click. Then I add a check if the element is visible or not. When visible I hide it. When hidden I show it. You can change direction to left or right and duration from 200 ms to anything you like.

Edit: I have also added

.stop(true,true)

in order to clearQueue and jumpToEnd. Read about jQuery stop here

In Postgresql, force unique on combination of two columns

If, like me, you landed here with:

  • a pre-existing table,
  • to which you need to add a new column, and
  • also need to add a new unique constraint on the new column as well as an old one, AND
  • be able to undo it all (i.e. write a down migration)

Here is what worked for me, utilizing one of the above answers and expanding it:

-- up

ALTER TABLE myoldtable ADD COLUMN newcolumn TEXT;
ALTER TABLE myoldtable ADD CONSTRAINT myoldtable_oldcolumn_newcolumn_key UNIQUE (oldcolumn, newcolumn);

---

ALTER TABLE myoldtable DROP CONSTRAINT myoldtable_oldcolumn_newcolumn_key;
ALTER TABLE myoldtable DROP COLUMN newcolumn;

-- down

Angular 2 - NgFor using numbers instead collections

My solution:

export class DashboardManagementComponent implements OnInit {
  _cols = 5;
  _rows = 10;
  constructor() { }

  ngOnInit() {
  }

  get cols() {
    return Array(this._cols).fill(null).map((el, index) => index);
  }
  get rows() {
    return Array(this._rows).fill(null).map((el, index) => index);
  }

In html:

<div class="charts-setup">
  <div class="col" *ngFor="let col of cols; let colIdx = index">
    <div class="row" *ngFor="let row of rows; let rowIdx = index">
      Col: {{colIdx}}, row: {{rowIdx}}
    </div>
  </div>
</div>

"psql: could not connect to server: Connection refused" Error when connecting to remote database

I think you are using the machine-name instead of the ip of the host.

I got the same error when i tried with machine's name. Because, It is allowed only when both the client and host are under same network and they have the same Operating system installed.

Opening a remote machine's Windows C drive

By default, Windows makes the root of each drive available (provided you've got Administrator privileges) as (e.g.) \\server\c$. These are known as Administrative Shares.

How to play ringtone/alarm sound in Android

Your example is basically what I'm using. It never works on the emulator, however, because the emulator doesn't have any ringtones by default, and content://settings/system/ringtone doesn't resolve to anything playable. It works fine on my actual phone.

SQL Case Sensitive String Compare

You can also convert that attribute as case sensitive using this syntax :

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive.

If you want to make that column case insensitive again, then use

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How to allow <input type="file"> to accept only image files?

This can be achieved by

<input type="file" accept="image/*" /> 

But this is not a good way. you have to code on the server side to check the file an image or not.

Check if image file is an actual image or fake image

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    }
    else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

For more reference, see here

http://www.w3schools.com/tags/att_input_accept.asp
http://www.w3schools.com/php/php_file_upload.asp

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

RadioGroup: How to check programmatically

try this if you want your radio button to be checked based on value of some variable e.g. "genderStr" then you can use following code snippet

    if(genderStr.equals("Male"))
       genderRG.check(R.id.maleRB);
    else 
       genderRG.check(R.id.femaleRB);

What is the PostgreSQL equivalent for ISNULL()

Create the following function

CREATE OR REPLACE FUNCTION isnull(text, text) RETURNS text AS 'SELECT (CASE (SELECT $1 "
    "is null) WHEN true THEN $2 ELSE $1 END) AS RESULT' LANGUAGE 'sql'

And it'll work.

You may to create different versions with different parameter types.

How to use workbook.saveas with automatic Overwrite

To split the difference of opinion

I prefer:

   xls.DisplayAlerts = False    
   wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
   xls.DisplayAlerts = True

Compare two files report difference in python

import difflib
f=open('a.txt','r')  #open a file
f1=open('b.txt','r') #open another file to compare
str1=f.read()
str2=f1.read()
str1=str1.split()  #split the words in file by default through the spce
str2=str2.split()
d=difflib.Differ()     # compare and just print
diff=list(d.compare(str2,str1))
print '\n'.join(diff)

Electron: jQuery is not defined

you may try the following code:

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration:false,
        }
});

Kill all processes for a given user

The following kills all the processes created by this user:

kill  -9  -1

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

If you have imported your project from Eclipse.

1. The select project 
2. Go to File -> **Project Structure**
3. Select app in **module** section on left hand panel
4. Select **Dependency** tab
5. Your able to see jars you have added in eclipse project for v4 and v13.
6. Remove that jar by clicking on minus sign at bottom after selection
7. Click on Plus sign select **Library Dependency** 
8. Choose V4 and V13 if added
9. Press Ok and Clean and Rebuild your project

The scenario I have faced after importing Eclipse project to Android studio.

Hope this helps..

Convert LocalDate to LocalDateTime or java.sql.Timestamp

JodaTime

To convert JodaTime's org.joda.time.LocalDate to java.sql.Timestamp, just do

Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());

To convert JodaTime's org.joda.time.LocalDateTime to java.sql.Timestamp, just do

Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());

JavaTime

To convert Java8's java.time.LocalDate to java.sql.Timestamp, just do

Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());

To convert Java8's java.time.LocalDateTime to java.sql.Timestamp, just do

Timestamp timestamp = Timestamp.valueOf(localDateTime);

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

MySQL Removing Some Foreign keys

Here's a way to drop foreign key constraint, it will work. ALTER TABLE location.location_id DROP FOREIGN KEY location_ibfk_1;

Laravel Redirect Back with() Message

In Laravel 5.5:

return back()->withErrors($arrayWithErrors);

In the view using Blade:

@if($errors->has())
    <ul>
    @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Producer/Consumer threads using a Queue

You are reinventing the wheel.

If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).

If you need fast in-memory queues use one of the impementations of java's Queue.

If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.

How can I determine the type of an HTML element in JavaScript?

You can use generic code inspection via instanceof:

var e = document.getElementById('#my-element');
if (e instanceof HTMLInputElement) {}         // <input>
elseif (e instanceof HTMLSelectElement) {}    // <select>
elseif (e instanceof HTMLTextAreaElement) {}  // <textarea>
elseif (  ... ) {}                            // any interface

Look here for a complete list of interfaces.

How to extract one column of a csv file

The other answers work well, but since you asked for a solution using just the bash shell, you can do this:

AirBoxOmega:~ d$ cat > file #First we'll create a basic CSV
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10

And then you can pull out columns (the first in this example) like so:

AirBoxOmega:~ d$ while IFS=, read -a csv_line;do echo "${csv_line[0]}";done < file
a
1
a
1
a
1
a
1
a
1
a
1

So there's a couple of things going on here:

  • while IFS=, - this is saying to use a comma as the IFS (Internal Field Separator), which is what the shell uses to know what separates fields (blocks of text). So saying IFS=, is like saying "a,b" is the same as "a b" would be if the IFS=" " (which is what it is by default.)

  • read -a csv_line; - this is saying read in each line, one at a time and create an array where each element is called "csv_line" and send that to the "do" section of our while loop

  • do echo "${csv_line[0]}";done < file - now we're in the "do" phase, and we're saying echo the 0th element of the array "csv_line". This action is repeated on every line of the file. The < file part is just telling the while loop where to read from. NOTE: remember, in bash, arrays are 0 indexed, so the first column is the 0th element.

So there you have it, pulling out a column from a CSV in the shell. The other solutions are probably more practical, but this one is pure bash.

Emulate/Simulate iOS in Linux

Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium

"Failed to install the following Android SDK packages as some licences have not been accepted" error

You need to accept the licences before building.

According to Android SDK docs you can use the following command depending on the sdkmanager location: Docs on --licenses option seems to be missing though.

yes | sdkmanager --licenses

GNU/Linux Distributions:

yes | ~/Android/Sdk/tools/bin/sdkmanager --licenses

macOS:

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home
yes | ~/Library/Android/sdk/tools/bin/sdkmanager --licenses

Windows:

%ANDROID_HOME%/tools/bin/sdkmanager --licenses

Flutter:

> flutter doctor --android-licenses

base 64 encode and decode a string in angular (2+)

Use btoa("yourstring")

more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs

Is it possible to get a history of queries made in postgres

pgBadger is another option - also listed here: https://github.com/dhamaniasad/awesome-postgres#utilities

Requires some additional setup in advance to capture the necessary data in the postgres logs though, see the official website.

How to import and export components using React + ES6 + webpack?

Try defaulting the exports in your components:

import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class MyNavbar extends React.Component {
    render(){
      return (
        <Navbar className="navbar-dark" fluid>
        ...
        </Navbar>
      );
    }
}

by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Your command line mvn eclipse project generator may not be the same version as that of your eclipse, and eclipse doesn't understand for your command line tool is generating. Just use eclipse's in this case:

  • remove the project from eclipse (including all modules if multi-module)
  • run: rm -rf .settings/ .project .classpath to delete eclipse project files, also from modules
  • import your project as an existing maven project

Counting the number of True Booleans in a Python List

You can use sum():

>>> sum([True, True, False, False, False, True])
3

Adding 'serial' to existing column in Postgres

You can also use START WITH to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,

SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');

Rendering React Components from Array of Objects

I have an answer that might be a bit less confusing for newbies like myself. You can just use map within the components render method.

render () {
   return (
       <div>
           {stations.map(station => <div key={station}> {station} </div>)} 
       </div>
   );
}

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

this is my simple implementation for ASYNC requests with jQuery. I hope this help anyone.

var queueUrlsForRemove = [
    'http://dev-myurl.com/image/1', 
    'http://dev-myurl.com/image/2',
    'http://dev-myurl.com/image/3',
];

var queueImagesDelete = function(){

    deleteImage( queueUrlsForRemove.splice(0,1), function(){
        if (queueUrlsForRemove.length > 0) {
            queueImagesDelete();
        }
    });

}

var deleteImage = function(url, callback) {
    $.ajax({
        url: url,
        method: 'DELETE'
    }).done(function(response){
        typeof(callback) == 'function' ? callback(response) : null;
    });
}

queueImagesDelete();

check if jquery has been loaded, then load it if false

var f = ()=>{
    if (!window.jQuery) {
        var e = document.createElement('script');
        e.src = "https://code.jquery.com/jquery-3.2.1.min.js";
        e.onload = function () {
            jQuery.noConflict();
            console.log('jQuery ' + jQuery.fn.jquery + ' injected.');
        };
        document.head.appendChild(e);
    } else {
        console.log('jQuery ' + jQuery.fn.jquery + '');
    }
};
f();

Excel compare two columns and highlight duplicates

A simple formula to use is

=COUNTIF($B:$B,A1)

Formula specified is for cell A1. Simply copy and paste special - format to the whole of column A

How to fix "Incorrect string value" errors?

I solved this problem today by altering the column to 'LONGBLOB' type which stores raw bytes instead of UTF-8 characters.

The only disadvantage of doing this is that you have to take care of the encoding yourself. If one client of your application uses UTF-8 encoding and another uses CP1252, you may have your emails sent with incorrect characters. To avoid this, always use the same encoding (e.g. UTF-8) across all your applications.

Refer to this page http://dev.mysql.com/doc/refman/5.0/en/blob.html for more details of the differences between TEXT/LONGTEXT and BLOB/LONGBLOB. There are also many other arguments on the web discussing these two.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

I don't have enough context to give you a correct answer, but I'll suggest you to make you code immutable as much as possible. Use public final fields. No more getters or setters : every field has to be defined by the constructor. Your code is shorter, more readable and prevents you from writing code with side effects.

It doesn't prevent you from passing null arguments to your constructor though... You can still check every argument as suggested by @cletus, but I'll suggest you to throw IllegalArgumentException instead of NullPointerException that doesn't give no new hint about what you've done.

Anyway, that's what I do as much as I can and it improved my code (readability, stability) to a great extend. Everyone in my team does so and we are very happy with that. We learned that when we try to write some erlang code where everything is immutable.

Hope this helps.

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

What is the use of the @Temporal annotation in Hibernate?

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date/time or both (TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that converts back and forth between timestamp and java.util.Date. It also converts time-stamp into time. For example, in the snippet below, @Temporal(TemporalType.DATE) drops the time value and only preserves the date.

@Temporal(TemporalType.DATE)
private java.util.Date creationDate;

As per javadocs,

Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default TemporalType.DATE

[Information above collected from various sources]

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

UnicodeDecodeError, invalid continuation byte

Because UTF-8 is multibyte and there is no char corresponding to your combination of \xe9 plus following space.

Why should it succeed in both utf-8 and latin-1?

Here how the same sentence should be in utf-8:

>>> o.decode('latin-1').encode("utf-8")
'a test of \xc3\xa9 char'

How to support placeholder attribute in IE8 and 9

Add the below code and it will be done.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
    <script type="text/javascript">
        // Mock client code for testing purpose
        $(function(){
            // Client should be able to add another change event to the textfield
            $("input[name='input1']").blur(function(){ alert("Custom event triggered."); });    
            // Client should be able to set the field's styles, without affecting place holder
            $("textarea[name='input4']").css("color", "red");

            // Initialize placeholder
            $.Placeholder.init();

            // or try initialize with parameter
            //$.Placeholder.init({ color : 'rgb(255, 255, 0)' });

            // call this before form submit if you are submitting by JS
            //$.Placeholder.cleanBeforeSubmit();
        });
    </script>

Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip

How to open URL in Microsoft Edge from the command line?

I want to complement other answers here in regards to opening a blank tab in Microsoft Edge from command-line.

One observation that I want to add from my end is that Windows doesn't detect the command microsoft-edge if I remove the trailing colon. I thought it would be the case when I've to open the browser without mentioning the target URL e.g. in case of opening a blank tab.

How to open a blank tab in Microsoft Edge?

  • From run prompt - microsoft-edge:about:blank
  • From command prompt - start microsoft-edge:about:blank

You can also initiate a search using Edge from run prompt. Let's say I've to search Barack Obama then fire below command on run prompt-

microsoft-edge:Barack Obama

It starts Microsoft's Bing search website in Edge with Barack Obama as search term.

Mock a constructor with parameter

Without Using Powermock .... See the example below based on Ben Glasser answer since it took me some time to figure it out ..hope that saves some times ...

Original Class :

public class AClazz {

    public void updateObject(CClazz cClazzObj) {
        log.debug("Bundler set.");
        cClazzObj.setBundler(new BClazz(cClazzObj, 10));
    } 
}

Modified Class :

@Slf4j
public class AClazz {

    public void updateObject(CClazz cClazzObj) {
        log.debug("Bundler set.");
        cClazzObj.setBundler(getBObject(cClazzObj, 10));
    }

    protected BClazz getBObject(CClazz cClazzObj, int i) {
        return new BClazz(cClazzObj, 10);
    }
 }

Test Class

public class AClazzTest {

    @InjectMocks
    @Spy
    private AClazz aClazzObj;

    @Mock
    private CClazz cClazzObj;

    @Mock
    private BClazz bClassObj;

    @Before
    public void setUp() throws Exception {
        Mockito.doReturn(bClassObj)
               .when(aClazzObj)
               .getBObject(Mockito.eq(cClazzObj), Mockito.anyInt());
    }

    @Test
    public void testConfigStrategy() {
        aClazzObj.updateObject(cClazzObj);

        Mockito.verify(cClazzObj, Mockito.times(1)).setBundler(bClassObj);
    }
}

Center the nav in Twitter Bootstrap

For Bootstrap v4 check this:

https://v4-alpha.getbootstrap.com/components/pagination/#alignment

only add class to ul.pagination:

<nav">
  <ul class="pagination justify-content-center">
    <li class="page-item disabled">
      <a class="page-link" href="#" tabindex="-1">Previous</a>
    </li>
    <li class="page-item"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">3</a></li>
    <li class="page-item">
      <a class="page-link" href="#">Next</a>
    </li>
  </ul>
</nav>

Writing data into CSV file in C#

Instead of reinventing the wheel a library could be used. CsvHelper is great for creating and reading csv files. It's read and write operations are stream based and therefore also support operations with a big amount of data.


You can write your csv like the following.

using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv"))
{
    var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
    writer.Configuration.Delimiter = ",";

    foreach (var item in list)
    {
        writer.WriteField( "a" );
        writer.WriteField( 2 );
        writer.WriteField( true );
        writer.NextRecord();
    }
}

As the library is using reflection it will take any type and parse it directly.

public class CsvRow
{
    public string Column1 { get; set; }
    public bool Column2 { get; set; }

    public CsvRow(string column1, bool column2)
    {
        Column1 = column1;
        Column2 = column2;
    }
}

IEnumerable<CsvRow> rows = new [] {
    new CsvRow("value1", true),
    new CsvRow("value2", false)
};
using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv")
{
    var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
    writer.Configuration.Delimiter = ",";
    writer.WriteRecords(rows);
}

value1,true

value2,false


If you want to read more about the librarys configurations and possibilities you can do so here.

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

Remove all whitespaces from NSString

stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle.

1) If you need to remove only a given character (say the space character) from your string, use:

[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]

2) If you really need to remove a set of characters (namely not only the space character, but any whitespace character like space, tab, unbreakable space, etc), you could split your string using the whitespaceCharacterSet then joining the words again in one string:

NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:@""];

Note that this last solution has the advantage of handling every whitespace character and not only spaces, but is a bit less efficient that the stringByReplacingOccurrencesOfString:withString:. So if you really only need to remove the space character and are sure you won't have any other whitespace character than the plain space char, use the first method.

Spring REST Service: how to configure to remove null objects in json response

Since version 1.6 we have new annotation JsonSerialize (in version 1.9.9 for example).

Example:

@JsonSerialize(include=Inclusion.NON_NULL)
public class Test{
...
}

Default value is ALWAYS.

In old versions you can use JsonWriteNullProperties, which is deprecated in new versions. Example:

@JsonWriteNullProperties(false)
public class Test{
    ...
}

How do I make XAML DataGridColumns fill the entire DataGrid?

This will not expand the last column of the xaml grid to take the remaining space if AutoGeneratedColumns="True".

Change Default branch in gitlab

To change default branch in GitLab:
1. Settings > General > General project settings > Expand
2. Default Branch > Change your project default branch
3. Save changes

enter image description here

New Line Issue when copying data from SQL Server 2012 to Excel

My best guess is that this is not a bug, but a feature of Sql 2012. ;-) In other contexts, you'd be happy to retain your cr-lf's, like when copying a big chunk of text. It's just that it doesn't work well in your situation.

You could always strip them out in your select. This would make your query for as you intend in both versions:

select REPLACE(col, CHAR(13) + CHAR(10), ', ') from table

How do I add space between two variables after a print in Python

Alternatively you can use ljust/rjust to make the formatting nicer.

print "%s%s" % (str(count).rjust(10), conv)

or

print str(count).ljust(10), conv

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

Calling Scalar-valued Functions in SQL

Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

How do I enable TODO/FIXME/XXX task tags in Eclipse?

In the distribution I use, the tasks are listed in the task list by default (at least for Java). For other content types, you may check the following settings.

Display the Tasks View: Window > Show View > Other > General > Tasks

For non-Java Task Tags: check the following settings: Window > Preferences > General > Editors > Structured Text Editors > Task Tags You can enable searching for task tags in the [Task Tags] tab and select the content types in the [Filters] tab.

For Java task tags, you should look in: Window > Preferences > Java > Compiler > Task Tags

J.

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

How do I set the visibility of a text box in SSRS using an expression?

Switch your false and true returns? I think if you put those as a function in the visibility area, then false will show it and true will not show it.

Angular 2 @ViewChild annotation returns undefined

If you're using Ionic you'll need to use the ionViewDidEnter() lifecycle hook. Ionic runs some additional stuff (mainly animation-related) which typically causes unexpected errors like this, hence the need for something that runs after ngOnInit, ngAfterContentInit, and so on.

Apache Tomcat :java.net.ConnectException: Connection refused

I also faced this problem . You can try any of these steps :

How to set the action for a UIBarButtonItem in Swift

Swift 5 & iOS 13+ Programmatic Example

  1. You must mark your function with @objc, see below example!
  2. No parenthesis following after the function name! Just use #selector(name).
  3. private or public doesn't matter; you can use private.

Code Example

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    let menuButtonImage = UIImage(systemName: "flame")
    let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
    navigationItem.rightBarButtonItem = menuButton
}

@objc public func didTapMenuButton() {
    print("Hello World")
}

How to get the device's IMEI/ESN programmatically in android?

From: http://mytechead.wordpress.com/2011/08/28/how-to-get-imei-number-of-android-device/:

The following code helps in obtaining IMEI number of android devices :

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_id = tm.getDeviceId();

Permissions required in Android Manifest:

android.permission.READ_PHONE_STATE

NOTE: In case of tablets or devices which can’t act as Mobile Phone IMEI will be null.

jQuery: Count number of list elements?

Try:

$("#mylist li").length

Just curious: why do you need to know the size? Can't you just use:

$("#mylist").append("<li>New list item</li>");

?

500.21 Bad module "ManagedPipelineHandler" in its module list

I had this issue in Windows 10 when I needed IIS instead of IIS Express. New Web Project failed with OP's error. Fix was

Control Panel > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application Development Features

tick ASP.NET 4.7 (in my case)

Most pythonic way to delete a file which may not exist

os.path.exists returns True for folders as well as files. Consider using os.path.isfile to check for whether the file exists instead.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

FormData Objects: Upload Files Using Ajax

XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.

function AjaxFileUpload() {
    var file = document.getElementById("files");
    //var file = fileInput;
    var fd = new FormData();
    fd.append("imageFileData", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/ws/fileUpload.do');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
             alert('success');
        }
        else if (uploadResult == 'success')
             alert('error');
    };
    xhr.send(fd);
}

https://developer.mozilla.org/en-US/docs/Web/API/FormData

Unable to open debugger port in IntelliJ

I had the same problem and this solution also did the trick for me: Provide the IP 127.0.0.1 in the Intellij Debug configuration instead of the host name "localhost", in case you're using this hostname.

What is REST? Slightly confused

REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).

First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).

EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

byte[] to file in Java

Without any libraries:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

Files.write(bytes, new File(path));

With Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

java.util.regex - importance of Pattern.compile()?

It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.

Below is a sample validator, which is really called a lot :)

public class AmountValidator {
    //Accept 123 - 123,456 - 123,345.34
    private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
    //Compile and save the pattern  
    private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);


    public boolean validate(String amount){

         if (!AMOUNT_PATTERN.matcher(amount).matches()) {
            return false;
         }    
        return true;
    }    
}

As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.

Extracting specific columns in numpy array

I assume you wanted columns 1 and 9?

To select multiple columns at once, use

X = data[:, [1, 9]]

To select one at a time, use

x, y = data[:, 1], data[:, 9]

With names:

data[:, ['Column Name1','Column Name2']]

You can get the names from data.dtype.names

python list by value not by reference

To copy a list you can use list(a) or a[:]. In both cases a new object is created.
These two methods, however, have limitations with collections of mutable objects as inner objects keep their references intact:

>>> a = [[1,2],[3],[4]]

>>> b = a[:]
>>> c = list(a)

>>> c[0].append(9)

>>> a
[[1, 2, 9], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>> b
[[1, 2, 9], [3], [4]]
>>> 

If you want a full copy of your objects you need copy.deepcopy

>>> from copy import deepcopy
>>> a = [[1,2],[3],[4]]

>>> b = a[:]
>>> c = deepcopy(a)

>>> c[0].append(9)

>>> a
[[1, 2], [3], [4]]
>>> b
[[1, 2], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>> 

Getting the ID of the element that fired an event

Element which fired event we have in event property

event.currentTarget

We get DOM node object on which was set event handler.


Most nested node which started bubbling process we have in

event.target

Event object is always first attribute of event handler, example:

document.querySelector("someSelector").addEventListener(function(event){

 console.log(event.target);
 console.log(event.currentTarget);

});

More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/

How exactly does binary code get converted into letters?

Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.

1 - Convert every 4 binary digits into one hex digit.

Here's a binary to hex conversion chart:

0001 = 1 
0010 = 2 
0011 = 3 
0100 = 4 
0101 = 5
0110 = 6
0111 = 7
1000 = 8

1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f

(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)

Once you know that chart, converting any string of binary digits into a string of hex digits is simple.

For example,

01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex

Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.

(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)

2 - Split the string of hex digits into pairs.

When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.

You would split a hex number like 7340298b392 this into 6 pairs, like this:

7340298b392 = 07 34 02 98 b3 92

(Notice I prepended a 0, since I had an odd number of hex digits.)

That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)

3 - Convert each pair of hex digits into a decimal number.

Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.

For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)

4 - Convert the decimal numbers into ASCII characters.

Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.

So what letter is 68?

68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.

So 68 is 'D'.

You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.


Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that

hex 41 = 'A' 
hex 61 = 'a'

So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.

For example

01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'

(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)

I saw this on a shirt once, and was able to read it in my head:

01000100
01000001
01000100

I did it like this:

01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D

The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.


How did I know right away that 92, b3, and 98 were not letters?

Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.


So that's how you can do it as a human.

How do computer programs do it?

For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.

(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

How to choose between Hudson and Jenkins?

Jenkins is the new Hudson. It really is more like a rename, not a fork, since the whole development community moved to Jenkins. (Oracle is left sitting in a corner holding their old ball "Hudson", but it's just a soul-less project now.)

C.f. Ethereal -> WireShark

How to initialize static variables

I use a combination of Tjeerd Visser's and porneL's answer.

class Something
{
    private static $foo;

    private static getFoo()
    {
        if ($foo === null)
            $foo = [[ complicated initializer ]]
        return $foo;
    }

    public static bar()
    {
        [[ do something with self::getFoo() ]]
    }
}

But an even better solution is to do away with the static methods and use the Singleton pattern. Then you just do the complicated initialization in the constructor. Or make it a "service" and use DI to inject it into any class that needs it.

Conditional operator in Python?

From Python 2.5 onwards you can do:

value = b if a > 10 else c

Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

Postgres: clear entire database before re-creating / re-populating from bash script

Note: my answer is about really deleting the tables and other database objects; for deleting all data in the tables, i.e. truncating all tables, Endre Both has provided a similarily well-executed (direct execution) statement a month later.

For the cases where you can’t just DROP SCHEMA public CASCADE;, DROP OWNED BY current_user; or something, here’s a stand-alone SQL script I wrote, which is transaction-safe (i.e. you can put it between BEGIN; and either ROLLBACK; to just test it out or COMMIT; to actually do the deed) and cleans up “all” database objects… well, all those used in the database our application uses or I could sensibly add, which is:

  • triggers on tables
  • constraints on tables (FK, PK, CHECK, UNIQUE)
  • indices
  • VIEWs (normal or materialised)
  • tables
  • sequences
  • routines (aggregate functions, functions, procedures)
  • all non-default (i.e. not public or DB-internal) schemata “we” own: the script is useful when run as “not a database superuser”; a superuser can drop all schemata (the really important ones are still explicitly excluded, though)
  • extensions (user-contributed but I normally deliberately leave them in)

Not dropped are (some deliberate; some only because I had no example in our DB):

  • the public schema (e.g. for extension-provided stuff in them)
  • collations and other locale stuff
  • event triggers
  • text search stuff, … (see here for other stuff I might have missed)
  • roles or other security settings
  • composite types
  • toast tables
  • FDW and foreign tables

This is really useful for the cases when the dump you want to restore is of a different database schema version (e.g. with Debian dbconfig-common, Flyway or Liquibase/DB-Manul) than the database you want to restore it into.

I’ve also got a version which deletes “everything except two tables and what belongs to them” (a sequence, tested manually, sorry, I know, boring) in case someone is interested; the diff is small. Contact me or check this repo if interested.

SQL

-- Copyright © 2019, 2020
--      mirabilos <[email protected]>
--
-- Provided that these terms and disclaimer and all copyright notices
-- are retained or reproduced in an accompanying document, permission
-- is granted to deal in this work without restriction, including un-
-- limited rights to use, publicly perform, distribute, sell, modify,
-- merge, give away, or sublicence.
--
-- This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
-- the utmost extent permitted by applicable law, neither express nor
-- implied; without malicious intent or gross negligence. In no event
-- may a licensor, author or contributor be held liable for indirect,
-- direct, other damage, loss, or other issues arising in any way out
-- of dealing in the work, even if advised of the possibility of such
-- damage or existence of a defect, except proven that it results out
-- of said person’s immediate fault when using the work as intended.
-- -
-- Drop everything from the PostgreSQL database.

DO $$
DECLARE
        q TEXT;
        r RECORD;
BEGIN
        -- triggers
        FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
                FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pt.tgisinternal=false
            ) LOOP
                EXECUTE format('DROP TRIGGER %I ON %I.%I;',
                    r.tgname, r.nspname, r.relname);
        END LOOP;
        -- constraints #1: foreign key
        FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
                FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pcon.contype='f'
            ) LOOP
                EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
                    r.nspname, r.relname, r.conname);
        END LOOP;
        -- constraints #2: the rest
        FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
                FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pcon.contype<>'f'
            ) LOOP
                EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
                    r.nspname, r.relname, r.conname);
        END LOOP;
        -- indices
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='i'
            ) LOOP
                EXECUTE format('DROP INDEX %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- normal and materialised views
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind IN ('v', 'm')
            ) LOOP
                EXECUTE format('DROP VIEW %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- tables
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='r'
            ) LOOP
                EXECUTE format('DROP TABLE %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- sequences
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='S'
            ) LOOP
                EXECUTE format('DROP SEQUENCE %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- extensions (only if necessary; keep them normally)
        FOR r IN (SELECT pns.nspname, pe.extname
                FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
                WHERE pns.oid=pe.extnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
            ) LOOP
                EXECUTE format('DROP EXTENSION %I;', r.extname);
        END LOOP;
        -- aggregate functions first (because they depend on other functions)
        FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
                FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
                WHERE pns.oid=pp.pronamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pagg.aggfnoid=pp.oid
            ) LOOP
                EXECUTE format('DROP AGGREGATE %I.%I(%s);',
                    r.nspname, r.proname,
                    pg_get_function_identity_arguments(r.oid));
        END LOOP;
        -- routines (functions, aggregate functions, procedures, window functions)
        IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
                WHERE attrelid='pg_catalog.pg_proc'::regclass
                    AND attname='prokind' -- PostgreSQL 11+
            ) THEN
                q := 'CASE pp.prokind
                        WHEN ''p'' THEN ''PROCEDURE''
                        WHEN ''a'' THEN ''AGGREGATE''
                        ELSE ''FUNCTION''
                    END';
        ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
                WHERE attrelid='pg_catalog.pg_proc'::regclass
                    AND attname='proisagg' -- PostgreSQL =10
            ) THEN
                q := 'CASE pp.proisagg
                        WHEN true THEN ''AGGREGATE''
                        ELSE ''FUNCTION''
                    END';
        ELSE
                q := '''FUNCTION''';
        END IF;
        FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
                FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
                WHERE pns.oid=pp.pronamespace
                    AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
            ' LOOP
                EXECUTE format('DROP %s %I.%I(%s);', r.pt,
                    r.nspname, r.proname,
                    pg_get_function_identity_arguments(r.oid));
        END LOOP;
        -- non-default schemata we own; assume to be run by a not-superuser
        FOR r IN (SELECT pns.nspname
                FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
                WHERE pr.oid=pns.nspowner
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
                    AND pr.rolname=current_user
            ) LOOP
                EXECUTE format('DROP SCHEMA %I;', r.nspname);
        END LOOP;
        -- voilà
        RAISE NOTICE 'Database cleared!';
END; $$;

Tested, except later additions (extensions contributed by Clément Prévost), on PostgreSQL 9.6 (jessie-backports). Aggregate removal tested on 9.6 and 12.2, procedure removal tested on 12.2 as well. Bugfixes and further improvements welcome!

How to print colored text to the terminal?

Here's a solution that works on Windows 10 natively.

Using a system call, such as os.system(""), allows colours to be printed in Command Prompt and Powershell natively:

import os

# System call
os.system("")

# Class of different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.

Thanks to @j-l for finding an even shorter method.

tl;dr: Add os.system("")

Make selected block of text uppercase

Without defining keyboard shortcuts

  1. Select the text you want capitalized

  2. Open View->Command Palette (or Shift+Command+P)

  3. Start typing "Transform to uppercase" and select that option

  4. Voila!

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Proper usage of Java -D command-line parameters

You're giving parameters to your program instead to Java. Use

java -Dtest="true" -jar myApplication.jar 

instead.

Consider using

"true".equalsIgnoreCase(System.getProperty("test"))

to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like

System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")

is right (providing default true). A shorter possibility is

!"false".equalsIgnoreCase(System.getProperty("test"))

but not using double negation doesn't make it less hard to misunderstand.

Convert month name to month number in SQL Server

You can use below code

DECLARE @T TABLE ([Month] VARCHAR(20))
INSERT INTO @T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`

SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM @T
ORDER BY MonthNumeric

Why can't I center with margin: 0 auto?

An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.

This is how it works for me:

#content {
display: block;
margin: 0 auto;
}

Select All as default value for Multivalue parameter

Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.

How to recover stashed uncommitted changes

To check your stash content :-

git stash list

apply a particular stash no from stash list:-

git stash apply stash@{2}

or for applying just the first stash:-

git stash pop

Note: git stash pop will remove the stash from your stash list whereas git stash apply wont. So use them accordingly.

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

In my case, I was installing a project with MinimumSDK bigger than the Android version of my real device. I used another device and it solved MinSDK -> 24 My Phone -> 21

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
    schoolName  = school
    cityName = city
    standardName = standard
    studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

CSS selector for a checked radio button's label

I forget where I first saw it mentioned but you can actually embed your labels in a container elsewhere as long as you have the for= attribute set. So, let's check out a sample on SO:

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
  background-color: #262626;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
.radio-button {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
#filter {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.filter-label {_x000D_
  display: inline-block;_x000D_
  border: 4px solid green;_x000D_
  padding: 10px 20px;_x000D_
  font-size: 1.4em;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
main {_x000D_
  clear: left;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  padding: 3% 10%;_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  font-size: 2em;_x000D_
}_x000D_
_x000D_
.date {_x000D_
  padding: 5px 30px;_x000D_
  font-style: italic;_x000D_
}_x000D_
_x000D_
.filter-label:hover {_x000D_
  background-color: #505050;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~#filter .featured,_x000D_
#personal-radio:checked~#filter .personal,_x000D_
#tech-radio:checked~#filter .tech {_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
#featured-radio:checked~main .featured {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#personal-radio:checked~main .personal {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#tech-radio:checked~main .tech {_x000D_
  display: block;_x000D_
}
_x000D_
<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">_x000D_
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">_x000D_
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">_x000D_
_x000D_
<header id="filter">_x000D_
  <label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>_x000D_
  <label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>_x000D_
  <label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>_x000D_
</header>_x000D_
_x000D_
<main>_x000D_
  <article class="content featured tech">_x000D_
    <header>_x000D_
      <h1>Cool Stuff</h1>_x000D_
      <h3 class="date">Today</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      I'm showing cool stuff in this article!_x000D_
    </p>_x000D_
  </article>_x000D_
_x000D_
  <article class="content personal">_x000D_
    <header>_x000D_
      <h1>Not As Cool</h1>_x000D_
      <h3 class="date">Tuesday</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      This stuff isn't nearly as cool for some reason :(;_x000D_
    </p>_x000D_
  </article>_x000D_
_x000D_
  <article class="content tech">_x000D_
    <header>_x000D_
      <h1>Cool Tech Article</h1>_x000D_
      <h3 class="date">Last Monday</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      This article has awesome stuff all over it!_x000D_
    </p>_x000D_
  </article>_x000D_
_x000D_
  <article class="content featured personal">_x000D_
    <header>_x000D_
      <h1>Cool Personal Article</h1>_x000D_
      <h3 class="date">Two Fridays Ago</h3>_x000D_
    </header>_x000D_
_x000D_
    <p>_x000D_
      This article talks about how I got a job at a cool startup because I rock!_x000D_
    </p>_x000D_
  </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Whew. That was a lot for a "sample" but I feel it really drives home the effect and point: we can certainly select a label for a checked input control without it being a sibling. The secret lies in keeping the input tags a child to only what they need to be (in this case - only the body element).

Since the label element doesn't actually utilize the :checked pseudo selector, it doesn't matter that the labels are stored in the header. It does have the added benefit that since the header is a sibling element we can use the ~ generic sibling selector to move from the input[type=radio]:checked DOM element to the header container and then use descendant/child selectors to access the labels themselves, allowing the ability to style them when their respective radio boxes/checkboxes are selected.

Not only can we style the labels, but also style other content that may be descendants of a sibling container relative to all of the inputs. And now for the moment you've all been waiting for, the JSFIDDLE! Go there, play with it, make it work for you, find out why it works, break it, do what you do!

Hopefully that all makes sense and fully answers the question and possibly any follow ups that may crop up.

PHP json_decode() returns NULL with valid JSON?

If you are getting json from database, put

mysqli_set_charset($con, "utf8");

after defining connection link $con

How to set array length in c# dynamically

Use Array.CreateInstance to create an array dynamically.

    private Update BuildMetaData(MetaData[] nvPairs)
    {
        Update update = new Update();
        InputProperty[] ip = Array.CreateInstance(typeof(InputProperty), nvPairs.Count()) as InputProperty[];
        int i;
        for (i = 0; i < nvPairs.Length; i++)
        {
            if (nvPairs[i] == null) break;
            ip[i] = new InputProperty();
            ip[i].Name = "udf:" + nvPairs[i].Name;
            ip[i].Val = nvPairs[i].Value;
        }
        update.Items = ip;
        return update;
    }

Why should C++ programmers minimize use of 'new'?

Because the stack is faster and leak-proof

In C++, it takes but a single instruction to allocate space -- on the stack -- for every local scope object in a given function, and it's impossible to leak any of that memory. That comment intended (or should have intended) to say something like "use the stack and not the heap".

Using generic std::function objects with member functions in one class

Either you need

std::function<void(Foo*)> f = &Foo::doSomething;

so that you can call it on any instance, or you need to bind a specific instance, for example this

std::function<void(void)> f = std::bind(&Foo::doSomething, this);

using favicon with css

You can't set a favicon from CSS - if you want to do this explicitly you have to do it in the markup as you described.

Most browsers will, however, look for a favicon.ico file on the root of the web site - so if you access http://example.com most browsers will look for http://example.com/favicon.ico automatically.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Add the following under @NgModule({})in 'app.module.ts' :

import {CUSTOM_ELEMENTS_SCHEMA} from `@angular/core`;

and then

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
]

Your 'app.module.ts' should look like this:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [],
  imports: [],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

How to compile a 64-bit application using Visual C++ 2010 Express?

Programming in a 64-bit environment is quite different than 32-bit environment. Code generated has totally different assembly constitution in 32 & 64-bit code, even the protocols of communicating with functions change. So you can't generate 64-bit code using 32-bit compiler.

You might want to see an article on Microsoft's web site about targeting a 64-bit target but using a 32-bit development machine.

Cross-Origin Request Headers(CORS) with PHP headers

Access-Control-Allow-Headers does not allow * as accepted value, see the Mozilla Documentation here.

Instead of the asterisk, you should send the accepted headers (first X-Requested-With as the error says).

Call PHP function from Twig template

This worked for me (using Slim Twig-View):

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('md5', function($arg){ return md5($arg); })
);

This creates a new filter named md5 which returns the MD5 checksum of the argument.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I simply solve this problem like this, which should work in all browsers:

_x000D_
_x000D_
ul li {
  color: red
}

ul li span {
  color: blue;
}
_x000D_
<ul>
  <li><span>Foo</span></li>
  <li><span>Bar</span></li>
  <li><span>Bat</span></li>
</ul>
_x000D_
_x000D_
_x000D_

How to specify more spaces for the delimiter using cut?

One way around this is to go:

$ps axu | grep jboss | sed 's/\s\+/ /g' | cut -d' ' -f3

to replace multiple consecutive spaces with a single one.

Viewing unpushed Git commits

If you want to see all commits on all branches that aren't pushed yet, you might be looking for something like this:

git log --branches --not --remotes

And if you only want to see the most recent commit on each branch, and the branch names, this:

git log --branches --not --remotes --simplify-by-decoration --decorate --oneline

Request is not available in this context

In visual studio 2012, When I published the solution mistakenly with 'debug' option I got this exception. With 'release' option it never occurred. Hope it helps.

Android : change button text and background color

I think doing this way is much simpler:

button.setBackgroundColor(Color.BLACK);

And you need to import android.graphics.Color; not: import android.R.color;

Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000 where the first byte is setting the alpha.

Difference between h:button and h:commandButton

<h:button>

The <h:button> generates a HTML <input type="button">. The generated element uses JavaScript to navigate to the page given by the attribute outcome, using a HTTP GET request.

E.g.

<h:button value="GET button" outcome="otherpage" />

will generate

<input type="button" onclick="window.location.href='/contextpath/otherpage.xhtml'; return false;" value="GET button" />

Even though this ends up in a (bookmarkable) URL change in the browser address bar, this is not SEO-friendly. Searchbots won't follow the URL in the onclick. You'd better use a <h:outputLink> or <h:link> if SEO is important on the given URL. You could if necessary throw in some CSS on the generated HTML <a> element to make it to look like a button.

Do note that while you can put an EL expression referring a method in outcome attribute as below,

<h:button value="GET button" outcome="#{bean.getOutcome()}" />

it will not be invoked when you click the button. Instead, it is already invoked when the page containing the button is rendered for the sole purpose to obtain the navigation outcome to be embedded in the generated onclick code. If you ever attempted to use the action method syntax as in outcome="#{bean.action}", you would already be hinted by this mistake/misconception by facing a javax.el.ELException: Could not find property actionMethod in class com.example.Bean.

If you intend to invoke a method as result of a POST request, use <h:commandButton> instead, see below. Or if you intend to invoke a method as result of a GET request, head to Invoke JSF managed bean action on page load or if you also have GET request parameters via <f:param>, How do I process GET query string URL parameters in backing bean on page load?


<h:commandButton>

The <h:commandButton> generates a HTML <input type="submit"> button which submits by default the parent <h:form> using HTTP POST method and invokes the actions attached to action, actionListener and/or <f:ajax listener>, if any. The <h:form> is required.

E.g.

<h:form id="form">
    <h:commandButton id="button" value="POST button" action="otherpage" />
</h:form>

will generate

<form id="form" name="form" method="post" action="/contextpath/currentpage.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="form" value="form" />
    <input type="submit" name="form:button" value="POST button" />
    <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="...." autocomplete="off" />
</form>

Note that it thus submits to the current page (the form action URL will show up in the browser address bar). It will afterwards forward to the target page, without any change in the URL in the browser address bar. You could add ?faces-redirect=true parameter to the outcome value to trigger a redirect after POST (as per the Post-Redirect-Get pattern) so that the target URL becomes bookmarkable.

The <h:commandButton> is usually exclusively used to submit a POST form, not to perform page-to-page navigation. Normally, the action points to some business action, such as saving the form data in DB, which returns a String outcome.

<h:commandButton ... action="#{bean.save}" />

with

public String save() {
    // ...
    return "otherpage";
}

Returning null or void will bring you back to the same view. Returning an empty string also, but it would recreate any view scoped bean. These days, with modern JSF2 and <f:ajax>, more than often actions just return to the same view (thus, null or void) wherein the results are conditionally rendered by ajax.

public void save() {
    // ...
}

See also:

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Equivalent of "continue" in Ruby

Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

Output: Enter the nmber 10

1 2 3 4 6 7 8 9 10

How to make the tab character 4 spaces instead of 8 spaces in nano?

In nano 2.2.6 the line in ~/.nanorc to do this seems to be

set tabsize 4

Setting tabspace gave me the error: 'Unknown flag "tabspace"'

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

How to build a Horizontal ListView with RecyclerView?

It's for both for Horizontal and for Vertical.

RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_recycler);
    recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);

    RecyclAdapter adapter = new RecyclAdapter();

    //Vertical RecyclerView
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);

    //Horizontal RecyclerView
    //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

    recyclerView.setAdapter(adapter);

}

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Set the Screen orientation to portrait in Manifest file under the activity Tag.

Received fatal alert: handshake_failure through SSLHandshakeException

To troubleshoot from developer (item 1) and system admin (item 2 and 3) perspective:

  1. Enable SSL handshake debug at Java via -Djavax.net.debug=ssl:handshake:verbose.
  2. Install ssldump at server via sudo apt install ssldump or compile from source by following this link if you observe Unknown value in cipher when you run below step.
  3. At server, sudo ssldump -k <your-private-key> -i <your-network-interface>
  4. Check the log about real reason of the failure.

Example of not working handshake of ssldump log:

New TCP connection #1: 10.1.68.86(45308) <-> 10.1.68.83(5671)
1 1  0.0111 (0.0111)  C>S  Handshake
      ClientHello
        Version 3.3
        cipher suites
        TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        TLS_RSA_WITH_AES_256_GCM_SHA384
        TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
        TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
        TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
        TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
        TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_RSA_WITH_AES_128_GCM_SHA256
        TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
        TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
        TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
        TLS_RSA_WITH_AES_256_CBC_SHA256
        TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
        TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
        TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
        TLS_RSA_WITH_AES_256_CBC_SHA
        TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
        TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA
        TLS_DHE_DSS_WITH_AES_256_CBC_SHA
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_RSA_WITH_AES_128_CBC_SHA256
        TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
        TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
        TLS_RSA_WITH_AES_128_CBC_SHA
        TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
        TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA
        TLS_DHE_DSS_WITH_AES_128_CBC_SHA
        TLS_EMPTY_RENEGOTIATION_INFO_SCSV
        compression methods
                  NULL
1 2  0.0122 (0.0011)  S>C  Alert
    level           fatal
    value           insufficient_security
1    0.0126 (0.0004)  S>C  TCP RST

Example of successful handshake of ssldump log

New TCP connection #1: 10.1.68.86(56558) <-> 10.1.68.83(8443)
1 1  0.0009 (0.0009)  C>S  Handshake
      ClientHello
        Version 3.3
        cipher suites
        TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
        TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
        Unknown value 0xcca9
        Unknown value 0xcca8
        Unknown value 0xccaa
        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA
        TLS_RSA_WITH_AES_256_GCM_SHA384
        TLS_RSA_WITH_AES_128_GCM_SHA256
        TLS_RSA_WITH_AES_256_CBC_SHA256
        TLS_RSA_WITH_AES_128_CBC_SHA256
        TLS_RSA_WITH_AES_256_CBC_SHA
        TLS_RSA_WITH_AES_128_CBC_SHA
        TLS_EMPTY_RENEGOTIATION_INFO_SCSV
        compression methods
                  NULL
1 2  0.0115 (0.0106)  S>C  Handshake
      ServerHello
        Version 3.3
        session_id[0]=

        cipherSuite         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        compressionMethod                   NULL
1 3  0.0115 (0.0000)  S>C  Handshake
      Certificate
1 4  0.0115 (0.0000)  S>C  Handshake
      ServerKeyExchange
Not enough data. Found 294 bytes (expecting 32767)
1 5    0.0115   (0.0000)    S>C    Handshake
        ServerHelloDone
1 6    0.0141   (0.0025)    C>S    Handshake
        ClientKeyExchange
Not enough data. Found 31 bytes (expecting 16384)
1 7    0.0141   (0.0000)    C>S    ChangeCipherSpec
1 8    0.0141   (0.0000)    C>S      Handshake
1 9    0.0149   (0.0008)    S>C    Handshake
1 10   0.0149   (0.0000)    S>C    ChangeCipherSpec
1 11   0.0149   (0.0000)    S>C      Handshake

Example of not working Java log

javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.778 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.779 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.779 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.780 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.780 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.780 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.781 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.781 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.781 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: T LS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLS10 javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.787 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLS10
javax.net.ssl|WARNING|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.818 MYT|SignatureScheme.java:282|Signature algorithm, ed25519, is not supported by the underlying providers
javax.net.ssl|WARNING|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.818 MYT|SignatureScheme.java:282|Signature algorithm, ed448, is not supported by the underlying providers
javax.net.ssl|ALL|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.822 MYT|SignatureScheme.java:358|Ignore disabled signature sheme: rsa_md5
javax.net.ssl|INFO|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.822 MYT|AlpnExtension.java:161|No available application protocols
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.823 MYT|SSLExtensions.java:256|Ignore, context unavailable extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.823 MYT|SSLExtensions.java:256|Ignore, context unavailable extension: renegotiation_info
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.825 MYT|ClientHello.java:651|Produced ClientHello handshake message (
"ClientHello": {
  "client version"      : "TLSv1.2",
  "random"              : "FB BC CD 7C 17 65 86 49 3E 1C 15 37 24 94 7D E7 60 44 1B B8 F4 18 21 D0 E1 B1 31 0D E1 80 D6 A7",
  "session id"          : "",
  "cipher suites"       : "[TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384(0xC02C), TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256(0xC02B), TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384(0xC030), TLS_RSA_WITH_AES_256_GCM_SHA384(0x009D), TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384(0xC02E), TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384(0xC032), TLS_DHE_RSA_WITH_AES_256_GCM_SHA384(0x009F), TLS_DHE_DSS_WITH_AES_256_GCM_SHA384(0x00A3), TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256(0xC02F), TLS_RSA_WITH_AES_128_GCM_SHA256(0x009C), TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256(0xC02D), TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256(0xC031), TLS_DHE_RSA_WITH_AES_128_GCM_SHA256(0x009E), TLS_DHE_DSS_WITH_AES_128_GCM_SHA256(0x00A2), TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384(0xC024), TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384(0xC028), TLS_RSA_WITH_AES_256_CBC_SHA256(0x003D), TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384(0xC026), TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384(0xC02A), TLS_DHE_RSA_WITH_AES_256_CBC_SHA256(0x006B), TLS_DHE_DSS_WITH_AES_256_CBC_SHA256(0x006A), TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA(0xC00A), TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA(0xC014), TLS_RSA_WITH_AES_256_CBC_SHA(0x0035), TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA(0xC005), TLS_ECDH_RSA_WITH_AES_256_CBC_SHA(0xC00F), TLS_DHE_RSA_WITH_AES_256_CBC_SHA(0x0039), TLS_DHE_DSS_WITH_AES_256_CBC_SHA(0x0038), TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256(0xC023), TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256(0xC027), TLS_RSA_WITH_AES_128_CBC_SHA256(0x003C), TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256(0xC025), TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256(0xC029), TLS_DHE_RSA_WITH_AES_128_CBC_SHA256(0x0067), TLS_DHE_DSS_WITH_AES_128_CBC_SHA256(0x0040), TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA(0xC009), TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA(0xC013), TLS_RSA_WITH_AES_128_CBC_SHA(0x002F), TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA(0xC004), TLS_ECDH_RSA_WITH_AES_128_CBC_SHA(0xC00E), TLS_DHE_RSA_WITH_AES_128_CBC_SHA(0x0033), TLS_DHE_DSS_WITH_AES_128_CBC_SHA(0x0032), TLS_EMPTY_RENEGOTIATION_INFO_SCSV(0x00FF)]",
  "compression methods" : "00",  "extensions"          : [
    "server_name (0)": {
      type=host_name (0), value=mq.tpc-ohcis.moh.gov.my
    },
    "status_request (5)": {
      "certificate status type": ocsp
      "OCSP status request": {
        "responder_id": <empty>
        "request extensions": {
          <empty>
        }
      }
    },
    "supported_groups (10)": {
      "versions": [secp256r1, secp384r1, secp521r1, sect283k1, sect283r1, sect409k1, sect409r1, sect571k1, sect571r1, secp256k1, ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192]
    },
    "ec_point_formats (11)": {
      "formats": [uncompressed]
    },
    "signature_algorithms (13)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp512r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, dsa_sha256, ecdsa_sha224, rsa_sha224, dsa_sha224, ecdsa_sha1, rsa_pkcs1_sha1, dsa_sha1]
    },
    "signature_algorithms_cert (50)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp512r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, dsa_sha256, ecdsa_sha224, rsa_sha224, dsa_sha224, ecdsa_sha1, rsa_pkcs1_sha1, dsa_sha1]
    },
    "status_request_v2 (17)": {
      "cert status request": {
        "certificate status type": ocsp_multi
        "OCSP status request": {
          "responder_id": <empty>
          "request extensions": {
            <empty>
          }
        }      }
    },
    "extended_master_secret (23)": {
      <empty>
    },
    "supported_versions (43)": {
      "versions": [TLSv1.2, TLSv1.1, TLSv1]
    }
  ]
}
)
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.829 MYT|Alert.java:238|Received alert message (
"Alert": {
  "level"      : "fatal",
  "description": "insufficient_security"
}
)

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them

For div to extend full height

This might be of some help: http://www.webmasterworld.com/forum83/200.htm

A relevant quote:

Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.

The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.

html, body { 
  margin:0; 
  padding:0; 
  height:100%; 
}

Horizontal swipe slider with jQuery and touch devices support?

If I was you, I would implement my own solution based on the event specs. Basically, what swipe is - it's handling of touch down, touch move, touch up events. here is excerpt of my own lib for handling iPhone touch events:

touch_object.prototype.handle_touchstart = function(e){
    if (e.targetTouches.length != 1){
        return false;
    }
    this.obj.style.zIndex = 100;
    e.preventDefault();
    this.startX = e.targetTouches[0].pageX - this.geometry.x;
    this.startY = e.targetTouches[0].pageY - this.geometry.y;
    /* adjust for left /top */
    this.bind_handler('touchmove');
    this.bind_handler('touchend');
}
touch_object.prototype.handle_touchmove = function(e) {
    e.preventDefault();
    if (e.targetTouches.length != 1){
        return false;
    }
    var x=e.targetTouches[0].pageX - this.startX;
    var y=e.targetTouches[0].pageY - this.startY;
    this.move(x,y);

}
touch_object.prototype.handle_touchend = function(e){
    this.obj.style.zIndex = 10;
    this.unbind_handler('touchmove');
    this.unbind_handler('touchend');
}

I used that code to "move things around". But, instead of moving, you can create your own algorithm for e.g. triggering redirect to some other location, or you can use that move to "move/swipe" the element, on which the swipe is on to other location.

so, it really helps to understand basics of how things work and then create more complicated solutions. this might help as well.

I used this, to create my solution:

http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html

Can I escape html special chars in javascript?

Using lodash

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

source code

Setting action for back button in navigation controller

You can try accessing the NavigationBars Right Button item and set its selector property...heres a reference UIBarButtonItem reference, another thing if this doenst work that will def work is, set the right button item of the nav bar to a custom UIBarButtonItem that you create and set its selector...hope this helps

Insertion sort vs Bubble Sort Algorithms

In bubble sort in ith iteration you have n-i-1 inner iterations (n^2)/2 total, but in insertion sort you have maximum i iterations on i'th step, but i/2 on average, as you can stop inner loop earlier, after you found correct position for the current element. So you have (sum from 0 to n) / 2 which is (n^2) / 4 total;

That's why insertion sort is faster than bubble sort.

Rename a column in MySQL

From MySQL 8.0 you could use

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

ALTER TABLE Syntax:

RENAME COLUMN:

  • Can change a column name but not its definition.

  • More convenient than CHANGE to rename a column without changing its definition.

DBFiddle Demo

How to assign more memory to docker container

If you want to change the default container and you are using Virtualbox, you can do it via the commandline / CLI:

docker-machine stop
VBoxManage modifyvm default --cpus 2
VBoxManage modifyvm default --memory 4096
docker-machine start

Emulate Samsung Galaxy Tab

I don't know if it is help. Create an AVD for a tablet-type device: Set the target to "Android 3.0" and the skin to "WXGA" (the default skin). You can check this site. http://developer.android.com/guide/practices/optimizing-for-3.0.html

Vertically align text next to an image?

Using flex property in css.

To align text vertically center by using in flex using align-items:center; if you want to align text horizontally center by using in flex using justify-content:center;.

_x000D_
_x000D_
div{
  display: flex;
  align-items: center;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Using table-cell in css.

_x000D_
_x000D_
div{
  display: table;
}
div *{
  display: table-cell;
  vertical-align: middle;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

How do I capture all of my compiler's output to a file?

In a bourne shell:

make > my.log 2>&1

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

Why does Java's hashCode() in String use 31 as a multiplier?

Actually, 37 would work pretty well! z := 37 * x can be computed as y := x + 8 * x; z := x + 4 * y. Both steps correspond to one LEA x86 instructions, so this is extremely fast.

In fact, multiplication with the even-larger prime 73 could be done at the same speed by setting y := x + 8 * x; z := x + 8 * y.

Using 73 or 37 (instead of 31) might be better, because it leads to denser code: The two LEA instructions only take 6 bytes vs. the 7 bytes for move+shift+subtract for the multiplication by 31. One possible caveat is that the 3-argument LEA instructions used here became slower on Intel's Sandy bridge architecture, with an increased latency of 3 cycles.

Moreover, 73 is Sheldon Cooper's favorite number.

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

With jQuery date format :

$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');

https://github.com/phstc/jquery-dateFormat

Enjoy

Selected value for JSP drop down using JSTL

I tried the accepted answer, it did not work.

However the simple way to do it is below:-

<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>

Enjoy!!

How to view an HTML file in the browser with Visual Studio Code

@InvisibleDev - to get this working on a mac trying using this:

{
    "version": "0.1.0",
    "command": "Chrome",
    "osx": {
        "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    },
    "args": [
        "${file}"
    ]
}

If you have chrome already open, it will launch your html file in a new tab.

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

I am facing the same issue. I am using 'Lumen' microservice framework. I recently resolved the same issue by installing two packages:-

  1. sudo apt-get install php7.0-mbstring,
  2. sudo apt-get install php7.0-xml or sudo apt-get install php-xml

After installing this, you need to execute this command:- composer update

Hope, it will resolve the issue. I work on my system.

Eloquent Collection: Counting and Detect Empty

I think you try something like

  @if(!$result->isEmpty())
         // $result is not empty
    @else
        // $result is empty
    @endif

or also use

if (!$result) { }
if ($result) { } 

Android: Quit application when press back button

In my understanding Google wants Android to handle memory management and shutting down the apps. If you must exit the app from code, it might be beneficial to ask Android to run garbage collector.

@Override
public void onBackPressed(){
    System.gc();
    System.exit(0);
}

You can also add finish() to the code, but it is probably redundant, if you also do System.exit(0)

phpmailer error "Could not instantiate mail function"

If you are sending file attachments and your code works for small attachments but fails for large attachments:

If you get the error "Could not instantiate mail function" error when you try to send large emails and your PHP error log contains the message "Cannot send message: Too big" then your mail transfer agent (sendmail, postfix, exim, etc) is refusing to deliver these emails.

The solution is to configure the MTA to allow larger attachments. But this is not always possible. The alternate solution is to use SMTP. You will need access to a SMTP server (and login credentials if your SMTP server requires authentication):

$mail             = new PHPMailer();
$mail->IsSMTP();                           // telling the class to use SMTP
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "mail.yourdomain.com"; // set the SMTP server
$mail->Port       = 26;                    // set the SMTP port
$mail->Username   = "yourname@yourdomain"; // SMTP account username
$mail->Password   = "yourpassword";        // SMTP account password

PHPMailer defaults to using PHP mail() function which uses settings from php.ini which normally defaults to use sendmail (or something similar). In the above example we override the default behavior.

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

Disable-web-security in Chrome 48+

The chosen answer is good, but for those who are still struggling with what they are talking about(your first time dealing with this issue), the following worked for me.

I created a new shortcut to Chrome on my desktop, right clicked it, and set the "Target" field to the following,

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chromedev"

The directory can be anything you want, I decided to make an empty folder called chrome dev in my C: directory. It has nothing to do where chrome is installed on your computer. It's just a fluff type thing.

This link also has clear directions for other OSes. How to disable web securityin Chrome

Should I return EXIT_SUCCESS or 0 from main()?

EXIT_FAILURE, either in a return statement in main or as an argument to exit(), is the only portable way to indicate failure in a C or C++ program. exit(1) can actually signal successful termination on VMS, for example.

If you're going to be using EXIT_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry.

On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)

Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit()) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.

For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main() does an implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 0; to be better style.)

(Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0 to 1, so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.)

Showing an image from an array of images - Javascript

Here's your problem:

if(imgArray[i] == img)

You're comparing an array element to a DOM object.

400 vs 422 response to POST of data

There is no correct answer, since it depends on what the definition of "syntax" is for your request. The most important thing is that you:

  1. Use the response code(s) consistently
  2. Include as much additional information in the response body as you can to help the developer(s) using your API figure out what's going on.=

Before everyone jumps all over me for saying that there is no right or wrong answer here, let me explain a bit about how I came to the conclusion.

In this specific example, the OP's question is about a JSON request that contains a different key than expected. Now, the key name received is very similar, from a natural language standpoint, to the expected key, but it is, strictly, different, and hence not (usually) recognized by a machine as being equivalent.

As I said above, the deciding factor is what is meant by syntax. If the request was sent with a Content Type of application/json, then yes, the request is syntactically valid because it's valid JSON syntax, but not semantically valid, since it doesn't match what's expected. (assuming a strict definition of what makes the request in question semantically valid or not).

If, on the other hand, the request was sent with a more specific custom Content Type like application/vnd.mycorp.mydatatype+json that, perhaps, specifies exactly what fields are expected, then I would say that the request could easily be syntactically invalid, hence the 400 response.

In the case in question, since the key was wrong, not the value, there was a syntax error if there was a specification for what valid keys are. If there was no specification for valid keys, or the error was with a value, then it would be a semantic error.

Unknown version of Tomcat was specified in Eclipse

Just in case... Apache Tomcat 8.5.X is not compatible with Apache Tomcat 8.0 server selection in eclipse. And it gives this error.

Executing multi-line statements in the one-line command-line?

I wanted a solution with the following properties:

  1. Readable
  2. Read stdin for processing output of other tools

Both requirements were not provided in the other answers, so here's how to read stdin while doing everything on the command line:

grep special_string -r | sort | python3 <(cat <<EOF
import sys
for line in sys.stdin:
    tokens = line.split()
    if len(tokens) == 4:
        print("%-45s %7.3f    %s    %s" % (tokens[0], float(tokens[1]), tokens[2], tokens[3]))
EOF
)

database vs. flat files

SQL ad hoc query abilities are enough of a reason for me. With a good schema and indexing on the tables, this is fast and effective and will have good performance.

Convert command line argument to string

It's already an array of C-style strings:

#include <iostream>
#include <string>
#include <vector>


int main(int argc, char *argv[]) // Don't forget first integral argument 'argc'
{
  std::string current_exec_name = argv[0]; // Name of the current exec program
  std::vector<std::string> all_args;

  if (argc > 1) {
    all_args.assign(argv + 1, argv + argc);
  }
}

Argument argc is count of arguments plus the current exec file.

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Show div #id on click with jQuery

This is simple way to Display Div using:-

$("#musicinfo").show();  //or
$("#musicinfo").css({'display':'block'});  //or
$("#musicinfo").toggle("slow");   //or
$("#musicinfo").fadeToggle();    //or

Remove the title bar in Windows Forms

You can set the Property FormBorderStyle to none in the designer, or in code:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

Debugging with command-line parameters in Visual Studio

Right click on the project in the Solution window of Visual Studio, select "Debugging" (on the left side), and enter the arguments into the field "Command Arguments":

Enter image description here

How to find indices of all occurrences of one string in another in JavaScript?

You sure can do this!

//make a regular expression out of your needle
var needle = 'le'
var re = new RegExp(needle,'gi');
var haystack = 'I learned to play the Ukulele';

var results = new Array();//this is the results you want
while (re.exec(haystack)){
  results.push(re.lastIndex);
}

Edit: learn to spell RegExp

Also, I realized this isn't exactly what you want, as lastIndex tells us the end of the needle not the beginning, but it's close - you could push re.lastIndex-needle.length into the results array...

Edit: adding link

@Tim Down's answer uses the results object from RegExp.exec(), and all my Javascript resources gloss over its use (apart from giving you the matched string). So when he uses result.index, that's some sort of unnamed Match Object. In the MDC description of exec, they actually describe this object in decent detail.

PHP preg_match - only allow alphanumeric strings and - _ characters

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

What does the @Valid annotation indicate in Spring?

public String create(@Valid @NotNull ScriptFile scriptFile, BindingResult result, ModelMap modelMap) {    
    if (scriptFile == null) throw new IllegalArgumentException("A scriptFile is required");        

I guess this @NotNull annotation is valid therefore if condition is not needed.

Determine function name from within that function (without using traceback)

This is actually derived from the other answers to the question.

Here's my take:

import sys

# for current func name, specify 0 or no argument.
# for name of caller of current func, specify 1.
# for name of caller of caller of current func, specify 2. etc.
currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name


def testFunction():
    print "You are in function:", currentFuncName()
    print "This function's caller was:", currentFuncName(1)    


def invokeTest():
    testFunction()


invokeTest()

# end of file

The likely advantage of this version over using inspect.stack() is that it should be thousands of times faster [see Alex Melihoff's post and timings regarding using sys._getframe() versus using inspect.stack() ].

Handling optional parameters in javascript

If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:

function getData(id, opt){
    var data = voodooMagic(id, opt.parameters);
    if (opt.callback!=undefined)
      opt.callback.call(data);
    return data;         
}

getData(5, {parameters: "1,2,3", callback: 
    function(){for (i=0;i<=1;i--)alert("FAIL!");}
});

Preferred way of loading resources in Java

I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:

try {
    InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
    img = ImageIO.read(path);
} catch (IOException e) {
    e.printStackTrace();
}

jQuery Mobile how to check if button is disabled?

You can use jQuery.is() function along with :disabled selector:

$("#savematerial").is(":disabled")

How to remove all line breaks from a string

This is probably a FAQ. Anyhow, line breaks (better: newlines) can be one of Carriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.)

Therefore, the most efficient RegExp literal to match all variants is

/\r?\n|\r/

If you want to match all newlines in a string, use a global match,

/\r?\n|\r/g

respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Old Q, but for posterity...it also also happens (.NET Core 2.1) if you have a self-referencing navigation property ("Parent" or "Children" of the same type) but the Id property name isn't what EF expects. That is, I had an "Id" property on my class called WorkflowBase, and it had an array of related child steps, which were also of type WorkflowBase, and it kept trying to associate them with a non-existent "WorkflowBaseId" (the name i suppose it prefers as a natural/conventional default). I had to explicitly configure it using HasMany(), WithOne(), and HasConstraintName() to tell it how to traverse. But I spent a few hours thinking the problem was in 'locally' mapping the object's primary key, which i attempted to fix a bunch of different ways but which was probably always working.

Which data type for latitude and longitude?

If you do not need all the functionality PostGIS offers, Postgres (nowadays) offers an extension module called earthdistance. It uses the point or cube data type depending on your accuracy needs for distance calculations.

You can now use the earth_box function to -for example- query for points within a certain distance of a location.

Keystore change passwords

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.

  1. Open an existing KeyStore
  2. Tools -> Set KeyStore password

How do I get information about an index and table owner in Oracle?

The following may help give you want you need:

SELECT
    index_owner, index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
ORDER BY
    index_owner, 
    table_name,
    index_name,
    column_position
    ;

For my use case, I wanted the column_names and order that they are in the indices (so that I could recreate them in a different database engine after migrating to AWS). The following was what I used, in case it is of use to anyone else:

SELECT
    index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
WHERE
    INDEX_OWNER = 'FOO'
    AND TABLE_NAME NOT LIKE '%$%'
ORDER BY
    table_name,
    index_name,
    column_position
    ;

How to edit log message already committed in Subversion?

Essentially you have to have admin rights (directly or indirectly) to the repository to do this. You can either configure the repository to allow all users to do this, or you can modify the log message directly on the server.

See this part of the Subversion FAQ (emphasis mine):

Log messages are kept in the repository as properties attached to each revision. By default, the log message property (svn:log) cannot be edited once it is committed. That is because changes to revision properties (of which svn:log is one) cause the property's previous value to be permanently discarded, and Subversion tries to prevent you from doing this accidentally. However, there are a couple of ways to get Subversion to change a revision property.

The first way is for the repository administrator to enable revision property modifications. This is done by creating a hook called "pre-revprop-change" (see this section in the Subversion book for more details about how to do this). The "pre-revprop-change" hook has access to the old log message before it is changed, so it can preserve it in some way (for example, by sending an email). Once revision property modifications are enabled, you can change a revision's log message by passing the --revprop switch to svn propedit or svn propset, like either one of these:

$svn propedit -r N --revprop svn:log URL 
$svn propset -r N --revprop svn:log "new log message" URL 

where N is the revision number whose log message you wish to change, and URL is the location of the repository. If you run this command from within a working copy, you can leave off the URL.

The second way of changing a log message is to use svnadmin setlog. This must be done by referring to the repository's location on the filesystem. You cannot modify a remote repository using this command.

$ svnadmin setlog REPOS_PATH -r N FILE

where REPOS_PATH is the repository location, N is the revision number whose log message you wish to change, and FILE is a file containing the new log message. If the "pre-revprop-change" hook is not in place (or you want to bypass the hook script for some reason), you can also use the --bypass-hooks option. However, if you decide to use this option, be very careful. You may be bypassing such things as email notifications of the change, or backup systems that keep track of revision properties.

async/await - when to return a Task vs void?

I have come across this very useful article about async and void written by Jérôme Laban: https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

The bottom line is that an async+void can crash the system and usually should be used only on the UI side event handlers.

The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.

When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.

How can I get dictionary key as variable directly in Python (not by searching from value)?

You could simply use * which unpacks the dictionary keys. Example:

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')

Is this a good way to clone an object in ES6?

All the methods above do not handle deep cloning of objects where it is nested to n levels. I did not check its performance over others but it is short and simple.

The first example below shows object cloning using Object.assign which clones just till first level.

_x000D_
_x000D_
var person = {_x000D_
    name:'saksham',_x000D_
    age:22,_x000D_
    skills: {_x000D_
        lang:'javascript',_x000D_
        experience:5_x000D_
    }_x000D_
}_x000D_
_x000D_
newPerson = Object.assign({},person);_x000D_
newPerson.skills.lang = 'angular';_x000D_
console.log(newPerson.skills.lang); //logs Angular
_x000D_
_x000D_
_x000D_

Using the below approach deep clones object

_x000D_
_x000D_
var person = {_x000D_
    name:'saksham',_x000D_
    age:22,_x000D_
    skills: {_x000D_
        lang:'javascript',_x000D_
        experience:5_x000D_
    }_x000D_
}_x000D_
_x000D_
anotherNewPerson = JSON.parse(JSON.stringify(person));_x000D_
anotherNewPerson.skills.lang = 'angular';_x000D_
console.log(person.skills.lang); //logs javascript
_x000D_
_x000D_
_x000D_

Oracle: how to INSERT if a row doesn't exist

you can use this syntax:

INSERT INTO table_name ( name, age )
select  'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');

if its open an pop for asking as "enter substitution variable" then use this before the above queries:

set define off;
INSERT INTO table_name ( name, age )
select  'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');

How to programmatically set the ForeColor of a label to its default?

labelname.ForeColor = Color.Colorname;   ­­­­

Easiest way to convert a List to a Set in Java

There are various ways to get a Set as:

    List<Integer> sourceList = new ArrayList();
    sourceList.add(1);
    sourceList.add(2);
    sourceList.add(3);
    sourceList.add(4);

    // Using Core Java
    Set<Integer> set1 = new HashSet<>(sourceList);  //needs null-check if sourceList can be null.

    // Java 8
    Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
    Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));

    //Guava
    Set<Integer> set4 = Sets.newHashSet(sourceList);

    // Apache commons
    Set<Integer> set5 = new HashSet<>(4);
    CollectionUtils.addAll(set5, sourceList);

When we use Collectors.toSet() it returns a set and as per the doc:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. If we want to get a HashSet then we can use the other alternative to get a set (check set3).

How come I can't remove the blue textarea border in Twitter Bootstrap?

You have write -webkit-appearance:none; like this:

textarea:hover, 
input:hover, 
textarea:active, 
input:active, 
textarea:focus, 
input:focus,
button:focus,
button:active,
button:hover,
label:focus,
.btn:active,
.btn.active
{
    outline:0px !important;
    -webkit-appearance:none;
    box-shadow: none !important;
}

How to load URL in UIWebView in Swift?

In Swift 4 or 4.2 You can use like:

  1. Add WKWebView & connect to you view comtroller.
  2. Your view is like bellow:

     import UIKit
     import WebKit
    
    class ViewController: UIViewController {
    
       @IBOutlet weak var wkwebview: WKWebView!
    
        override func viewDidLoad() {
           super.viewDidLoad()
    
          let request = URLRequest(url: URL(string: "**your URL**")!)        
          wkwebview?.load(request)
    
      }
    
    }
    
  3. Allow Allow Arbitrary Loads true info.plist

      <key>NSAppTransportSecurity</key>
         <dict>
           <key>Allow Arbitrary Loads</key>
              <true/>
        </dict>
    

    Note info.plist will look like bellow

enter image description here

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

How do I get a button to open another activity?

Write code on xml file.

<Button android:width="wrap_content"
        android:height="wrap_content"
        android:id="@+id/button"
        android:text="Click"/>

Write Code in your java file

Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(getApplicationContext(),Secondclass.class));
           /* if you want to finish the first activity then just call
            finish(); */
        }
    });

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

MS Access - execute a saved query by name in VBA

You should investigate why VBA can't find queryname.

I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute.

CurrentDb.Execute "qryAddLoginfoRow"

My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.

Edit: You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute line.

Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name

The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.

How do I import a specific version of a package using go get?

A little cheat sheet on module queries.

To check all existing versions: e.g. go list -m -versions github.com/gorilla/mux

  1. Specific version @v1.2.8
  2. Specific commit @c783230
  3. Specific branch @master
  4. Version prefix @v2
  5. Comparison @>=2.1.5
  6. Latest @latest

E.g. go get github.com/gorilla/[email protected]

How to Pass Parameters to Activator.CreateInstance<T>()

As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code:

How to pass ctor args in Activator.CreateInstance or use IL?

Using psql to connect to PostgreSQL in SSL mode

Well, you cloud provide all the information with following command in CLI, if connection requires in SSL mode:

psql "sslmode=verify-ca sslrootcert=server-ca.pem sslcert=client-cert.pem sslkey=client-key.pem hostaddr=your_host port=5432 user=your_user dbname=your_db" 

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

I understand it’s an old question – however I would like to add an example where cost is same but one query is better than the other.

As you observed in the question, % shown in execution plan is not the only yardstick for determining best query. In the following example, I have two queries doing the same task. Execution Plan shows both are equally good (50% each). Now I executed the queries with SET STATISTICS IO ON which shows clear differences.

In the following example, the query 1 uses seek whereas Query 2 uses scan on the table LWManifestOrderLineItems. When we actually checks the execution time however it is find that Query 2 works better.

Also read When is a Seek not a Seek? by Paul White

QUERY

---Preparation---------------
-----------------------------
DBCC FREEPROCCACHE
GO
DBCC DROPCLEANBUFFERS
GO

SET STATISTICS IO ON  --IO
SET STATISTICS TIME ON

--------Queries---------------
------------------------------

SELECT LW.Manifest,LW.OrderID,COUNT(DISTINCT LineItemID)
FROM LWManifestOrderLineItems LW
INNER JOIN ManifestContainers MC
    ON MC.Manifest = LW.Manifest
GROUP BY LW.Manifest,LW.OrderID
ORDER BY COUNT(DISTINCT LineItemID) DESC  

SELECT LW.Manifest,LW.OrderID,COUNT( LineItemID) LineCount
FROM LWManifestOrderLineItems LW
WHERE LW.Manifest IN (SELECT Manifest FROM ManifestContainers)
GROUP BY LW.Manifest,LW.OrderID
ORDER BY COUNT( LineItemID) DESC  

Statistics IO

enter image description here

Execution Plan

enter image description here

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

How to replace all strings to numbers contained in each string in Notepad++?

Replace (.*")\d+(")

With $1x$2

Where x is your "value inside scopes".

Why is Node.js single threaded?

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

XML element with attribute and content using JAXB

Here is working solution:

Output:

public class XmlTest {

    private static final Logger log = LoggerFactory.getLogger(XmlTest.class);

    @Test
    public void createDefaultBook() throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        StringWriter writer = new StringWriter();
        marshaller.marshal(new Book(), writer);

        log.debug("Book xml:\n {}", writer.toString());
    }


    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "book")
    public static class Book {

        @XmlElementRef(name = "price")
        private Price price = new Price();


    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "price")
    public static class Price {
        @XmlAttribute(name = "drawable")
        private Boolean drawable = true; //you may want to set default value here

        @XmlValue
        private int priceValue = 1234;

        public Boolean getDrawable() {
            return drawable;
        }

        public void setDrawable(Boolean drawable) {
            this.drawable = drawable;
        }

        public int getPriceValue() {
            return priceValue;
        }

        public void setPriceValue(int priceValue) {
            this.priceValue = priceValue;
        }
    }
}

Output:

22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
    <price drawable="true">1234</price>
</book>

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

The problem is in your pod files deployment target iOS Version not in your project deployment target iOS Version, so you need to change the deployment iOS version for your pods as well to anything higher than 8.0 to do so open your project workspace and do this:

1- Click on pods.

2- Select each project and target and click on build settings.

3- Under Deployment section change the iOS Deployment Target version to anything more than 8.0 (better to try the same project version).

4- Repeat this for every other project in your pods then run the app.

see the photo for details enter image description here

PHP: Get key from array?

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.

How to get file size in Java

Use the length() method in the File class. From the javadocs:

Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.

UPDATED Nowadays we should use the Files.size() method:

Paths path = Paths.get("/path/to/file");
long size = Files.size(path);

For the second part of the question, straight from File's javadocs:

  • getUsableSpace() Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname

  • getTotalSpace() Returns the size of the partition named by this abstract pathname

  • getFreeSpace() Returns the number of unallocated bytes in the partition named by this abstract path name

Can Windows Containers be hosted on linux?

Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.

What is the easiest way to initialize a std::vector with hardcoded elements?

I build my own solution using va_arg. This solution is C++98 compliant.

#include <cstdarg>
#include <iostream>
#include <vector>

template <typename T>
std::vector<T> initVector (int len, ...)
{
  std::vector<T> v;
  va_list vl;
  va_start(vl, len);
  for (int i = 0; i < len; ++i)
    v.push_back(va_arg(vl, T));
  va_end(vl);
  return v;
}

int main ()
{
  std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
  for (std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
    std::cout << *it << std::endl;
  return 0;
}

Demo

How to check if element in groovy array/hash/collection/list?

.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()

[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')