Programs & Examples On #Dehl

DeHL is a library making use of advanced features (Generics and Anonymous Methods) introduced in recent Delphi versions.

Decreasing height of bootstrap 3.0 navbar

if you are using the less source, there should be a variable for the navbar height in the variables.less file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

How to Lock/Unlock screen programmatically?

The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.

Thanks all for this helpful question!

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kns"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LockScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyAdmin"
                android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data android:name="android.app.device_admin"
                       android:resource="@xml/policies" />
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

policies.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
    </uses-policies>
</device-admin>

How to scale a BufferedImage

scale(..) works a bit differently. You can use bufferedImage.getScaledInstance(..)

ENOENT, no such file or directory

I had that issue : use path module

const path = require('path');

and also do not forget to create the uploads directory first period.

Javascript Image Resize

Tried the following code, worked OK on IE6 on WinXP Pro SP3.

function Resize(imgId)
{
  var img = document.getElementById(imgId);
  var w = img.width, h = img.height;
  w /= 2; h /= 2;
  img.width = w; img.height = h;
}

Also OK in FF3 and Opera 9.26.

What is the Maximum Size that an Array can hold?

I think if you don't consider the VM, it is Integer.MaxValue

External resource not being loaded by AngularJs

Another simple solution is to create a filter:

app.filter('trusted', ['$sce', function ($sce) {
    return function(url) {
        return $sce.trustAsResourceUrl(url);
    };
}]);

Then specify the filter in ng-src:

<video controls poster="img/poster.png">
       <source ng-src="{{object.src | trusted}}" type="video/mp4"/>
</video>

How to count string occurrence in string?

_x000D_
_x000D_
var countInstances = function(body, target) {_x000D_
  var globalcounter = 0;_x000D_
  var concatstring  = '';_x000D_
  for(var i=0,j=target.length;i<body.length;i++){_x000D_
    concatstring = body.substring(i-1,j);_x000D_
    _x000D_
    if(concatstring === target){_x000D_
       globalcounter += 1;_x000D_
       concatstring = '';_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  _x000D_
  return globalcounter;_x000D_
 _x000D_
};_x000D_
_x000D_
console.log(   countInstances('abcabc', 'abc')   ); // ==> 2_x000D_
console.log(   countInstances('ababa', 'aba')   ); // ==> 2_x000D_
console.log(   countInstances('aaabbb', 'ab')   ); // ==> 1
_x000D_
_x000D_
_x000D_

How to take keyboard input in JavaScript?

You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:

_x000D_
_x000D_
window.addEventListener("keydown", function (event) {_x000D_
  if (event.defaultPrevented) {_x000D_
    return; // Do nothing if the event was already processed_x000D_
  }_x000D_
_x000D_
  switch (event.key) {_x000D_
    case "ArrowDown":_x000D_
      // code for "down arrow" key press._x000D_
      break;_x000D_
    case "ArrowUp":_x000D_
      // code for "up arrow" key press._x000D_
      break;_x000D_
    case "ArrowLeft":_x000D_
      // code for "left arrow" key press._x000D_
      break;_x000D_
    case "ArrowRight":_x000D_
      // code for "right arrow" key press._x000D_
      break;_x000D_
    default:_x000D_
      return; // Quit when this doesn't handle the key event._x000D_
  }_x000D_
_x000D_
  // Cancel the default action to avoid it being handled twice_x000D_
  event.preventDefault();_x000D_
}, true);_x000D_
// the last option dispatches the event to the listener first,_x000D_
// then dispatches event to window
_x000D_
_x000D_
_x000D_

Multi-dimensional arraylist or list in C#?

Not exactly. But you can create a list of lists:

var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var l = new List<int>();
    ll.Add(l);
}

Change <br> height using CSS

The line height of the br tag can be different from the line height of the rest of the text inside a paragraph text by setting font-size for br tag.

Example: br { font-size: 200%; }

MySQL error - #1062 - Duplicate entry ' ' for key 2

  1. Drop the primary key first: (The primary key is your responsibility)

    ALTER TABLE Persons DROP PRIMARY KEY ;
    
  2. Then make all insertions:

  3. Add new primary key just like before dropping:

    ALTER TABLE Persons ADD PRIMARY KEY (P_Id);
    

When is assembly faster than C?

How about creating machine code at run-time?

My brother once (around 2000) realised an extremely fast real-time ray-tracer by generating code at run-time. I can't remember the details, but there was some kind of main module which was looping through objects, then it was preparing and executing some machine code which was specific to each object.

However, over time, this method was outruled by new graphics hardware, and it became useless.

Today, I think that possibly some operations on big-data (millions of records) like pivot tables, drilling, calculations on-the-fly, etc. could be optimized with this method. The question is: is the effort worth it?

Download a specific tag with Git

try:

git clone -b <name_of_the_tag> <repository_url> <destination>

CSS, Images, JS not loading in IIS

Try removing the staticContent section from your web.config.

<system.webServer>
    <staticContent>
        ...
    </staticContent>
</system.webServer>

How to lose margin/padding in UITextView?

[firstNameTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];

Use Async/Await with Axios in React.js

Two issues jump out:

  1. Your getData never returns anything, so its promise (async functions always return a promise) will resolve with undefined when it resolves

  2. The error message clearly shows you're trying to directly render the promise getData returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: getData should return the result of calling json:

async getData(){
   const res = await axios('/data');
   return await res.json();
}

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

<SomeElement>{getData()}</SomeElement>

...because that doesn't wait for the resolution. You'd need instead to use getData to set state:

this.getData().then(data => this.setState({data}))
              .catch(err => { /*...handle the error...*/});

...and use that state when rendering:

<SomeElement>{this.state.data}</SomeElement>

Update: Now that you've shown us your code, you'd need to do something like this:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            this.getData().then(data => this.setState({data}))
                          .catch(err => { /*...handle the error...*/});
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

Futher update: You've indicated a preference for using await in componentDidMount rather than then and catch. You'd do that by nesting an async IIFE function within it and ensuring that function can't throw. (componentDidMount itself can't be async, nothing will consume that promise.) E.g.:

class App extends React.Component{
    async getData() {
        const res = await axios('/data');
        return await res.json(); // (Or whatever)
    }
    constructor(...args) {
        super(...args);
        this.state = {data: null};
    }
    componentDidMount() {
        if (!this.state.data) {
            (async () => {
                try {
                    this.setState({data: await this.getData()});
                } catch (e) {
                    //...handle the error...
                }
            })();
        }
    }
    render() {
        return (
            <div>
                {this.state.data ? <em>Loading...</em> : this.state.data}
            </div>
        );
    }
}

How to paginate with Mongoose in Node.js?

Pagination using mongoose, express and jade - Here's a link to my blog with more detail

var perPage = 10
  , page = Math.max(0, req.params.page)

Event.find()
    .select('name')
    .limit(perPage)
    .skip(perPage * page)
    .sort({
        name: 'asc'
    })
    .exec(function(err, events) {
        Event.count().exec(function(err, count) {
            res.render('events', {
                events: events,
                page: page,
                pages: count / perPage
            })
        })
    })

Get File Path (ends with folder)

Have added ErrorHandler to this in case the user hits the cancel button instead of selecting a folder. So instead of getting a horrible error message you get a message that a folder must be selected and then the routine ends. Below code also stores the folder path in a range name (Which is just linked to cell A1 on a sheet).

Sub SelectFolder()

Dim diaFolder As FileDialog

'Open the file dialog
On Error GoTo ErrorHandler
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Title = "Select a folder then hit OK"
diaFolder.Show
Range("IC_Files_Path").Value = diaFolder.SelectedItems(1)
Set diaFolder = Nothing
Exit Sub

ErrorHandler:
Msg = "No folder selected, you must select a folder for program to run"
Style = vbError
Title = "Need to Select Folder"
Response = MsgBox(Msg, Style, Title)

End Sub

How to run a function in jquery

I would do it this way:

(function($) {
jQuery.fn.doSomething = function() {
   return this.each(function() {
      var $this = $(this);

      $this.click(function(event) {
         event.preventDefault();
         // Your function goes here
      });
   });
};
})(jQuery);

Then on document ready you can do stuff like this:

