Programs & Examples On #Onkeypress

0

How to handle the `onKeyPress` event in ReactJS?

You need to call event.persist(); this method on your keyPress event. Example:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes

Thanks & Regards

P.S: React Version : 16.13.1

How to capture Enter key press?

You need to create a handler for the onkeypress action.

HTML

<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleEnter(this, event)" />

JS

function handleEnter(inField, e)
{
    var charCode;

    //Get key code (support for all browsers)
    if(e && e.which)
    {
        charCode = e.which;
    }
    else if(window.event)
    {
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13)
    {
       //Call your submit function
    }
}

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

just do this

@Override
public void onBackPressed() {
    super.onBackPressed();
}

How to get text of an input text box during onKeyPress?

<asp:TextBox ID="txtMobile" runat="server" CssClass="form-control" style="width:92%;  margin:0px 5px 0px 5px;" onkeypress="javascript:return isNumberKey(event);" MaxLength="12"></asp:TextBox>

<script>
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
</script>

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

The following answer is to merge data into same table

MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
    ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif') 
WHEN NOT MATCHED THEN
        INSERT ( d.USERS_ID, d.USER_NAME)
        VALUES ('123','itszaif');

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert.

set the width of select2 input (through Angular-ui directive)

You can try like this. It works for me

$("#MISSION_ID").select2();

On hide/show or ajax request, we have to reinitialize the select2 plugin

For example:

$("#offialNumberArea").show();
$("#eventNameArea").hide();

$('.selectCriteria').change(function(){
    var thisVal = $(this).val();
    if(thisVal == 'sailor'){
        $("#offialNumberArea").show();
        $("#eventNameArea").hide();
    }
    else
    {
        $("#offialNumberArea").hide();
        $("#eventNameArea").show();
        $("#MISSION_ID").select2();
    }
});

Changing width property of a :before css selector using JQuery

The answer should be Jain. You can not select an element via pseudo-selector, but you can add a new rule to your stylesheet with insertRule.

I made something that should work for you:

var addRule = function(sheet, selector, styles) {
    if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
    if (sheet.addRule) return sheet.addRule(selector, styles);
};

addRule(document.styleSheets[0], "body:before", "content: 'foo'");

http://fiddle.jshell.net/MDyxg/1/

To be super-cool (and to answer the question really) I rolled it out again and wrapped this in a jQuery-plugin (however, jquery is still not required!):

/*!
 * jquery.addrule.js 0.0.1 - https://gist.github.com/yckart/5563717/
 * Add css-rules to an existing stylesheet.
 *
 * @see http://stackoverflow.com/a/16507264/1250044
 *
 * Copyright (c) 2013 Yannick Albert (http://yckart.com)
 * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
 * 2013/05/12
 **/

(function ($) {

    window.addRule = function (selector, styles, sheet) {

        styles = (function (styles) {
            if (typeof styles === "string") return styles;
            var clone = "";
            for (var p in styles) {
                if (styles.hasOwnProperty(p)) {
                    var val = styles[p];
                    p = p.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
                    clone += p + ":" + (p === "content" ? '"' + val + '"' : val) + "; ";
                }
            }
            return clone;
        }(styles));
        sheet = sheet || document.styleSheets[document.styleSheets.length - 1];

        if (sheet.insertRule) sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        else if (sheet.addRule) sheet.addRule(selector, styles);

        return this;

    };

    if ($) $.fn.addRule = function (styles, sheet) {
        addRule(this.selector, styles, sheet);
        return this;
    };

}(window.jQuery));

The usage is quite simple:

$("body:after").addRule({
    content: "foo",
    color: "red",
    fontSize: "32px"
});

// or without jquery
addRule("body:after", {
    content: "foo",
    color: "red",
    fontSize: "32px"
});

https://gist.github.com/yckart/5563717

How do I run a PowerShell script when the computer starts?

Be sure, whenever you want PowerShell to run automatically / in the background / non-interactive, it’s a good idea to specify the parameters -ExecutionPolicy Bypass to PowerShell.exe

PowerShell.exe -ExecutionPolicy Bypass

Using textures in THREE.js

In version r75 of three.js, you should use:

var loader = new THREE.TextureLoader();
loader.load('texture.png', function ( texture ) {
  var geometry = new THREE.SphereGeometry(1000, 20, 20);
  var material = new THREE.MeshBasicMaterial({map: texture, overdraw: 0.5});
  var mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
});

Bootstrap Carousel : Remove auto slide

data-interval="false"

Add this to the corresponding div ...

How to fix 'Microsoft Excel cannot open or save any more documents'

Go to this key on Registry Editor (Run | Regedit) HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

change key Cache to something like C:\Windows\Temp

My similar problem was solved like this.

Regards,

Ripley

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Go to Project properties.

Then 'Java Compiler' -> Check the box and "Enable project specific settings"

Uncheck the box to "Use Compliance from execution environment 'OSGi/Minimum-1.2' on the Java"

Then change the compiler compliance level to '1.5' and click Ok.

Rebuild it and your problem will be resolved.

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

CSS: Creating textured backgrounds

If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('') section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.

Example link: http://www.base64-image.de/

When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:

url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')

With your texture images, you'll want to employ a similar process.

Print DIV content by JQuery

your question doesn't sound as if you even tried it yourself, so i shouldn't even think of answering, but: if a hidden div can't be printed with that one line:

$('SelectorToPrint').printElement();

simply change it to:

$('SelectorToPrint').show().printElement();

which should make it work in all cases.

for the rest, there's no solution. the plugin will open the print-dialog for you where the user has to choose his printer. you simply can't find out if a printer is attached with javascript (and you (almost) can't print without print-dialog - if you're thinking about that).

NOTE:

The $.browser object has been removed in version 1.9.x of jQuery making this library unsupported.

Fastest JavaScript summation

Or you could do it the evil way.

var a = [1,2,3,4,5,6,7,8,9];

sum = eval(a.join("+"));

;)

Performance of Java matrix math libraries?

Jeigen https://github.com/hughperkins/jeigen

  • wraps Eigen C++ library http://eigen.tuxfamily.org , which is one of the fastest free C++ libraries available
  • relatively terse syntax, eg 'mmul', 'sub'
  • handles both dense and sparse matrices

A quick test, by multiplying two dense matrices, ie:

import static jeigen.MatrixUtil.*;

int K = 100;
int N = 100000;
DenseMatrix A = rand(N, K);
DenseMatrix B = rand(K, N);
Timer timer = new Timer();
DenseMatrix C = B.mmul(A);
timer.printTimeCheckMilliseconds();

Results:

Jama: 4090 ms
Jblas: 1594 ms
Ojalgo: 2381 ms (using two threads)
Jeigen: 2514 ms
  • Compared to jama, everything is faster :-P
  • Compared to jblas, Jeigen is not quite as fast, but it handles sparse matrices.
  • Compared to ojalgo, Jeigen takes about the same amount of elapsed time, but only using one core, so Jeigen uses half the total cpu. Jeigen has a terser syntax, ie 'mmul' versus 'multiplyRight'

Call a React component method from outside

I've done something like this:

class Cow extends React.Component {

    constructor (props) {
        super(props);
        this.state = {text: 'hello'};
    }

    componentDidMount () {
        if (this.props.onMounted) {
            this.props.onMounted({
                say: text => this.say(text)
            });
        }
    }

    render () {
        return (
            <pre>
                 ___________________
                < {this.state.text} >
                 -------------------
                        \   ^__^
                         \  (oo)\_______
                            (__)\       )\/\
                                ||----w |
                                ||     ||
            </pre>
        );
    }

    say (text) {
        this.setState({text: text});
    }

}

And then somewhere else:

class Pasture extends React.Component {

    render () {
        return (
            <div>
                <Cow onMounted={callbacks => this.cowMounted(callbacks)} />
                <button onClick={() => this.changeCow()} />
            </div>
        );
    }

    cowMounted (callbacks) {
        this.cowCallbacks = callbacks;
    }

    changeCow () {
        this.cowCallbacks.say('moo');
    }

}

I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.

fatal error LNK1104: cannot open file 'kernel32.lib'

OS : Win10, Visual Studio 2015

Solution : Go to control panel ---> uninstall program ---MSvisual studio ----> change ---->organize = repair

and repair it. Note that you must connect to internet until repairing finish.

Good luck.

Get week of year in JavaScript like in PHP

getWeekOfYear: function(date) {
        var target = new Date(date.valueOf()),
            dayNumber = (date.getUTCDay() + 6) % 7,
            firstThursday;

        target.setUTCDate(target.getUTCDate() - dayNumber + 3);
        firstThursday = target.valueOf();
        target.setUTCMonth(0, 1);

        if (target.getUTCDay() !== 4) {
            target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
        }

        return Math.ceil((firstThursday - target) /  (7 * 24 * 3600 * 1000)) + 1;
    }

Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

Convert NSDate to NSString

How about...

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];

//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

//unless ARC is active
[formatter release];

Swift 4.2 :

func stringFromDate(_ date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
    return formatter.string(from: date)
}

Load vs. Stress testing

Load - Test S/W at max Load. Stress - Beyond the Load of S/W.Or To determine the breaking point of s/w.

How can I upgrade specific packages using pip and a requirements file?

First make sure you have checked the most voted answer.


I'm not sure if it's exactly your problem, but in my case, I wasn't able to upgrade Django to 1.2.4 - I was always finishing with 1.2.3 version, so I uninstalled Django with:

<virtualenv>/bin/pip uninstall Django

Then I removed <virtualenv>/build/Django directory and finally I installed the proper version with:

<virtualenv>/bin/pip install Django

Remove Blank option from Select Option with AngularJS

It is kind of a workaround but works like a charm. Just add <option value="" style="display: none"></option> as a filler. Like in:

<select size="4" ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
       <option value="" style="display: none"></option>
</select>

Shrink a YouTube video to responsive width

This is old thread, but I have find new answer on https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php

The problem with previous solution is that you need to have special div around video code, which is not suitable for most uses. So here is JavaScript solution without special div.

