Programs & Examples On #Metadata repository

Remove credentials from Git

I found something that worked for me. When I wrote my comment to the OP I had failed to check the system config file:

git config --system -l

shows a

credential.helper=!github --credentials

line. I unset it with

git config --system --unset credential.helper

and now the credentials are forgotten.

Grep and Python

You might be interested in pyp. Citing my other answer:

"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

Mocking Extension Methods with Moq

You can easily mock an extension method with JustMock. The API is the same as mocking normal method. Consider the following

public static string Echo(this Foo foo, string strValue) 
{ 
    return strValue; 
}

To arrange and verify this method use the following:

string expected = "World";

var foo = new Foo();
Mock.Arrange(() => foo.Echo(Arg.IsAny<string>())).Returns(expected);

string result = foo.Echo("Hello");

Assert.AreEqual(expected, result);

Here is also a link to the documentation: Extension Methods Mocking

Disclaimer. I am one of the developers responsible for JustMock.

Setting a backgroundImage With React Inline Styles

For a local File in case of ReactJS. Try

import Image from "../../assets/image.jpg";

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
>Hello
</div>

This is the case of ReactJS with inline styling where Image is a local file that you must have imported with a path.

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace

Inserting a text where cursor is using Javascript/jquery

using @quick_sliv answer:

function insertAtCaret(el, text) {
    var caretPos = el.selectionStart;
    var textAreaTxt = el.value;
    el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
};

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

Center Div inside another (100% width) div

.parent { text-align: center; }
.parent > .child { margin: 0 auto; width: 900px; }

Currency Formatting in JavaScript

You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

C++ Array of pointers: delete or delete []?

Your second example is correct; you don't need to delete the monsters array itself, just the individual objects you created.

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

android:imeActionLabel="Done" 
android:singleLine="true"

In the XML file works just fine. But this will also cause the editText to keep typing in a single line which you may not want. So adding following to your code will make sure that you won't end up typing everything on a single line.

mainText.setHorizontallyScrolling(false);
mainText.setMaxLines("Maximum integer value that you want to provide");

Get time difference between two dates in seconds

Below code will give the time difference in second.

var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second

alert(timeDiffInSecond );

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

reading text file with utf-8 encoding using java

Ok, I am definitively late to the party but if you are still looking for an optimal solution I would use the following ( for Java 8 )

    Charset inputCharset = Charset.forName("ISO-8859-1");
    Path pathToFile = ....
    try (BufferedReader br = Files.newBufferedReader( pathToFile, inputCharset )) {
        ...
     }

XPath with multiple conditions

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

Generic deep diff between two objects

I modified @sbgoran's answer so that the resulting diff object includes only the changed values, and omits values that were the same. In addition, it shows both the original value and the updated value.

var deepDiffMapper = function () {
    return {
        VALUE_CREATED: 'created',
        VALUE_UPDATED: 'updated',
        VALUE_DELETED: 'deleted',
        VALUE_UNCHANGED: '---',
        map: function (obj1, obj2) {
            if (this.isFunction(obj1) || this.isFunction(obj2)) {
                throw 'Invalid argument. Function given, object expected.';
            }
            if (this.isValue(obj1) || this.isValue(obj2)) {
                let returnObj = {
                    type: this.compareValues(obj1, obj2),
                    original: obj1,
                    updated: obj2,
                };
                if (returnObj.type != this.VALUE_UNCHANGED) {
                    return returnObj;
                }
                return undefined;
            }

            var diff = {};
            let foundKeys = {};
            for (var key in obj1) {
                if (this.isFunction(obj1[key])) {
                    continue;
                }

                var value2 = undefined;
                if (obj2[key] !== undefined) {
                    value2 = obj2[key];
                }

                let mapValue = this.map(obj1[key], value2);
                foundKeys[key] = true;
                if (mapValue) {
                    diff[key] = mapValue;
                }
            }
            for (var key in obj2) {
                if (this.isFunction(obj2[key]) || foundKeys[key] !== undefined) {
                    continue;
                }

                let mapValue = this.map(undefined, obj2[key]);
                if (mapValue) {
                    diff[key] = mapValue;
                }
            }

            //2020-06-13: object length code copied from https://stackoverflow.com/a/13190981/2336212
            if (Object.keys(diff).length > 0) {
                return diff;
            }
            return undefined;
        },
        compareValues: function (value1, value2) {
            if (value1 === value2) {
                return this.VALUE_UNCHANGED;
            }
            if (this.isDate(value1) && this.isDate(value2) && value1.getTime() === value2.getTime()) {
                return this.VALUE_UNCHANGED;
            }
            if (value1 === undefined) {
                return this.VALUE_CREATED;
            }
            if (value2 === undefined) {
                return this.VALUE_DELETED;
            }
            return this.VALUE_UPDATED;
        },
        isFunction: function (x) {
            return Object.prototype.toString.call(x) === '[object Function]';
        },
        isArray: function (x) {
            return Object.prototype.toString.call(x) === '[object Array]';
        },
        isDate: function (x) {
            return Object.prototype.toString.call(x) === '[object Date]';
        },
        isObject: function (x) {
            return Object.prototype.toString.call(x) === '[object Object]';
        },
        isValue: function (x) {
            return !this.isObject(x) && !this.isArray(x);
        }
    }
}();

How to get maximum value from the Collection (for example ArrayList)?

In Java8

arrayList.stream()
         .reduce(Integer::max)
         .get()

How to create border in UIButton?

You don't need to import QuartzCore.h now. Taking iOS 8 sdk and Xcode 6.1 in referrence.

Directly use:

[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];

Counting the Number of keywords in a dictionary in python

If the question is about counting the number of keywords then would recommend something like

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

in the main function have something that loops through the data and pass the values to countoccurrences function

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

The code outputs

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

Is the Javascript date object always one day off?

if you're just looking to make sure the individual parts of the date stay the same for display purposes, *this appears to work, even when I change my timezone:

var doo = new Date("2011-09-24 00:00:00")

just add the zeros in there.

In my code I do this:

let dateForDisplayToUser = 
  new Date( `${YYYYMMDDdateStringSeparatedByHyphensFromAPI} 00:00:00` )
  .toLocaleDateString( 
    'en-GB', 
    { day: 'numeric', month: 'short', year: 'numeric' }
  )

And I switch around my timezone on my computer and the date stays the same as the yyyy-mm-dd date string I get from the API.

But am I missing something/is this a bad idea ?

*at least in chrome. This Doesn't work in Safari ! as of this writing

How to create cron job using PHP?

function _cron_exe($schedules) {
        if ($obj->get_option('cronenabledisable') == "yes") {
            // $interval = 1*20;
            $interval = $obj->get_option('cronhowtime');
            if ($obj->get_option('crontiming') == 'minutes') {
                $interval = $interval * 60;
            } else if ($obj->get_option('crontiming') == 'hours') {
                $interval = $interval * 3600;
            } else if ($obj->get_option('crontiming') == 'days') {
                $interval = $interval * 86400;
            }
            $schedules['hourlys'] = array(
                'interval' => $interval,
                'display' => 'cronjob'
            );
            return $schedules;
        }

}

Git - push current branch shortcut

You should take a look to a similar question in Default behavior of "git push" without a branch specified

Basically it explains how to set the default behavior to push your current branch just executing git push. Probably what you need is:

git config --global push.default current

Other options:

  • nothing : Do not push anything
  • matching : Push all matching branches
  • upstream/tracking : Push the current branch to whatever it is tracking
  • current : Push the current branch

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

keycode 13 is for which key

That would be the Enter key.

Simple pagination in javascript

Following is the Logic which accepts count from user and performs pagination in Javascript. It prints alphabets. Hope it helps!!. Thankyou.