$(document).ready(function() {
   $('#div1').doSomething();
   $('#div2').doSomething();
});

form confirm before submit

Simply...

  $('#myForm').submit(function() {
   return confirm("Click OK to continue?");
  });

or

  $('#myForm').submit(function() {
   var status = confirm("Click OK to continue?");
   if(status == false){
   return false;
   }
   else{
   return true; 
   }
  });

display html page with node.js

This did the trick for me:

var express = require('express'),
app = express(); 
app.use('/', express.static(__dirname + '/'));
app.listen(8080);

How to execute XPath one-liners from shell?

Saxon will do this not only for XPath 2.0, but also for XQuery 1.0 and (in the commercial version) 3.0. It doesn't come as a Linux package, but as a jar file. Syntax (which you can easily wrap in a simple script) is

java net.sf.saxon.Query -s:source.xml -qs://element/attribute

2020 UPDATE

Saxon 10.0 includes the Gizmo tool, which can be used interactively or in batch from the command line. For example

java net.sf.saxon.Gizmo -s:source.xml
/>show //element/@attribute
/>quit

How do I use Apache tomcat 7 built in Host Manager gui?

For tomcat 8

1.Go to context.xml file located for instance../home/ubuntu/tomcat/webapps/manager/META-INF/

comment out valve tag. save and exit

2.Go to tomcat-users.xml file located in conf directory of tomcat. Add the respective roles

under the tomcat-users tag. Save and exit.

  1. Restart the tomcat.

Now, you will be able to have access to the manager app.

How to run .jar file by double click on Windows 7 64-bit?

Installing the newest JRE fixed this for me.

(Even though I had a JDK and JRE(s) installed before.)

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:

=A1=A50

If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

In ES6, you can simply utilize the Spread syntax.

Example:

let arr = ['a', 'b', 'c'];
let arr2 = [...arr];

Please note that the spread operator generates a completely new array, so modifying one won't affect the other.

Example:

arr2.push('d') // becomes ['a', 'b', 'c', 'd']
console.log(arr) // while arr retains its values ['a', 'b', 'c']

Case statement with multiple values in each 'when' block

You might take advantage of ruby's "splat" or flattening syntax.

This makes overgrown when clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:

honda  = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...

if include_concept_cars
  honda += ['ev-ster', 'concept c', 'concept s', ...]
  ...
end

case car
when *toyota
  # Do something for Toyota cars
when *honda
  # Do something for Honda cars
...
end

Another common approach would be to use a hash as a dispatch table, with keys for each value of car and values that are some callable object encapsulating the code you wish to execute.

How to return 2 values from a Java method?

Java does not support multi-value returns. Return an array of values.

// Function code
public static int[] something(){
    int number1 = 1;
    int number2 = 2;
    return new int[] {number1, number2};
}

// Main class code
public static void main(String[] args) {
  int result[] = something();
  System.out.println(result[0] + result[1]);
}

jQuery UI Slider (setting programmatically)

One part of @gaurav solution worked for jQuery 2.1.3 and JQuery UI 1.10.2 with multiple sliders. My project is using four range sliders to filter data with this filter.js plugin. Other solutions were resetting the slider handles back to their starting end points just fine, but apparently they were not firing an event that filter.js understood. So here's how I looped through the sliders:

$("yourSliderSelection").each (function () {
    var hs = $(this); 
    var options = $(this).slider('option');

    //reset the ui
    $(this).slider( 'values', [ options.min, options.max ] ); 

    //refresh/trigger event so that filter.js can reset handling the data
    hs.slider('option', 'slide').call(
        hs, 
        null, 
        {
            handle: $('.ui-slider-handle', hs),
            values: [options.min, options.max]
        }
    );

});

The hs.slider() code resets the data, but not the UI in my scenario. Hope this helps others.

Android Spinner: Get the selected item change event

I know this was long solved but I have a "Please select" string at the top of my string arrays. Then when you write the listener

yourspinner.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
                yourvalue = yourspinner.getSelectedItem().toString()

                when(yourvalue){
                    "Please Select" -> // DO nothing
                    else -> // Do something
                }
            }

            override fun onNothingSelected(adapterView: AdapterView<*>?) {
                return
            }
        }

You can of course extend the when statement to have different responses or actions.

Update with two tables?

For Microsoft Access

UPDATE TableA A
    INNER JOIN TableB B
    ON A.ID = B.ID
SET A.Name = B.Name

How to properly add cross-site request forgery (CSRF) token using PHP

Security Warning: md5(uniqid(rand(), TRUE)) is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.

Looks like you need an else with your if.

if (!isset($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
}
else
{
    $token = $_SESSION['token'];
}

Remove empty array elements

I use the following script to remove empty elements from an array

for ($i=0; $i<$count($Array); $i++)
  {
    if (empty($Array[$i])) unset($Array[$i]);
  }

Changing an element's ID with jQuery

Your syntax is incorrect, you should pass the value as the second parameter:

jQuery(this).prev("li").attr("id","newId");

What is the difference between React Native and React?

Here is a very nice explanation:

Reactjs is a JavaScript library that supports both front-end and server. Furthermore, it can be used to create user interfaces for mobile apps and websites.

React Native is a cross-platform mobile framework that uses Reactjs for building apps and websites. React Native compiles to native app components enables the programmer to build mobile applications that can run on different platforms such as Windows, Android, iOS in JavaScript.

  • Reactjs can be described as a base derivative of React DOM, for the web platform while React Native is a base derivative in itself, which means that the syntax and workflow remain the same, but components alter.

  • Reactjs, eventually, is a JavaScript library, which enables the programmer to create an engaging and high performing UI Layer while React Native is an entire framework for building cross-platform apps, be it web, iOS or Android.

  • In Reactjs, virtual DOM is used to render browser code in Reactjs while in React Native, native APIs are used to render components in mobile.

  • The apps developed with Reactjs renders HTML in UI while React Native uses JSX for rendering UI, which is nothing but javascript.

  • CSS is used for creating styling in Reactjs while a stylesheet is used for styling in React Native.

  • In Reactjs, the animation is possible, using CSS, just like web development while in React Native, an animated API is used for inducing animation across different components of the React Native application.

  • If the need is to build a high performing, dynamic, and responsive UI for web interfaces, then Reactjs is the best option while if the need is to give mobile apps a truly native feeling, then React Native is the best option.

More here: https://www.simform.com/reactjs-vs-reactnative/

Import Google Play Services library in Android Studio

I just tried out your build.gradle and it worked fine for me to import GMS, so that's not the issue.

This was with Google Play services (rev 13) and Google Repository (rev 4). Check out those are installed one more time :)

How to merge multiple lists into one list in python?

import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)

Just another method....

Java - Convert integer to string

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();

Image inside div has extra space below the image

I just added float:left to div and it worked

Remove first Item of the array (like popping from stack)

Plunker

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

Made changes to .. now it will remove from the top

How to make background of table cell transparent

You can do it setting the transparency via style right within the table tag:

<table id="Main table" style="background-color:rgba(0, 0, 0, 0);">

The last digit in the rgba function is for transparency. 1 means 100% opaque, while 0 stands for 100% transparent.

What is default list styling (CSS)?

As per the documentation, most browsers will display the <ul>, <ol> and <li> elements with the following default values:

Default CSS settings for UL or OL tag:

ul, ol { 
    display: block;
    list-style: disc outside none;
    margin: 1em 0;
    padding: 0 0 0 40px;
}
ol { 
    list-style-type: decimal;
}

Default CSS settings for LI tag:

li { 
    display: list-item;
}

Style nested list items as well:

ul ul, ol ul {
    list-style-type: circle;
    margin-left: 15px; 
}
ol ol, ul ol { 
    list-style-type: lower-latin;
    margin-left: 15px; 
}

Note: The result will be perfect if we use the above styles with a class. Also see different List-Item markers.

Set transparent background using ImageMagick and commandline prompt

Using ImageMagick, this is very similar to hackerb9 code and result, but is a little simpler command line. It does assume that the top left pixel is the background color. I just flood fill the background with transparency, then select the alpha channel and blur it and remove half of the blurred area using -level 50x100%. Then turn back on all the channels and flatten it against the brown color. The -blur 0x1 -level 50x100% acts to antialias the boundaries of the alpha channel transparency. You can adjust the fuzz value, blur amount and the -level 50% value to change the degree of antialiasing.