// Find all YouTube videos - RESIZE YOUTUBE VIDEOS!!!
var $allVideos = $("iframe[src^='https://www.youtube.com']"),

// The element that is fluid width
$fluidEl = $("body");

// Figure out and save aspect ratio for each video
$allVideos.each(function() {

    $(this)
    .data('aspectRatio', this.height / this.width)

    // and remove the hard coded width/height
    .removeAttr('height')
    .removeAttr('width');

});

// When the window is resized
$(window).resize(function() {

    var newWidth = $fluidEl.width();

    // Resize all videos according to their own aspect ratio
    $allVideos.each(function() {

        var $el = $(this);
        $el
        .width(newWidth)
        .height(newWidth * $el.data('aspectRatio'));

    });

// Kick off one resize to fix all videos on page load
}).resize();

// END RESIZE VIDEOS

Java JTextField with input hint

For any Swing component (that is, anything that extends JComponent), you can call the setToolTipText(String) method.

For more information, reference the following links:

What is the bower (and npm) version syntax?

Bower uses semver syntax, but here are a few quick examples:

You can install a specific version:

$ bower install jquery#1.11.1

You can use ~ to specify 'any version that starts with this':

$ bower install jquery#~1.11

You can specify multiple version requirements together:

$ bower install "jquery#<2.0 >1.10"

How to get the home directory in Python?

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

How can I install MacVim on OS X?

That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead

See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line

Python function pointer

eval(compile(myvar,'<str>','eval'))(myargs)

compile(...,'eval') allows only a single statement, so that there can't be arbitrary commands after a call, or there will be a SyntaxError. Then a tiny bit of validation can at least constrain the expression to something in your power, like testing for 'mypackage' to start.

How do I add an existing directory tree to a project in Visual Studio?

I think I found a way to do this with the Compile Include=".\Code***.cs" What I wanted is to include code recursively under my Code folder.

Here is the project file sample.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="15.0" DefaultTargets="BuildTarget">
    <PropertyGroup>
        <OutputType>Library</OutputType>
    </PropertyGroup>
    <PropertyGroup>
        <StartupObject />
    </PropertyGroup>
    <PropertyGroup>
        <RootNamespace>Autogen</RootNamespace>
    </PropertyGroup>
    <ItemGroup>
        <Compile Remove="@(Compile)" />
        <Compile Include=".\Code\**\*.cs" />
    </ItemGroup>
    <Target Name="BuildTarget">
        <Message Text="Build selected" Importance="high"/>
    </Target>
</Project>

Combining two sorted lists in Python

This is simply merging. Treat each list as if it were a stack, and continuously pop the smaller of the two stack heads, adding the item to the result list, until one of the stacks is empty. Then add all remaining items to the resulting list.

Bootstrap 3 Horizontal and Vertical Divider

The <hr> should be placed inside a <div> for proper functioning.

Place it like this to get desired width `

<div class='row'>
        <div class='col-lg-8 col-lg-offset-2'>
        <hr>
       </div>
       </div>

`

Hope this helps a future reader!

How to compare numbers in bash?

There is also one nice thing some people might not know about:

echo $(( a < b ? a : b ))

This code will print the smallest number out of a and b

Address validation using Google Maps API

You could consider using CDYNE's PAV-I API that validates international addresses. international-address-verification They cover over 240 countries, so it should cover all of the countries that you are looking to validate for.

Check for database connection, otherwise display message

very basic:

<?php 
$username = 'user';
$password = 'password';
$server = 'localhost'; 
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>

result:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please

as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php

Tracking the script execution time in PHP

Shorter version of talal7860's answer

<?php
// At start of script
$time_start = microtime(true); 

// Anywhere else in the script
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);

As pointed out, this is 'wallclock time' not 'cpu time'

Deserialize from string instead TextReader

public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

How to decode HTML entities using jQuery?

I think you're confusing the text and HTML methods. Look at this example, if you use an element's inner HTML as text, you'll get decoded HTML tags (second button). But if you use them as HTML, you'll get the HTML formatted view (first button).

<div id="myDiv">
    here is a <b>HTML</b> content.
</div>
<br />
<input value="Write as HTML" type="button" onclick="javascript:$('#resultDiv').html($('#myDiv').html());" />
&nbsp;&nbsp;
<input value="Write as Text" type="button" onclick="javascript:$('#resultDiv').text($('#myDiv').html());" />
<br /><br />
<div id="resultDiv">
    Results here !
</div>

First button writes : here is a HTML content.

Second button writes : here is a <B>HTML</B> content.

By the way, you can see a plug-in that I found in jQuery plugin - HTML decode and encode that encodes and decodes HTML strings.

npm install error from the terminal

In mac you might have downloaded and installed Node js in /Users/yourusername/Downloads/nodejs-todo-master , so go here and run npm install command, no need of sudo as well., you should get output like this...

[email protected] node_modules/underscore

[email protected] node_modules/ejs

[email protected] node_modules/redis

[email protected] node_modules/jasmine-node
+-- [email protected]
+-- [email protected] ([email protected])
+-- [email protected]
+-- [email protected] ([email protected])

[email protected] node_modules/express
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected] ([email protected])
+-- [email protected] ([email protected])
+-- [email protected] ([email protected], [email protected], [email protected], [email protected])

Unable to resolve host "<insert URL here>" No address associated with hostname

Please, check if you have valid internet connection.

curl : (1) Protocol https not supported or disabled in libcurl

This is specifically mentioned in the libcurl FAQ entry "Protocol xxx not supported or disabled in libcurl".

For your pleasure I'm embedding the explanation here too:

When passing on a URL to curl to use, it may respond that the particular protocol is not supported or disabled. The particular way this error message is phrased is because curl doesn't make a distinction internally of whether a particular protocol is not supported (ie never got any code added that knows how to speak that protocol) or if it was explicitly disabled. curl can be built to only support a given set of protocols, and the rest would then be disabled or not supported.

Note that this error will also occur if you pass a wrongly spelled protocol part as in "htpt://example.com" or as in the less evident case if you prefix the protocol part with a space as in " http://example.com/".

Classpath resource not found when running as jar

in spring boot :

1) if your file is ouside jar you can use :        

@Autowired
private ResourceLoader resourceLoader;

**.resource(resourceLoader.getResource("file:/path_to_your_file"))**

2) if your file is inside resources of jar you can `enter code here`use :

**.resource(new ClassPathResource("file_name"))**

R - argument is of length zero in if statement

The same error message results not only for null but also for e.g. factor(0). In this case, the query must be if(length(element) > 0 & otherCondition) or better check both cases with if(!is.null(element) & length(element) > 0 & otherCondition).

Node.js EACCES error when listening on most ports

I got this error on my mac because it ran the apache server by default using the same port as the one used by the node server which in my case was the port 80. All I had to do is stop it with sudo apachectl stop

Hope this helps someone.

Fetch frame count with ffmpeg

Not all formats store their frame count or total duration - and even if they do, the file might be incomplete - so ffmpeg doesn't detect either of them accurately by default.

Instead, try seeking to the end of the file and read the time, then count the current time while you go.

Alternatively, you can try AVFormatContext->nb_index_entries or the detected duration, which should work on fine at least undamaged AVI/MOV, or the library FFMS2, which is probably too slow to bother with for a progress bar.

What is the difference between visibility:hidden and display:none?

They are not synonyms.

display:none removes the element from the normal flow of the page, allowing other elements to fill in.

visibility:hidden leaves the element in the normal flow of the page such that is still occupies space.

Imagine you are in line for a ride at an amusement park and someone in the line gets so rowdy that security plucks them from the line. Everyone in line will then move forward one position to fill the now empty slot. This is like display:none.

Contrast this with the similar situation, but that someone in front of you puts on an invisibility cloak. While viewing the line, it will look like there is an empty space, but people can't really fill that empty looking space because someone is still there. This is like visibility:hidden.

Difference between return and exit in Bash functions

return will cause the current function to go out of scope, while exit will cause the script to end at the point where it is called. Here is a sample program to help explain this:

#!/bin/bash

retfunc()
{
    echo "this is retfunc()"
    return 1
}

exitfunc()
{
    echo "this is exitfunc()"
    exit 1
}

retfunc
echo "We are still here"
exitfunc
echo "We will never see this"

Output

$ ./test.sh
this is retfunc()
We are still here
this is exitfunc()

php REQUEST_URI

I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

Is there an embeddable Webkit component for Windows / C# development?

Berkelium is a C++ tool for making chrome embeddable.

AwesomiumDotNet is a wrapper around both Berkelium and Awesomium

BTW, the link here to Awesomium appears to be more current.

What does getActivity() mean?

Two likely definitions:

Npm install failed with "cannot run in wd"

The only thing that worked for me was adding a .npmrc file containing:

unsafe-perm = true

Adding the same config to package.json didn't have any effect.

java.lang.OutOfMemoryError: Java heap space

  1. Local variables are located on the stack. Heap space is occupied by objects.

  2. You can use the -Xmx option.

  3. Basically heap space is used up everytime you allocate a new object with new and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.

Spring Boot how to hide passwords in properties file

You can use Jasypt to encrypt properties, so you could have your property like this:

db.password=ENC(XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=)

Jasypt allows you to encrypt your properties using different algorithms, once you get the encrypted property you put inside the ENC(...). For instance, you can encrypt this way through Jasypt using the terminal:

encrypted-pwd$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES

----ENVIRONMENT-----------------

Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08



----ARGUMENTS-------------------

algorithm: PBEWithMD5AndDES
input: contactspassword
password: supersecretz



----OUTPUT----------------------

XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=

To easily configure it with Spring Boot you can use its starter jasypt-spring-boot-starter with group ID com.github.ulisesbocchio

Keep in mind, that you will need to start your application using the same password you used to encrypt the properties. So, you can start your app this way:

mvn -Djasypt.encryptor.password=supersecretz spring-boot:run

Or using the environment variable (thanks to spring boot relaxed binding):

export JASYPT_ENCRYPTOR_PASSWORD=supersecretz
mvn spring-boot:run