_x000D_
_x000D_
/*_x000D_
*****_x000D_
USER INPUT : NUMBER OF SUGGESTIONS._x000D_
*****_x000D_
*/_x000D_
_x000D_
var recordSize = prompt('please, enter the Record Size');_x000D_
console.log(recordSize);_x000D_
_x000D_
_x000D_
/*_x000D_
*****_x000D_
POPULATE SUGGESTIONS IN THE suggestion_set LIST._x000D_
*****_x000D_
*/_x000D_
var suggestion_set = [];_x000D_
counter = 0;_x000D_
_x000D_
asscicount = 65;_x000D_
do{_x000D_
if(asscicount <= 90){_x000D_
 var temp = String.fromCharCode(asscicount);_x000D_
 suggestion_set.push(temp);_x000D_
 asscicount += 1;     _x000D_
}else{_x000D_
 asscicount = 65;_x000D_
 var temp = String.fromCharCode(asscicount);_x000D_
 suggestion_set.push(temp); _x000D_
 asscicount += 1;     _x000D_
}_x000D_
counter += 1;_x000D_
}while(counter < recordSize);_x000D_
_x000D_
console.log(suggestion_set); _x000D_
_x000D_
_x000D_
_x000D_
/*_x000D_
*****_x000D_
LOGIC FOR PAGINATION_x000D_
*****_x000D_
*/_x000D_
_x000D_
var totalRecords = recordSize, pageSize = 6;_x000D_
var q = Math.floor(totalRecords/pageSize);_x000D_
var r = totalRecords%pageSize;_x000D_
var itr = 1;_x000D_
_x000D_
if(r==0 ||r==1 ||r==2) {_x000D_
itr=q;_x000D_
}_x000D_
else {_x000D_
itr=q+1;_x000D_
}_x000D_
console.log(itr);_x000D_
_x000D_
var output = "", pageCnt=1, newPage=false;_x000D_
_x000D_
if(totalRecords <= pageSize+2) {_x000D_
output += "\n";_x000D_
_x000D_
 for(var i=0; i < totalRecords; i++){_x000D_
  output += suggestion_set[i] + "\t";_x000D_
 }_x000D_
}_x000D_
_x000D_
else {_x000D_
 output += "\n";_x000D_
 for(var i=0; i<totalRecords; i++) {_x000D_
  //output += (i+1) + "\t";_x000D_
  if(pageCnt==1){_x000D_
  output += suggestion_set[i] + "\t";_x000D_
  if((i+1)==(pageSize+1)) {_x000D_
  output += "Next" + "\t";_x000D_
  pageCnt++;_x000D_
  newPage=true;_x000D_
 }_x000D_
}_x000D_
else {_x000D_
if(newPage) {_x000D_
output += "\n" + "Previous" + "\t";_x000D_
newPage = false;_x000D_
}_x000D_
output += suggestion_set[i] + "\t";_x000D_
if((i+1)==(pageSize*pageCnt+1) && (pageSize*pageCnt+1)<totalRecords) {_x000D_
if((i+2) == (pageSize*pageCnt+2) && pageCnt==itr) {_x000D_
output += (suggestion_set[i] + 1) + "\t";_x000D_
break;_x000D_
}_x000D_
else {_x000D_
output += "Next" + "\t";_x000D_
pageCnt++;_x000D_
newPage=true;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

Inner text shadow with CSS

Building on the :before :after technique by web_designer, here is something that comes closer to your look:

First, make your text the color of the inner shadow (black-ish in the case of the OP).

Now, use an :after psuedo class to create a transparent duplicate of the original text, placed directly on top of it. Assign a regular text shadow to it with no offset. Assign the original text color to the shadow, and adjust alpha as needed.

http://dabblet.com/gist/2499892

You don't get complete control over spread, etc. of the shadow like you do in PS, but for smaller blur values it is quite passable. The shadow goes past the bounds of the text, so if you are working in an environment with a high contrast background-foreground, it will be obvious. For lower contrast items, especially ones with the same hue, it's not too noticeable. For example, I've been able to make very nice looking etched text in metal backgrounds using this technique.

SQL select only rows with max value on a column

My preference is to use as little code as possible...

You can do it using IN try this:

SELECT * 
FROM t1 WHERE (id,rev) IN 
( SELECT id, MAX(rev)
  FROM t1
  GROUP BY id
)

to my mind it is less complicated... easier to read and maintain.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Java: Convert String to TimeStamp

DateFormat formatter;
formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date) formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());

CSS3 Transparency + Gradient

#grad
{
    background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /*Safari 5.1-6*/
    background: -o-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Opera 11.1-12*/
    background: -moz-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Fx 3.6-15*/
    background: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1)); /*Standard*/
}

I found this in w3schools and suited my needs while I was looking for gradient and transparency. I am providing the link to refer to w3schools. Hope this helps if any one is looking for gradient and transparency.

http://www.w3schools.com/css/css3_gradients.asp

Also I tried it in w3schools to change the opacity pasting the link for it check it

http://www.w3schools.com/css/tryit.asp?filename=trycss3_gradient-linear_trans

Hope it helps.

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Calculating Time Difference

You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try

import time
time.time()

which gives you the seconds since the start of the epoch.

You can then get the intermediate time with something like

timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)

Random strings in Python

Sometimes, I've wanted random strings that are semi-pronounceable, semi-memorable.

import random

def randomWord(length=5):
    consonants = "bcdfghjklmnpqrstvwxyz"
    vowels = "aeiou"

    return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))

Then,

>>> randomWord()
nibit
>>> randomWord()
piber
>>> randomWord(10)
rubirikiro

To avoid 4-letter words, don't set length to 4.

Jim

Enable binary mode while restoring a Database from an SQL dump

Old but gold!

On MacOS (Catalina 10.15.7) it was a bit weird: I had to rename my dump.sql into dump.zip and after that, i had to use finder(!) to unzip it. in terminal, unzip dump.zip oder tar xfz dump.sql[or .gz .tar ...] leads to error msgs.

Finally, finder has unziped it totally fine, after that i could import the file without problems.

How do I convert a PDF document to a preview image in PHP?

Here is a simple class I've written and used on a couple of projects. It just wraps imagick and handles writing each page out to disk. If anyone is still looking for an easy way to do this, this link might be helpful.

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub

Google Maps JavaScript API RefererNotAllowedMapError

Come on Google, you guys are smarter than the API Credential page lets on. (I know because I have two sons working there.)

The list of "referrers" is far pickier than it lets on. (Of course, it should be more forgiving.) Here are some rules that took me hours to discover:

There are probably other rules, but this is a tedious guessing game.

Node.js – events js 72 throw er unhandled 'error' event

I always do the following whenever I get such error:

// remove node_modules/
rm -rf node_modules/
// install node_modules/ again
npm install // or, yarn

and then start the project

npm start //or, yarn start

It works fine after re-installing node_modules. But I don't know if it's good practice.

change html text from link with jquery

From W3 Schools HTML DOM Changes: If you look at the 3rd example it shows how you can change the text in your link, "click here". Example:

<a id="a_tbnotesverbergen" href="#nothing">click here</a>

JS:

var element=document.getElementById("a_tbnotesverbergen"); 
element.innerHTML="New Text";

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

Reduce git repository size

This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.

You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules directory. To make redundant submodule files gone away, see this question.

However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules, and do a, for example, git gc --aggressive --prune.

These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.

how to end ng serve or firebase serve

With Windows 10 / Powershell ctrl + c did not work; Powershell tried to gracefully stop the app.

Used normal cmd and had no issues stopping the ng serve with ctrl + c.

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

In my case, it was the comment line that was messing up the COPY command

I removed the comment after the COPY command and placed it to a dedicated line above the command. Surprisingly it resolved the issue.

Faulty Dockerfile command

COPY qt-downloader .     # https://github.com/engnr/qt-downloader -> contains the script to auto download qt for different architectures and versions

Working Dockerfile command

# https://github.com/engnr/qt-downloader -> contains the script to auto download qt for different architectures and versions
COPY qt-downloader .     

Hope it helps someone.

How to validate Google reCAPTCHA v3 on server side?

Source Tutorial Link

V2 of Google reCAPTCHA.

Step 1 - Go to Google reCAPTCHA

Login then get Site Key and Secret Key

Step 2 - Download PHP code here and upload src folder on your server.

Step 3 - Use below code in your form.php

        <head>
            <title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
            <script src='https://www.google.com/recaptcha/api.js'></script>
        </head>

        <body>
            <?php

            require('src/autoload.php');

            $siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
            $secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';

            $recaptcha = new \ReCaptcha\ReCaptcha($secret);

            $gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
            $remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip

            $recaptchaErrors = ''; // blank varible to store error

            $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
            if ($resp->isSuccess()) {

               /******** 

                Add code to create User here when form submission is successful

               *****/

            } else {

                /****

                // This variable will have error when reCAPTCHA is not entered correctly.

                ****/

               $recaptchaErrors = $resp->getErrorCodes(); 
            }


            ?>
                <form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
                    <div class="panel periodic-login">
                        <div class="panel-body text-center">
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
                                <span class="bar"></span>
                                <label>Username</label>
                            </div>
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
                                <span class="bar"></span>
                                <label>Phone</label>
                            </div>
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
                                <span class="bar"></span>
                                <label>Password</label>
                            </div>
                            <?php 
                                    if(isset($recaptchaErrors[0])){
                                        print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
                                    }
                              ?>
                            <div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
                            <input type="submit" class="btn col-md-12" value="Create User">
                        </div>
                    </div>
                </form>
        </body>

        </html>

Unicode (UTF-8) reading and writing to files in Python

The \x.. sequence is something that's specific to Python. It's not a universal byte escape sequence.

How you actually enter in UTF-8-encoded non-ASCII depends on your OS and/or your editor. Here's how you do it in Windows. For OS X to enter a with an acute accent you can just hit option + E, then A, and almost all text editors in OS X support UTF-8.

Datatype for storing ip address in SQL Server