convert logo: -fuzz 25% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x1 -level 50x100% +channel -background saddlebrown -flatten result.jpg

enter image description here

How to create an HTML button that acts like a link?

@Nicolas,following worked for me as yours didn't have type="button" due to which it started behaving as submit type..since i already have one submit type.it didn't worked for me ....and now you can either add class to button or to <a> to get required layout:

<a href="http://www.google.com/">
    <button type="button">Click here</button>
</a>

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of <, the XML parser is implicitly looking for the tag name and the end tag >. However, in your particular case, you were using < as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The content of elements must consist of well-formed character data or markup.

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The < must be escaped as &lt;.

So, essentially, the

for (var i = 0; i < length; i++) {

must become

for (var i = 0; i &lt; length; i++) {

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="functions.js" target="head" />

This way you don't need to worry about XML-special characters in your JS code. Additional advantage is that this gives the browser the opportunity to cache the JS file so that average response size is smaller.

See also:

Why is my Git Submodule HEAD detached from master?

The other way to make your submodule to check out the branch is to go the .gitmodules file in the root folder and add the field branch in the module configuration as following:

branch = <branch-name-you-want-module-to-checkout>

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

Input type number "only numeric value" validation

You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

Take a look at a sample app here:

https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator

Grant execute permission for a user on all stored procedures in database?

This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO

IF  EXISTS (SELECT * FROM sys.database_principals 
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO

--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO

--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO

--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be 
--executed by users who are members of the db_execproc database role

--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net 
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE] 
WITH DEFAULT_SCHEMA=[dbo]
GO

--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO

Reference: Grant Execute Permission on All Stored Procedures

TypeError: unhashable type: 'list' when using built-in set function

Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.

Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.

result = sorted(set(map(tuple, my_list)), reverse=True)

Additional note: If a tuple contains a list, the tuple is still considered mutable.

Some examples:

>>> hash( tuple() )
3527539
>>> hash( dict() )

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    hash( list() )
TypeError: unhashable type: 'list'

PHPExcel Make first row bold

Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:

$header = array(
    'Header 1',
    'Header 2'
);

$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

The Issue

The error presents itself as a message similar to this:

Cannot open database "DATABASE NAME" requested by the login. The login failed. Login failed for user XYZ.

  • The error cannot usually be rectified by a simple Visual Studio or full-computer restart.
  • The error can also be found as a seemingly locked database file.

The Fix

The solution is laid in the following steps. You will not lose any data in your database and you should not delete your database file!

Pre-requisite: You must have installed SQL Server Management Studio (Full or Express)

  1. Open SQL Server Management Studio
  2. In the "Connect to Server" window (File->Connect object explorer) enter the following:
    • Server type : Database Engine
    • Server name : (localdb)\v11.0
    • Authentication : [Whatever you used when you created your local db. Probably Windows Authentication).
  3. Click "Connect"
  4. Expand the "Databases" folder in the Object Explorer (View->Object Explorer, F8)
  5. Find your database. It should be named as the full path to your database (.mdf) file
    • You should see it says "(Pending Recovery)" at the end of the database name or when you try to expand the database it won't be able to and may or may not give you an error message.
    • This the issue! Your database has crashed essentially..
  6. Right click on the database then select "Tasks -> Detach...".
  7. In the detach window, select your database in the list and check the column that says "Drop Connections"
  8. Click OK.
  9. You should see the database disappear from the list of databases. Your problem should now be fixed. Go and run your application that uses your localdb.
  10. After running your application, your database will re-appear in the list of databases - this is correct. It should not say "Pending recovery" any more since it should be working properly.

The source of the solution: https://www.codeproject.com/Tips/775607/How-to-fix-LocalDB-Requested-Login-failed

binning data in python with scipy/numpy

Not sure why this thread got necroed; but here is a 2014 approved answer, which should be far faster:

import numpy as np

data = np.random.rand(100)
bins = 10
slices = np.linspace(0, 100, bins+1, True).astype(np.int)
counts = np.diff(slices)

mean = np.add.reduceat(data, slices[:-1]) / counts
print mean

Auto height div with overflow and scroll when needed

You can do this just with flexboxes and overflow property.

Even if parent height is computed too.

Please see this answer or JSFiddle for details.

HashMap and int as key

I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

An array is also an Object, so HashMap<int[], MyObject> is a valid construct that uses int arrays as keys.

Compiler doesn't know what you want or what you need, it just sees a language construct that is almost correct, and warns what's missing for it to be fully correct.

java- reset list iterator to first element of the list

Best would be not using LinkedList at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)

Use ArrayList, and iterate with

int len = list.size();
for (int i = 0; i < len; i++) {
  Element ele = list.get(i);
}

Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:

iter = list.listIterator();

(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)

How to uncheck checkbox using jQuery Uniform library

Just do this:

$('#checkbox').prop('checked',true).uniform('refresh');

if A vs if A is not None:

Most guides I've seen suggest that you should use

if A:

unless you have a reason to be more specific.

There are some slight differences. There are values other than None that return False, for example empty lists, or 0, so have a think about what it is you're really testing for.

What is the difference between exit(0) and exit(1) in C?

exit(0) indicates that the program terminated without errors. exit(1) indicates that there were an error.

You can use different values other than 1 to differentiate between different kind of errors.

How do I replace whitespaces with underscore?

perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } <*>;'

Match et replace space > underscore of all files in current directory

On design patterns: When should I use the singleton?

I think if your app has multiple layers e.g presentation, domain and model. Singleton is a good candidate to be a part of cross cutting layer. And provide service to each layer in the system.

Essentially Singleton wraps a service for example like logging, analytics and provides it to other layers in the system.

And yes singleton needs to follow single responsibility principle.

Dynamically create checkbox with JQuery from text input

<div id="cblist">
    <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
    });
});

function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>

How to find the parent element using javascript

Using plain javascript:

element.parentNode

In jQuery:

element.parent()

How to set a variable to be "Today's" date in Python/Pandas

i got the same problem so tried so many things but finally this is the solution.

import time 

print (time.strftime("%d/%m/%Y"))

jquery ui Dialog: cannot call methods on dialog prior to initialization

I simply had to add the ScriptManager to the page. Issue resolved.

Constructors in JavaScript objects

Here we need to notice one point in java script, it is a class-less language however,we can achieve it by using functions in java script. The most common way to achieve this we need to create a function in java script and use new keyword to create an object and use this keyword to define property and methods.Below is the example.

// Function constructor

   var calculator=function(num1 ,num2){
   this.name="This is function constructor";
   this.mulFunc=function(){
      return num1*num2
   };

};

var objCal=new calculator(10,10);// This is a constructor in java script
alert(objCal.mulFunc());// method call
alert(objCal.name);// property call

//Constructors With Prototypes

var calculator=function(){
   this.name="Constructors With Prototypes";
};

calculator.prototype.mulFunc=function(num1 ,num2){
 return num1*num2;
};
var objCal=new calculator();// This is a constructor in java script
alert(objCal.mulFunc(10,10));// method call
alert(objCal.name); // property call

Checking length of dictionary object

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
   if (c.hasOwnProperty(i)) count++;
}

alert(count);

Is it possible to set UIView border properties from interface builder?

If you want to save time, just use two UIViews on top of each other, the one at the back being the border color, and the one in front smaller, giving the bordered effect. I don't think this is an elegant solution either, but if Apple cared a little more then you shouldn't have to do this.

Android Studio - Failed to apply plugin [id 'com.android.application']

In my case, if your version of build tools in the build.gradle file in the root folder like :

classpath 'com.android.tools.build:gradle:3.x.x' <--- version of tools

is not supported by the Gradle installed in your project, you can check the build tools/plugin supported versions here, and make sure that the version installed in your project is supported by that version of Gradle.

You don't need to upgrade Gradle, you just check if it supports the plugin installed in your project or not.

C++ pointer to objects

if you want the object on the stack, try this:

MyClass myclass;
myclass.DoSomething();

If you need a pointer to that object:

MyClass* myclassptr = &myclass;
myclassptr->DoSomething();

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