You can check below link for more details:

https://www.ricston.com/blog/encrypting-properties-in-spring-boot-with-jasypt-spring-boot/

To use your encrypted properties in your app just use it as usual, use either method you like (Spring Boot wires the magic, anyway the property must be of course in the classpath):

Using @Value annotation

@Value("${db.password}")
private String password;

Or using Environment

@Autowired
private Environment environment;

public void doSomething(Environment env) {
    System.out.println(env.getProperty("db.password"));
}

Update: for production environment, to avoid exposing the password in the command line, since you can query the processes with ps, previous commands with history, etc etc. You could:

  • Create a script like this: touch setEnv.sh
  • Edit setEnv.sh to export the JASYPT_ENCRYPTOR_PASSWORD variable

    #!/bin/bash

    export JASYPT_ENCRYPTOR_PASSWORD=supersecretz

  • Execute the file with . setEnv.sh
  • Run the app in background with mvn spring-boot:run &
  • Delete the file setEnv.sh
  • Unset the previous environment variable with: unset JASYPT_ENCRYPTOR_PASSWORD

How to convert an object to JSON correctly in Angular 2 with TypeScript

If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:

<p> {{ product | json }} </p>

I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

MySQL > Table doesn't exist. But it does (or it should)

After having to reinstall MySQL I had this same problem, it seems that during the install, some configuration files that store data about the InnoDB log files, these files ib_logfile* (they are log files right?), are overwriten. To solve this problem I just deleted the ib_logfile* files.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

PyTypeObject PyDict_Type=
{ ...

PyTypeObject PyDict_Type=
{
  PyObject_HEAD_INIT(&PyType_Type),
                     "dict",
                     dict_print,
                     0,
                     0
}; 

watch the name field, in gcc it compile without warning, but in g++ it will, i don't know why.

in gcc (Compiling C), -Wno-write-strings is active by default.

in g++ (Compiling C++) -Wwrite-strings is active by default

This is why there is a different behaviour. For us using macros of Boost_python generates such warnings. So we use -Wno-write-strings when compiling C++ since we always use -Werror

check if "it's a number" function in Oracle

Here's a simple method which :

  • does not rely on TRIM
  • does not rely on REGEXP
  • allows to specify decimal and/or thousands separators ("." and "," in my example)
  • works very nicely on Oracle versions as ancient as 8i (personally tested on 8.1.7.4.0; yes, you read that right)
SELECT
    TEST_TABLE.*,

    CASE WHEN
        TRANSLATE(TEST_TABLE.TEST_COLUMN, 'a.,0123456789', 'a') IS NULL
    THEN 'Y'
    ELSE 'N'
    END
    AS IS_NUMERIC

FROM
    (
    -- DUMMY TEST TABLE
        (SELECT '1' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT '1,000.00' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT 'xyz1' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT 'xyz 123' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT '.,' AS TEST_COLUMN FROM DUAL)
    ) TEST_TABLE

Result:

TEST_COLUMN IS_NUMERIC
----------- ----------
.,          Y
1           Y
1,000.00    Y
xyz 123     N
xyz1        N

5 rows selected.

Granted this might not be the most powerful method of all; for example ".," is falsely identified as a numeric. However it is quite simple and fast and it might very well do the job, depending on the actual data values that need to be processed.

For integers, we can simplify the Translate operation as follows :

TRANSLATE(TEST_TABLE.TEST_COLUMN, 'a0123456789', 'a') IS NULL

How it works

From the above, note the Translate function's syntax is TRANSLATE(string, from_string, to_string). Now the Translate function cannot accept NULL as the to_string argument. So by specifying 'a0123456789' as the from_string and 'a' as the to_string, two things happen:

  • character a is left alone;
  • numbers 0 to 9 are replaced with nothing since no replacement is specified for them in the to_string.

In effect the numbers are discarded. If the result of that operation is NULL it means it was purely numbers to begin with.

Java; String replace (using regular expressions)?

Try this, may not be the best way. but it works

String str = "5 * x^3 - 6 * x^1 + 1";
str = str.replaceAll("(?x)(\\d+)(\\s+?\\*?\\s+?)(\\w+?)(\\^+?)(\\d+?)", "$1$3<sup>$5</sup>");
System.out.println(str);

Laravel view not found exception

In my case I had to run php artisan optimize:clear in order to make everything to work again.

Removing a non empty directory programmatically in C or C++

If you are using a POSIX compliant OS, you could use nftw() for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.

In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):

#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>

static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
{
    if(remove(pathname) < 0)
    {
        perror("ERROR: remove");
        return -1;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr,"usage: %s path\n",argv[0]);
        exit(1);
    }

    // Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links

    if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
    {
        perror("ERROR: ntfw");
        exit(1);
    }

    return 0;
}

Simple and fast method to compare images for similarity

If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.

Search for string within text column in MySQL

When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:

   $Table_Name    = $wpdb->prefix.'tablename';
   $SearchField = '%'. $YourVariable . '%';   
   $sql_query     = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
 $rows = $wpdb->get_results($sql_query, ARRAY_A);

AngularJS : Custom filters and ng-repeat

If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview

How do I specify a password to 'psql' non-interactively?

An alternative to using the PGPASSWORD environment variable is to use the conninfo string according to the documentation:

An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism give you very wide control over the connection.

$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>"

postgres=>

Argument of type 'X' is not assignable to parameter of type 'X'

In my case, strangely enough, I was missing the import of the class it was complaining about and my IDE didn't detect it.

How to fix div on scroll

On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.

Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/

$(document).ready(function () {
  var $obj = $('#comment');
  var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));

  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $obj.addClass('fixed');
    } else {
      // otherwise remove it
      $obj.removeClass('fixed');
    }
  });
});

Android Studio - How to increase Allocated Heap Size

Open studio.vmoptions and change JVM options

studio.vmoptions locates at /Applications/Android\ Studio.app/bin/studio.vmoptions (Mac OS). In my machine, it looks like

-Xms128m
-Xmx800m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

Change to

-Xms256m
-Xmx1024m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

And restart Android Studio

See more Android Studio website

Creating a list of dictionaries results in a list of copies of the same dictionary

info is a pointer to a dictionary - you keep adding the same pointer to your list contact.

Insert info = {} into the loop and it should solve the problem:

...
content = []
for iframe in soup.find_all('iframe'):
    info = {}
    info['src'] = iframe.get('src')
    info['height'] = iframe.get('height')
    info['width'] = iframe.get('width')
...

How can I get all the request headers in Django?

<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
  <code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}

Why has it failed to load main-class manifest attribute from a JAR file?

I faced the same problem. This unix command is not able to find the main class. This is because the runtime and compile time JDK versions are different. Make the jar through eclipse after changing the java compiler version. The following link helped me.

http://crunchify.com/exception-in-thread-main-java-lang-unsupportedclassversionerror-comcrunchifymain-unsupported-major-minor-version-51-0/

Try running the jar created after this step and then execute it

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

jQuery - How to dynamically add a validation rule

To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like

$("#DivIdContainer .classToValidate").each(function () {
    $(this).rules('add', {
        required: true
    });
});

How to see full absolute path of a symlink

realpath isn't available on all linux flavors, but readlink should be.

readlink -f symlinkName

The above should do the trick.

Alternatively, if you don't have either of the above installed, you can do the following if you have python 2.6 (or later) installed

python -c 'import os.path; print(os.path.realpath("symlinkName"))'

How to read/write from/to file using Go?

Try this:

package main

import (
  "io"; 
  )


func main() {
  contents,_ := io.ReadFile("filename");
  println(string(contents));
  io.WriteFile("filename", contents, 0644);
}

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

"Can't find Project or Library" for standard VBA functions

I've had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! - I suspect orphaned Excel processes are part of the problem)

The most efficient solution I had found has been to use Python with oletools https://github.com/decalage2/oletools/wiki/Install and extract the VBA code all the modules and save in a text file.

Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.

Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.

This has saved me when other methods haven't.

YMMV.

Targeting both 32bit and 64bit with Visual Studio in same solution/project

Not sure of the total answer to your question - but thought I would point out a comment in the Additional Information section of the SQL Compact 3.5 SP1 download page seeing you are looking at x64 - hope it helps.

Due to changes in SQL Server Compact SP1 and additional 64-bit version support, centrally installed and mixed mode environments of 32-bit version of SQL Server Compact 3.5 and 64-bit version of SQL Server Compact 3.5 SP1 can create what appear to be intermittent problems. To minimize the potential for conflicts, and to enable platform neutral deployment of managed client applications, centrally installing the 64-bit version of SQL Server Compact 3.5 SP1 using the Windows Installer (MSI) file also requires installing the 32-bit version of SQL Server Compact 3.5 SP1 MSI file. For applications that only require native 64-bit, private deployment of the 64-bit version of SQL Server Compact 3.5 SP1 can be utilized.

I read this as "include the 32bit SQLCE files as well as the 64bit files" if distributing for 64bit clients.

Makes life interesting I guess.. must say that I love the "what appears to be intermittent problems" line... sounds a bit like "you are imagining things, but just in case, do this..."