We do a lot of work where we need to figure out which IP's are within certain subnets. I've found that the simplest and most reliable way to do this is:

  1. Add a field to each table called IPInteger (bigint) (when invalid, set IP= '0.0.0.0')
  2. For smaller tables, I use a trigger that updates IPInteger on change
  3. For larger tables, I use a SPROC to refresh the IPIntegers
    ALTER FUNCTION [dbo].[IP_To_INT ]
    ( 
        @IP CHAR(15) 
    ) 
    RETURNS BIGINT 
    AS 
    BEGIN 
        DECLARE @IntAns BIGINT, 
            @block1 BIGINT, 
            @block2 BIGINT, 
            @block3 BIGINT, 
            @block4 BIGINT, 
            @base BIGINT 
     
        SELECT 
            @block1 = CONVERT(BIGINT, PARSENAME(@IP, 4)), 
            @block2 = CONVERT(BIGINT, PARSENAME(@IP, 3)), 
            @block3 = CONVERT(BIGINT, PARSENAME(@IP, 2)), 
            @block4 = CONVERT(BIGINT, PARSENAME(@IP, 1)) 
     
        IF (@block1 BETWEEN 0 AND 255) 
            AND (@block2 BETWEEN 0 AND 255) 
            AND (@block3 BETWEEN 0 AND 255) 
            AND (@block4 BETWEEN 0 AND 255) 
        BEGIN      
            SET @base = CONVERT(BIGINT, @block1 * 16777216)
            SET @IntAns = @base +  
                (@block2 * 65536) +  
                (@block3 * 256) + 
                (@block4) 
        END 
        ELSE 
            SET @IntAns = -1 
        RETURN @IntAns 
    END

Strip off URL parameter with PHP

The safest "correct" method would be:

  1. Parse the url into an array with parse_url()
  2. Extract the query portion, decompose that into an array using parse_str()
  3. Delete the query parameters you want by unset() them from the array
  4. Rebuild the original url using http_build_query()

Quick and dirty is to use a string search/replace and/or regex to kill off the value.

Javascript Get Element by Id and set the value

<html>
<head>
<script>
function updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />

<br>

<textarea id="myDiv" ></textarea>

</body>
</html>

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

I had the same problem and I could solve making a new instance of the object that I was trying to Update. Then I passed that object to my reposotory.

Remove a specific character using awk or sed

Using just awk you could do (I also shortened some of your piping):

strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'

I can't verify it for you because I don't know your exact input, but the following works:

echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'

See also this question on removing single quotes.

Binary Search Tree - Java Implementation

Here is my simple binary search tree implementation in Java SE 1.8:

public class BSTNode
{
    int data;
    BSTNode parent;
    BSTNode left;
    BSTNode right;

    public BSTNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
        this.parent = null;
    }

    public BSTNode()
    {
    }
}

public class BSTFunctions
{
    BSTNode ROOT;

    public BSTFunctions()
    {
        this.ROOT = null;
    }

    void insertNode(BSTNode node, int data)
    {
        if (node == null)
        {
            node = new BSTNode(data);
            ROOT = node;
        }
        else if (data < node.data && node.left == null)
        {
            node.left = new BSTNode(data);
            node.left.parent = node;
        }
        else if (data >= node.data && node.right == null)
        {
            node.right = new BSTNode(data);
            node.right.parent = node;
        }
        else
        {
            if (data < node.data)
            {
                insertNode(node.left, data);
            }
            else
            {
                insertNode(node.right, data);
            }
        }
    }

    public boolean search(BSTNode node, int data)
    {
        if (node == null)
        {
            return false;
        }
        else if (node.data == data)
        {
            return true;
        }
        else
        {
            if (data < node.data)
            {
                return search(node.left, data);
            }
            else
            {
                return search(node.right, data);
            }
        }
    }

    public void printInOrder(BSTNode node)
    {
        if (node != null)
        {
            printInOrder(node.left);
            System.out.print(node.data + " - ");
            printInOrder(node.right);
        }
    }

    public void printPostOrder(BSTNode node)
    {
        if (node != null)
        {
            printPostOrder(node.left);
            printPostOrder(node.right);
            System.out.print(node.data + " - ");
        }
    }

    public void printPreOrder(BSTNode node)
    {
        if (node != null)
        {
            System.out.print(node.data + " - ");
            printPreOrder(node.left);
            printPreOrder(node.right);
        }
    }

    public static void main(String[] args)
    {
        BSTFunctions f = new BSTFunctions();
        /**
         * Insert
         */
        f.insertNode(f.ROOT, 20);
        f.insertNode(f.ROOT, 5);
        f.insertNode(f.ROOT, 25);
        f.insertNode(f.ROOT, 3);
        f.insertNode(f.ROOT, 7);
        f.insertNode(f.ROOT, 27);
        f.insertNode(f.ROOT, 24);

        /**
         * Print
         */
        f.printInOrder(f.ROOT);
        System.out.println("");
        f.printPostOrder(f.ROOT);
        System.out.println("");
        f.printPreOrder(f.ROOT);
        System.out.println("");

        /**
         * Search
         */
        System.out.println(f.search(f.ROOT, 27) ? "Found" : "Not Found");
        System.out.println(f.search(f.ROOT, 10) ? "Found" : "Not Found");
    }
}

And the output is:

3 - 5 - 7 - 20 - 24 - 25 - 27 - 
3 - 7 - 5 - 24 - 27 - 25 - 20 - 
20 - 5 - 3 - 7 - 25 - 24 - 27 - 
Found
Not Found

How to access session variables from any class in ASP.NET?

I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.

MA

Eclipse Bug: Unhandled event loop exception No more handles

As suggested by Nineroad Installing WindowBuilder as the default editor for files with a *.java extention fixed this issue for me.

In Eclipse, navigate to Help > Install New Software

Add http://archive.eclipse.org/windowbuilder/WB/release/R201309271200/4.3 to the "Work with" path, select all components suggested, and install WindowBuilder.

Once complete, Eclipse will request restart. Once restarted, within Eclipse navigate to Window > Preferences. In The Preferences dialogue-box navigate to General > Editor > File Associations. Under "File Associations" list, be sure to select *.java file types. The bottom window (labeled "Associated Editors") should have WindowBuilder as an option. Select WindowBuilder and click "Default" to the right, to set WindowBuilder as your default *.java file editor.

This fixed the SWT error for me.

Note: Eclipse Version: Kepler Service Release 2 Windows 7 64-bit

How do I import a .bak file into Microsoft SQL Server 2012?

Not sure why they removed the option to just right click on the database and restore like you could in SQL Server Management Studio 2008 and earlier, but as mentioned above you can restore from a .BAK file with:

RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBaackUpFile.bak' WITH REPLACE

But you will want WITH REPLACE instead of WITH RESTORE if your moving it from one server to another.

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

Input widths on Bootstrap 3

Bootstrap uses the class 'form-input' for controlling the attributes of 'input fields'. Simply, add your own 'form-input' class with the desired width, border, text size, etc in your css file or head section.

(or else, directly add the size='5' inline code in input attributes in the body section.)

<script async src="//jsfiddle.net/tX3ae/embed/"></script> 

CSS Circular Cropping of Rectangle Image

You need to use jQuery to do this. This approach gives you the abbility to have dynamic images and do them round no matter the size.

My demo has one flaw right now I don't center the image in the container, but ill return to it in a minute (need to finish a script I'm working on).

DEMO

<div class="container">
    <img src="" class="image" alt="lambo" />
</div>

//script
var container = $('.container'),
    image = container.find('img');

container.width(image.height());


//css    
.container {
    height: auto;
    overflow: hidden;
    border-radius: 50%;    
}

.image {
    height: 100%;    
    display: block;    
}

Insert, on duplicate update in PostgreSQL?

I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.

My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.

This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.

The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.

 #This is pseudo-code - within the application:
 BEGIN TRANSACTION - get transaction lock
 SELECT all current name value pairs where id = $id into a hash record
 create a merge record from the current and update record
  (set intersection where shared keys in new win, and empty values in new are deleted).
 DELETE all name value pairs where id = $id
 COPY/INSERT merged records 
 END TRANSACTION

How can one run multiple versions of PHP 5.x on a development LAMP server?

Understanding that you're probably talking about a local/desktop machine and would probably like to continue talking about a local/desktop machine, I'll throw an alternative out there for you just in case it might help you or someone else:

Set up multiple virtual server instances in the cloud, and share your code between them as a git repository (or mercurial, I suppose, though I have no personal experience all you really need is something decentralized). This has the benefit of giving you as close to a production experience as possible, and if you have experience setting up servers then it's not that complicated (or expensive, if you just want to spin a server up, do what you need to do, then spin it down again, then you're talking about a few cents up to say 50 cents, up to a few bucks if you just leave it running).

I do all of my project development in the cloud these days and I've found it much simpler to manage the infrastructure than I ever did when using local/non-virtualized installs, and it makes this sort of side-by-side scenario fairly straight forward. I just wanted to throw the idea out there if you hadn't considered it.

using batch echo with special characters

The way to output > character is to prepend it with ^ escape character:

echo ^>

will print simply

>

What's the difference between using CGFloat and float?

Objective-C

From the Foundation source code, in CoreGraphics' CGBase.h:

/* Definition of `CGFLOAT_TYPE', `CGFLOAT_IS_DOUBLE', `CGFLOAT_MIN', and
   `CGFLOAT_MAX'. */

#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif

/* Definition of the `CGFloat' type and `CGFLOAT_DEFINED'. */

typedef CGFLOAT_TYPE CGFloat;
#define CGFLOAT_DEFINED 1

Copyright (c) 2000-2011 Apple Inc.

This is essentially doing:

#if defined(__LP64__) && __LP64__
typedef double CGFloat;
#else
typedef float CGFloat;
#endif

Where __LP64__ indicates whether the current architecture* is 64-bit.

Note that 32-bit systems can still use the 64-bit double, it just takes more processor time, so CoreGraphics does this for optimization purposes, not for compatibility. If you aren't concerned about performance but are concerned about accuracy, simply use double.