How do I convert a String to a BigInteger?

According to the documentation:

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

sum = sum.add(new BigInteger(newNumber));

What are .a and .so files?

Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.

The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.

This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

Hope this helps.

Python - Passing a function into another function

Just pass it in like any other parameter:

def a(x):
    return "a(%s)" % (x,)

def b(f,x):
    return f(x)

print b(a,10)

Git on Windows: How do you set up a mergetool?

If you're doing this through cygwin, you may need to use cygpath:

git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge `cygpath -w $BASE` `cygpath -w $LOCAL` `cygpath -w $REMOTE` `cygpath -w $MERGED`'

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

How to get div height to auto-adjust to background size?

If you know the ratio of the image at build time, want the height based off of the window height and you're ok targeting modern browsers (IE9+), then you can use viewport units for this:

.width-ratio-of-height {
  overflow-x: scroll;
  height: 100vh;
  width: 500vh; /* width here is 5x height */
  background-image: url("http://placehold.it/5000x1000");
  background-size: cover;
}

Not quite what the OP was asking, but probably a good fit for a lot of those viewing this question, so wanted to give another option here.

Fiddle: https://jsfiddle.net/6Lkzdnge/

Parse String date in (yyyy-MM-dd) format

You are creating a Date object, which is a representation of a certain point in the timeline. This means that it will have all the parts necessary to represent it correctly, including minutes and seconds and so on. Because you initialize it from a string containing only a part of the date, the missing data will be defaulted.

I assume you are then "printing" this Date object, but without actually specifying a format like you did when parsing it. Use the same SimpleDateFormat but call the reverse method, format(Date) as Holger suggested

How to break out from a ruby block?

use the keyword break instead of return

How to close a Java Swing application from the code

Your JFrame default close action can be set to "DISPOSE_ON_CLOSE" instead of EXIT_ON_CLOSE (why people keep using EXIT_ON_CLOSE is beyond me).

If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).

The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.

If you want to check for all active frames, you can use Frame.getFrames(). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.

Spring security CORS Filter

There's 8 hours of my life I will never get back...

Make sure that you set both Exposed Headers AND Allowed Headers in your CorsConfiguration

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
    configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

There is a difference in the * usage when you are defining a variable and when you are using it.

In declaration,

int *myVariable;

Means a pointer to an integer data type. In usage however,

*myVariable = 3;

Means dereference the pointer and make the structure it is pointing at equal to three, rather then make the pointer equal to the memory address 0x 0003.

So in your function, you want to do this:

void makePointerEqualSomething(int* pInteger)
{
    *pInteger = 7;
}

In the function declaration, * means you are passing a pointer, but in its actual code body * means you are accessing what the pointer is pointing at.

In an attempt to wave away any confusion you have, I'll briefly go into the ampersand (&)

& means get the address of something, its exact location in the computers memory, so

 int & myVariable;

In a declaration means the address of an integer, or a pointer!

This however

int someData;    
pInteger = &someData;

Means make the pInteger pointer itself (remember, pointers are just memory addresses of what they point at) equal to the address of 'someData' - so now pInteger will point at some data, and can be used to access it when you deference it:

*pInteger += 9000;

Does this make sense to you? Is there anything else that you find confusing?

@Edit3:

Nearly correct, except for three statements

bar = *oof;

means that the bar pointer is equal to an integer, not what bar points at, which is invalid.

&bar = &oof;

The ampersand is like a function, once it returns a memory address you cannot modify where it came from. Just like this code:

returnThisInt("72") = 86; 

Is invalid, so is yours.

Finally,

bar = oof

Does not mean that "bar points to the oof pointer." Rather, this means that bar points to the address that oof points to, so bar points to whatever foo is pointing at - not bar points to foo which points to oof.

Restore a deleted file in the Visual Studio Code Recycle Bin

Running on Ubuntu 18.04, with VS code 1.51.0

My deleted files from VS Code are located at:

~/.local/share/Trash/files

To search for your deleted files:

find ~/.local/share/Trash/files -name your_file_name 

Hope my case helped!

Checking if a folder exists (and creating folders) in Qt, C++

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

You can see more on Qt Documentation

How do you set the document title in React?

You can use React Helmet:

import React from 'react'
import { Helmet } from 'react-helmet'

const TITLE = 'My Page Title'

class MyComponent extends React.PureComponent {
  render () {
    return (
      <>
        <Helmet>
          <title>{ TITLE }</title>
        </Helmet>
        ...
      </>
    )
  }
}

Java: export to an .jar file in eclipse

FatJar can help you in this case.

In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects

This is useful if your final exported jar includes other external jars.

If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.

After Ganymede, you have:

Export Jar

Node Multer unexpected field

Unfortunately, the error message doesn't provide clear information about what the real problem is. For that, some debugging is required.

From the stack trace, here's the origin of the error in the multer package:

function wrappedFileFilter (req, file, cb) {
  if ((filesLeft[file.fieldname] || 0) <= 0) {
    return cb(makeError('LIMIT_UNEXPECTED_FILE', file.fieldname))
  }

  filesLeft[file.fieldname] -= 1
  fileFilter(req, file, cb)
}

And the strange (possibly mistaken) translation applied here is the source of the message itself...

'LIMIT_UNEXPECTED_FILE': 'Unexpected field'

filesLeft is an object that contains the name of the field your server is expecting, and file.fieldname contains the name of the field provided by the client. The error is thrown when there is a mismatch between the field name provided by the client and the field name expected by the server.

The solution is to change the name on either the client or the server so that the two agree.

For example, when using fetch on the client...

var theinput = document.getElementById('myfileinput')
var data = new FormData()
data.append('myfile',theinput.files[0])
fetch( "/upload", { method:"POST", body:data } )

And the server would have a route such as the following...

app.post('/upload', multer(multerConfig).single('myfile'),function(req, res){
  res.sendStatus(200)
}

Notice that it is myfile which is the common name (in this example).

Stop form from submitting , Using Jquery

This is a JQuery code for Preventing Submit

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });

Convert double to string C++?

Use std::stringstream. Its operator << is overloaded for all built-in types.

#include <sstream>    

std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();

This works like you'd expect - the same way you print to the screen with std::cout. You're simply "printing" to a string instead. The internals of operator << take care of making sure there's enough space and doing any necessary conversions (e.g., double to string).

Also, if you have the Boost library available, you might consider looking into lexical_cast. The syntax looks much like the normal C++-style casts:

#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;

storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
                       "," + lexical_cast<std::string>(c2) + ")";

Under the hood, boost::lexical_cast is basically doing the same thing we did with std::stringstream. A key advantage to using the Boost library is you can go the other way (e.g., string to double) just as easily. No more messing with atof() or strtod() and raw C-style strings.

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.


Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

Android DialogFragment vs Dialog

DialogFragment is basically a Fragment that can be used as a dialog.

Using DialogFragment over Dialog due to the following reasons:

  • DialogFragment is automatically re-created after configuration changes and save & restore flow
  • DialogFragment inherits full Fragment’s lifecycle
  • No more IllegalStateExceptions and leaked window crashes. This was pretty common when the activity was destroyed with the Alert Dialog still there.

More detail

Carriage return in C?

Step-by-step:

[newline]ab

ab

[backspace]si

asi

[carriage-return]ha

hai

Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.

CSS Display an Image Resized and Cropped

You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

It's was great if delete return the delete pair of the hash. I'm doing this:

hash = {a: 1, b: 2, c: 3}
{b: hash.delete(:b)} # => {:b=>2}
hash  # => {:a=>1, :c=>3} 

Failed to load ApplicationContext for JUnit test of Spring controller

If you are using Maven, add the below config in your pom.xml:

<build>
    <testResources>
                <testResource>
                    <directory>src/main/webapp</directory>
                </testResource>
    </testResources>
</build>

With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.

WaitAll vs WhenAll

Task.WaitAll blocks the current thread until everything has completed.

Task.WhenAll returns a task which represents the action of waiting until everything has completed.

That means that from an async method, you can use:

await Task.WhenAll(tasks);

... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.

What's the best way to generate a UML diagram from Python source code?