Check for special characters (/*-+_@&$#%) in a string?

Simple:

function HasSpecialChars(string yourString)
{
    return yourString.Any( ch => ! Char.IsLetterOrDigit( ch ) )
}

SQL Server: Importing database from .mdf?

If you do not have an LDF file then:

1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\

2) In ssms, go to Databases -> Attach and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.

3) Make sure the user you are running ssms.exe as has acccess to this MDF file.

4) Now that you know the DbName, run

EXEC sp_attach_single_file_db @dbname = 'DbName', 
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';

Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf

Need to ZIP an entire directory using Node.js

To pipe the result to the response object (scenarios where there is a need to download the zip rather than store locally)

 archive.pipe(res);

Sam's hints for accessing the content of the directory worked for me.

src: ["**/*"]

Android Get Application's 'Home' Data Directory

You can try Context.getApplicationInfo().dataDir if you want the package's persistent data folder.

getFilesDir() returns a subroot of this.

Best timing method in C?

gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.

Converting HTML files to PDF

If you have the funding, nothing beats Prince XML as this video shows

Where to put Gradle configuration (i.e. credentials) that should not be committed?

For those of you who are building on a MacOS, and don't like leaving your password in clear text on your machine, you can use the keychain tool to store the credentials and then inject it into the build. Credits go to Viktor Eriksson. https://pilloxa.gitlab.io/posts/safer-passwords-in-gradle/

Setting action for back button in navigation controller

Here's my Swift solution. In your subclass of UIViewController, override the navigationShouldPopOnBackButton method.

extension UIViewController {
    func navigationShouldPopOnBackButton() -> Bool {
        return true
    }
}

extension UINavigationController {

    func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
        if let vc = self.topViewController {
            if vc.navigationShouldPopOnBackButton() {
                self.popViewControllerAnimated(true)
            } else {
                for it in navigationBar.subviews {
                    let view = it as! UIView
                    if view.alpha < 1.0 {
                        [UIView .animateWithDuration(0.25, animations: { () -> Void in
                            view.alpha = 1.0
                        })]
                    }
                }
                return false
            }
        }
        return true
    }

}

Commit only part of a file in Git

Should you use emacs, take a look at Magit, which provides a git interface for emacs. It supports staging hunks (parts of files) quite well.

How to format background color using twitter bootstrap?

Just add a div around the container so it looks like:

<div style="background: red;">
  <div class="container marketing">
    <h2 style="padding-top: 60px;"></h2>
  </div>
</div>

How to run Nginx within a Docker container without halting?

Here you have an example of a Dockerfile that runs nginx. As mentionned by Charles, it uses the daemon off configuration:

https://github.com/darron/docker-nginx-php5/blob/master/Dockerfile#L17

Get Mouse Position

I am doing something like this to get mouse coordinates using Robot, I use these coordinates further in few of the games I am developing:

public class ForMouseOnly {
    public static void main(String[] args) throws InterruptedException {
        int x = MouseInfo.getPointerInfo().getLocation().x;
        int y = MouseInfo.getPointerInfo().getLocation().y;
        while (true) {

            if (x != MouseInfo.getPointerInfo().getLocation().x || y != MouseInfo.getPointerInfo().getLocation().y) {
                System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x + ", "
                        + MouseInfo.getPointerInfo().getLocation().y + ")");
                x = MouseInfo.getPointerInfo().getLocation().x;
                y = MouseInfo.getPointerInfo().getLocation().y;
            }
        }
    }
}

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Use Jackson-annotations.jar will solve the problem, as it worked for me.

No resource identifier found for attribute '...' in package 'com.app....'

This also happened to me when a PercentageRelativeLayout https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html was used and the build was targeting Android 0 = 26. PercentageRelativeLayout layout is obsolete starting from Android O and obviously sometime was changed in the resource generation. Replacing the layout with a ConstraintLayout or just a RelativeLayout solved it.

Using both Python 2.x and Python 3.x in IPython Notebook

I looked at this excellent info and then wondered, since

  1. i have python2, python3 and IPython all installed,
  2. i have PyCharm installed,
  3. PyCharm uses IPython for its Python Console,

if PyCharm would use

  1. IPython-py2 when Menu>File>Settings>Project>Project Interpreter == py2 AND
  2. IPython-py3 when Menu>File>Settings>Project>Project Interpreter == py3

ANSWER: Yes!

P.S. i have Python Launcher for Windows installed as well.

How To Set Text In An EditText

Solution in Android Java:

  1. Start your EditText, the ID is come to your xml id.

    EditText myText = (EditText)findViewById(R.id.my_text_id);
    
  2. in your OnCreate Method, just set the text by the name defined.

    String text = "here put the text that you want"
    
  3. use setText method from your editText.

    myText.setText(text); //variable from point 2
    

How to compare a local git branch with its remote branch?

Let's say you have already set up your origin as the remote repository. Then,

git diff <local branch> <origin>/<remote branch name>

Location Services not working in iOS 8

One common error for Swift developers:

First make sure you add a value to the plist for either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription.

If you are still not seeing a window pop up asking for authorization, look to see if you are putting the line var locationManager = CLLocationManager() in your View Controller's viewDidLoad method. If you do, then even if you call locationManager.requestWhenInUseAuthorization(), nothing will show up. This is because after viewDidLoad executes, the locationManager variable is deallocated (cleared out).

The solution is to locate the line var locationManager = CLLocationManager() at the top of the class method.

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

For testing I just run multiple instances of httpd on different IP addresses, so I have php7 running on 192.168.0.70 and php5.6 running on 192.168.0.56. In production I have a site running an old oscommerce running php5.3 and I just have a different conf file for the site

httpd -f /etc/apache2/php70.conf
httpd -f /etc/apache2/php53.conf

It's also a clean way to have different php.ini files for different sites. If you just have a couple of sites if a nice way to keep things organized and you don't have to worry about more then 1 site at a time when you upgrade something

Change Name of Import in Java, or import two classes with the same name

As the other answers already stated, Java does not provide this feature.

Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.

From the comments:

This is not an unreasonable request, though hardly essential. The occasional use of fully qualified names is not an undue burden (unless the library really reuses the same simple names right and left, which is bad style).

In any event, it doesn't pass the bar of price/performance for a language change.

So I guess we will not see this feature in Java anytime soon :-P

Git Ignores and Maven targets

I ignore all classes residing in target folder from git. add following line in open .gitignore file:

/.class

OR