Swift

In Swift, CGFloat is a struct wrapper around either Float on 32-bit architectures or Double on 64-bit ones (You can detect this at run- or compile-time with CGFloat.NativeType) and cgFloat.native.

From the CoreGraphics source code, in CGFloat.swift.gyb:

public struct CGFloat {
#if arch(i386) || arch(arm)
  /// The native type used to store the CGFloat, which is Float on
  /// 32-bit architectures and Double on 64-bit architectures.
  public typealias NativeType = Float
#elseif arch(x86_64) || arch(arm64)
  /// The native type used to store the CGFloat, which is Float on
  /// 32-bit architectures and Double on 64-bit architectures.
  public typealias NativeType = Double
#endif

*Specifically, longs and pointers, hence the LP. See also: http://www.unix.org/version2/whatsnew/lp64_wp.html

Android studio Gradle build speed up

The dev are working on it. Like I posted in this answer the fastest solution right now is to use gradle from the command line and you should switch to binary libs for all modules you do not develop. On g+ there is a discussion with the developers about it.

How to run JUnit tests with Gradle?

If you set up your project with the default gradle package structure, i.e.:

src/main/java
src/main/resources
src/test/java
src/test/resources

then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.

How to clear/delete the contents of a Tkinter Text widget?

for me "1.0" didn't work, but '0' worked. This is Python 2.7.12, just FYI. Also depends on how you import the module. Here's how:

import Tkinter as tk
window = tk.Tk()
textBox = tk.Entry(window)
textBox.pack()

And the following code is called when you need to clear it. In my case there was a button Save that saves the data from the Entry text box and after the button is clicked, the text box is cleared

textBox.delete('0',tk.END)

Javascript: open new page in same window

I'd take that a slightly different way if I were you. Change the text link when the page loads, not on the click. I'll give the example in jQuery, but it could easily be done in vanilla javascript (though, jQuery is nicer)

$(function() {
    $('a[href$="url="]')    // all links whose href ends in "url="
        .each(function(i, el) {
            this.href += escape(document.location.href);
        })
    ;
});

and write your HTML like this:

<a href="http://example.com/submit.php?url=">...</a>

the benefits of this are that people can see what they're clicking on (the href is already set), and it removes the javascript from your HTML.

All this said, it looks like you're using PHP... why not add it in server-side?

JavaScript: IIF like statement

I typed this in my URL bar:

javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }

GLYPHICONS - bootstrap icon font hex value

The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Change the document root in the file C:\xampp\apache\conf\httpd.conf to the folder where is the index.php of your project.

How to add option to select list in jQuery

Doing it this way has always worked for me, I hope this helps.

var ddl = $("#dropListBuilding");   
for (k = 0; k < buildings.length; k++)
   ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");

Modifying the "Path to executable" of a windows service

You can delete the service:

sc delete ServiceName

Then recreate the service.

what is Array.any? for javascript

What you want is .empty not .empty() to fully mimics Ruby :

     Object.defineProperty( Array.prototype, 'empty', {
           get: function ( ) { return this.length===0 }
      } );    

then

[].empty //true
[3,2,8].empty //false

For any , see my answer here

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

Where does gcc look for C and C++ header files?

The CPP Section of the GCC Manual indicates that header files may be located in the following directories:

GCC looks in several different places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with #include in:

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

For C++ programs, it will also look in /usr/include/g++-v3, first.

(13: Permission denied) while connecting to upstream:[nginx]

if "502 Bad Gateway" error throws on centos api url for api gateway proxy pass on nginx , run following command to solve the issue

sudo setsebool -P httpd_can_network_connect 1

How to avoid precompiled headers

You can create an empty project by selecting the "Empty Project" from the "General" group of Visual C++ projects (maybe that project template isn't included in Express?).

To fix the problem in the project you already have, open the project properties and navigate to:

Configuration Properties | C/C++ | Precompiled Headers

And choose "Not using Precompiled Headers" for the "Precompiled Header" option.

How to sort findAll Doctrine's method?

$this->getDoctrine()->getRepository('MyBundle:MyTable')->findBy([], ['username' => 'ASC']);

Default values in a C Struct

I'm rusty with structs, so I'm probably missing a few keywords here. But why not start with a global structure with the defaults initialized, copy it to your local variable, then modify it?

An initializer like:

void init_struct( structType * s )
{
   memcopy(s,&defaultValues,sizeof(structType));
}

Then when you want to use it:

structType foo;
init_struct( &foo ); // get defaults
foo.fieldICareAbout = 1; // modify fields
update( &foo ); // pass to function

Value cannot be null. Parameter name: source

It could be as silly as in my case where savechanges was erroring bcoz the db did not have foreign keys and associations were added to EDM tables. I added foreign keys in the db and regenerated EDM for a fix.

The errors I was seeing are as follows: Case 1 -> when using DBContext for EDM Message=Value cannot be null. Parameter name: source at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)

Case 2 -> when using ObjectContext for EDM Message=Unable to update the EntitySet 'Contact' because it has a DefiningQuery and no element exists in the element to support the current operation.

(Just wanted to throw it in there in case it helps someone).

Removing whitespace from strings in Java

If you prefer utility classes to regexes, there is a method trimAllWhitespace(String) in StringUtils in the Spring Framework.

How do I pass along variables with XMLHTTPRequest

If you're allergic to string concatenation and don't need IE compatibility, you can use URL and URLSearchParams:

_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
const params = new URLSearchParams();_x000D_
params.set('var1', 'foo');_x000D_
params.set('var2', 'bar');_x000D_
target.search = params.toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

Or to convert an entire object's worth of parameters:

_x000D_
_x000D_
const paramsObject = {_x000D_
  var1: 'foo',_x000D_
  var2: 'bar'_x000D_
};_x000D_
_x000D_
const target = new URL('https://example.com/endpoint');_x000D_
target.search = new URLSearchParams(paramsObject).toString();_x000D_
_x000D_
console.log(target);
_x000D_
_x000D_
_x000D_

How can I fetch all items from a DynamoDB table without specifying the primary key?

I figured you are using PHP but not mentioned (edited). I found this question by searching internet and since I got solution working , for those who use nodejs here is a simple solution using scan :

  var dynamoClient = new AWS.DynamoDB.DocumentClient();
  var params = {
    TableName: config.dynamoClient.tableName, // give it your table name 
    Select: "ALL_ATTRIBUTES"
  };

  dynamoClient.scan(params, function(err, data) {
    if (err) {
       console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
       console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
  });

I assume same code can be translated to PHP too using different AWS SDK

How do you beta test an iphone app?

Note that there is a distinction between traditional "beta testing" which is done by professional QA engineers, and "public beta testing" which is releasing your product to the public before it's ready : )

You can do "beta testing" -- loading to specific iPhones/iPods your testers will be using. You can't do "public beta testing" -- pre-releasing to the public.

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

The same situation occurred when I was using VSCode with eslint. If you use VSCode,

1 - Click area that name can be both LF or CRLF where at the bottom right of the VScode.

2 - Select LF from the drop-down menu.

That's worked for me.

enter image description here

Setting an environment variable before a command in Bash is not working for the second command in a pipe

A simple approach is to make use of ;

For example:

ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

Bootstrap Dropdown with Hover

This is what I use to make it dropdown on hover with some jQuery

$(document).ready(function () {
    $('.navbar-default .navbar-nav > li.dropdown').hover(function () {
        $('ul.dropdown-menu', this).stop(true, true).slideDown('fast');
        $(this).addClass('open');
    }, function () {
        $('ul.dropdown-menu', this).stop(true, true).slideUp('fast');
        $(this).removeClass('open');
    });
});

How do I view an older version of an SVN file?

Update to a specific revision:

svn up -r1234 file

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

Convert DateTime to String PHP

The simplest way I found is:

$date   = new DateTime(); //this returns the current date time
$result = $date->format('Y-m-d-H-i-s');
echo $result . "<br>";
$krr    = explode('-', $result);
$result = implode("", $krr);
echo $result;

I hope it helps.

Where can I find MySQL logs in phpMyAdmin?

I am using phpMyAdmin version 4.2.11. At the time of writing, my Status tab looks like this (a few options expanded; note "Current settings", bottom right):

Image of Status Panel

Note, there are no directly visible "features" that allow for the enabling of things such as slow_query_log. So, I went digging on the internet because UI-oriented answers will only be relevant to a particular release and, therefore, will quickly become out of date. So, what do you do if you don't see a relevant answer, above?

As this article explains, you can run a global query to enable or disable the slow_query_log et al. The queries for enabling and disabling these logs are not difficult, so don't be afraid of them, e.g.

SET GLOBAL slow_query_log = 'ON';

From here, phpMyAdmin is pretty helpful and a bit of Googling will get you up to speed in no time. For instance, after I ran the above query, I can go back to the "Instructions/Setup" option under the Status tab's Monitor window and see this (note the further instructions):

Slow query enabled

How can I have a newline in a string in sh?

If you're using Bash, the solution is to use $'string', for example:

$ STR=$'Hello\nWorld'
$ echo "$STR" # quotes are required here!
Hello
World

If you're using pretty much any other shell, just insert the newline as-is in the string:

$ STR='Hello
> World'

Bash is pretty nice. It accepts more than just \n in the $'' string. Here is an excerpt from the Bash manual page:

   Words of the form $'string' are treated specially.  The word expands to
   string, with backslash-escaped characters replaced as specified by  the
   ANSI  C  standard.  Backslash escape sequences, if present, are decoded
   as follows:
          \a     alert (bell)
          \b     backspace
          \e
          \E     an escape character
          \f     form feed
          \n     new line
          \r     carriage return
          \t     horizontal tab
          \v     vertical tab
          \\     backslash
          \'     single quote
          \"     double quote
          \nnn   the eight-bit character whose value is  the  octal  value
                 nnn (one to three digits)
          \xHH   the  eight-bit  character  whose value is the hexadecimal
                 value HH (one or two hex digits)
          \cx    a control-x character

   The expanded result is single-quoted, as if the  dollar  sign  had  not
   been present.

   A double-quoted string preceded by a dollar sign ($"string") will cause
   the string to be translated according to the current  locale.   If  the
   current  locale  is  C  or  POSIX,  the dollar sign is ignored.  If the
   string is translated and replaced, the replacement is double-quoted.

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}