Certain classes of well-behaved programs may be diagrammable, but in the general case, it can't be done. Python objects can be extended at run time, and objects of any type can be assigned to any instance variable. Figuring out what classes an object can contain pointers to (composition) would require a full understanding of the runtime behavior of the program.

Python's metaclass capabilities mean that reasoning about the inheritance structure would also require a full understanding of the runtime behavior of the program.

To prove that these are impossible, you argue that if such a UML diagrammer existed, then you could take an arbitrary program, convert "halt" statements into statements that would impact the UML diagram, and use the UML diagrammer to solve the halting problem, which as we know is impossible.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Django Server Error: port is already in use

netstat -ntlp

It will show something like this.

   Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State           PID/Program name    
tcp        0      0 127.0.0.1:8000          0.0.0.0:*               LISTEN      6599/python         
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      -                   
tcp        0      0 192.168.124.1:53        0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      -                   
tcp6       0      0 :::3306                 :::*                    LISTEN     

So now just close the port in which Django/python running already by killing the process associated with it.

kill -9 PID

in my case

kill -9 6599

Now run your Django app.

Get selected element's outer HTML

This is quite simple with vanilla JavaScript...

document.querySelector('#selector')

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

Mongodb: failed to connect to server on first connect

I connected to a VPN and it worked. I was using school's WiFi.

Deprecation warning in Moment.js - Not in a recognized ISO format

Check out all their awesome documentation!

Here is where they discuss the Warning Message.

String + Format

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

moment("12-25-1995", "MM-DD-YYYY");

String + Formats (multiple formats)

If you have more than one format, check out their String + Formats (with an 's').

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);

Please checkout the documentation for anything more specific.

Timezone

Checkout Parsing in Zone, the equivalent documentation for timezones.

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto");

EDIT

//...
var dateFormat = "YYYY-M-D H:m"; //<-------- This part will get rid of the warning.
var aus1_s, aus2_s, aus3_s, aus4_s, aus5_s, aus6_s, aus6_e;
if ($("#custom1 :selected").val() == "AU" ) {
    var region = 'Australia/Sydney';

    aus1_s = moment.tz('2016-9-26 19:30', dateFormat, region);              
    aus2_s = moment.tz('2016-10-2 19:30', dateFormat, region);              
    aus3_s = moment.tz('2016-10-9 19:30', dateFormat, region);                  
    aus4_s = moment.tz('2016-10-16 19:30', dateFormat, region);                 
    aus5_s = moment.tz('2016-10-23 19:30', dateFormat, region);
    aus6_s = moment.tz('2016-10-30 19:30', dateFormat, region);
    aus6_e = moment.tz('2016-11-5 19:30', dateFormat, region);
} else if ($("#custom1 :selected").val() == "NZ" ) {
    var region = 'Pacific/Auckland';

    aus1_s =  moment.tz('2016-9-28 20:30', dateFormat, region);
    aus2_s =  moment.tz('2016-10-4 20:30', dateFormat, region);
    aus3_s =  moment.tz('2016-10-11 20:30', dateFormat, region);
    aus4_s =  moment.tz('2016-10-18 20:30', dateFormat, region);
    aus5_s =  moment.tz('2016-10-25 20:30', dateFormat, region);
    aus6_s =  moment.tz('2016-11-2 20:30', dateFormat, region);
    aus6_e =  moment.tz('2016-11-9 20:30', dateFormat, region);
}
//...

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

Simple excel find and replace for formulas

You can also click on the Formulas tab in Excel and select Show Formulas, then use the regular "Find" and "Replace" function. This should not affect the rest of your formula.

How would you count occurrences of a string (actually a char) within a string?

int count = new Regex(Regex.Escape(needle)).Matches(haystack).Count;

How to access the SMS storage on Android?

For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.

Convert Json String to C# Object List

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
    public class Option
    {
        public string text { get; set; }
        public string selectedMarks { get; set; }
    }

    public class Model
    {
        public List<Option> options { get; set; }
        public int maxOptions { get; set; }
        public int minOptions { get; set; }
        public bool isAnswerRequired { get; set; }
        public string selectedOption { get; set; }
        public string answerText { get; set; }
        public bool isRangeType { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string mins { get; set; }
        public string secs { get; set; }
    }

    public class Question
    {
        public int QuestionId { get; set; }
        public string QuestionText { get; set; }
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public Model Model { get; set; }
    }

    public class RootObject
    {
        public Question Question { get; set; }
        public string CheckType { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }
        public string S6 { get; set; }
        public string S7 { get; set; }
        public string S8 { get; set; }
        public string S9 { get; set; }
        public string S10 { get; set; }
        public string ScoreIfNoMatch { get; set; }
    }
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

Difference between Static and final?

static means there is only one copy of the variable in memory shared by all instances of the class.

The final keyword just means the value can't be changed. Without final, any object can change the value of the variable.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

If you are using JAVA8 API then this code will help.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeString = LocalDateTime.now().format(formatter);
System.out.println(dateTimeString);

It will print the date in the given format.

But if you again create a object of LocalDateTime it will print the 'T' in between the date and time.

LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime.toString());

So as mentioned in earlier posts as well, the representation and usage is different.

Its better to use "yyyy-MM-dd'T'HH:mm:ss" pattern and convert the string/date object accordingly.

Changing the color of an hr element

hr {
    height: 1px;
    color: #123455;
    background-color: #123455;
    border: none;
}

Doing it this way allows you to change the height if needed. Good luck. Source: How To Style HR with CSS

How to retrieve the hash for the current commit in Git?

Here is another direct-access implementation:

head="$(cat ".git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(cat ".git/${head#ref: }")"
done