*/target/**

It is working perfectly for me. try it.

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

How do I list one filename per output line in Linux?

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

Test if object implements interface

In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.

Best way to check for null values in Java?

Your last proposal is the best.

if (foo != null && foo.bar()) {
    etc...
}

Because:

  1. It is easier to read.
  2. It is safe : foo.bar() will never be executed if foo == null.
  3. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
  4. It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).

How to remove an item from an array in AngularJS scope?

Angular have a built-in function called arrayRemove, in your case the method can simply be:

arrayRemove($scope.persons, person)

Most simple code to populate JTable from ResultSet

With all factors put into consideration, with regard to code architecture using modular programming would work very well and with more simplicity in the code. Write a simple

getData() function @returns a 2D array of the data from the database.

pass this funtion to the constructor of the JTabel() constructor i.e

JTabel myTable = new JTable(getData(),columnsArray);

In this case the second argument: columnsArray is a single dimensional array that has the column names

String[] columns = {{"ID","DataOfBirth","Age","Grade","Marks","RegNumber"}};

pass the JTable object to a JScrollPane then you are done, right after adding the ScrollPane to the container ofcourse

JScrollPane scrollPane = new JScrollPane(myTable);

JFrame myFrame = new JFrame();
myFrame.add(scrollPane);

Here is a sample function getData() that queries the database for the data that later is passed on to the JTable

public String[][] getRecords() {
    try (Connection conect = DriverManager.getConnection("jdbc:mysql://localhost:3306/online_students_registration", "root", "")) {
        Statement stm = conect.createStatement();
        String SELECT_QUERY = "SELECT COUNT(*) FROM medicalrecords ;";
        ResultSet cursor = stm.executeQuery(SELECT_QUERY);
        while (cursor.next()) {
            rows = cursor.getInt("COUNT(*)");
            System.out.println("Table will have " + rows + " Rows");
        }
        System.err.println("Contacts row count is obtained!!");
        if (rows < 1) {
            JOptionPane.showMessageDialog(null, "There is NO DATA");
            //contactsRowsCount = 1;
            //System.out.println("Table rows succefully reset to  " + contactsRowsCount + " Rows");
            dataValues = new String[1][8];
            //dataValues[1][5] = "No Values";

            for (int i = 0; i < 1; i++) {
                for (int j = 0; j < 8; j++) {
                    if (j == 0) {
                        dataValues[i][j] = "No Details Available";
                        System.out.println("" + dataValues);
                    } else {
                        dataValues[i][j] = "...";
                        System.out.println("Contacts" + dataValues[i][j]);
                    }
                }
            }

            System.out.println("Return statement is being executed on 0 rows ");
            //return doctoredDataValues;
        } else if (rows > 0) {

            System.out.println("obtain contacts code is being run under  " + rows + " Rows");
            dataValues = new String[rows][8];    //declare array for contacts table data
            System.out.println("[ Line 1584 ]The dataValues object for the JTable succefully set");

            String SELECT_QUERY_CONTACT = "SELECT * FROM medicalrecords; ";

            //OBTAIN CONTACTS FROM DB WITH REGARD TO CONTACT CATEGORY SPECIFIED
            ResultSet contactsTableCursor = stm.executeQuery(SELECT_QUERY_CONTACT);
            //use iterator-algorithm to insert values into the JTable
            for (int i = 0; contactsTableCursor.next() && i < rows; i++) {
                for (int j = 0; j < 8; j++) {
                    dataValues[i][j] = contactsTableCursor.getString(j + 1);
                    System.out.println("Contacts" + dataValues[i][j]);
                }
            }
        }
        JOptionPane.showMessageDialog(null, "Medical Details Added Succefully!!");
    } catch (SQLException e) {

        JOptionPane.showMessageDialog(null, "Unable to Obtain contacts:Server is Offline(LINE 1568)" + e.getMessage());
    }

    return dataValues;

}

How can I count the number of elements with same class?

You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size

_x000D_
_x000D_
var parent = document.getElementById("parentId");_x000D_
var nodesSameClass = parent.getElementsByClassName("test");_x000D_
console.log(nodesSameClass.length);
_x000D_
<div id="parentId">_x000D_
  <p class="prueba">hello word1</p>_x000D_
  <p class="test">hello word2</p>_x000D_
  <p class="test">hello word3</p>_x000D_
  <p class="test">hello word4</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ValueError: math domain error

You may also use math.log1p.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using math.expm1 which returns e raised to the power x, minus 1.

html5 - canvas element - Multiple layers

No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Draw your first layer on the layer1 canvas, and the second layer on the layer2 canvas. Then when you clearRect on the top layer, whatever's on the lower canvas will show through.

Why use a ReentrantLock if one can use synchronized(this)?

Lets assume this code is running in a thread:

private static ReentrantLock lock = new ReentrantLock();

void accessResource() {
    lock.lock();
    if( checkSomeCondition() ) {
        accessResource();
    }
    lock.unlock();
}

Because the thread owns the lock it will allow multiple calls to lock(), so it re-enter the lock. This can be achieved with a reference count so it doesn't has to acquire lock again.

How to make Python speak

The python-espeak package is available in Debian, Ubuntu, Redhat, and other Linux distributions. It has recent updates, and works fine.

from espeak import espeak
espeak.synth("Hello world.")

Jonathan Leaders notes that it also works on Windows, and you can install the mbrola voices as well. See the espeak website at http://espeak.sourceforge.net

What are Maven goals and phases and what is their difference?

There are following three built-in build lifecycles:

  • default
  • clean
  • site

Lifecycle default -> [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]

Lifecycle clean -> [pre-clean, clean, post-clean]

Lifecycle site -> [pre-site, site, post-site, site-deploy]

The flow is sequential, for example, for default lifecycle, it starts with validate, then initialize and so on...

You can check the lifecycle by enabling debug mode of mvn i.e., mvn -X <your_goal>

How can I remove a key and its value from an associative array?

Use this function to remove specific arrays of keys without modifying the original array:

function array_except($array, $keys) {
  return array_diff_key($array, array_flip((array) $keys));   
} 

First param pass all array, second param set array of keys to remove.

For example:

$array = [
    'color' => 'red', 
    'age' => '130', 
    'fixed' => true
];
$output = array_except($array, ['color', 'fixed']);
// $output now contains ['age' => '130']

How do you loop through each line in a text file using a windows batch file?

Improving the first "FOR /F.." answer: What I had to do was to call execute every script listed in MyList.txt, so it worked for me:

for /F "tokens=*" %A in  (MyList.txt) do CALL %A ARG1

--OR, if you wish to do it over the multiple line:

for /F "tokens=*" %A in  (MuList.txt) do (
ECHO Processing %A....
CALL %A ARG1
)

Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:

---START of MyScript.bat---
@echo off
for /F "tokens=*" %%A in  ( MyList.TXT) do  (
   ECHO Processing %%A.... 
   CALL %%A ARG1 
)
@echo on
;---END of MyScript.bat---

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

How to hide Table Row Overflow?

Need to specify two attributes, table-layout:fixed on table and white-space:nowrap; on the cells. You also need to move the overflow:hidden; to the cells too

table { width:250px;table-layout:fixed; }
table tr { height:1em;  }
td { overflow:hidden;white-space:nowrap;  } 

Here's a Demo . Tested in Firefox 3.5.3 and IE 7

Angular.js How to change an elements css class on click and to remove all others

To me it seems like the best solution is to use a directive; there's no need for the controller to know that the view is being updated.

Javascript:

var app = angular.module('app', ['directives']);

angular.module('directives', []).directive('toggleClass', function () {
    var directiveDefinitionObject = {
        restrict: 'A',
        template: '<span ng-click="localFunction()" ng-class="selected"  ng-transclude></span>',
        replace: true,
        scope: {
            model: '='
        },
        transclude: true,
        link: function (scope, element, attrs) {
            scope.localFunction = function () {
                scope.model.value = scope.$id;
            };
            scope.$watch('model.value', function () {
                // Is this set to my scope?
                if (scope.model.value === scope.$id) {
                    scope.selected = "active";
                } else {
                    // nope
                    scope.selected = '';
                }
            });
        }
    };
    return directiveDefinitionObject;
});

HTML:

<div ng-app="app" ng-init="model = { value: 'dsf'}"> <span>Click a span... then click another</span>

<br/>
<br/>
<span toggle-class model="model">span1</span>

<br/><span toggle-class model="model">span2</span>

<br/><span toggle-class model="model">span3</span>

CSS:

.active {
     color:red;
 }

I have a fiddle that demonstrates. The idea is when a directive is clicked, a function is called on the directive that sets a variable to the current scope id. Then each directive also watches the same value. If the scope ID's match, then the current element is set to be active using ng-class.

The reason to use directives, is that you no longer are dependent on a controller. In fact I don't have a controller at all (I do define a variable in the view named "model"). You can then reuse this directive anywhere in your project, not just on one controller.

How to open a new file in vim in a new window

If you don't mind using gVim, you can launch a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance.

to do this you can write: gVim --remote-tab-silent file

You could always make an alias to this command so that you don't have to type so many words. For example I use linux and bash and in my ~/.bashrc file I have:

alias g='gvim --remote-tab-silent'

so instead of doing $ mate file I do: $ g file

How can I make a time delay in Python?

While everyone else has suggested the de facto time module, I thought I'd share a different method using matplotlib's pyplot function, pause.

An example

from matplotlib import pyplot as plt
plt.pause(5)    # Pauses the program for 5 seconds

Typically this is used to prevent the plot from disappearing as soon as it is plotted or to make crude animations.

This would save you an import if you already have matplotlib imported.

ConnectivityManager getNetworkInfo(int) deprecated

NetManager that you can use to check internet connection on Android with Kotlin

If you use minSdkVersion >= 23

class NetManager @Inject constructor(var applicationContext: Context) {
    val isConnectedToInternet: Boolean?
        get() = with(
            applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
                    as ConnectivityManager
        ) {
            isConnectedToInternet()
        }
}

fun ConnectivityManager.isConnectedToInternet() = isConnected(getNetworkCapabilities(activeNetwork))

fun isConnected(networkCapabilities: NetworkCapabilities?): Boolean {
    return when (networkCapabilities) {
        null -> false
        else -> with(networkCapabilities) { hasTransport(TRANSPORT_CELLULAR) || hasTransport(TRANSPORT_WIFI) }
    }
}

If you use minSdkVersion < 23

class NetManager @Inject constructor(var applicationContext: Context) {
    val isConnectedToInternet: Boolean?
        get() = with(
            applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)
                    as ConnectivityManager
        ) {
            isConnectedToInternet()
        }
}

fun ConnectivityManager.isConnectedToInternet(): Boolean = if (Build.VERSION.SDK_INT < 23) {
    isConnected(activeNetworkInfo)
} else {
    isConnected(getNetworkCapabilities(activeNetwork))
}


fun isConnected(network: NetworkInfo?): Boolean {
    return when (network) {
        null -> false
        else -> with(network) { isConnected && (type == TYPE_WIFI || type == TYPE_MOBILE) }
    }
}

fun isConnected(networkCapabilities: NetworkCapabilities?): Boolean {
    return when (networkCapabilities) {
        null -> false
        else -> with(networkCapabilities) { hasTransport(TRANSPORT_CELLULAR) || hasTransport(TRANSPORT_WIFI) }
    }
}

How to enable PHP's openssl extension to install Composer?

If you are using xampp .Go back to where you choose which command-line php you want to use at the beginning of your installation and select the path where your xampp folder is included.After that if your installer says youve got duplicate 'extension=php_openssl.dll' comment one ssl file in your php ini with a ';'and your installation should run smoothly.

Cannot run the macro... the macro may not be available in this workbook

In my case this error came up when the Sub name was identical to the Module name.

Should I test private methods or only public ones?

It's not only about public or private methods or functions, it is about implementation details. Private functions are just one aspect of implementation details.

Unit-testing, after all, is a white box testing approach. For example, whoever uses coverage analysis to identify parts of the code that have been neglected in testing so far, goes into the implementation details.

A) Yes, you should be testing implementation details:

Think of a sort function which for performance reasons uses a private implementation of BubbleSort if there are up to 10 elements, and a private implementation of a different sort approach (say, heapsort) if there are more than 10 elements. The public API is that of a sort function. Your test suite, however, better makes use of the knowledge that there are actually two sort algorithms used.

In this example, surely, you could perform the tests on the public API. This would, however, require to have a number of test cases that execute the sort function with more than 10 elements, such that the heapsort algorithm is sufficiently well tested. The existence of such test cases alone is an indication that the test suite is connected to the implementation details of the function.

If the implementation details of the sort function change, maybe in the way that the limit between the two sorting algorithms is shifted or that heapsort is replaced by mergesort or whatever: The existing tests will continue to work. Their value nevertheless is then questionable, and they likely need to be reworked to better test the changed sort function. In other words, there will be a maintenance effort despite the fact that tests were on the public API.

B) How to test implementation details

One reason why many people argue one should not test private functions or implementation details is, that the implementation details are more likely to change. This higher likelyness of change at least is one of the reasons for hiding implementation details behind interfaces.

Now, assume that the implementation behind the interface contains larger private parts for which individual tests on the internal interface might be an option. Some people argue, these parts should not be tested when private, they should be turned into something public. Once public, unit-testing that code would be OK.

This is interesting: While the interface was internal, it was likely to change, being an implementation detail. Taking the same interface, making it public does some magic transformation, namely turning it into an interface that is less likely to change. Obviously there is some flaw in this argumentation.

But, there is nevertheless some truth behind this: When testing implementation details, in particular using internal interfaces, one should strive to use interfaces that are likely to remain stable. Whether some interface is likely to be stable is, however, not simply decidable based on whether it is public or private. In the projects from world I have been working in for some time, public interfaces also often enough change, and many private interfaces have remained untouched for ages.

Still, it is a good rule of thumb to use the "front door first" (see http://xunitpatterns.com/Principles%20of%20Test%20Automation.html). But keep in mind that it is called "front door first" and not "front door only".

C) Summary

Test also the implementation details. Prefer testing on stable interfaces (public or private). If implementation details change, also tests on the public API need to be revised. Turning something private into public does not magically change its stability.

case-insensitive matching in xpath?

One possible PHP solution:

// load XML to SimpleXML
$x = simplexml_load_string($xmlstr);

// index it by title once
$index = array();
foreach ($x->CD as &$cd) {
  $title = strtolower((string)$cd['title']); 
  if (!array_key_exists($title, $index)) $index[$title] = array();
  $index[$title][] = &$cd;
}

// query the index 
$result = $index[strtolower("EMPIRE BURLESQUE")];

Read user input inside a loop

You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:

{ cat notify-finished | while read line; do
    read -u 3 input
    echo "$input"
done; } 3<&0

BTW, if you really are using cat this way, replace it with a redirect and things become even easier:

while read line; do
    read -u 3 input
    echo "$input"
done 3<&0 <notify-finished

Or, you can swap stdin and unit 3 in that version -- read the file with unit 3, and just leave stdin alone:

while read line <&3; do
    # read & use stdin normally inside the loop
    read input
    echo "$input"
done 3<notify-finished

Get names of all keys in the collection

I am surprise, no one here has ans by using simple javascript and Set logic to automatically filter the duplicates values, simple example on mongo shellas below:

var allKeys = new Set()
db.collectionName.find().forEach( function (o) {for (key in o ) allKeys.add(key)})
for(let key of allKeys) print(key)

This will print all possible unique keys in the collection name: collectionName.

Delete many rows from a table using id in Mysql

The best way is to use IN statement :

DELETE from tablename WHERE id IN (1,2,3,...,254);

You can also use BETWEEN if you have consecutive IDs :

DELETE from tablename WHERE id BETWEEN 1 AND 254;

You can of course limit for some IDs using other WHERE clause :

DELETE from tablename WHERE id BETWEEN 1 AND 254 AND id<>10;

How to find all combinations of coins when given some dollar value

public static int calcCoins(int cents){
        return coins(cents,new int[cents+1]);
    }
    public static int coins(int cents,int[] memo){
        if(memo[cents] != 0){
            return -1;
        }
        int sum = 0;
        int arr[] = {25,10,5,1};

        for (int i = 0; i < arr.length; i++) {
            if(cents/arr[i] != 0){
                int temp = coins(cents-arr[i],memo);
                if(temp == 0){
                    sum+=1;
                } else if(temp == -1){
                    sum +=0;
                }
                else{
                    sum += temp;
                }
            } 
        }
        memo[cents] = sum;
        return sum;
    }

custom facebook share button

The best way is to use your code and then store the image in OG tags in the page you are linking to, then Facebook will pick them up.

<meta property="og:title" content="Facebook Open Graph Demo">
<meta property="og:image" content="http://example.com/main-image.png">
<meta property="og:site_name" content="Example Website">
<meta property="og:description" content="Here is a nice description">

You can find documentation to OG tags and how to use them with share buttons here

IntelliJ: Working on multiple projects

To expand @Neo answer: after choosing your directory. select import module from external model and choose your model (maven in this case).

choose model

Then check keep project files option from next dialog. It will keep all files in original directory.

options

Your final project structure would be something like this.

structure

Now you can add your module as dependency to other module's pom.xml and if you change the source code of your dependencies, Intellij takes care of updating your project (there is no need to run mvn build manually for dependencies)

Command-line Git on Windows

These instructions worked for a Windows 8 with a msysgit/TortoiseGit installation, but should be applicable for other types of git installations on Windows.

  • Go to Control Panel\System and Security\System
  • Click on Advanced System Settings on the left which opens System Properties.
  • Click on the Advanced Tab
  • Click on the Environment Variables button at the bottom of the dialog box.
  • Edit the System Variable called PATH.
  • Append these two paths to the list of existing paths already present in the system variable. The tricky part was two paths were required. These paths may vary for your PC. ;C:\msysgit\bin\;C:\msysgit\mingw\bin\
  • Close the CMD prompt window if it is open already. CMD needs to restart to get the updated Path variable.
  • Try typing git in the command line, you should see a list of the git commands scroll down the screen.

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

How to use LogonUser properly to impersonate domain user from workgroup client

Very few posts suggest using LOGON_TYPE_NEW_CREDENTIALS instead of LOGON_TYPE_NETWORK or LOGON_TYPE_INTERACTIVE. I had an impersonation issue with one machine connected to a domain and one not, and this fixed it. The last code snippet in this post suggests that impersonating across a forest does work, but it doesn't specifically say anything about trust being set up. So this may be worth trying:

const int LOGON_TYPE_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_WINNT50 = 3;
bool returnValue = LogonUser(user, domain, password,
            LOGON_TYPE_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50,
            ref tokenHandle);

MSDN says that LOGON_TYPE_NEW_CREDENTIALS only works when using LOGON32_PROVIDER_WINNT50.

What are the advantages of NumPy over regular Python lists?

NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.

For example, you could read your cube directly from a file into an array:

x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100))

Sum along the second dimension:

s = x.sum(axis=1)

Find which cells are above a threshold:

(x > 0.5).nonzero()

Remove every even-indexed slice along the third dimension:

x[:, :, ::2]

Also, many useful libraries work with NumPy arrays. For example, statistical analysis and visualization libraries.

Even if you don't have performance problems, learning NumPy is worth the effort.

No module named Image

You are missing PIL (Python Image Library and Imaging package). To install PIL I used

 pip install pillow

For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:

    $ gunzip Imaging-1.1.6.tar.gz
    $ tar xvf Imaging-1.1.6.tar
    $ cd Imaging-1.1.6
    $ python setup.py install

Or if you have PIP installed in your Mac

 pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz

then you can use:

from PIL import Image

in your python code.

How to show loading spinner in jQuery?

For jQuery I use

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show();
  },
  complete: function(){
     $('#loader').hide();
  },
  success: function() {}
});

Is there a performance difference between i++ and ++i in C?

I always prefer pre-increment, however ...

I wanted to point out that even in the case of calling the operator++ function, the compiler will be able to optimize away the temporary if the function gets inlined. Since the operator++ is usually short and often implemented in the header, it is likely to get inlined.

So, for practical purposes, there likely isn't much of a difference between the performance of the two forms. However, I always prefer pre-increment since it seems better to directly express what I"m trying to say, rather than relying on the optimizer to figure it out.

Also, giving the optmizer less to do likely means the compiler runs faster.

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Add a background image to shape in XML Android

I used the following for a drawable image with a circular background.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorAccent"/>
        </shape>
    </item>
    <item
        android:drawable="@drawable/ic_select"
        android:bottom="20dp"
        android:left="20dp"
        android:right="20dp"
        android:top="20dp"/>
</layer-list>

Here is what it looks like

enter image description here

Hope that helps someone out.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

This is not an error message but a warning. It is very clearly explained in their website as :

This warning, i.e. not an error, message is reported when no SLF4J providers could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem. Note that these providers must target slf4j-api 1.8 or later.

In the absence of a provider, SLF4J will default to a no-operation (NOP) logger provider.

https://www.slf4j.org/codes.html#StaticLoggerBinder

How to append multiple values to a list in Python

letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
... 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
    

Laravel Password & Password_Confirmation Validation

Try doing it this way, it worked for me:

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`

Seems like the rule always has the validation on the first input among the pair...

How can I delete all of my Git stashes at once?

this command enables you to look all stashed changes.

git stash list

Here is the following command use it to clear all of your stashed Changes

git stash clear

Now if you want to delete one of the stashed changes from stash area

git stash drop stash@{index}   // here index will be shown after getting stash list.

Note : git stash list enables you to get index from stash area of git.

memcpy() vs memmove()

Both memcpy and memove do similar things.

But to sight out one difference:

#include <memory.h>
#include <string.h>
#include <stdio.h>

char str1[7] = "abcdef";

int main()
{

   printf( "The string: %s\n", str1 );
   memcpy( (str1+6), str1, 10 );
   printf( "New string: %s\n", str1 );

   strcpy_s( str1, sizeof(str1), "aabbcc" );   // reset string


   printf("\nstr1: %s\n", str1);
   printf( "The string: %s\n", str1 );
   memmove( (str1+6), str1, 10 );
   printf( "New string: %s\n", str1 );

}

gives:

The string: abcdef
New string: abcdefabcdefabcd
The string: abcdef
New string: abcdefabcdef

Pass path with spaces as parameter to bat file

@echo off
setlocal enableextensions enabledelayedexpansion

if %1=="" (     
        rem Set default path
        set PWA_PATH="C:\Program Files\PWA"
        rem
        echo You have not specified your PWA url.
        echo Default will be assumed: C:\Program Files\PWA.     
        choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
                IF ERRORLEVEL ==2 GOTO CANCEL
                IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
        GOTO END
    ) else (
        set PWA_PATH=%1
        @echo !PWA_PATH! vs. %1
        goto end
    )
:READ_WSS_SERVER_EXTENSIONS_PATH
echo ok
goto end
:CANCEL
echo cancelled
:end
echo. final %PWA_PATH% vs. %1

As VardhanDotNet mentions, %1 is enough.

"%1%" would add quotes around quotes: ""c:\Program Files\xxx"" which means:

  • 'empty string' (""),
  • followed by 'c:\Program',
  • followed by the "unexpected here" 'Files\xxx',
  • followed by an empty string ("")

Note however that if you need to use PWA_PATH within your IF clause, you need to refer if as !PWA_PATH! (hence the enabledelayedexpansion as the beginning of the script)

Directory index forbidden by Options directive

Either the main httpd.conf or the .htaccess file in this directory or a nearby parent directory probably includes:

Options -Indexes

Your host may have to set it to +Indexes if you don't have access in .htaccess and want to list & browse the directory contents, absent a default index.html, index.php, etc. If the directory should not have a default file and you don't enable Indexes, you may only directly target the filenames of contents within it.

The Indexes option is commonly disabled by default on many Apache installations.

Full details are available in the Apache core documentation on Options

percentage of two int?

Two options:

Do the division after the multiplication:

int n = 25;
int v = 100;
int percent = n * 100 / v;

Convert an int to a float before dividing

int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
//  float percent = (float) n * 100 / v;
//  float percent = n * 100 / (float) v;

How to generate random positive and negative numbers in Java

In case folks are interested in the double version (note this breaks down if passed MAX_VALUE or MIN_VALUE):

private static final Random generator = new Random();
public static double random(double min, double max) {
    return min + (generator.nextDouble() * (max - min));
 }

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

How to open up a form from another form in VB.NET?

You can also use showdialog

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                      Handles Button3.Click

     dim mydialogbox as new aboutbox1
     aboutbox1.showdialog()

End Sub

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

The request method getRequestDispatcher() can be used for referring to local servlets within single webapp.

Servlet context based getRequestDispatcher() method can used of referring servlets from other web applications deployed on SAME server.

How can I access an internal class from an external assembly?

Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).

You've described it as a public instance field; to get this via reflection:

object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);

If it is actually a property (not a field):

string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);

If it is non-public, you'll need to use the BindingFlags overload of GetField/GetProperty.

Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?

Change some value inside the List<T>

I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:

 foreach (var mc in list.Where(x => x.Name == "height"))  
     mc.Value = 30;

How to restart Jenkins manually?

This can also be done using the Jenkins CLI:

java -jar jenkins-cli.jar -s http://[jenkins-server]/ restart

The jenkins-cli.jar file along with a full list of commands are available at http://[jenkins-server]/cli.

Transport security has blocked a cleartext HTTP

How to fix it?

enter image description here

Below steps to fix it.

enter image description here enter image description here enter image description here enter image description here enter image description here

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

The standard Sun JDK for linux has an absolutely ok cacerts and overall all files in the specified directory. The problem is the installation you use.

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Importing large sql file to MySql via command line

You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between <-p> and <password>

Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p asks you to input password by standard input.

Why do Twitter Bootstrap tables always have 100% width?

All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span* grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:

.table-nonfluid {
   width: auto !important;
}

You can add this class inside your own stylesheet and simply add it to the container of your table like so:

<table class="table table-nonfluid"> ... </table>

This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).

Hosting ASP.NET in IIS7 gives Access is denied?

In the Authentication settings for APP itself (IN IIS), see if you have anonymous enabled.

Get all variables sent with POST?

you should be able to access them from $_POST variable:

foreach ($_POST as $param_name => $param_val) {
    echo "Param: $param_name; Value: $param_val<br />\n";
}

How to use vagrant in a proxy environment?

On windows, you must set a variable to specify proxy settings, download the vagrant-proxyconf plugin: (replace {PROXY_SCHEME}(http:// or https://), {PROXY_IP} and {PROXY_PORT} by the right values)

set http_proxy={PROXY_SCHEME}{PROXY_IP}:{PROXY_PORT}
set https_proxy={PROXY_SCHEME}{PROXY_IP}:{PROXY_PORT}

After that, you can add the plugin to hardcode your proxy settings in the vagrant file

vagrant plugin install vagrant-proxyconf --plugin-source http://rubygems.org

and then you can provide config.proxy.xxx settings in your Vagrantfile to be independent against environment settings variables

Equivalent of typedef in C#

Both C++ and C# are missing easy ways to create a new type which is semantically identical to an exisiting type. I find such 'typedefs' totally essential for type-safe programming and its a real shame c# doesn't have them built-in. The difference between void f(string connectionID, string username) to void f(ConID connectionID, UserName username) is obvious ...

(You can achieve something similar in C++ with boost in BOOST_STRONG_TYPEDEF)

It may be tempting to use inheritance but that has some major limitations:

  • it will not work for primitive types
  • the derived type can still be casted to the original type, ie we can send it to a function receiving our original type, this defeats the whole purpose
  • we cannot derive from sealed classes (and ie many .NET classes are sealed)

The only way to achieve a similar thing in C# is by composing our type in a new class:

Class SomeType { 
  public void Method() { .. }
}

sealed Class SomeTypeTypeDef {
  public SomeTypeTypeDef(SomeType composed) { this.Composed = composed; }

  private SomeType Composed { get; }

  public override string ToString() => Composed.ToString();
  public override int GetHashCode() => HashCode.Combine(Composed);
  public override bool Equals(object obj) => obj is TDerived o && Composed.Equals(o.Composed); 
  public bool Equals(SomeTypeTypeDefo) => object.Equals(this, o);

  // proxy the methods we want
  public void Method() => Composed.Method();
}

While this will work it is very verbose for just a typedef. In addition we have a problem with serializing (ie to Json) as we want to serialize the class through its Composed property.

Below is a helper class that uses the "Curiously Recurring Template Pattern" to make this much simpler:

namespace Typedef {

  [JsonConverter(typeof(JsonCompositionConverter))]
  public abstract class Composer<TDerived, T> : IEquatable<TDerived> where TDerived : Composer<TDerived, T> {
    protected Composer(T composed) { this.Composed = composed; }
    protected Composer(TDerived d) { this.Composed = d.Composed; }

    protected T Composed { get; }

    public override string ToString() => Composed.ToString();
    public override int GetHashCode() => HashCode.Combine(Composed);
    public override bool Equals(object obj) => obj is Composer<TDerived, T> o && Composed.Equals(o.Composed); 
    public bool Equals(TDerived o) => object.Equals(this, o);
  }

  class JsonCompositionConverter : JsonConverter {
    static FieldInfo GetCompositorField(Type t) {
      var fields = t.BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      if (fields.Length!=1) throw new JsonSerializationException();
      return fields[0];
    }

    public override bool CanConvert(Type t) {
      var fields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy);
      return fields.Length == 1;
    }

    // assumes Compositor<T> has either a constructor accepting T or an empty constructor
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      while (reader.TokenType == JsonToken.Comment && reader.Read()) { };
      if (reader.TokenType == JsonToken.Null) return null; 
      var compositorField = GetCompositorField(objectType);
      var compositorType = compositorField.FieldType;
      var compositorValue = serializer.Deserialize(reader, compositorType);
      var ctorT = objectType.GetConstructor(new Type[] { compositorType });
      if (!(ctorT is null)) return Activator.CreateInstance(objectType, compositorValue);
      var ctorEmpty = objectType.GetConstructor(new Type[] { });
      if (ctorEmpty is null) throw new JsonSerializationException();
      var res = Activator.CreateInstance(objectType);
      compositorField.SetValue(res, compositorValue);
      return res;
    }

    public override void WriteJson(JsonWriter writer, object o, JsonSerializer serializer) {
      var compositorField = GetCompositorField(o.GetType());
      var value = compositorField.GetValue(o);
      serializer.Serialize(writer, value);
    }
  }

}

With Composer the above class becomes simply:

sealed Class SomeTypeTypeDef : Composer<SomeTypeTypeDef, SomeType> {
   public SomeTypeTypeDef(SomeType composed) : base(composed) {}

   // proxy the methods we want
   public void Method() => Composed.Method();
}

And in addition the SomeTypeTypeDef will serialize to Json in the same way that SomeType does.

Hope this helps !

UICollectionView - Horizontal scroll, horizontal layout?

If you need to set the UICollectionView scrolling Direction Horizental and you need to set cell width and height static. Please set the collectionview estimate size Automatic into None .

View The ScreenShot

Zoom to fit: PDF Embedded in HTML

This method uses "object", it also has "embed". Either method works:

<div id="pdf">
    <object id="pdf_content" width="100%" height="1500px" type="application/pdf" trusted="yes" application="yes" title="Assembly" data="Assembly.pdf?#zoom=100&scrollbar=1&toolbar=1&navpanes=1">
    <!-- <embed src="Assembly.pdf" width="100%" height="100%" type="application/x-pdf" trusted="yes" application="yes" title="Assembly">
    </embed> -->
    <p>System Error - This PDF cannot be displayed, please contact IT.</p>
    </object>
</div>

How does the "view" method work in PyTorch?

Let's try to understand view by the following examples:

    a=torch.range(1,16)

print(a)

    tensor([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12., 13., 14.,
            15., 16.])

print(a.view(-1,2))

    tensor([[ 1.,  2.],
            [ 3.,  4.],
            [ 5.,  6.],
            [ 7.,  8.],
            [ 9., 10.],
            [11., 12.],
            [13., 14.],
            [15., 16.]])

print(a.view(2,-1,4))   #3d tensor

    tensor([[[ 1.,  2.,  3.,  4.],
             [ 5.,  6.,  7.,  8.]],

            [[ 9., 10., 11., 12.],
             [13., 14., 15., 16.]]])
print(a.view(2,-1,2))

    tensor([[[ 1.,  2.],
             [ 3.,  4.],
             [ 5.,  6.],
             [ 7.,  8.]],

            [[ 9., 10.],
             [11., 12.],
             [13., 14.],
             [15., 16.]]])

print(a.view(4,-1,2))

    tensor([[[ 1.,  2.],
             [ 3.,  4.]],

            [[ 5.,  6.],
             [ 7.,  8.]],

            [[ 9., 10.],
             [11., 12.]],

            [[13., 14.],
             [15., 16.]]])

-1 as an argument value is an easy way to compute the value of say x provided we know values of y, z or the other way round in case of 3d and for 2d again an easy way to compute the value of say x provided we know values of y or vice versa..

Git add and commit in one command

In the later version of git you can add and commit like this

git commit -a -m "commit message"

Additionally you an alias:

[alias]
    ac = commit -a -m

Then you can use it like this:

git ac "commit message"

how to mysqldump remote db from local machine

One can invoke mysqldump locally against a remote server.

Example that worked for me:

mysqldump -h hostname-of-the-server -u mysql_user -p database_name > file.sql

I followed the mysqldump documentation on connection options.

How to save a bitmap on internal storage

You might be able to use the following for decoding, compressing and saving an image:

     @Override
     public void onClick(View view) {
                onItemSelected1();
                InputStream image_stream = null;
                try {
                    image_stream = getContentResolver().openInputStream(myUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap image= BitmapFactory.decodeStream(image_stream );
                // path to sd card
                File path=Environment.getExternalStorageDirectory();
                //create a file
                File  dir=new File(path+"/ComDec/");
                dir.mkdirs();
                Date date=new Date();
                File file=new File(dir,date+".jpg");

                OutputStream out=null;
                try{
                    out=new FileOutputStream(file);
                    image.compress(format,size,out);
                    out.flush();
                    out.close();


                    MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");

                    image=null;


                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
            }
        });

CSS div element - how to show horizontal scroll bars only?

To show both:

<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: scroll; padding-bottom:10px;">      </div>

Hide X Axis:

<div style="height:250px; width:550px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;">      </div>

Hide Y Axis:

<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;">      </div>

java SSL and cert keystore

Just a word of caution. If you are trying to open an existing JKS keystore in Java 9 onwards, you need to make sure you mention the following properties too with value as "JKS":

javax.net.ssl.keyStoreType
javax.net.ssl.trustStoreType

The reason being that the default keystore type as prescribed in java.security file has been changed to pkcs12 from jks from Java 9 onwards.

React JS onClick event handler

_x000D_
_x000D_
import React from 'react';_x000D_
_x000D_
class MyComponent extends React.Component {_x000D_
_x000D_
  getComponent(event) {_x000D_
      event.target.style.backgroundColor = '#ccc';_x000D_
      _x000D_
      // or you can write_x000D_
      //arguments[0].target.style.backgroundColor = '#ccc';_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
       <div>_x000D_
         <ul>_x000D_
            <li onClick={this.getComponent.bind(this)}>Component 1</li>_x000D_
         </ul>_x000D_
       </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
export { MyComponent };  // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'_x000D_
export default MyComponent;
_x000D_
_x000D_
_x000D_

Twitter Bootstrap - full width navbar

Not sure if the navbar-static-top class was available prior to version 2.2.2 but I think you can accomplish your goal with the following:

<div class="navbar navbar-static-top">
    <div class="navbar-inner">
        <ul class="nav">
            <li class="active"><a href="#">Test1</a></li>
            <li><a href="#">Test2</a></li>
            <li><a href="#">Test3</a></li>
            <li><a href="#">Test4</a></li>
            <li><a href="#">Test5</a></li>
        </ul>
    </div>
</div>
<div class="container">
    ...
</div>

I put together a jsFiddle as an example.

Configuring Hibernate logging using Log4j XML config file?

Here's what I use:

<logger name="org.hibernate">
    <level value="warn"/>
</logger>

<logger name="org.hibernate.SQL">
    <level value="warn"/>
</logger>

<logger name="org.hibernate.type">
    <level value="warn"/>
</logger>

<root>
    <priority value="info"/>
    <appender-ref ref="C1"/>
</root> 

Obviously, I don't like to see Hibernate messages ;) -- set the level to "debug" to get the output.

What is the purpose of backbone.js?

JQuery and Mootools are just a toolbox with lot of tools of your project. Backbone acts like an architecture or a backbone for your project on which you can build an application using JQuery or Mootools.

do { ... } while (0) — what is it good for?

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

Creating a range of dates in Python

Marginally better...

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

Quote from xlsxwriter module documentation:

This module cannot be used to modify or write to an existing Excel XLSX file.

If you want to modify existing xlsx workbook, consider using openpyxl module.

See also:

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Why is System.Web.Mvc not listed in Add References?

Check these step:

  1. Check MVC is installed properly.
  2. Check the project's property and see what is the project Target Framework. If the target framework is not set to .Net Framework 4, set it.

Note: if target framework is set to .Net Framework 4 Client Profile, it will not list MVC reference on references list. You can find different between .Net Framework 4 and .Net Framework 4 Client Profile here.

The .NET Framework 4 Client Profile is a subset of the .NET Framework 4 that is optimized for client applications. It provides functionality for most client applications, including Windows Presentation Foundation (WPF), Windows Forms, Windows Communication Foundation (WCF), and ClickOnce features. This enables faster deployment and a smaller install package for applications that target the .NET Framework 4 Client Profile.

PHP sessions default timeout

Yes, that's usually happens after 1440s (24 minutes)

Installing and Running MongoDB on OSX

Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:

Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed

The easiest solution is to open the terminal and type

$ mongod --dbpath ~/data/db

Note: dbpath here is "Users/user" where data/db directories are created

i.e., you need to create directory data and sub directory db in your user folder. For e.g say `

/Users/johnny/data

After mongo db is up. Open another terminal in new window and type

$ mongo

it will open mongo shell with your mongo db connection opened in another terminal.

Why should I use core.autocrlf=true in Git?

The only specific reasons to set autocrlf to true are:

  • avoid git status showing all your files as modified because of the automatic EOL conversion done when cloning a Unix-based EOL Git repo to a Windows one (see issue 83 for instance)
  • and your coding tools somehow depends on a native EOL style being present in your file:

Unless you can see specific treatment which must deal with native EOL, you are better off leaving autocrlf to false (git config --global core.autocrlf false).

Note that this config would be a local one (because config isn't pushed from repo to repo)

If you want the same config for all users cloning that repo, check out "What's the best CRLF handling strategy with git?", using the text attribute in the .gitattributes file.

Example:

*.vcproj    text eol=crlf
*.sh        text eol=lf

Note: starting git 2.8 (March 2016), merge markers will no longer introduce mixed line ending (LF) in a CRLF file.
See "Make Git use CRLF on its “<<<<<<< HEAD” merge lines"

Replace only some groups with Regex

If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.

var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);

var firstPart = text.Substring(0,match.Groups[1].Index);    
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;

Go to Matching Brace in Visual Studio?

I found this for you: Jump between braces in Visual Studio:

Put your cursor before or after the brace (your choice) and then press CTRL + ]. It works with parentheses ( ), brackets [ ] and braces { }. From now on you don’t need to play Where’s Waldo? to find that brace.

On MacOS, use CMD + SHIFT + \

Get counts of all tables in a schema

This can be done with a single statement and some XML magic:

select table_name, 
       to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'FOOBAR'

How to convert date to timestamp in PHP?

function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
    $return = false;
    $_timezone = date_default_timezone_get();
    date_default_timezone_set( $timezone );
    if( preg_match( $expression, $date, $matches ) )
        $return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
    date_default_timezone_set( $_timezone );
    return $return;
}

// expression may need changing in relation to timezone
echo date_to_stamp('19/03/1986', false) . '<br />';
echo date_to_stamp('19**03**1986', false) . '<br />';
echo date_to_stamp('19.03.1986') . '<br />';
echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';
echo date('Y-m-d h:i:s') . '<br />';

//1986-03-19 02:37:30
//1986-03-19 02:37:30
//1986-03-19 00:00:00
//1986-03-19 05:37:30
//2012-02-12 02:37:30

If condition inside of map() React

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

Update multiple columns in SQL

Your query is nearly correct. The T-SQL for this is:

UPDATE  Table1
SET     Field1 = Table2.Field1,
        Field2 = Table2.Field2,
        other columns...
FROM    Table2
WHERE   Table1.ID = Table2.ID

target="_blank" vs. target="_new"

This may have been asked before but:

"every link that specifies target="_new" looks for and finds that window by name, and opens in it.

If you use target="_blank," a brand new window will be created each time, on top of the current window."

from here: http://thedesignspace.net/MT2archives/000316.html

Sort ObservableCollection<string> through C#

Here is a slight variation on Shimmy's one for collection of classes that already implement the well-known IComparable<T> interface. In this case, the "order by" selector is implicit.

public class SortedObservableCollection<T> : ObservableCollection<T> where T : IComparable<T>
{
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnCollectionChanged(e);
        if (e.Action != NotifyCollectionChangedAction.Reset &&
            e.Action != NotifyCollectionChangedAction.Move &&
            e.Action != NotifyCollectionChangedAction.Remove)
        {
            var query = this.Select((item, index) => (Item: item, Index: index)).OrderBy(tuple => tuple.Item, Comparer.Default);
            var map = query.Select((tuple, index) => (OldIndex: tuple.Index, NewIndex: index)).Where(o => o.OldIndex != o.NewIndex);
            using (var enumerator = map.GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    base.MoveItem(enumerator.Current.OldIndex, enumerator.Current.NewIndex);
                }
            }
        }
    }

    // (optional) user is not allowed to move items in a sorted collection
    protected override void MoveItem(int oldIndex, int newIndex) => throw new InvalidOperationException();
    protected override void SetItem(int index, T item) => throw new InvalidOperationException();

    private class Comparer : IComparer<T>
    {
        public static readonly Comparer Default = new Comparer();

        public int Compare(T x, T y) => x.CompareTo(y);
    }

    // explicit sort; sometimes needed.
    public virtual void Sort()
    {
        if (Items.Count <= 1)
            return;

        var items = Items.ToList();
        Items.Clear();
        items.Sort();
        foreach (var item in items)
        {
            Items.Add(item);
        }
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

Function for C++ struct

Structs can have functions just like classes. The only difference is that they are public by default:

struct A {
    void f() {}
};

Additionally, structs can also have constructors and destructors.

struct A {
    A() : x(5) {}
    ~A() {}

    private: int x;
};

Delete keychain items when an app is uninstalled

There is no trigger to perform code when the app is deleted from the device. Access to the keychain is dependant on the provisioning profile that is used to sign the application. Therefore no other applications would be able to access this information in the keychain.

It does not help with you aim to remove the password in the keychain when the user deletes application from the device but it should give you some comfort that the password is not accessible (only from a re-install of the original application).

AngularJS - Access to child scope

Using $emit and $broadcast, (as mentioned by walv in the comments above)

To fire an event upwards (from child to parent)

$scope.$emit('myTestEvent', 'Data to send');

To fire an event downwards (from parent to child)

$scope.$broadcast('myTestEvent', {
  someProp: 'Sending you some data'
});

and finally to listen

$scope.$on('myTestEvent', function (event, data) {
  console.log(data);
});

For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Enjoy :)

What is this date format? 2011-08-12T20:17:46.384Z

If you guys are looking for a solution for Android, you can use the following code to get the epoch seconds from the timestamp string.

public static long timestampToEpochSeconds(String srcTimestamp) {
    long epoch = 0;

    try {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Instant instant = Instant.parse(srcTimestamp);
            epoch = instant.getEpochSecond();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date date = sdf.parse(srcTimestamp);
            if (date != null) {
                epoch = date.getTime() / 1000;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return epoch;
}

Sample input: 2019-10-15T05:51:31.537979Z

Sample output: 1571128673