How can I output the value of an enum class in C++11

Unlike an unscoped enumeration, a scoped enumeration is not implicitly convertible to its integer value. You need to explicitly convert it to an integer using a cast:

std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl;

You may want to encapsulate the logic into a function template:

template <typename Enumeration>
auto as_integer(Enumeration const value)
    -> typename std::underlying_type<Enumeration>::type
{
    return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}

used as:

std::cout << as_integer(a) << std::endl;

Convert list or numpy array of single element to float in python

np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead.

For example:

a = np.array([[0.6813]])
print(a.item())

gives:

0.6813

Can I edit an iPad's host file?

If you have the freedom to choose the hostname, then you can just add your host to a dynanmic DNS service, like dyndns.org. Then you can rely on the iPad's normal resolution mechanisms to resolve the address.

Search in all files in a project in Sublime Text 3

Solution:

Use the Search all shortcut: Ctrl+Shift+F, then select the folder in the "Where:" box below. (And for Mac, it's ?+Shift+F).

If the root directory for the project is proj, with subdirectories src and aux and you want to search in all subfolders, use the proj folder. To restrict the search to only the src folder, use proj/src in the "Where: " box.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

The solution that work for me is the following:

  1. Delete .metadata folder
  2. Restart eclipse

Can an Option in a Select tag carry multiple values?

When I need to do this, I make the other values data-values and then use js to assign them to a hidden input

<select id=select>
<option value=1 data-othervalue=2 data-someothervalue=3>
//...
</select>

<input type=hidden name=otherValue id=otherValue />
<input type=hidden name=someOtherValue id=someOtherValue />

<script>
$('#select').change(function () {
var otherValue=$(this).find('option:selected').attr('data-othervalue');
var someOtherValue=$(this).find('option:selected').attr('data-someothervalue');
$('#otherValue').val(otherValue);
$('#someOtherValue').val(someOtherValue);
});
</script>

Limit length of characters in a regular expression?

(^(\d{2})|^(\d{4})|^(\d{5}))$

This expression takes the number of length 2,4 and 5. Valid Inputs are 12 1234 12345

Difference between document.addEventListener and window.addEventListener?

The document and window are different objects and they have some different events. Using addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.

For example, there is a "resize" event on the window object that is not on the document object.

For example, the "DOMContentLoaded" event is only on the document object.

So basically, you need to know which object receives the event you are interested in and use .addEventListener() on that particular object.

Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference


If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

How to compare two strings are equal in value, what is the best method?

string1.equals(string2) is the way.

It returns true if string1 is equals to string2 in value. Else, it will return false.

equals reference

Setting DEBUG = False causes 500 Error

This is old and my problem ended up being related to the problem but not for the OP but my solution is for anyone else who tried the above to no avail.

I had a setting in a modified version of Django to minify CSS and JS files that only ran when DEBUG was off. My server did not have the CSS minifier installed and threw the error. If you are using Django-Mako-Plus, this might be your issue.

How to style the option of an html "select" element?

Leaving here a quick alternative, using class toggle on a table. The behavior is very similar than a select, but can be styled with transition, filters and colors, each children individually.

_x000D_
_x000D_
function toggleSelect(){ _x000D_
 if (store.classList[0] === "hidden"){_x000D_
    store.classList = "viewfull"_x000D_
  }_x000D_
  else {_x000D_
    store.classList = "hidden"_x000D_
  }_x000D_
}
_x000D_
#store {_x000D_
  overflow-y: scroll;_x000D_
  max-height: 110px;_x000D_
  max-width: 50%_x000D_
 }_x000D_
 _x000D_
.hidden {_x000D_
  display: none_x000D_
 }_x000D_
 _x000D_
.viewfull {_x000D_
  display: block_x000D_
}_x000D_
_x000D_
#store :nth-child(4) {_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
span {font-size:2rem;cursor:pointer}
_x000D_
<span onclick="toggleSelect()">?</span>_x000D_
 <div id="store" class="hidden">_x000D_
 _x000D_
<ul><li><a href="#keylogger">keylogger</a></li><li><a href="#1526269343113">1526269343113</a></li><li><a href="#slow">slow</a></li><li><a href="#slow2">slow2</a></li><li><a href="#Benchmark">Benchmark</a></li><li><a href="#modal">modal</a></li><li><a href="#buma">buma</a></li><li><a href="#1526099371108">1526099371108</a></li><a href="#1526099371108o">1526099371108o</a></li><li><a href="#pwnClrB">pwnClrB</a></li><li><a href="#stars%20u">stars%20u</a></li><li><a href="#pwnClrC">pwnClrC</a></li><li><a href="#stars ">stars </a></li><li><a href="#wello">wello</a></li><li><a href="#equalizer">equalizer</a></li><li><a href="#pwnClrA">pwnClrA</a></li></ul>_x000D_
 _x000D_
 </div>
_x000D_
_x000D_
_x000D_

Using Mockito to mock classes with generic parameters

I think you do need to cast it, but it shouldn't be too bad:

Foo<Bar> mockFoo = (Foo<Bar>) mock(Foo.class);
when(mockFoo.getValue()).thenReturn(new Bar());

How can I return the current action in an ASP.NET MVC view?

Use the ViewContext and look at the RouteData collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.

Docker error : no space left on device

Check that you have free space on /var as this is where Docker stores the image files by default (in /var/lib/docker).

First clean stuff up by using docker ps -a to list all containers (including stopped ones) and docker rm to remove them; then use docker images to list all the images you have stored and docker rmi to remove them.

Next change the storage location with a -g option on the docker daemon or by editing /etc/default/docker and adding the -g option to DOCKER_OPTS. -g specifies the location of the "Docker runtime" which is basically all the stuff that Docker creates as you build images and run containers. Choose a location with plenty of space as the disk space used will tend to grow over time. If you edit /etc/default/docker, you will need to restart the docker daemon for the change to take effect.

Now you should be able to create a new image (or pull one from Docker Hub) and you should see a bunch of files getting created in the directory you specified with the -g option.

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

How to overload functions in javascript?

I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:

var out = def({
    'int': function(a) {
        alert('Here is int '+a);
    },

    'float': function(a) {
        alert('Here is float '+a);
    },

    'string': function(a) {
        alert('Here is string '+a);
    },

    'int,string': function(a, b) {
        alert('Here is an int '+a+' and a string '+b);
    },
    'default': function(obj) {
        alert('Here is some other value '+ obj);
    }

});

out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);

The methods used to achieve this:

var def = function(functions, parent) {
 return function() {
    var types = [];
    var args = [];
    eachArg(arguments, function(i, elem) {
        args.push(elem);
        types.push(whatis(elem));
    });
    if(functions.hasOwnProperty(types.join())) {
        return functions[types.join()].apply(parent, args);
    } else {
        if (typeof functions === 'function')
            return functions.apply(parent, args);
        if (functions.hasOwnProperty('default'))
            return functions['default'].apply(parent, args);        
    }
  };
};

var eachArg = function(args, fn) {
 var i = 0;
 while (args.hasOwnProperty(i)) {
    if(fn !== undefined)
        fn(i, args[i]);
    i++;
 }
 return i-1;
};

var whatis = function(val) {

 if(val === undefined)
    return 'undefined';
 if(val === null)
    return 'null';

 var type = typeof val;

 if(type === 'object') {
    if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
        return 'array';
    if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
        return 'date';
    if(val.hasOwnProperty('toExponential'))
        type = 'number';
    if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
        return 'string';
 }

 if(type === 'number') {
    if(val.toString().indexOf('.') > 0)
        return 'float';
    else
        return 'int';
 }

 return type;
};

Force re-download of release dependency using Maven

Most answers provided above would solve the problem.

But if you use IntelliJ and want it to just fix it for you automatically, go to Maven Settings.

Build,Execution, Deployment -> Build Tools -> Maven

enter image description here

Disable Work Offline

Enable Always update snapshots (Switch when required)

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

Java: Static vs inner class

Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:

Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.

And now to quote:

Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.

A static nested class does not have access to the enclosing instance. It uses less space too.

Powershell equivalent of bash ampersand (&) for forking/running background processes