This also works over http which is useful for local package archives (I know: for public web sites it's not recommended to make the .git directory accessable):

head="$(curl -s "$baseurl/.git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(curl -s "$baseurl/.git/${head#ref: }")"
done

Add newly created specific folder to .gitignore in Git

For this there are two cases

Case 1: File already added to git repo.

Case 2: File newly created and its status still showing as untracked file when using

git status

If you have case 1:

STEP 1: Then run

git rm --cached filename 

to remove it from git repo cache

if it is a directory then use

git rm -r --cached  directory_name

STEP 2: If Case 1 is over then create new file named .gitignore in your git repo

STEP 3: Use following to tell git to ignore / assume file is unchanged

git update-index --assume-unchanged path/to/file.txt

STEP 4: Now, check status using git status open .gitignore in your editor nano, vim, geany etc... any one, add the path of the file / folder to ignore. If it is a folder then user folder_name/* to ignore all file.

If you still do not understand read the article git ignore file link.

How can I change Eclipse theme?

Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins folder.

When you have done that go to

Window -> Preferences -> General -> Appearance

And change the theme from GTK (or what ever it is currently) to Dark Juno (or Dark).

That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.

Eclipse Color Themes

This adds a "Color Theme" menu item under

Window -> Preferences -> Appearance

Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark

Table row and column number in jQuery

its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am

AngularJS : Factory and Service?

Service vs Factory


enter image description here enter image description here

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Factory are a great way for communicating between controllers like sharing data.

  • Can use other dependencies

  • Usually used when the service instance requires complex creation logic

  • Cannot be injected in .config() function.

  • Used for non configurable services

  • If you're using an object, you could use the factory provider.

  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Services are used for communication between controllers to share data

  • You can add properties and functions to a service object by using the this keyword

  • Dependencies are injected as constructor arguments

  • Used for simple creation logic

  • Cannot be injected in .config() function.

  • If you're using a class you could use the service provider

  • Syntax: module.service(‘serviceName’, function);

Sample Demo

In below example I have define MyService and MyFactory. Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

Also Take a look at this beautiful stuffs

Confused about service vs factory

AngularJS Factory, Service and Provider

Angular.js: service vs provider vs factory?

How to fix curl: (60) SSL certificate: Invalid certificate chain

Another cause of this can be duplicate keys in your KeyChain. I've seen this problem on two macs where there were duplicate "DigiCert High Assurance EV Root CA". One was in the login keychain, the other in the system one. Removing the certificate from the login keychain solved the problem.

This affected Safari browser as well as git on the command line.

Handling Enter Key in Vue.js

You can also pass events down into child components with something like this:

<CustomComponent
    @keyup.enter="handleKeyUp"
/>

...

<template>
    <div>
        <input
            type="text"
            v-on="$listeners"
        >
    </div>
</template>

<script>
export default {
    name: 'CustomComponent',

    mounted() {
        console.log('listeners', this.$listeners)
    },
}
</script>

That works well if you have a pass-through component and want the listeners to go onto a specific element.

HTML5 record audio to file

Here's a gitHub project that does just that.

It records audio from the browser in mp3 format, and it automatically saves it to the webserver. https://github.com/Audior/Recordmp3js

You can also view a detailed explanation of the implementation: http://audior.ec/blog/recording-mp3-using-only-html5-and-javascript-recordmp3-js/

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>

EDIT

I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

Markdown to create pages and table of contents?

You can generate it using this bash one-liner. Assumes your markdown file is called FILE.md.

echo "## Contents" ; echo ; 
cat FILE.md | grep '^## ' | grep -v Contents | sed 's/^## //' | 
  while read -r title ; do 
    link=$(echo $title | tr 'A-Z ' 'a-z-') ; 
    echo "- [$title](#$link)" ; 
    done

How can I update NodeJS and NPM to the next versions?

SIMPLY USE THIS

npm i -g npm

This is what i get promped on my console from npm when new update/bug-fix are released:

enter image description here

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

It's not a big deal on a small/personal scale, but it can become a bigger deal quickly on a larger scale. My employer is a large Microsoft shop, but won't/can't buy into Team System/TFS for a number of reasons. We currently use Subversion + Orcas + MBUnit + TestDriven.NET and it works well, but getting TD.NET was a huge hassle. The version sensitivity of MBUnit + TestDriven.NET is also a big hassle, and having one additional commercial thing (TD.NET) for legal to review and procurement to handle and manage, isn't trivial. My company, like a lot of companies, are fat and happy with a MSDN Subscription model, and it's just not used to handling one off procurements for hundreds of developers. In other words, the fully integrated MS offer, while definitely not always best-of-bread, is a significant value-add in my opinion.

I think we'll stay with our current step because it works and we've already gotten over the hump organizationally, but I sure do wish MS had a compelling offering in this space so we could consolidate and simplify our dev stack a bit.

db.collection is not a function when using MongoClient v3.0

I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.

MongoClient.connect(
    'mongodb://localhost:27017/mytestingdb', 
    { useNewUrlParser: true}
)
.then(client => {

    // The database name is part of the url.  client.db() seems 
    // to know that and works even without a parameter that 
    // relays the db name.
    let db = client.db(); 

    console.log('the current database is: ' + db.s.databaseName);
    // client.close() if you want to

})
.catch(err => console.log(err));

My package.json lists monbodb ^3.2.5.

The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.

sqlite database default time value 'now'

This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.

Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.

Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.

SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.

$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on

create table if not exists example (
   id integer primary key autoincrement
  ,data text not null unique
  ,created_at integer(4) not null default (strftime('%s','now'))
);

insert into example(data) values
 ('foo')
,('bar')
;

select
 id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;

id|data|epoch     |utc                |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02

Localtime is correct as I'm located at UTC+2 DST at the moment of the query.

How to implement zoom effect for image view in android?

Here is one of the most efficient way, it works smoothly:

https://github.com/MikeOrtiz/TouchImageView

Place TouchImageView.java in your project. It can then be used the same as ImageView.

Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view.

Example:

    <com.example.touch.TouchImageView
            android:id="@+id/img”
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

What is the 'override' keyword in C++ used for?

Wikipedia says:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

In detail, when you have an object foo that has a void hello() function:

class foo {
    virtual void hello(); // Code : printf("Hello!");
}

A child of foo, will also have a hello() function:

class bar : foo {
    // no functions in here but yet, you can call
    // bar.hello()
}

However, you may want to print "Hello Bar!" when hello() function is being called from a bar object. You can do this using override

class bar : foo {
    virtual void hello() override; // Code : printf("Hello Bar!");
}

@angular/material/index.d.ts' is not a module

? DO NOT:

// old code that breaks
import { MatDialogModule,
  MatInputModule,
  MatButtonModule} from '@angular/material';

? DO:

// new code that works
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';

? Because:

Components can no longer be imported through "@angular/material". Use the individual secondary entry-points, such as @angular/material/button.

Java Desktop application: SWT vs. Swing

I whould choose swing just because it's "native" for java.

Plus, have a look at http://swingx.java.net/.

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

Group query results by month and year in postgresql

There is another way to achieve the result using the date_part() function in postgres.

 SELECT date_part('month', txn_date) AS txn_month, date_part('year', txn_date) AS txn_year, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY date_part('month', txn_date)

Thanks

Clearing localStorage in javascript?

If you want to clear all item you stored in localStorage then

localStorage.clear();

Use this for clear all stored key.

If you want to clear/remove only specific key/value then you can use removeItem(key).

localStorage.removeItem('yourKey');

ROW_NUMBER() in MySQL

The rownumber functionality can't be mimicked. You might get the results you expect, but you'll most likely get disappointed at some stage. Here's what mysql documentation says:

For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second: SELECT @a, @a:=@a+1, ...; However, the order of evaluation for expressions involving user variables is undefined.

Regards, Georgi.

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

How to change TextField's height and width?

I think you want to change the inner padding/margin of the TextField.

You can do that by adding isDense: true and contentPadding: EdgeInsets.all(8) properties as follow:

Container(
  padding: EdgeInsets.all(12),
  child: Column(
    children: <Widget>[
      TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Default TextField',
        ),
      ),
      SizedBox(height: 16,),
      TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Densed TextField',
          isDense: true,                      // Added this
        ),
      ),
      SizedBox(height: 16,),
      TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Even Densed TextFiled',
          isDense: true,                      // Added this
          contentPadding: EdgeInsets.all(8),  // Added this
        ),
      )
    ],
  ),
)

It will be displayed as:

How to update flutter TextField's height and width / Inner Padding?

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

If you are on Mac OSX,

The default location for the MySQL Unix socket is different on Mac OS X and Mac OS X Server depending on the installation type you chose

MySQL Unix Socket Locations on Mac OS X by Installation Type

  • Package Installer from MySQL ------------------/tmp/mysql.sock

  • Tarball from MySQL -------------------------------/tmp/mysql.sock

  • MySQL Bundled with Mac OS X Server -------/var/mysql/mysql.sock

So just change your database.yml in socket: /tmp/mysql.sock to point to the right place depending on what OS and installation type you are using

What is the difference between Numpy's array() and asarray() functions?

The definition of asarray is:

def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

So it is like array, except it has fewer options, and copy=False. array has copy=True by default.

The main difference is that array (by default) will make a copy of the object, while asarray will not unless necessary.

How to install pip for Python 3 on Mac OS X?

To use Python EasyInstall (which is what I think you're wanting to use), is super easy!

sudo easy_install pip

so then with pip to install Pyserial you would do:

pip install pyserial

How to install a package inside virtualenv?

From documentation https://docs.python.org/3/library/venv.html:

The pyvenv script has been deprecated as of Python 3.6 in favor of using python3 -m venv to help prevent any potential confusion as to which Python interpreter a virtual environment will be based on.

In order to create a virtual environment for particular project, create a file /home/user/path/to/create_venv.sh:

#!/usr/bin/env bash

# define path to your project's directory
PROJECT_DIR=/home/user/path/to/Project1

# a directory with virtual environment
# will be created in your Project1 directory
# it recommended to add this path into your .gitignore
VENV_DIR="${PROJECT_DIR}"/venv

# https://docs.python.org/3/library/venv.html
python3 -m venv "${VENV_DIR}"

# activates the newly created virtual environment
. "${VENV_DIR}"/bin/activate

# prints activated version of Python
python3 -V

pip3 install --upgrade pip

# Write here all Python libraries which you want to install over pip
# An example or requirements.txt see here:
# https://docs.python.org/3/tutorial/venv.html#managing-packages-with-pip
pip3 install -r "${PROJECT_DIR}"/requirements.txt

echo "Virtual environment ${VENV_DIR} has been created"

deactivate

Then run this script in the console:

$ bash /home/user/path/to/create_venv.sh

IsNull function in DB2 SQL?

I'm not familiar with DB2, but have you tried COALESCE?

ie:


SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product

Cannot import XSSF in Apache POI

After trying multiple things,what really worked was: 1. downloading "poi" and "poi-ooxml" manually 2.Adding these d/w jars into "Maven Dependencies"

MySQL export into outfile : CSV escaping chars

Probably won't help but you could try creating a CSV table with that content:

DROP TABLE IF EXISTS foo_export;
CREATE TABLE foo_export LIKE foo;
ALTER TABLE foo_export ENGINE=CSV;
INSERT INTO foo_export SELECT id, 
   client,
   project,
   task,
   REPLACE(REPLACE(ifnull(ts.description,''),'\n',' '),'\r',' ') AS description, 
   time,
   date
  FROM ....

How to fix missing dependency warning when using useEffect React Hook?

you try this way

const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };

and

useEffect(() => {
    fetchBusinesses();
  });

it's work for you. But my suggestion is try this way also work for you. It's better than before way. I use this way:

useEffect(() => {
        const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };
        fetchBusinesses();
      }, []);

if you get data on the base of specific id then add in callback useEffect [id] then cannot show you warning React Hook useEffect has a missing dependency: 'any thing'. Either include it or remove the dependency array

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

I think your best bet is going to be to convert those lists into something parcelable such as a string (or map?) to get it to the Activity. Then the Activity will have to convert it back to an array.

Implementing custom parcelables is a pain in the neck IMHO so I would avoid it if possible.

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

Bootstrap modal appearing under background

Like Davide Lorigliola, I fixed it by cranking up the z-index:

.modal-backdrop { z-index: -999999; }

Pass a data.frame column name to a function

Personally I think that passing the column as a string is pretty ugly. I like to do something like:

get.max <- function(column,data=NULL){
    column<-eval(substitute(column),data, parent.frame())
    max(column)
}

which will yield:

> get.max(mpg,mtcars)
[1] 33.9
> get.max(c(1,2,3,4,5))
[1] 5

Notice how the specification of a data.frame is optional. you can even work with functions of your columns:

> get.max(1/mpg,mtcars)
[1] 0.09615385

How do I sort an observable collection?

You can use this simple method:

public static void Sort<TSource, TKey>(this Collection<TSource> source, Func<TSource, TKey> keySelector)
{
    List<TSource> sortedList = source.OrderBy(keySelector).ToList();
    source.Clear();
    foreach (var sortedItem in sortedList)
        source.Add(sortedItem);
}

You can sort like this:

_collection.Sort(i => i.Key);

Adjust width and height of iframe to fit with content in it

In case someone getting to here: I had a problem with the solutions when I removed divs from the iframe - the iframe didnt got shorter.

There is an Jquery plugin that does the job:

http://www.jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html

How to return JSON data from spring Controller using @ResponseBody

Yes just add the setters/getters with public modifier ;)

How do I generate random number for each row in a TSQL Select?

If you want to generate a random number between 1 and 14 inclusive.

SELECT CONVERT(int, RAND() * (14 - 1) + 1)

OR

SELECT ABS(CHECKSUM(NewId())) % (14 -1) + 1

SQL update from one Table to another based on a ID match

I had the same problem with foo.new being set to null for rows of foo that had no matching key in bar. I did something like this in Oracle:

update foo
set    foo.new = (select bar.new
                  from bar 
                  where foo.key = bar.key)
where exists (select 1
              from bar
              where foo.key = bar.key)

Font is not available to the JVM with Jasper Reports

I tried installing mscorefonts, but the package was installed and up-to-date.

sudo apt-get update
sudo apt-get install ttf-mscorefonts-installer

I tried searching for the font in the filesystem, with:

ls /usr/share/fonts/truetype/msttcorefonts/

This folder just had the README, with the correct instructions on how to install.

cat /usr/share/fonts/truetype/msttcorefonts/README

You need an internet connection for this:

sudo apt-get install --reinstall ttf-mscorefonts-installer

I re-installed ttf-mscorefonts-installer (as shown above, making sure to accept the EULA!) and the problem was solved.

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

ImportError: No module named PytQt5

pip install pyqt5 for python3 for ubuntu

Mercurial — revert back to old version and continue from there

IMHO, hg strip -r 39 suits this case better.

It requires the mq extension to be enabled and has the same limitations as the "cloning repo method" recommended by Martin Geisler: If the changeset was somehow published, it will (probably) return to your repo at some point in time because you only changed your local repo.

How to concatenate text from multiple rows into a single text string in SQL server?

In MySQL, there is a function, GROUP_CONCAT(), which allows you to concatenate the values from multiple rows. Example:

SELECT 1 AS a, GROUP_CONCAT(name ORDER BY name ASC SEPARATOR ', ') AS people 
FROM users 
WHERE id IN (1,2,3) 
GROUP BY a

jQuery "on create" event for dynamically-created elements

For me binding to the body does not work. Binding to the document using jQuery.bind() does.

$(document).bind('DOMNodeInserted',function(e){
             var target = e.target;
         });

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

The term 'ng' is not recognized as the name of a cmdlet

Also you can run following command to resolve, npm install -g @angular/cli

Getting a machine's external IP address with Python

If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.

Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)

Install:

pip install upnpclient

Simple Code:

import upnpclient

devices = upnpclient.discover()

if(len(devices) > 0):
    externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
    print(externalIP)
else:
    print('No Connected network interface detected')

Full Code (to get more information as mentioned in the github readme)

In [1]: import upnpclient

In [2]: devices = upnpclient.discover()

In [3]: devices
Out[3]: 
[<Device 'OpenWRT router'>,
 <Device 'Harmony Hub'>,
 <Device 'walternate: root'>]

In [4]: d = devices[0]

In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]: 
{'NewConnectionStatus': 'Connected',
 'NewLastConnectionError': 'ERROR_NONE',
 'NewUptime': 14851479}

In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}

In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}

What are the specific differences between .msi and setup.exe file?

MSI is an installer file which installs your program on the executing system.

Setup.exe is an application (executable file) which has msi file(s) as its one of the resources. Executing Setup.exe will in turn execute msi (the installer) which writes your application to the system.

Edit (as suggested in comment): Setup executable files don't necessarily have an MSI resource internally

Pure CSS collapse/expand div

Using <summary> and <details>

Using <summary> and <details> elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.

_x000D_
_x000D_
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
  color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
  outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
  <summary>Summary, caption, or legend for the content</summary>_x000D_
  Content goes here._x000D_
</details>
_x000D_
_x000D_
_x000D_

See also how to style the <details> element (HTML5 Doctor) (little bit tricky).

Pure CSS3

The :target selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.

_x000D_
_x000D_
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
  display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
  display: block;_x000D_
}
_x000D_
<div>_x000D_
  <a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
  <a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
  <a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
  <a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
  <div class="details">_x000D_
    Content goes here._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

slideToggle JQuery right to left

include Jquery and Jquery UI plugins and try this

 $("#LeftSidePane").toggle('slide','left',400);

Does uninstalling a package with "pip" also remove the dependent packages?

No, it doesn't uninstall the dependencies packages. It only removes the specified package:

$ pip install specloud
$ pip freeze # all the packages here are dependencies of specloud package

figleaf==0.6.1
nose==1.1.2
pinocchio==0.3
specloud==0.4.5

$ pip uninstall specloud
$ pip freeze

figleaf==0.6.1
nose==1.1.2
pinocchio==0.3

As you can see those packages are dependencies from specloud and they're still there, but not the specloud package itself.

As mentioned below, You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

There is plugin called Partial Diff which helps to compare text selections within a file, across different files, or to the clipboard.

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

That's a half-open interval.

  • A closed interval [a,b] includes the end points.
  • An open interval (a,b) excludes them.

In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".

Half-open intervals are useful in programming because they correspond to the common idiom for looping:

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

Here i is in the range [0, n).

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

How to properly validate input values with React.JS?

Use onChange={this.handleChange.bind(this, "name") method and value={this.state.fields["name"]} on input text field and below that create span element to show error, see the below example.

export default class Form extends Component {

  constructor(){
    super()
    this.state ={
       fields: {
         name:'',
         email: '',
         message: ''
       },
       errors: {},
       disabled : false
    }
  }

  handleValidation(){
       let fields = this.state.fields;
       let errors = {};
       let formIsValid = true;

       if(!fields["name"]){
          formIsValid = false;
          errors["name"] = "Name field cannot be empty";
       }

       if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
          if(!fields["name"].match(/^[a-zA-Z]+$/)){
             formIsValid = false;
             errors["name"] = "Only letters";
          }
       }

       if(!fields["email"]){
          formIsValid = false;
          errors["email"] = "Email field cannot be empty";
       }

       if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
          let lastAtPos = fields["email"].lastIndexOf('@');
          let lastDotPos = fields["email"].lastIndexOf('.');

          if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
             formIsValid = false;
             errors["email"] = "Email is not valid";
           }
      }

      if(!fields["message"]){
         formIsValid = false;
         errors["message"] = " Message field cannot be empty";
      }

      this.setState({errors: errors});
      return formIsValid;
  }

  handleChange(field, e){
      let fields = this.state.fields;
      fields[field] = e.target.value;
      this.setState({fields});
  }

  handleSubmit(e){
      e.preventDefault();
      if(this.handleValidation()){
          console.log('validation successful')
        }else{
          console.log('validation failed')
        }
  }

  render(){
    return (
      <form onSubmit={this.handleSubmit.bind(this)} method="POST">
          <div className="row">
            <div className="col-25">
                <label htmlFor="name">Name</label>
            </div>
            <div className="col-75">
                <input type="text" placeholder="Enter Name"  refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
                <span style={{color: "red"}}>{this.state.errors["name"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
              <label htmlFor="exampleInputEmail1">Email address</label>
            </div>
            <div className="col-75">
                <input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
                <span style={{color: "red"}}>{this.state.errors["email"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
                <label htmlFor="message">Message</label>
            </div>
            <div className="col-75">
                <textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
                <span style={{color: "red"}}>{this.state.errors["message"]}</span>
            </div>
          </div>
          <div className="row">
            <button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
          </div>
      </form>
    )
  }
}

Toggle Class in React

refs is not a DOM element. In order to find a DOM element, you need to use findDOMNode menthod first.

Do, this

var node = ReactDOM.findDOMNode(this.refs.btn);
node.classList.toggle('btn-menu-open');

alternatively, you can use like this (almost actual code)

this.state.styleCondition = false;


<a ref="btn" href="#" className={styleCondition ? "btn-menu show-on-small" : ""}><i></i></a>

you can then change styleCondition based on your state change conditions.

ArrayList - How to modify a member of an object?

Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.

public Employee(String name,String email){
this.name=name;
this.email=email;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setEmail(String email) {
this.email = email;
}

public String getEmail() {
return email;
}

for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("[email protected]");
}

What is the "right" way to iterate through an array in Ruby?

Use each_with_index when you need both.

ary.each_with_index { |val, idx| # ...

How to generate UML diagrams (especially sequence diagrams) from Java code?

What is your codebase? Java or C++?

alt text

eUML2 for Java is a powerful UML modeler designed for Java developper in Eclipse. The free edition can be used for commercial use. It supports the following features:

  • CVS and Team Support
  • Designed for large project with multiple and customizable model views
  • Helios Compliant
  • Real-time code/model synchronization
  • UML2.1 compliant and support of OMG XMI
  • JDK 1.4 and 1.5 support
  • The commercial edition provides:

  • Advanced reversed engineering

  • Powerful true dependency analyze tools
  • UML Profile and MDD
  • Database tools
  • Customizable template support

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

Excel - find cell with same value in another worksheet and enter the value to the left of it

Assuming employee numbers are in the first column and their names are in the second:

=VLOOKUP(A1, Sheet2!A:B, 2,false)

Clear dropdownlist with JQuery

Just use .empty():

// snip...
}).done(function (data) {
    // Clear drop down list
    $(dropdown).empty(); // <<<<<< No more issue here
    // Fill drop down list with new data
    $(data).each(function () {
        // snip...

There's also a more concise way to build up the options:

// snip...
$(data).each(function () {
    $("<option />", {
        val: this.value,
        text: this.text
    }).appendTo(dropdown);
});

How to list the tables in a SQLite database file that was opened with ATTACH?

It appears you need to go through the sqlite_master table, like this:

SELECT * FROM dbname.sqlite_master WHERE type='table';

And then manually go through each table with a SELECT or similar to look at the rows.

The .DUMP and .SCHEMA commands doesn't appear to see the database at all.

How to disable all <input > inside a form with jQuery?

Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true)

Sort a Map<Key, Value> by values

If you have duplicate keys and only a small set of data (<1000) and your code is not performance critical you can just do the following:

Map<String,Integer> tempMap=new HashMap<String,Integer>(inputUnsortedMap);
LinkedHashMap<String,Integer> sortedOutputMap=new LinkedHashMap<String,Integer>();

for(int i=0;i<inputUnsortedMap.size();i++){
    Map.Entry<String,Integer> maxEntry=null;
    Integer maxValue=-1;
    for(Map.Entry<String,Integer> entry:tempMap.entrySet()){
        if(entry.getValue()>maxValue){
            maxValue=entry.getValue();
            maxEntry=entry;
        }
    }
    tempMap.remove(maxEntry.getKey());
    sortedOutputMap.put(maxEntry.getKey(),maxEntry.getValue());
}

inputUnsortedMap is the input to the code.

The variable sortedOutputMap will contain the data in decending order when iterated over. To change order just change > to a < in the if statement.

Is not the fastest sort but does the job without any additional dependencies.

How can I change the thickness of my <hr> tag

height attribute has been deprecated in html 5. What I would do is create a border around the hr and increase the thickness of the border as such: hr style="border:solid 2px black;"

How to use global variables in React Native?

The way you should be doing it in React Native (as I understand it), is by saving your 'global' variable in your index.js, for example. From there you can then pass it down using props.

Example:

    class MainComponent extends Component {

        componentDidMount() {
            //Define some variable in your component
            this.variable = "What's up, I'm a variable";
        }
        ...
        render () {
            <Navigator
                renderScene={(() => {
                    return(
                        <SceneComponent
                                //Pass the variable you want to be global through here
                                myPassedVariable={this.variable}/>
                    );
                })}/>
        }
    }


    class SceneComponent extends Component {

        render() {
            return(
                <Text>{this.props.myPassedVariable}</Text>
            );
        }

    }

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

The solution that seemed to fix this for me, on top of PTP, is not selecting Always allow from this computer when allowing USB debugging. Revoking the authorisations and manually accepting each time the device is connected fixed this for me. (Settings -> Developer options -> Revoke USB debugging authorisations)

Why does Maven have such a bad rep?

Maven does not easily support non-standard operations. The number of useful plugins is though constantly growing. Neither Maven, nor Ant easily/intrinsically support the file dependency concept of Make.

What's the difference between returning value or Promise.resolve from then()

The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.

Quoting from the Promises/A+ spec:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

The key thing to notice here is this line:

if x is a promise, adopt its state [3.4]

link: https://promisesaplus.com/#point-49

How to automatically close cmd window after batch file execution?

This works for me

cd "C:\Program Files\SmartBear\SoapUI-5.6.0\bin"

start SoapUI-5.6.0.exe -w "C:\DATA\SoapUi\Workspaces\Production-workspace.xml"

exit

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

WITH UPD AS (UPDATE TEST_TABLE SET SOME_DATA = 'Joe' WHERE ID = 2 
RETURNING ID),
INS AS (SELECT '2', 'Joe' WHERE NOT EXISTS (SELECT * FROM UPD))
INSERT INTO TEST_TABLE(ID, SOME_DATA) SELECT * FROM INS

Tested on Postgresql 9.3

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line.
$ points to the end of the line.

\1 will be the source match within the parentheses.

Where to put default parameter value in C++?

If the functions are exposed - non-member, public or protected - then the caller should know about them, and the default values must be in the header.

If the functions are private and out-of-line, then it does make sense to put the defaults in the implementation file because that allows changes that don't trigger client recompilation (a sometimes serious issue for low-level libraries shared in enterprise scale development). That said, it is definitely potentially confusing, and there is documentation value in presenting the API in a more intuitive way in the header, so pick your compromise - though consistency's the main thing when there's no compelling reason either way.

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.