From PowerShell Core 6.0 you are able to write & at end of command and it will be equivalent to running you pipeline in background in current working directory.

It's not equivalent to & in bash, it's just a nicer syntax for current PowerShell jobs feature. It returns a job object so you can use all other command that you would use for jobs. For example Receive-Job:

C:\utils> ping google.com &

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
35     Job35           BackgroundJob   Running       True            localhost            Microsoft.PowerShell.M...


C:\utils> Receive-Job 35

Pinging google.com [172.217.16.14] with 32 bytes of data:
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55

Ping statistics for 172.217.16.14:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 10ms, Maximum = 11ms, Average = 10ms
C:\utils>

If you want to execute couple of statements in background you can combine & call operator, { } script block and this new & background operator like here:

& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &

Here's some more info from documentation pages:

from What's New in PowerShell Core 6.0:

Support backgrounding of pipelines with ampersand (&) (#3360)

Putting & at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard *-Job cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so Copy-Item $foo $bar & just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.

from about_operators / Ampersand background operator &:

Ampersand background operator &

Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX "ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job. The following command contains basic usage of the ampersand background operator.

Get-Process -Name pwsh &

This is functionally equivalent to the following usage of Start-Job.

Start-Job -ScriptBlock {Get-Process -Name pwsh}

Since it's functionally equivalent to using Start-Job, the ampersand background operator returns a Job object just like Start-Job does. This means that you are able to use Receive-Job and Remove-Job just as you would if you had used Start-Job to start the job.

$job = Get-Process -Name pwsh &
Receive-Job $job

Output

NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
------    -----      -----     ------      --  -- -----------
    0     0.00     221.16      25.90    6988 988 pwsh
    0     0.00     140.12      29.87   14845 845 pwsh
    0     0.00      85.51       0.91   19639 988 pwsh


$job = Get-Process -Name pwsh &
Remove-Job $job

For more information on PowerShell jobs, see about_Jobs.

Xampp localhost/dashboard

Try this solution:

Go to->

  1. xammp ->htdocs-> then open index.php from the htdocs folder
  2. you can modify the dashboard
  3. restart the server

Example Code index.php :

    <?php
    if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
        $uri = 'https://';
    } else {
        $uri = 'http://';
    }
    $uri .= $_SERVER['HTTP_HOST'];
    header('Location: '.$uri.'/dashboard/');
    exit;
   ?>

Why I can't access remote Jupyter Notebook server?

Try doing below step:

Following command fixes the read/write

    sudo chmod -R a+rw /home/ubuntu/certs/mycert.pem

How to build & install GLFW 3 and use it in a Linux project

The well-described answer is already there, but I went through this SHORTER recipe:

  1. Install Linuxbrew
  2. $ brew install glfw
  3. cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
  4. sudo cp -R GLFW /usr/include

Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include).

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

Defining a variable with or without export

Although not explicitly mentioned in the discussion, it is NOT necessary to use export when spawning a subshell from inside bash since all the variables are copied into the child process.

How to use color picker (eye dropper)?

To open the Eye Dropper simply:

  1. Open DevTools F12
  2. Go to Elements tab
  3. Under Styles side bar click on any color preview box

enter image description here

Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.

Set QLineEdit to accept only numbers

You could also set an inputMask:

QLineEdit.setInputMask("9")

This allows the user to type only one digit ranging from 0 to 9. Use multiple 9's to allow the user to enter multiple numbers. See also the complete list of characters that can be used in an input mask.

(My answer is in Python, but it should not be hard to transform it to C++)

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

If you are using Jackson 2, the message-converters tag is:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="prefixJson" value="true"/>
            <property name="supportedMediaTypes" value="application/json"/>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

MySQL Error 1093 - Can't specify target table for update in FROM clause

This is what I did for updating a Priority column value by 1 if it is >=1 in a table and in its WHERE clause using a subquery on same table to make sure that at least one row contains Priority=1 (because that was the condition to be checked while performing update) :


UPDATE My_Table
SET Priority=Priority + 1
WHERE Priority >= 1
AND (SELECT TRUE FROM (SELECT * FROM My_Table WHERE Priority=1 LIMIT 1) as t);

I know it's a bit ugly but it does works fine.

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

Why is Python running my module when I import it, and how do I stop it?

Use the if __name__ == '__main__' idiom -- __name__ is a special variable whose value is '__main__' if the module is being run as a script, and the module name if it's imported. So you'd do something like

# imports
# class/function definitions
if __name__ == '__main__':
    # code here will only run when you invoke 'python main.py'

Dictionary text file

For an English dictionary .txt file, you can use Custom Dictionary.

You can also generate a list aspell or wordlist with own settings.

Also you can take a look at http://wordlist.sourceforge.net/

Only english words: http://www.math.sjsu.edu/~foster/dictionary.txt

Generate a UUID on iOS from Swift

For Swift 4;

let uuid = NSUUID().uuidString.lowercased()

deny directory listing with htaccess

Options -Indexes should work to prevent directory listings.

If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.

Backup/Restore a dockerized PostgreSQL database

Okay, I've figured this out. Postgresql does not detect changes to the folder /var/lib/postgresql once it's launched, at least not the kind of changes I want it do detect.

The first solution is to start a container with bash instead of starting the postgres server directly, restore the data, and then start the server manually.

The second solution is to use a data container. I didn't get the point of it before, now I do. This data container allows to restore the data before starting the postgres container. Thus, when the postgres server starts, the data are already there.

How to add item to the beginning of List<T>?

Use Insert method of List<T>:

List.Insert Method (Int32, T): Inserts an element into the List at the specified index.

var names = new List<string> { "John", "Anna", "Monica" };
names.Insert(0, "Micheal"); // Insert to the first element

how to use html2canvas and jspdf to export to pdf in a proper and simple way

Changing this line:

var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);

To fix the dimensions.

Error in file(file, "rt") : cannot open the connection

Got this error and found that RStudio on my Windows machine try to use \ as escape symbol, so had to replace it with \\ to deal with it.

Try file.exists function with your path, e.g.:

file.exists("D:\\R\\path_to_file.csv")

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

Apologize for resurrect this thread, but for Windows 8.x users can find my.cnf at this folder:

C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

Then also can find data folder on same folder.

What does the KEY keyword mean?

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

column_definition:
      data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      ...

Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Bootstrap Modal before form Submit

So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.

For this, you first change your input type="submit" to input type="button" and add data-toggle="modal" data-target="#confirm-submit" so that the modal gets triggered when you click on it:

<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />

Next, the modal dialog:

<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Confirm Submit
            </div>
            <div class="modal-body">
                Are you sure you want to submit the following details?

                <!-- We display the details entered by the user here -->
                <table class="table">
                    <tr>
                        <th>Last Name</th>
                        <td id="lname"></td>
                    </tr>
                    <tr>
                        <th>First Name</th>
                        <td id="fname"></td>
                    </tr>
                </table>

            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a href="#" id="submit" class="btn btn-success success">Submit</a>
            </div>
        </div>
    </div>
</div>

Lastly, a little bit of jQuery:

$('#submitBtn').click(function() {
     /* when the button in the form, display the entered values in the modal */
     $('#lname').text($('#lastname').val());
     $('#fname').text($('#firstname').val());
});

$('#submit').click(function(){
     /* when the submit button in the modal is clicked, submit the form */
    alert('submitting');
    $('#formfield').submit();
});

You haven't specified what the function validateForm() does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button #submitBtn click and then load the modal after the validations have been checked.

DEMO

How to compile LEX/YACC files on Windows?

the easiest method is to download and install cygwin and download gcc and flex packages during installation. Then to run a lex file for eg. abc.l

we write

flex abc.l
gcc lex.yy.c -o abc.exe
./abc.exe

Response.Redirect to new window

The fixform trick is neat, but:

  1. You may not have access to the code of what loads in the new window.

  2. Even if you do, you are depending on the fact that it always loads, error free.

  3. And you are depending on the fact that the user won't click another button before the other page gets a chance to load and run fixform.

I would suggest doing this instead:

OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"

And set up fixform on the same page, looking like this:

function fixform() {
   document.getElementById("aspnetForm").target = '';
}

Please initialize the log4j system properly. While running web service

You have to create your own log4j.properties in the classpath folder.

Angular2 multiple router-outlet in the same template

Yes you can as said by @tomer above. i want to add some point to @tomer answer.

  • firstly you need to provide name to the router-outlet where you want to load the second routing view in your view. (aux routing angular2.)
  • In angular2 routing few important points are here.

    • path or aux (requires exactly one of these to give the path you have to show as the url).
    • component, loader, redirectTo (requires exactly one of these, which component you want to load on routing)
    • name or as (optional) (requires exactly one of these, the name which specify at the time of routerLink)
    • data (optional, whatever you want to send with the routing that you have to get using routerParams at the receiver end.)

for more info read out here and here.

import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
  new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I had a similar situation, and the following process worked for me:

  1. In the terminal, type

    vi ~/.profile
    
  2. Then add this line in the file, and save

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
    

    where version is the one on your computer, such as 1.7.0_25

  3. Exit the editor, then type the following command make it become effective

    source ~/.profile 
    

Then type java -version to check the result

    java -version 

What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515

.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.

What resources are shared between threads?

In an x86 framework, one can divide as many segments (up to 2^16-1). The ASM directives SEGMENT/ENDS allows this, and the operators SEG and OFFSET allows initialization of segment registers. CS:IP are usually initialized by the loader, but for DS, ES, SS the application is responsible with initialization. Many environments allow the so-called "simplified segment definitions" like .code, .data, .bss, .stack etc. and, depending also on the "memory model" (small, large, compact etc.) the loader initializes segment registers accordingly. Usually .data, .bss, .stack and other usual segments (I haven't done this since 20 years so I don't remember all) are grouped in one single group - that is why usually DS, ES and SS points to teh same area, but this is only to simplify things.

In general, all segment registers can have different values upon run-time. So, the interview question was right: which one of the CODE, DATA, and STACK are shared between threads. Heap management is something else - it is simply a sequence of calls to the OS. But what if you don't have an OS at all, like in an embedded system - can you still have new/delete in your code?

My advice to the young people - read some good assembly programming book. It seems that university curriculae are quite poor in this respect.

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

How can I get a user's media from Instagram without authenticating as a user?

One more trick, search photos by hashtags:

GET https://www.instagram.com/graphql/query/?query_hash=3e7706b09c6184d5eafd8b032dbcf487&variables={"tag_name":"nature","first":25,"after":""}

Where:

query_hash - permanent value(i belive its hash of 17888483320059182, can be changed in future)

tag_name - the title speaks for itself

first - amount of items to get (I do not know why, but this value does not work as expected. The actual number of returned photos is slightly larger than the value multiplied by 4.5 (about 110 for the value 25, and about 460 for the value 100))

after - id of the last item if you want to get items from that id. Value of end_cursor from JSON response can be used here.

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

A Java collection of value pairs? (tuples?)

This is based on JavaHelp4u 's code.

Less verbose and shows how to do in one line and how to loop over things.

//======>  Imports
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

//======>  Single Entry
SimpleEntry<String, String> myEntry = new SimpleEntry<String, String>("ID", "Text");
System.out.println("key: " + myEntry.getKey() + "    value:" + myEntry.getValue());
System.out.println();

//======>  List of Entries
List<Entry<String,String>> pairList = new ArrayList<>();

//-- Specify manually
Entry<String,String> firstButton = new SimpleEntry<String, String>("Red ", "Way out");
pairList.add(firstButton);

//-- one liner:
pairList.add(new SimpleEntry<String,String>("Gray", "Alternate route"));  //Ananomous add.

//-- Iterate over Entry array:
for (Entry<String, String> entr : pairList) {
    System.out.println("Button: " + entr.getKey() + "    Label: " + entr.getValue());
}

How do I check if a C++ string is an int?

I have modified paercebal's method to meet my needs:

typedef std::string String;    

bool isInt(const String& s, int base){
   if(s.empty() || std::isspace(s[0])) return false ;
   char * p ;
   strtol(s.c_str(), &p, base) ;
   return (*p == 0) ;
}


bool isPositiveInt(const String& s, int base){
   if(s.empty() || std::isspace(s[0]) || s[0]=='-') return false ;
   char * p ;
   strtol(s.c_str(), &p, base) ;
   return (*p == 0) ;
}


bool isNegativeInt(const String& s, int base){
   if(s.empty() || std::isspace(s[0]) || s[0]!='-') return false ;
   char * p ;
   strtol(s.c_str(), &p, base) ;
   return (*p == 0) ;
}

Note:

  1. You can check for various bases (binary, oct, hex and others)
  2. Make sure you don't pass 1, negative value or value >36 as base.
  3. If you pass 0 as the base, it will auto detect the base i.e for a string starting with 0x will be treated as hex and string starting with 0 will be treated as oct. The characters are case-insensitive.
  4. Any white space in string will make it return false.

How to make a radio button unchecked by clicking it?

A working bug free update to Shmili Breuer answer.

(function() {
    $( "input[type='radio'].revertible" ).click(function() {
        var $this = $( this );

        // update and remove the previous checked class
        var $prevChecked = $('input[name=' + $this.attr('name') + ']:not(:checked).checked');
            $prevChecked.removeClass('checked');

        if( $this.hasClass("checked") ) {
            $this.removeClass("checked");
            $this.prop("checked", false);
        }
        else {
            $this.addClass("checked");
        }
    });
})();

How to clear variables in ipython?

Adding the following lines to a new script will clear all variables each time you rerun the script:

from IPython import get_ipython
get_ipython().magic('reset -sf') 

To make life easy, you can add them to your default template.

In Spyder: Tools>Preferences>Editor>Edit template

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

SQL: Select columns with NULL values only

Or did you want to just see if a column only has NULL values (and, thus, is probably unused)?

Further clarification of the question might help.

EDIT: Ok.. here's some really rough code to get you going...

SET NOCOUNT ON
DECLARE @TableName Varchar(100)
SET @TableName='YourTableName'
CREATE TABLE #NullColumns (ColumnName Varchar(100), OnlyNulls BIT)
INSERT INTO #NullColumns (ColumnName, OnlyNulls) SELECT c.name, 0 FROM syscolumns c INNER JOIN sysobjects o ON c.id = o.id AND o.name = @TableName AND o.xtype = 'U'
DECLARE @DynamicSQL AS Nvarchar(2000)
DECLARE @ColumnName Varchar(100)
DECLARE @RC INT
    SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0
    WHILE @@ROWCOUNT > 0
    BEGIN
        SET @RC=0
        SET @DynamicSQL = 'SELECT TOP 1 1 As HasNonNulls FROM ' + @TableName + ' (nolock) WHERE ''' + @ColumnName + ''' IS NOT NULL'
        EXEC sp_executesql @DynamicSQL
        set @RC=@@rowcount
        IF @RC=1
        BEGIN
            SET @DynamicSQL = 'UPDATE #NullColumns SET OnlyNulls=1 WHERE ColumnName=''' + @ColumnName + ''''
            EXEC sp_executesql @DynamicSQL
        END
        ELSE
        BEGIN
            SET @DynamicSQL = 'DELETE FROM #NullColumns WHERE ColumnName=''' + @ColumnName+ ''''
            EXEC sp_executesql @DynamicSQL
        END
    SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0
    END

SELECT * FROM #NullColumns

DROP TABLE #NullColumns
SET NOCOUNT OFF

Yes, there are easier ways, but I have a meeting to go to right now. Good luck!

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How to lock specific cells but allow filtering and sorting

I just came up with a tricky way to get almost the same functionality. Instead of protecting the sheet the normal way, use an event handler to undo anything the user tries to do.

Add the following to the worksheet's module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Locked = True Then
        Application.EnableEvents = False
        Application.Undo
        Application.EnableEvents = True
    End If
End Sub

If the user does anything to change a cell that's locked, the action will get immediately undone. The temporary disabling of events is to keep the undoing itself from triggering this event, resulting in an infinite loop.

Sorting and filtering do not trigger the Change event, so those functions remain enabled.

Note that this solution prevents changing or clearing cell contents, but does not prevent changing formats. A determined user could get around it by simply setting the cells to be unlocked.

Uninstalling Android ADT

i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

How do I encode URI parameter values?

Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

Lodash remove duplicates from array

You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.

Example:

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

More info: https://lodash.com/docs/#uniqWith

Using Java 8's Optional with Stream::flatMap

What about that?

private static List<String> extractString(List<Optional<String>> list) {
    List<String> result = new ArrayList<>();
    list.forEach(element -> element.ifPresent(result::add));
    return result;
}

https://stackoverflow.com/a/58281000/3477539

When to use DataContract and DataMember attributes?

In terms of WCF, we can communicate with the server and client through messages. For transferring messages, and from a security prospective, we need to make a data/message in a serialized format.

For serializing data we use [datacontract] and [datamember] attributes. In your case if you are using datacontract WCF uses DataContractSerializer else WCF uses XmlSerializer which is the default serialization technique.

Let me explain in detail:

basically WCF supports 3 types of serialization:

  1. XmlSerializer
  2. DataContractSerializer
  3. NetDataContractSerializer

XmlSerializer :- Default order is Same as class

DataContractSerializer/NetDataContractSerializer :- Default order is Alphabetical

XmlSerializer :- XML Schema is Extensive

DataContractSerializer/NetDataContractSerializer :- XML Schema is Constrained

XmlSerializer :- Versioning support not possible

DataContractSerializer/NetDataContractSerializer :- Versioning support is possible

XmlSerializer :- Compatibility with ASMX

DataContractSerializer/NetDataContractSerializer :- Compatibility with .NET Remoting

XmlSerializer :- Attribute not required in XmlSerializer

DataContractSerializer/NetDataContractSerializer :- Attribute required in this serializing

so what you use depends on your requirements...

Regex matching in a Bash if statement

I'd prefer to use [:punct:] for that. Also, a-zA-Z09-9 could be just [:alnum:]:

[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]

Converting A String To Hexadecimal In Java

Using Multiple Peoples help from multiple Threads..

I know this has been answered, but i would like to give a full encode & decode method for any others in my same situation..

Here's my Encoding & Decoding methods..

// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;

// Text To Hex
public static String textToHex(String text)
{
    byte[] buf = null;
    buf = text.getBytes(encodingType);
    char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i)
    {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

// Hex To Text
public static String hexToText(String hex)
{
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2)
    {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
            + Character.digit(hex.charAt(i + 1), 16));
    }
    String st = new String(data, encodingType);
    return st;
}

How to work with complex numbers in C?

For convenience, one may include tgmath.h library for the type generate macros. It creates the same function name as the double version for all type of variable. For example, For example, it defines a sqrt() macro that expands to the sqrtf() , sqrt() , or sqrtl() function, depending on the type of argument provided.

So one don't need to remember the corresponding function name for different type of variables!

#include <stdio.h>
#include <tgmath.h>//for the type generate macros. 
#include <complex.h>//for easier declare complex variables and complex unit I

int main(void)
{
    double complex z1=1./4.*M_PI+1./4.*M_PI*I;//M_PI is just pi=3.1415...
    double complex z2, z3, z4, z5; 

    z2=exp(z1);
    z3=sin(z1);
    z4=sqrt(z1);
    z5=log(z1);

    printf("exp(z1)=%lf + %lf I\n", creal(z2),cimag(z2));
    printf("sin(z1)=%lf + %lf I\n", creal(z3),cimag(z3));
    printf("sqrt(z1)=%lf + %lf I\n", creal(z4),cimag(z4));
    printf("log(z1)=%lf + %lf I\n", creal(z5),cimag(z5));

    return 0;
}

JAX-WS and BASIC authentication, when user names and passwords are in a database

I think you are looking for JAX-WS authentication in application level, not HTTP basic in server level. See following complete example :

Application Authentication with JAX-WS

On the web service client site, just put your “username” and “password” into request header.

Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);

Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("someUser"));
headers.put("Password", Collections.singletonList("somePass"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

On the web service server site, get the request header parameters via WebServiceContext.

@Resource
WebServiceContext wsctx;

@WebMethod
public String method() {
    MessageContext mctx = wsctx.getMessageContext();

    Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
    List userList = (List) http_headers.get("Username");
    List passList = (List) http_headers.get("Password");
    //...

Easiest way to read/write a file's content in Python

Use pathlib.

Python 3.5 and above:

from pathlib import Path
contents = Path(file_path).read_text()

For lower versions of Python use pathlib2:

$ pip install pathlib2

Then

from pathlib2 import Path
contents = Path(file_path).read_text()

Writing is just as easy:

Path(file_path).write_text('my text')

Cutting the videos based on start and end time using ffmpeg

Use -to instead of -t: -to specifies the end time, -t specifies the duration

error: member access into incomplete type : forward declaration of

Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

TypeError: $(...).modal is not a function with bootstrap Modal

Check that jquery library not included in html that load via Ajax .remove <script src="~/Scripts/jquery[ver].js"></script> in your AjaxUpdate/get_modal

What should I do when 'svn cleanup' fails?

Subclipse gets confused by Windows' truly diabolical locking behaviour. Unlocker is your friend. This can find locked files and forcibly release the locks.

Use bash to find first folder name that contains a string

pattern="foo"
for _dir in *"${pattern}"*; do
    [ -d "${_dir}" ] && dir="${_dir}" && break
done
echo "${dir}"

This is better than the other shell solution provided because

  • it will be faster for huge directories as the pattern is part of the glob and not checked inside the loop
  • actually works as expected when there is no directory matching your pattern (then ${dir} will be empty)
  • it will work in any POSIX-compliant shell since it does not rely on the =~ operator (if you need this depends on your pattern)
  • it will work for directories containing newlines in their name (vs. find)

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

The "backspace" escape character '\b': unexpected behavior?

If you want a destructive backspace, you'll need something like

"\b \b"

i.e. a backspace, a space, and another backspace.

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

How to view the contents of an Android APK file?

You can also use Jadx - https://github.com/skylot/jadx. I have used all the tools mentioned in this page and found that Jadx works the best. The manifest file and other class files are converted to readable format as much as possible by this tool.

PS - http://www.javadecompilers.com/apk also uses the jadx decompiler to do the same work online. Simpler if you want to unarchive a single apk.

Cheers!

How to connect Bitbucket to Jenkins properly

I am not familiar with this plugin, but we quite successfully use Bitbucket and Jenkins together, however we poll for changes instead of having them pushed from BitBucket (due to the fact our build server is hidden behind a company firewall). This approach may work for you if you are still having problems with the current approach.

This document on Setting up SSH for Git & Mercurial on Linux covers the details of what you need to do to be able to communicate between your build server and Bitbucket over SSH. Once this is done, with the Git Plugin installed, go to your build configuration and select 'Git' under Source Code Management, and enter the ssh URL of your repository as the repository URL. Finally, in the Build Triggers section, select Poll SCM and set the poll frequency to whatever you require.

PHP: convert spaces in string into %20?

Use the rawurlencode function instead.

CSS3 Rotate Animation

To achieve the 360 degree rotation, here is the Working Solution.

The HTML:

<img class="image" src="your-image.png">

The CSS:

.image {
    overflow: hidden;
    transition-duration: 0.8s;
    transition-property: transform;
}
.image:hover {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
}

You have to hover on the image and you will get the 360 degree rotation effect.

PS: Add a -webkit- extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE

How do you assert that a certain exception is thrown in JUnit 4 tests?

There are two ways of writing test case

  1. Annotate the test with the exception which is thrown by the method. Something like this @Test(expected = IndexOutOfBoundsException.class)
  2. You can simply catch the exception in the test class using the try catch block and assert on the message that is thrown from the method in test class.

    try{
    }
    catch(exception to be thrown from method e)
    {
         assertEquals("message", e.getmessage());
    }
    

I hope this answers your query Happy learning...

create multiple tag docker image

docker build  -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .

col align right

Use float-right for block elements, or text-right for inline elements:

<div class="row">
     <div class="col">left</div>
     <div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
      <div class="col">left</div>
      <div class="col">
          <div class="float-right">element needs to be right aligned</div>
      </div>
</div>

http://www.codeply.com/go/oPTBdCw1JV

If float-right is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex which can prevent float-right from working.

In some cases, the utility classes like align-self-end or ml-auto work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto (margin-left:auto) is used in a flexbox element to push elements to the right.

Bootstrap 4 align right examples

Run Command Prompt Commands

if you want to run the command in async mode - and print the results. you can you this class:

    public static class ExecuteCmd
{
    /// <summary>
    /// Executes a shell command synchronously.
    /// </summary>
    /// <param name="command">string command</param>
    /// <returns>string, as output of the command.</returns>
    public static void ExecuteCommandSync(object command)
    {
        try
        {
            // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            // The following commands are needed to redirect the standard output. 
            //This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput =  true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            // Get the output into a string
            string result = proc.StandardOutput.ReadToEnd();

            // Display the command output.
            Console.WriteLine(result);
        }
        catch (Exception objException)
        {
            // Log the exception
            Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
        }
    }

    /// <summary>
    /// Execute the command Asynchronously.
    /// </summary>
    /// <param name="command">string command.</param>
    public static void ExecuteCommandAsync(string command)
    {
        try
        {
            //Asynchronously start the Thread to process the Execute command request.
            Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
            //Make the thread as background thread.
            objThread.IsBackground = true;
            //Set the Priority of the thread.
            objThread.Priority = ThreadPriority.AboveNormal;
            //Start the thread.
            objThread.Start(command);
        }
        catch (ThreadStartException )
        {
            // Log the exception
        }
        catch (ThreadAbortException )
        {
            // Log the exception
        }
        catch (Exception )
        {
            // Log the exception
        }
    }

}

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

Find control by name from Windows Forms controls

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

If Controls.Find is not found "textBox1" => error. You must add code.

If(tbx != null)

Edit:

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
   tbx.Text = "found!";

Using an image caption in Markdown Jekyll

Andrew's @andrew-wei answer works great. You can also chain a few together, depending on what you are trying to do. This, for example, gets you an image with alt, title and caption with a line break and bold and italics in different parts of the caption:

img + br + strong {margin-top: 5px; margin-bottom: 7px; font-style:italic; font-size: 12px; }
img + br + strong + em {margin-top: 5px; margin-bottom: 7px; font-size: 12px; font-style:italic;}

With the following <img> markdown:

![description](https://img.jpg "description")
***Image:*** *description*

How to sum digits of an integer in java?

Sums all the digits regardless of number's size.

private static int sumOfAll(int num) {
    int sum = 0;

    if(num == 10) return 1;

    if(num > 10) {
        sum += num % 10;
        while((num = num / 10) >= 1) {
            sum += (num > 10) ? num%10 : num;
        }
    } else {
        sum += num;
    }
    return sum;
}

Get refresh token google api

For those using the Google API Client Library for PHP and seeking offline access and refresh tokens beware as of the time of this writing the docs are showing incorrect examples.

currently it's showing:

$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true);   // incremental auth

source: https://developers.google.com/identity/protocols/OAuth2WebServer#offline

All of this works great - except ONE piece

$client->setApprovalPrompt("consent");

After a bit of reasoning I changed this line to the following and EVERYTHING WORKED

$client->setPrompt("consent");

It makes sense since using the HTTP requests it was changed from approval_prompt=force to prompt=consent. So changing the setter method from setApprovalPrompt to setPrompt follows natural convention - BUT IT'S NOT IN THE DOCS!!! That I found at least.

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6