Programs & Examples On #Custom formatting

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

Swift - How to convert String to Double

Here's an extension method that allows you to simply call doubleValue() on a Swift string and get a double back (example output comes first)

println("543.29".doubleValue())
println("543".doubleValue())
println(".29".doubleValue())
println("0.29".doubleValue())

println("-543.29".doubleValue())
println("-543".doubleValue())
println("-.29".doubleValue())
println("-0.29".doubleValue())

//prints
543.29
543.0
0.29
0.29
-543.29
-543.0
-0.29
-0.29

Here's the extension method:

extension String {
    func doubleValue() -> Double
    {
        let minusAscii: UInt8 = 45
        let dotAscii: UInt8 = 46
        let zeroAscii: UInt8 = 48

        var res = 0.0
        let ascii = self.utf8

        var whole = [Double]()
        var current = ascii.startIndex

        let negative = current != ascii.endIndex && ascii[current] == minusAscii
        if (negative)
        {
            current = current.successor()
        }

        while current != ascii.endIndex && ascii[current] != dotAscii
        {
            whole.append(Double(ascii[current] - zeroAscii))
            current = current.successor()
        }

        //whole number
        var factor: Double = 1
        for var i = countElements(whole) - 1; i >= 0; i--
        {
            res += Double(whole[i]) * factor
            factor *= 10
        }

        //mantissa
        if current != ascii.endIndex
        {
            factor = 0.1
            current = current.successor()
            while current != ascii.endIndex
            {
                res += Double(ascii[current] - zeroAscii) * factor
                factor *= 0.1
                current = current.successor()
           }
        }

        if (negative)
        {
            res *= -1;
        }

        return res
    }
}

No error checking, but you can add it if you need it.

How to get ER model of database from server with Workbench

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.
  3. A wizard will be open and it will generate the ER Diagram for you.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

It seems that some apps won't read symlinked /etc/hosts (on macOS at least), you need to hardlink it.

ln /path/to/hosts_file /etc/hosts

windows batch file rename

@echo off
pushd "pathToYourFolder" || exit /b
for /f "eol=: delims=" %%F in ('dir /b /a-d *_*.jpg') do (
  for /f "tokens=1* eol=_ delims=_" %%A in ("%%~nF") do ren "%%F" "%%~nB_%%A%%~xF"
)
popd

Note: The name is split at the first occurrence of _. If a file is named "part1_part2_part3.jpg", then it will be renamed to "part2_part3_part1.jpg"

How to randomly pick an element from an array

With Java 7, one can use ThreadLocalRandom.

A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.

public static int getRandomElement(int[] arr){
    return arr[ThreadLocalRandom.current().nextInt(arr.length)];
}

//Example Usage:
int[] nums = {1, 2, 3, 4};
int randNum = getRandomElement(nums);
System.out.println(randNum);

A generic version can also be written, but it will not work for primitive arrays.

public static <T> T getRandomElement(T[] arr){
   return arr[ThreadLocalRandom.current().nextInt(arr.length)];
}

//Example Usage:
String[] strs = {"aa", "bb", "cc"};
String randStr = getRandomElement(strs);
System.out.println(randStr);

What is "loose coupling?" Please provide examples

Coupling refers to how tightly different classes are connected to one another. Tightly coupled classes contain a high number of interactions and dependencies.

Loosely coupled classes are the opposite in that their dependencies on one another are kept to a minimum and instead rely on the well-defined public interfaces of each other.

Legos, the toys that SNAP together would be considered loosely coupled because you can just snap the pieces together and build whatever system you want to. However, a jigsaw puzzle has pieces that are TIGHTLY coupled. You can’t take a piece from one jigsaw puzzle (system) and snap it into a different puzzle, because the system (puzzle) is very dependent on the very specific pieces that were built specific to that particular “design”. The legos are built in a more generic fashion so that they can be used in your Lego House, or in my Lego Alien Man.

Reference: https://megocode3.wordpress.com/2008/02/14/coupling-and-cohesion/

Best way to remove items from a collection

@smaclell asked why reverse iteration was more efficient in in a comment to @sambo99.

Sometimes it's more efficient. Consider you have a list of people, and you want to remove or filter all customers with a credit rating < 1000;

We have the following data

"Bob" 999
"Mary" 999
"Ted" 1000

If we were to iterate forward, we'd soon get into trouble

for( int idx = 0; idx < list.Count ; idx++ )
{
    if( list[idx].Rating < 1000 )
    {
        list.RemoveAt(idx); // whoops!
    }
}

At idx = 0 we remove Bob, which then shifts all remaining elements left. The next time through the loop idx = 1, but list[1] is now Ted instead of Mary. We end up skipping Mary by mistake. We could use a while loop, and we could introduce more variables.

Or, we just reverse iterate:

for (int idx = list.Count-1; idx >= 0; idx--)
{
    if (list[idx].Rating < 1000)
    {
        list.RemoveAt(idx);
    }
}

All the indexes to the left of the removed item stay the same, so you don't skip any items.

The same principle applies if you're given a list of indexes to remove from an array. In order to keep things straight you need to sort the list and then remove the items from highest index to lowest.

Now you can just use Linq and declare what you're doing in a straightforward manner.

list.RemoveAll(o => o.Rating < 1000);

For this case of removing a single item, it's no more efficient iterating forwards or backwards. You could also use Linq for this.

int removeIndex = list.FindIndex(o => o.Name == "Ted");
if( removeIndex != -1 )
{
    list.RemoveAt(removeIndex);
}

How to count the number of true elements in a NumPy bool array

In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:

Prediction:

[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]

Target:

[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

Extracting Nupkg files using command line

This worked for me:

Rename-Item -Path A_Package.nupkg -NewName A_Package.zip

Expand-Archive -Path A_Package.zip -DestinationPath C:\Reference

SQL Server loop - how do I loop through a set of records

You could choose to rank your data and add a ROW_NUMBER and count down to zero while iterate your dataset.

-- Get your dataset and rank your dataset by adding a new row_number
SELECT  TOP 1000 A.*, ROW_NUMBER() OVER(ORDER BY A.ID DESC) AS ROW
INTO #TEMPTABLE 
FROM DBO.TABLE AS A
WHERE STATUSID = 7;

--Find the highest number to start with
DECLARE @COUNTER INT = (SELECT MAX(ROW) FROM #TEMPTABLE);
DECLARE @ROW INT;

-- Loop true your data until you hit 0
WHILE (@COUNTER != 0)
BEGIN

    SELECT @ROW = ROW
    FROM #TEMPTABLE
    WHERE ROW = @COUNTER
    ORDER BY ROW DESC

    --DO SOMTHING COOL  

    -- SET your counter to -1
    SET @COUNTER = @ROW -1
END

DROP TABLE #TEMPTABLE

Why does sudo change the PATH?

You can also move your file in a sudoers used directory :

    sudo mv $HOME/bash/script.sh /usr/sbin/ 

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

How to extract public key using OpenSSL?

Though, the above technique works for the general case, it didn't work on Amazon Web Services (AWS) PEM files.

I did find in the AWS docs the following command works: ssh-keygen -y

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html

edit Thanks @makenova for the complete line:

ssh-keygen -y -f key.pem > key.pub

error C4996: 'scanf': This function or variable may be unsafe in c programming

It sounds like it's just a compiler warning.

Usage of scanf_s prevents possible buffer overflow.
See: http://code.wikia.com/wiki/Scanf_s

Good explanation as to why scanf can be dangerous: Disadvantages of scanf

So as suggested, you can try replacing scanf with scanf_s or disable the compiler warning.

pycharm running way slow

It is super easy by changing the heap size as it was mentioned. Just easily by going to Pycharm HELP -> Edit custom VM option ... and change it to:

-Xms2048m
-Xmx2048m

How do I check if a given Python string is a substring of another one?

string.find("substring") will help you. This function returns -1 when there is no substring.

Generating random numbers with Swift

you can use this in specific rate:

let die = [1, 2, 3, 4, 5, 6]
 let firstRoll = die[Int(arc4random_uniform(UInt32(die.count)))]
 let secondRoll = die[Int(arc4random_uniform(UInt32(die.count)))]

Switch: Multiple values in one case?

1 - 8 = -7

9 - 15 = -6

16 - 100 = -84

You have:

case -7:
    ...
    break;
case -6:
    ...
    break;
case -84:
    ...
    break;

Either use:

case 1:
case 2: 
case 3:

etc, or (perhaps more readable) use:

if(age >= 1 && age <= 8) {
     ...
} else if (age >= 9 && age <= 15) {
     ...
} else if (age >= 16 && age <= 100) {
     ...
} else {
     ...
}

etc

How to prevent XSS with HTML/PHP?

Cross-posting this as a consolidated reference from the SO Documentation beta which is going offline.

Problem

Cross-site scripting is the unintended execution of remote code by a web client. Any web application might expose itself to XSS if it takes input from a user and outputs it directly on a web page. If input includes HTML or JavaScript, remote code can be executed when this content is rendered by the web client.

For example, if a 3rd party side contains a JavaScript file:

// http://example.com/runme.js
document.write("I'm running");

And a PHP application directly outputs a string passed into it:

<?php
echo '<div>' . $_GET['input'] . '</div>';

If an unchecked GET parameter contains <script src="http://example.com/runme.js"></script> then the output of the PHP script will be:

<div><script src="http://example.com/runme.js"></script></div>

The 3rd party JavaScript will run and the user will see "I'm running" on the web page.

Solution

As a general rule, never trust input coming from a client. Every GET parameter, POST or PUT content, and cookie value could be anything at all, and should therefore be validated. When outputting any of these values, escape them so they will not be evaluated in an unexpected way.

Keep in mind that even in the simplest applications data can be moved around and it will be hard to keep track of all sources. Therefore it is a best practice to always escape output.

PHP provides a few ways to escape output depending on the context.

Filter Functions

PHPs Filter Functions allow the input data to the php script to be sanitized or validated in many ways. They are useful when saving or outputting client input.

HTML Encoding

htmlspecialchars will convert any "HTML special characters" into their HTML encodings, meaning they will then not be processed as standard HTML. To fix our previous example using this method:

<?php
echo '<div>' . htmlspecialchars($_GET['input']) . '</div>';
// or
echo '<div>' . filter_input(INPUT_GET, 'input', FILTER_SANITIZE_SPECIAL_CHARS) . '</div>';

Would output:

<div>&lt;script src=&quot;http://example.com/runme.js&quot;&gt;&lt;/script&gt;</div>

Everything inside the <div> tag will not be interpreted as a JavaScript tag by the browser, but instead as a simple text node. The user will safely see:

<script src="http://example.com/runme.js"></script>

URL Encoding

When outputting a dynamically generated URL, PHP provides the urlencode function to safely output valid URLs. So, for example, if a user is able to input data that becomes part of another GET parameter:

<?php
$input = urlencode($_GET['input']);
// or
$input = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_URL);
echo '<a href="http://example.com/page?input="' . $input . '">Link</a>';

Any malicious input will be converted to an encoded URL parameter.

Using specialised external libraries or OWASP AntiSamy lists

Sometimes you will want to send HTML or other kind of code inputs. You will need to maintain a list of authorised words (white list) and un-authorized (blacklist).

You can download standard lists available at the OWASP AntiSamy website. Each list is fit for a specific kind of interaction (ebay api, tinyMCE, etc...). And it is open source.

There are libraries existing to filter HTML and prevent XSS attacks for the general case and performing at least as well as AntiSamy lists with very easy use. For example you have HTML Purifier

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

How do I create an empty array/matrix in NumPy?

I think you can create empty numpy array like:

>>> import numpy as np
>>> empty_array= np.zeros(0)
>>> empty_array
array([], dtype=float64)
>>> empty_array.shape
(0,)

This format is useful when you want to append numpy array in the loop.

What's the purpose of git-mv?

From the official GitFaq:

Git has a rename command git mv, but that is just a convenience. The effect is indistinguishable from removing the file and adding another with different name and the same content

Bootstrap Modal before form Submit

You can use browser default prompt window. Instead of basic <input type="submit" (...) > try:

<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>

How to export data from Spark SQL to CSV

The error message suggests this is not a supported feature in the query language. But you can save a DataFrame in any format as usual through the RDD interface (df.rdd.saveAsTextFile). Or you can check out https://github.com/databricks/spark-csv.

How to focus on a form input text field on page load using jQuery?

Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.

You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:

var anyFieldReceivedFocus = false;

function fieldReceivedFocus() {
    anyFieldReceivedFocus = true;
}

function focusFirstField() {
    if (!anyFieldReceivedFocus) {
        // Do jQuery focus stuff
    }
}


<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">

How to delete object from array inside foreach loop?

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

How to change the text of a label?

I was having the same problem because i was using

$("#LabelID").val("some value");

I learned that you can either use the provisional jquery method to clear it first then append:

$("#LabelID").empty();
$("#LabelID").append("some Text");

Or conventionaly, you could use:

$("#LabelID").text("some value");

OR

$("#LabelID").html("some value");

Formatting a number with exactly two decimals in JavaScript

Put the following in some global scope:

Number.prototype.getDecimals = function ( decDigCount ) {
   return this.toFixed(decDigCount);
}

and then try:

var a = 56.23232323;
a.getDecimals(2); // will return 56.23

Update

Note that toFixed() can only work for the number of decimals between 0-20 i.e. a.getDecimals(25) may generate a javascript error, so to accomodate that you may add some additional check i.e.

Number.prototype.getDecimals = function ( decDigCount ) {
   return ( decDigCount > 20 ) ? this : this.toFixed(decDigCount);
}

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Regex for checking if a string is strictly alphanumeric

100% alphanumeric RegEx (it contains only alphanumeric, not even integers & characters, only alphanumeric)

For example:

special char (not allowed)
123 (not allowed)
asdf (not allowed)
1235asdf (allowed)


String name="^[^<a-zA-Z>]\\d*[a-zA-Z][a-zA-Z\\d]*$";

endsWith in JavaScript

  1. Unfortunately not.
  2. if( "mystring#".substr(-1) === "#" ) {}

How do I tell if a regular file does not exist in Bash?

To test file existence, the parameter can be any one of the following:

-e: Returns true if file exists (regular file, directory, or symlink)
-f: Returns true if file exists and is a regular file
-d: Returns true if file exists and is a directory
-h: Returns true if file exists and is a symlink

All the tests below apply to regular files, directories, and symlinks:

-r: Returns true if file exists and is readable
-w: Returns true if file exists and is writable
-x: Returns true if file exists and is executable
-s: Returns true if file exists and has a size > 0

Example script:

#!/bin/bash
FILE=$1

if [ -f "$FILE" ]; then
   echo "File $FILE exists"
else
   echo "File $FILE does not exist"
fi

Move existing, uncommitted work to a new branch in Git

If you commit it, you could also cherry-pick the single commit ID. I do this often when I start work in master, and then want to create a local branch before I push up to my origin/.

git cherry-pick <commitID>

There is alot you can do with cherry-pick, as described here, but this could be a use-case for you.

Can not change UILabel text color

It is possible, they are not connected in InterfaceBuilder.

Text colour(colorWithRed:(188/255) green:(149/255) blue:(88/255)) is correct, may be mistake in connections,

backgroundcolor is used for the background colour of label and textcolor is used for property textcolor.

Get file path of image on Android

To get the path of all images in android I am using following code

public void allImages() 
{
    ContentResolver cr = getContentResolver();
    Cursor cursor;
    Uri allimagessuri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Images.Media._ID + " != 0";

    cursor = cr.query(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
                Log.i("Image path ", fullpath + "");


            } while (cursor.moveToNext());
        }
        cursor.close();
    }

}

How do I find out my root MySQL password?

You can reset the root password by running the server with --skip-grant-tables and logging in without a password by running the following as root (or with sudo):

# service mysql stop
# mysqld_safe --skip-grant-tables &
$ mysql -u root
mysql> use mysql;
mysql> update user set authentication_string=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
# service mysql stop
# service mysql start
$ mysql -u root -p

Now you should be able to login as root with your new password.

It is also possible to find the query that reset the password in /home/$USER/.mysql_history or /root/.mysql_history of the user who reset the password, but the above will always work.

Note: prior to MySQL 5.7 the column was called password instead of authentication_string. Replace the line above with

mysql> update user set password=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

Export multiple classes in ES6 modules

For multiple classes in the same js file, extending Component from @wordpress/element, you can do that :

// classes.js
import { Component } from '@wordpress/element';

const Class1 = class extends Component {
}

const Class2 = class extends Component {
}

export { Class1, Class2 }

And import them in another js file :

import { Class1, Class2 } from './classes';

Calling a function when ng-repeat has finished

The answers that have been given so far will only work the first time that the ng-repeat gets rendered, but if you have a dynamic ng-repeat, meaning that you are going to be adding/deleting/filtering items, and you need to be notified every time that the ng-repeat gets rendered, those solutions won't work for you.

So, if you need to be notified EVERY TIME that the ng-repeat gets re-rendered and not just the first time, I've found a way to do that, it's quite 'hacky', but it will work fine if you know what you are doing. Use this $filter in your ng-repeat before you use any other $filter:

.filter('ngRepeatFinish', function($timeout){
    return function(data){
        var me = this;
        var flagProperty = '__finishedRendering__';
        if(!data[flagProperty]){
            Object.defineProperty(
                data, 
                flagProperty, 
                {enumerable:false, configurable:true, writable: false, value:{}});
            $timeout(function(){
                    delete data[flagProperty];                        
                    me.$emit('ngRepeatFinished');
                },0,false);                
        }
        return data;
    };
})

This will $emit an event called ngRepeatFinished every time that the ng-repeat gets rendered.

How to use it:

<li ng-repeat="item in (items|ngRepeatFinish) | filter:{name:namedFiltered}" >

The ngRepeatFinish filter needs to be applied directly to an Array or an Object defined in your $scope, you can apply other filters after.

How NOT to use it:

<li ng-repeat="item in (items | filter:{name:namedFiltered}) | ngRepeatFinish" >

Do not apply other filters first and then apply the ngRepeatFinish filter.

When should I use this?

If you want to apply certain css styles into the DOM after the list has finished rendering, because you need to have into account the new dimensions of the DOM elements that have been re-rendered by the ng-repeat. (BTW: those kind of operations should be done inside a directive)

What NOT TO DO in the function that handles the ngRepeatFinished event:

  • Do not perform a $scope.$apply in that function or you will put Angular in an endless loop that Angular won't be able to detect.

  • Do not use it for making changes in the $scope properties, because those changes won't be reflected in your view until the next $digest loop, and since you can't perform an $scope.$apply they won't be of any use.

"But filters are not meant to be used like that!!"

No, they are not, this is a hack, if you don't like it don't use it. If you know a better way to accomplish the same thing please let me know it.

Summarizing

This is a hack, and using it in the wrong way is dangerous, use it only for applying styles after the ng-repeat has finished rendering and you shouldn't have any issues.

Trim Cells using VBA in Excel

I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.

If you really want to use VBA I believe you could select first character

strSpace = left(range("A1").Value,1)

and use replace function in VBA the same way

Range("A1").Value = Replace(Range("A1").Value, strSpace, "")

or

for each cell in selection.cells
 cell.value = replace(cell.value, strSpace, "")
next

How do I activate a virtualenv inside PyCharm's terminal?

Following up on Peter's answer, here the Mac version of the .pycharmrc file:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

Hen

WebAPI to Return XML

In my project with netcore 2.2 I use this code:

[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
    string payload = "Something";

    OkObjectResult result = Ok( payload );

    // currently result.Formatters is empty but we'd like to ensure it will be so in the future
    result.Formatters.Clear();

    // force response as xml
    result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );

    return result;
}

It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).

Going further you could use a handy extension like this:

public static class ObjectResultExtensions
{
    public static T ForceResultAsXml<T>( this T result )
        where T : ObjectResult
    {
        result.Formatters.Clear();
        result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );

        return result;
    }
}

And your code will become like this:

[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
    string payload = "Something";

    return Ok( payload ).ForceResultAsXml();
}

In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.

P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.

Let JSON object accept bytes or let urlopen output strings

If you're experiencing this issue whilst using the flask microframework, then you can just do:

data = json.loads(response.get_data(as_text=True))

From the docs: "If as_text is set to True the return value will be a decoded unicode string"

Multi-statement Table Valued Function vs Inline Table Valued Function

There is another difference. An inline table-valued function can be inserted into, updated, and deleted from - just like a view. Similar restrictions apply - can't update functions using aggregates, can't update calculated columns, and so on.

How to search for occurrences of more than one space between words in a line

Here is my solution

[^0-9A-Z,\n]

This will remove all the digits, commas and new lines but select the middle space such as data set of

  • 20171106,16632 ESCG0000018SB
  • 20171107,280 ESCG0000018SB
  • 20171106,70476 ESCG0000018SB

HttpServletRequest - Get query string parameters, no form data

The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.

The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":

GET /persons?age=42

The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":

PUT /persons?age=42

hair=grey

So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.

#pragma once vs include guards?

After engaging in an extended discussion about the supposed performance tradeoff between #pragma once and #ifndef guards vs. the argument of correctness or not (I was taking the side of #pragma once based on some relatively recent indoctrination to that end), I decided to finally test the theory that #pragma once is faster because the compiler doesn't have to try to re-#include a file that had already been included.

For the test, I automatically generated 500 header files with complex interdependencies, and had a .c file that #includes them all. I ran the test three ways, once with just #ifndef, once with just #pragma once, and once with both. I performed the test on a fairly modern system (a 2014 MacBook Pro running OSX, using XCode's bundled Clang, with the internal SSD).

First, the test code:

#include <stdio.h>

//#define IFNDEF_GUARD
//#define PRAGMA_ONCE

int main(void)
{
    int i, j;
    FILE* fp;

    for (i = 0; i < 500; i++) {
        char fname[100];

        snprintf(fname, 100, "include%d.h", i);
        fp = fopen(fname, "w");

#ifdef IFNDEF_GUARD
        fprintf(fp, "#ifndef _INCLUDE%d_H\n#define _INCLUDE%d_H\n", i, i);
#endif
#ifdef PRAGMA_ONCE
        fprintf(fp, "#pragma once\n");
#endif


        for (j = 0; j < i; j++) {
            fprintf(fp, "#include \"include%d.h\"\n", j);
        }

        fprintf(fp, "int foo%d(void) { return %d; }\n", i, i);

#ifdef IFNDEF_GUARD
        fprintf(fp, "#endif\n");
#endif

        fclose(fp);
    }

    fp = fopen("main.c", "w");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "#include \"include%d.h\"\n", i);
    }
    fprintf(fp, "int main(void){int n;");
    for (int i = 0; i < 100; i++) {
        fprintf(fp, "n += foo%d();\n", i);
    }
    fprintf(fp, "return n;}");
    fclose(fp);
    return 0;
}

And now, my various test runs:

folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.164s
user    0m0.105s
sys 0m0.041s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.140s
user    0m0.097s
sys 0m0.018s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.193s
user    0m0.143s
sys 0m0.024s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.031s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.170s
user    0m0.109s
sys 0m0.033s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.155s
user    0m0.105s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ gcc pragma.c -DPRAGMA_ONCE -DIFNDEF_GUARD
folio[~/Desktop/pragma] fluffy$ ./a.out 
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.153s
user    0m0.101s
sys 0m0.027s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.181s
user    0m0.133s
sys 0m0.020s
folio[~/Desktop/pragma] fluffy$ time gcc -E main.c  > /dev/null

real    0m0.167s
user    0m0.119s
sys 0m0.021s
folio[~/Desktop/pragma] fluffy$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin17.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

As you can see, the versions with #pragma once were indeed slightly faster to preprocess than the #ifndef-only one, but the difference was quite negligible, and would be far overshadowed by the amount of time that actually building and linking the code would take. Perhaps with a large enough codebase it might actually lead to a difference in build times of a few seconds, but between modern compilers being able to optimize #ifndef guards, the fact that OSes have good disk caches, and the increasing speeds of storage technology, it seems that the performance argument is moot, at least on a typical developer system in this day and age. Older and more exotic build environments (e.g. headers hosted on a network share, building from tape, etc.) may change the equation somewhat but in those circumstances it seems more useful to simply make a less fragile build environment in the first place.

The fact of the matter is, #ifndef is standardized with standard behavior whereas #pragma once is not, and #ifndef also handles weird filesystem and search path corner cases whereas #pragma once can get very confused by certain things, leading to incorrect behavior which the programmer has no control over. The main problem with #ifndef is programmers choosing bad names for their guards (with name collisions and so on) and even then it's quite possible for the consumer of an API to override those poor names using #undef - not a perfect solution, perhaps, but it's possible, whereas #pragma once has no recourse if the compiler is erroneously culling an #include.

Thus, even though #pragma once is demonstrably (slightly) faster, I don't agree that this in and of itself is a reason to use it over #ifndef guards.

EDIT: Thanks to feedback from @LightnessRacesInOrbit I've increased the number of header files and changed the test to only run the preprocessor step, eliminating whatever small amount of time was being added in by the compile and link process (which was trivial before and nonexistent now). As expected, the differential is about the same.

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

How do I retrieve the number of columns in a Pandas data frame?

In order to include the number of row index "columns" in your total shape I would personally add together the number of columns df.columns.size with the attribute pd.Index.nlevels/pd.MultiIndex.nlevels:

Set up dummy data

import pandas as pd

flat_index = pd.Index([0, 1, 2])
multi_index = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), names=["letter", "id"])

columns = ["cat", "dog", "fish"]

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_df = pd.DataFrame(data, index=flat_index, columns=columns)
multi_df = pd.DataFrame(data, index=multi_index, columns=columns)

# Show data
# -----------------
# 3 columns, 4 including the index
print(flat_df)
    cat  dog  fish
id                
0     1    2     3
1     4    5     6
2     7    8     9

# -----------------
# 3 columns, 5 including the index
print(multi_df)
           cat  dog  fish
letter id                
a      1     1    2     3
       2     4    5     6
b      1     7    8     9

Writing our process as a function:

def total_ncols(df, include_index=False):
    ncols = df.columns.size
    if include_index is True:
        ncols += df.index.nlevels
    return ncols

print("Ignore the index:")
print(total_ncols(flat_df), total_ncols(multi_df))

print("Include the index:")
print(total_ncols(flat_df, include_index=True), total_ncols(multi_df, include_index=True))

This prints:

Ignore the index:
3 3

Include the index:
4 5

If you want to only include the number of indices if the index is a pd.MultiIndex, then you can throw in an isinstance check in the defined function.

As an alternative, you could use df.reset_index().columns.size to achieve the same result, but this won't be as performant since we're temporarily inserting new columns into the index and making a new index before getting the number of columns.

JPA: How to get entity based on field value other than ID?

All the answers require you to write some sort of SQL/HQL/whatever. Why? You don't have to - just use CriteriaBuilder:

Person.java:

@Entity
class Person  {
  @Id @GeneratedValue
  private int id;

  @Column(name = "name")
  private String name;
  @Column(name = "age")
  private int age;
  ...
}

Dao.java:

public class Dao  {
  public static Person getPersonByName(String name)  {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        CriteriaBuilder cb = session.getCriteriaBuilder();

        CriteriaQuery<Person> cr = cb.createQuery(Person.class);
        Root<Person> root = cr.from(Person.class);
        cr.select(root).where(cb.equal(root.get("name"), name));  //here you pass a class field, not a table column (in this example they are called the same)

        Query<Person> query = session.createQuery(cr);
        query.setMaxResults(1);
        List<Person> result = query.getResultList();
        session.close();

        return result.get(0);
  }
}

example of use:

public static void main(String[] args)  {
  Person person = Dao.getPersonByName("John");
  System.out.println(person.getAge());  //John's age
}

npm behind a proxy fails with status 403

If you need to provide a username and password to authenticate at your proxy, this is the syntax to use:

npm config set proxy http://usr:pwd@host:port
npm config set https-proxy http://usr:pwd@host:port

Python Pandas : pivot table with aggfunc = count unique distinct

Since at least version 0.16 of pandas, it does not take the parameter "rows"

As of 0.23, the solution would be:

df2.pivot_table(values='X', index='Y', columns='Z', aggfunc=pd.Series.nunique)

which returns:

Z    Z1   Z2   Z3
Y                
Y1  1.0  1.0  NaN
Y2  NaN  NaN  1.0

What is the cleanest way to ssh and run multiple commands in Bash?

The easiest way to configure your system to use single ssh sessions by default with multiplexing.

This can be done by creating a folder for the sockets:

mkdir ~/.ssh/controlmasters

And then adding the following to your .ssh configuration:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/controlmasters/%r@%h:%p.socket
    ControlMaster auto
    ControlPersist 10m

Now, you do not need to modify any of your code. This allows multiple calls to ssh and scp without creating multiple sessions, which is useful when there needs to be more interaction between your local and remote machines.

Thanks to @terminus's answer, http://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-multiplexing-to-speed-up-ssh-connections/ and https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing.

ReactJS - Get Height of an element

Following is an up to date ES6 example using a ref.

Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount() because we can only determine the height of an element after it is rendered in the DOM.

import React, {Component} from 'react'
import {render} from 'react-dom'

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

  componentDidMount() {
    const height = this.divElement.clientHeight;
    this.setState({ height });
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    )
  }
}

render(<DivSize />, document.querySelector('#container'))

You can find the running example here: https://codepen.io/bassgang/pen/povzjKw

What are the main differences between JWT and OAuth authentication?

Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.

XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e

li { display: list-item;}

With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.

How do I create a folder in VB if it doesn't exist?

Try the System.IO.DirectoryInfo class.

The sample from MSDN:

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            ' Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Detecting when a div's height changes using jQuery

There is a jQuery plugin that can deal with this very well

http://www.jqui.net/jquery-projects/jquery-mutate-official/

here is a demo of it with different scenarios as to when the height change, if you resize the red bordered div.

http://www.jqui.net/demo/mutate/

angular.service vs angular.factory

The clue is in the name

Services and factories are similar to one another. Both will yield a singleton object that can be injected into other objects, and so are often used interchangeably.

They are intended to be used semantically to implement different design patterns.

Services are for implementing a service pattern

A service pattern is one in which your application is broken into logically consistent units of functionality. An example might be an API accessor, or a set of business logic.

This is especially important in Angular because Angular models are typically just JSON objects pulled from a server, and so we need somewhere to put our business logic.

Here is a Github service for example. It knows how to talk to Github. It knows about urls and methods. We can inject it into a controller, and it will generate and return a promise.

(function() {
  var base = "https://api.github.com";

  angular.module('github', [])
    .service('githubService', function( $http ) {
      this.getEvents: function() {
        var url = [
          base,
          '/events',
          '?callback=JSON_CALLBACK'
        ].join('');
        return $http.jsonp(url);
      }
    });
  )();

Factories implement a factory pattern

Factories, on the other hand are intended to implement a factory pattern. A factory pattern in one in which we use a factory function to generate an object. Typically we might use this for building models. Here is a factory which returns an Author constructor:

angular.module('user', [])
  .factory('User', function($resource) {
    var url = 'http://simple-api.herokuapp.com/api/v1/authors/:id'
    return $resource(url);
  })

We would make use of this like so:

angular.module('app', ['user'])
  .controller('authorController', function($scope, User) {
    $scope.user = new User();
  })

Note that factories also return singletons.

Factories can return a constructor

Because a factory simply returns an object, it can return any type of object you like, including a constructor function, as we see above.

Factories return an object; services are newable

Another technical difference is in the way services and factories are composed. A service function will be newed to generate the object. A factory function will be called and will return the object.

  • Services are newable constructors.
  • Factories are simply called and return an object.

This means that in a service, we append to "this" which, in the context of a constructor, will point to the object under construction.

To illustrate this, here is the same simple object created using a service and a factory:

angular.module('app', [])
  .service('helloService', function() {
    this.sayHello = function() {
      return "Hello!";
    }
  })
  .factory('helloFactory', function() {
    return {
      sayHello: function() {
        return "Hello!";
      }
    }
  });

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

How to margin the body of the page (html)?

I would say: (simple zero will work, 0px is a zero ;))

<body style="margin: 0;">

but maybe something overwrites your css. (assigns different style after you ;))

If you use Firefox - check out firebug plugin.

And in Chrome - just right-click on the page and chose "inspect element" in the menu. Find BODY in elements tree and check its properties.

How can I read large text files in Python, line by line, without loading it into memory?

I couldn't believe that it could be as easy as @john-la-rooy's answer made it seem. So, I recreated the cp command using line by line reading and writing. It's CRAZY FAST.

#!/usr/bin/env python3.6

import sys

with open(sys.argv[2], 'w') as outfile:
    with open(sys.argv[1]) as infile:
        for line in infile:
            outfile.write(line)

Oracle Insert via Select from multiple tables where one table may not have a row

insert into received_messages(id, content, status)
    values (RECEIVED_MESSAGES_SEQ.NEXT_VAL, empty_blob(), '');

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

Toggle Class in React

For anybody reading this in 2019, after React 16.8 was released, take a look at the React Hooks. It really simplifies handling states in components. The docs are very well written with an example of exactly what you need.

res.sendFile absolute path

res.sendFile( __dirname + "/public/" + "index1.html" );

where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

How to refresh an access form

"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.

Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

How to run shell script on host from docker container?

That REALLY depends on what you need that bash script to do!

For example, if the bash script just echoes some output, you could just do

docker run --rm -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh

Another possibility is that you want the bash script to install some software- say the script to install docker-compose. you could do something like

docker run --rm -v /usr/bin:/usr/bin --privileged -v $(pwd)/mybashscript.sh:/mybashscript.sh ubuntu bash /mybashscript.sh

But at this point you're really getting into having to know intimately what the script is doing to allow the specific permissions it needs on your host from inside the container.

Global Git ignore

I am able to ignore a .tmproj file by including either .tmproj or *.tmproj in my /users/me/.gitignore-global file.

Note that the file name is .gitignore-global not .gitignore. It did not work by including .tmproj or *.tmproj in a file called .gitignore in the /users/me directory.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

How can I simulate mobile devices and debug in Firefox Browser?

You can use the already mentioned built in Responsive Design Mode (via dev tools) for setting customised screen sizes together with the Random Agent Spoofer Plugin to modify your headers to simulate you are using Mobile, Tablet etc. Many websites specify their content according to these identified headers.

As dev tools you can use the built in Developer Tools (Ctrl + Shift + I or Cmd + Shift + I for Mac) which have become quite similar to Chrome dev tools by now.

Options for initializing a string array

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

post checkbox value

There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html

Single check box

HTML code:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

PHP Code:

<?php

if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}    

?>

Check box group

<form action="checkbox-form.php" method="post">
    Which buildings do you want access to?<br />
    <input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
    <input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
    <input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
    <input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
    <input type="checkbox" name="formDoor[]" value="E" />Elliot House

    <input type="submit" name="formSubmit" value="Submit" />
 /form>

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor)) 
  {
    echo("You didn't select any buildings.");
  } 
  else
  {
    $N = count($aDoor);

    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

HTML 5 Geo Location Prompt in Chrome

As already mentioned in the answer by robertc, Chrome blocks certain functionality, like the geo location with local files. An easier alternative to setting up an own web server would be to just start Chrome with the parameter --allow-file-access-from-files. Then you can use the geo location, provided you didn't turn it off in your settings.

Print specific part of webpage

Here is my enhanced version that when we want to load css files or there are image references in the part to print.

In these cases, we have to wait until the css files or the images are fully loaded before calling the print() function. Therefor, we'd better to move the print() and close() function calls into the html. Following is the code example:

var prtContent = document.getElementById("order-to-print");
var WinPrint = window.open('', '', 'left=0,top=0,width=384,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write('<html><head>');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/normalize.css">');
WinPrint.document.write('<link rel="stylesheet" href="assets/css/print/receipt.css">');
WinPrint.document.write('</head><body onload="print();close();">');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write('</body></html>');
WinPrint.document.close();
WinPrint.focus();

How do you append to a file?

You need to open the file in append mode, by setting "a" or "ab" as the mode. See open().

When you open with "a" mode, the write position will always be at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (but all writes will still be at the end of the file!).

Example:

>>> with open('test1','wb') as f:
        f.write('test')
>>> with open('test1','ab') as f:
        f.write('koko')
>>> with open('test1','rb') as f:
        f.read()
'testkoko'

Note: Using 'a' is not the same as opening with 'w' and seeking to the end of the file - consider what might happen if another program opened the file and started writing between the seek and the write. On some operating systems, opening the file with 'a' guarantees that all your following writes will be appended atomically to the end of the file (even as the file grows by other writes).


A few more details about how the "a" mode operates (tested on Linux only). Even if you seek back, every write will append to the end of the file:

>>> f = open('test','a+') # Not using 'with' just to simplify the example REPL session
>>> f.write('hi')
>>> f.seek(0)
>>> f.read()
'hi'
>>> f.seek(0)
>>> f.write('bye') # Will still append despite the seek(0)!
>>> f.seek(0)
>>> f.read()
'hibye'

In fact, the fopen manpage states:

Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded the call:

fseek(stream, 0, SEEK_END);

Old simplified answer (not using with):

Example: (in a real program use with to close the file - see the documentation)

>>> open("test","wb").write("test")
>>> open("test","a+b").write("koko")
>>> open("test","rb").read()
'testkoko'

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell

How can I make git accept a self signed certificate?

Git Self-Signed Certificate Configuration

tl;dr

NEVER disable all SSL verification!

This creates a bad security culture. Don't be that person.

The config keys you are after are:

These are for configuring host certificates you trust

These are for configuring YOUR certificate to respond to SSL challenges.

Selectively apply the above settings to specific hosts.

Global .gitconfig for Self-Signed Certificate Authorities

For my own and my colleagues' sake here is how we managed to get self signed certificates to work without disabling sslVerify. Edit your .gitconfig to using git config --global -e add these:

# Specify the scheme and host as a 'context' that only these settings apply
# Must use Git v1.8.5+ for these contexts to work
[credential "https://your.domain.com"]
  username = user.name

  # Uncomment the credential helper that applies to your platform
  # Windows
  # helper = manager

  # OSX
  # helper = osxkeychain

  # Linux (in-memory credential helper)
  # helper = cache

  # Linux (permanent storage credential helper)
  # https://askubuntu.com/a/776335/491772

# Specify the scheme and host as a 'context' that only these settings apply 
# Must use Git v1.8.5+ for these contexts to work
[http "https://your.domain.com"]
  ##################################
  # Self Signed Server Certificate #
  ##################################

  # MUST be PEM format
  # Some situations require both the CAPath AND CAInfo 
  sslCAInfo = /path/to/selfCA/self-signed-certificate.crt
  sslCAPath = /path/to/selfCA/
  sslVerify = true

  ###########################################
  # Private Key and Certificate information #
  ###########################################

  # Must be PEM format and include BEGIN CERTIFICATE / END CERTIFICATE, 
  # not just the BEGIN PRIVATE KEY / END PRIVATE KEY for Git to recognise it.
  sslCert = /path/to/privatekey/myprivatecert.pem

  # Even if your PEM file is password protected, set this to false.
  # Setting this to true always asks for a password even if you don't have one.
  # When you do have a password, even with this set to false it will prompt anyhow. 
  sslCertPasswordProtected = 0

References:

Specify config when git clone-ing

If you need to apply it on a per repo basis, the documentation tells you to just run git config --local in your repo directory. Well that's not useful when you haven't got the repo cloned locally yet now is it?

You can do the global -> local hokey-pokey by setting your global config as above and then copy those settings to your local repo config once it clones...

OR what you can do is specify config commands at git clone that get applied to the target repo once it is cloned.

# Declare variables to make clone command less verbose     
OUR_CA_PATH=/path/to/selfCA/
OUR_CA_FILE=$OUR_CA_PATH/self-signed-certificate.crt
MY_PEM_FILE=/path/to/privatekey/myprivatecert.pem
SELF_SIGN_CONFIG="-c http.sslCAPath=$OUR_CA_PATH -c http.sslCAInfo=$OUR_CA_FILE -c http.sslVerify=1 -c http.sslCert=$MY_PEM_FILE -c http.sslCertPasswordProtected=0"

# With this environment variable defined it makes subsequent clones easier if you need to pull down multiple repos.
git clone $SELF_SIGN_CONFIG https://mygit.server.com/projects/myproject.git myproject/

One Liner

EDIT: See VonC's answer that points out a caveat about absolute and relative paths for specific git versions from 2.14.x/2.15 to this one liner

git clone -c http.sslCAPath="/path/to/selfCA" -c http.sslCAInfo="/path/to/selfCA/self-signed-certificate.crt" -c http.sslVerify=1 -c http.sslCert="/path/to/privatekey/myprivatecert.pem" -c http.sslCertPasswordProtected=0 https://mygit.server.com/projects/myproject.git myproject/

CentOS unable to load client key

If you are trying this on CentOS and your .pem file is giving you

unable to load client key: "-8178 (SEC_ERROR_BAD_KEY)"

Then you will want this StackOverflow answer about how curl uses NSS instead of Open SSL.

And you'll like want to rebuild curl from source:

git clone http://github.com/curl/curl.git curl/
cd curl/
# Need these for ./buildconf
yum install autoconf automake libtool m4 nroff perl -y
#Need these for ./configure
yum install openssl-devel openldap-devel libssh2-devel -y

./buildconf
su # Switch to super user to install into /usr/bin/curl
./configure --with-openssl --with-ldap --with-libssh2 --prefix=/usr/
make
make install

restart computer since libcurl is still in memory as a shared library

Python, pip and conda

Related: How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Get value from input (AngularJS)

If you want to get values in Javascript on frontend, you can use the native way to do it by using :

document.getElementsByName("movie")[0].value;

Where "movie" is the name of your input <input type="text" name="movie">

If you want to get it on angular.js controller, you can use;

$scope.movie

What should I set JAVA_HOME environment variable on macOS X 10.6?

I just set JAVA_HOME to the output of that command, which should give you the Java path specified in your Java preferences. Here's a snippet from my .bashrc file, which sets this variable:

export JAVA_HOME=$(/usr/libexec/java_home)

I haven't experienced any problems with that technique.

Occasionally I do have to change the value of JAVA_HOME to an earlier version of Java. For example, one program I'm maintaining requires 32-bit Java 5 on OS X, so when using that program, I set JAVA_HOME by running:

export JAVA_HOME=$(/usr/libexec/java_home -v 1.5)

For those of you who don't have java_home in your path add it like this.

sudo ln -s /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java_home /usr/libexec/java_home

References:

In Python, what is the difference between ".append()" and "+= []"?

The rebinding behaviour mentioned in other answers does matter in certain circumstances:

>>> a = ([],[])
>>> a[0].append(1)
>>> a
([1], [])
>>> a[1] += [1]
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

That's because augmented assignment always rebinds, even if the object was mutated in-place. The rebinding here happens to be a[1] = *mutated list*, which doesn't work for tuples.

How to set my default shell on Mac?

When in the terminal, open the terminal preferences using Command+,.

On the Setting Tab, select one of the themes, and choose the shell tab on the right.

You can set the autostart command fish.

Pointer vs. Reference

Use a reference when you can, use a pointer when you have to. From C++ FAQ: "When should I use references, and when should I use pointers?"

using sql count in a case statement

If you want to group the results based on a column and take the count based on the same, you can run the query as,

$sql = "SELECT COLUMNNAME,

COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'New',

COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'ACCPTED',

from TABLENAME

GROUP BY COLUMNANME";

Safely remove migration In Laravel

I accidentally created a migration with a bad name (command: php artisan migrate:make). I did not run (php artisan migrate) the migration, so I decided to remove it. My steps:

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Relax

If you did run the migration (php artisan migrate), you may do this:

a) Run migrate:rollback - it is the right way to undo the last migration (Thnx @Jakobud)

b) If migrate:rollback does not work, do it manually (I remember bugs with migrate:rollback in previous versions):

  1. Manually delete the migration file under app/database/migrations/my_migration_file_name.php
  2. Reset the composer autoload files: composer dump-autoload
  3. Modify your database: Remove the last entry from the migrations table

Credentials for the SQL Server Agent service are invalid

I found I had to be logged in as a domain user.

It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.

Logged in as domain user (but admin on machine) and it accepted the credentials.

String.Replace ignoring case

Using @Georgy Batalov solution I had a problem when using the following example

string original = "blah,DC=bleh,DC=blih,DC=bloh,DC=com"; string replaced = original.ReplaceIgnoreCase(",DC=", ".")

Below is how I rewrote his extension

public static string ReplaceIgnoreCase(this string source, string oldVale, 
string newVale)
    {
        if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
            return source;

        var stringBuilder = new StringBuilder();
        string result = source;

        int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
        bool initialRun = true;

        while (index >= 0)
        {
            string substr = result.Substring(0, index);
            substr = substr + newVale;
            result = result.Remove(0, index);
            result = result.Remove(0, oldVale.Length);

            stringBuilder.Append(substr);

            index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
        }

        if (result.Length > 0)
        {
            stringBuilder.Append(result);
        }

        return stringBuilder.ToString();
    }

How do you set a default value for a MySQL Datetime column?

Use the following code

DELIMITER $$

    CREATE TRIGGER bu_table1_each BEFORE UPDATE ON table1 FOR EACH ROW
    BEGIN
      SET new.datefield = NOW();
    END $$

    DELIMITER ;

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

Javascript - validation, numbers only

var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
   elem[i].addEventListener('keypress', function(event){
      var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
      var validIndex = keys.indexOf(event.charCode);
      if(validIndex == -1){
         event.preventDefault();
      }
  });
}

How to index into a dictionary?

If anybody still looking at this question, the currently accepted answer is now outdated:

Since Python 3.7* the dictionaries are order-preserving, that is they now behave exactly as collections.OrderedDicts used to. Unfortunately, there is still no dedicated method to index into keys() / values() of the dictionary, so getting the first key / value in the dictionary can be done as

first_key = list(colors)[0]
first_val = list(colors.values())[0]

or alternatively (this avoids instantiating the keys view into a list):

def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError

first_key = get_first_key(colors)
first_val = colors[first_key]

If you need an n-th key, then similarly

def get_nth_key(dictionary, n=0):
    if n < 0:
        n += len(dictionary)
    for i, key in enumerate(dictionary.keys()):
        if i == n:
            return key
    raise IndexError("dictionary index out of range") 

(*CPython 3.6 already included ordered dicts, but this was only an implementation detail. The language specification includes ordered dicts from 3.7 onwards.)

@class vs. #import

Compiler will complain only if you are going to use that class in such a way that the compiler needs to know its implementation.

Ex:

  1. This could be like if you are going to derive your class from it or
  2. If you are going to have an object of that class as a member variable (though rare).

It will not complain if you are just going to use it as a pointer. Of course, you will have to #import it in the implementation file (if you are instantiating an object of that class) since it needs to know the class contents to instantiate an object.

NOTE: #import is not same as #include. This means there is nothing called circular import. import is kind of a request for the compiler to look into a particular file for some information. If that information is already available, compiler ignores it.

Just try this, import A.h in B.h and B.h in A.h. There will be no problems or complaints and it will work fine too.

When to use @class

You use @class only if you don't even want to import a header in your header. This could be a case where you don't even care to know what that class will be. Cases where you may not even have a header for that class yet.

An example of this could be that you are writing two libraries. One class, lets call it A, exists in one library. This library includes a header from the second library. That header might have a pointer of A but again might not need to use it. If library 1 is not yet available, library B will not be blocked if you use @class. But if you are looking to import A.h, then library 2's progress is blocked.

How can I return to a parent activity correctly?

Adding to @LorenCK's answer, change

NavUtils.navigateUpFromSameTask(this);

to the code below if your activity can be initiated from another activity and this can become part of task started by some other app

Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
    TaskStackBuilder.create(this)
            .addNextIntentWithParentStack(upIntent)
            .startActivities();
} else {
    NavUtils.navigateUpTo(this, upIntent);
}

This will start a new task and start your Activity's parent Activity which you can define in Manifest like below of Min SDK version <= 15

<meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.app_name.A" />

Or using parentActivityName if its > 15

How to filter object array based on attributes?

here is the working fiddle which works fine in IE8 using jquery MAP function

http://jsfiddle.net/533135/Cj4j7/

json.HOMES = $.map(json.HOMES, function(val, key) {
    if (Number(val.price) <= 1000
            && Number(val.sqft) >= 500
            && Number(val.num_of_beds) >=2
            && Number(val.num_of_baths ) >= 2.5)
        return val;
});

Resetting a multi-stage form with jQuery

updated on March 2012.

So, two years after I originally answered this question I come back to see that it has pretty much turned into a big mess. I feel it's about time I come back to it and make my answer truly correct since it is the most upvoted + accepted.

For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.

My original answer was this:

// not correct, use answer below
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');

Which might work for a lot of cases, including for the OP, but as pointed out in the comments and in other answers, will clear radio/checkbox elements from any value attributes.

A more correct answer (but not perfect) is:

function resetForm($form) {
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
}

// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name

Using the :text, :radio, etc. selectors by themselves is considered bad practice by jQuery as they end up evaluating to *:text which makes it take much longer than it should. I do prefer the whitelist approach and wish I had used it in my original answer. Anyhow, by specifying the input part of the selector, plus the cache of the form element, this should make it the best performing answer here.

This answer might still have some flaws if people's default for select elements is not an option that has a blank value, but it is certainly as generic as it is going to get and this would need to be handled on a case-by-case basis.

Bootstrap 3: Keep selected tab on page refresh

Using html5 I cooked up this one:

Some where on the page:

<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>

The viewbag should just contain the id for the page/element eg.: "testing"

I created a site.js and added the scrip on the page:

/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
  function() {
    var setactive = $("#heading").data("activetab");
    var a = $('#' + setactive).addClass("active");
  }
)

Now all you have to do is to add your id's to your navbar. Eg.:

<ul class="nav navbar-nav">
  <li **id="testing" **>
    @Html.ActionLink("Lalala", "MyAction", "MyController")
  </li>
</ul>

All hail the data attribute :)

Check to see if python script is running

My solution is to check for the process and command line arguments Tested on windows and ubuntu linux

import psutil
import os

def is_running(script):
    for q in psutil.process_iter():
        if q.name().startswith('python'):
            if len(q.cmdline())>1 and script in q.cmdline()[1] and q.pid !=os.getpid():
                print("'{}' Process is already running".format(script))
                return True

    return False


if not is_running("test.py"):
    n = input("What is Your Name? ")
    print ("Hello " + n)

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

How can I pass arguments to a batch file?

Paired arguments

If you prefer passing the arguments in a key-value pair you can use something like this:

@echo off

setlocal enableDelayedExpansion

:::::  asigning arguments as a key-value pairs:::::::::::::
set counter=0
for %%# in (%*) do (    
    set /a counter=counter+1
    set /a even=counter%%2
    
    if !even! == 0 (
        echo setting !prev! to %%#
        set "!prev!=%%~#"
    )
    set "prev=%%~#"
)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: showing the assignments
echo %one% %two% %three% %four% %five%

endlocal

And an example :

c:>argumentsDemo.bat one 1 "two" 2 three 3 four 4 "five" 5
1 2 3 4 5

Predefined variables

You can also set some environment variables in advance. It can be done by setting them in the console or setting them from my computer:

@echo off

if defined variable1 (
    echo %variable1%
)

if defined variable2 (
    echo %variable2%
)

and calling it like:

c:\>set variable1=1

c:\>set variable2=2

c:\>argumentsTest.bat
1
2

File with listed values

You can also point to a file where the needed values are preset. If this is the script:

@echo off

setlocal
::::::::::
set "VALUES_FILE=E:\scripts\values.txt"
:::::::::::


for /f "usebackq eol=: tokens=* delims=" %%# in ("%VALUES_FILE%") do set "%%#"

echo %key1% %key2% %some_other_key%

endlocal

and values file is this:

:::: use EOL=: in the FOR loop to use it as a comment

key1=value1

key2=value2

:::: do not left spaces arround the =
:::: or at the begining of the line

some_other_key=something else

and_one_more=more

the output of calling it will be:

value1 value2 something else

Of course you can combine all approaches. Check also arguments syntax , shift

jQuery selector for inputs with square brackets in the name attribute

The attribute selector syntax is [name=value] where name is the attribute name and value is the attribute value.

So if you want to select all input elements with the attribute name having the value inputName[]:

$('input[name="inputName[]"]')

And if you want to check for two attributes (here: name and value):

$('input[name="inputName[]"][value=someValue]')

How to set a value of a variable inside a template code?

Perhaps the default template filter wasn't an option back in 2009...

<html>
<div>Hello {{name|default:"World"}}!</div>
</html>

SELECT last id, without INSERT

You could descendingly order the tabele by id and limit the number of results to one:

SELECT id FROM tablename ORDER BY id DESC LIMIT 1

BUT: ORDER BY rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.

What's better at freeing memory with PHP: unset() or $var = null

By doing an unset() on a variable, you've essentially marked the variable for 'garbage collection' (PHP doesn't really have one, but for example's sake) so the memory isn't immediately available. The variable no longer houses the data, but the stack remains at the larger size. Doing the null method drops the data and shrinks the stack memory almost immediately.

This has been from personal experience and others as well. See the comments of the unset() function here.

I personally use unset() between iterations in a loop so that I don't have to have the delay of the stack being yo-yo'd in size. The data is gone, but the footprint remains. On the next iteration, the memory is already being taken by php and thus, quicker to initialize the next variable.

TypeError: 'function' object is not subscriptable - Python

It is so simple, you have 2 objects with the same name and when you say: bank_holiday[month] python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ")

bank_holiday(int(input("Which month would you like to check out: ")))

How to split a delimited string into an array in awk?

To split a string to an array in awk we use the function split():

 awk '{split($0, a, ":")}'
 #           ^^  ^  ^^^
 #            |  |   |
 #       string  |   delimiter
 #               |
 #               array to store the pieces

If no separator is given, it uses the FS, which defaults to the space:

$ awk '{split($0, a); print a[2]}' <<< "a:b c:d e"
c:d

We can give a separator, for example ::

$ awk '{split($0, a, ":"); print a[2]}' <<< "a:b c:d e"
b c

Which is equivalent to setting it through the FS:

$ awk -F: '{split($0, a); print a[1]}' <<< "a:b c:d e"
b c

In gawk you can also provide the separator as a regexp:

$ awk '{split($0, a, ":*"); print a[2]}' <<< "a:::b c::d e" #note multiple :
b c

And even see what the delimiter was on every step by using its fourth parameter:

$ awk '{split($0, a, ":*", sep); print a[2]; print sep[1]}' <<< "a:::b c::d e"
b c
:::

Let's quote the man page of GNU awk:

split(string, array [, fieldsep [, seps ] ])

Divide string into pieces separated by fieldsep and store the pieces in array and the separator strings in the seps array. The first piece is stored in array[1], the second piece in array[2], and so forth. The string value of the third argument, fieldsep, is a regexp describing where to split string (much as FS can be a regexp describing where to split input records). If fieldsep is omitted, the value of FS is used. split() returns the number of elements created. seps is a gawk extension, with seps[i] being the separator string between array[i] and array[i+1]. If fieldsep is a single space, then any leading whitespace goes into seps[0] and any trailing whitespace goes into seps[n], where n is the return value of split() (i.e., the number of elements in array).

How do I uninstall nodejs installed from pkg (Mac OS X)?

In order to delete the 'native' node.js installation, I have used the method suggested in previous answers sudo npm uninstall npm -g, with additional sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*.

BUT, I had to also delete the following two directories:

sudo rm -rf /usr/local/include/node /Users/$USER/.npm

Only after that I could install node.js with Homebrew.

Can I use library that used android support with Androidx projects.

If your project is not AndroidX (mean Appcompat) and got this error, try to downgrade dependencies versions that triggers this error, in my case play-services-location ("implementation 'com.google.android.gms:play-services-location:17.0.0'") , I solved the problem by downgrading to com.google.android.gms:play-services-location:16.0.0'

Send Message in C#

You don't need to send messages.

Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.

How to select and change value of table cell with jQuery?

You can use CSS selectors.

Depending on how you get that td, you can either give it an id:

<td id='cell'>c</td>

and then use:

$("#cell").text("text");

Or traverse to the third cell of the first row of table_header, etc.

ImportError: No module named _ssl

I am writing this solution for those who are still facing such issue and cant find the solution.

in my case, I am using

shared hosting (Cpanel Access) Linux CentOS.

I was facing this issue

No module named '_ssl'

I tried for all possible solutions but as you know sometimes things don't work for you and in hosting you don't have access to fully root and run queries. even my hosting provider did for me.. but NO GOOD RESULT.

so how I solved if you are using shared hosting and you have deployed your Django App using

Setup Python App

You only have to downgrade your Python Version, I downgraded from

Python 3.7.3

(As Python 3.7 does not have SSL module in it) To

Python 3.6.8

through Setup Python App.

Hope it will be helpful for someone with the same issue,

Business logic in MVC

It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here

How do I get the day month and year from a Windows cmd.exe script?

I think that Andrei Coscodan answer is the best when you can't make many assumptions. But sometimes having a one-liner is nice if you can make some some assumptions. This solution assumes that 'date \t' will return one of two formats. On WindowsXP 'date /t 'returns "11/23/2011", but on Windows7 it returns "Wed 11/23/2011".

FOR /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mm=%%a&set dd=%%b&set yyyy=%%c& (if "%%a:~0,1" gtr "9" set mm=%%b&setdd=%%c&set yyyy=%%d))
:: Test results
echo day in 'DD' format is '%dd%'; month in 'MM' format is '%mm%'; year in 'YYYY' format is '%yyyy%'

Thanks to Andrei Consodan answer to help me with this one-line solution.

Is there a simple way that I can sort characters in a string in alphabetical order

Yes; copy the string to a char array, sort the char array, then copy that back into a string.

static string SortString(string input)
{
    char[] characters = input.ToArray();
    Array.Sort(characters);
    return new string(characters);
}

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}

how to read all files inside particular folder

If you are looking to copy all the text files in one folder to merge and copy to another folder, you can do this to achieve that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HowToCopyTextFiles
{
  class Program
  {
    static void Main(string[] args)
    {
      string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);     
      StringBuilder sb = new StringBuilder();
      foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
      {
        using (StreamReader sr = new StreamReader(txtName))
        {
          sb.AppendLine(txtName.ToString());
          sb.AppendLine("= = = = = =");
          sb.Append(sr.ReadToEnd());
          sb.AppendLine();
          sb.AppendLine();   
        }
      }
      using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
      {    
        outfile.Write(sb.ToString());
      }   
    }
  }
}

C++ string to double conversion

#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
    n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}

or

//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
    n+=( (s[x]- (s[x]<='9' ? '0':'0'+7)   ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}

Oracle JDBC ojdbc6 Jar as a Maven Dependency

It is better to add new Maven repository (preferably using your own artifactory) to your project instead of installing it to your local repository.

Maven syntax:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>
... 
<repositories>
    <repository>
      <id>codelds</id>
      <url>https://code.lds.org/nexus/content/groups/main-repo</url>
    </repository>
  </repositories>

Grails example:

mavenRepo "https://code.lds.org/nexus/content/groups/main-repo"
build 'com.oracle:ojdbc6:11.2.0.3'

Selenium WebDriver How to Resolve Stale Element Reference Exception?

This worked for me (source here):

 /**
     * Attempts to click on an element multiple times (to avoid stale element
     * exceptions caused by rapid DOM refreshes)
     *
     * @param d
     *            The WebDriver
     * @param by
     *            By element locator
     */
    public static void dependableClick(WebDriver d, By by)
    {
        final int MAXIMUM_WAIT_TIME = 10;
        final int MAX_STALE_ELEMENT_RETRIES = 5;

        WebDriverWait wait = new WebDriverWait(d, MAXIMUM_WAIT_TIME);
        int retries = 0;
        while (true)
        {
            try
            {
                wait.until(ExpectedConditions.elementToBeClickable(by)).click();

                return;
            }
            catch (StaleElementReferenceException e)
            {
                if (retries < MAX_STALE_ELEMENT_RETRIES)
                {
                    retries++;
                    continue;
                }
                else
                {
                    throw e;
                }
            }
        }
    }

Python - Count elements in list

len() 

it will count the element in the list, tuple and string and dictionary, eg.

>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string 
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple 
>>> len(tup)
3

To learn Python you can use byte of python , it is best ebook for python beginners.

Output (echo/print) everything from a PHP Array

This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.

function print_array($title,$array){

        if(is_array($array)){

            echo $title."<br/>".
            "||---------------------------------||<br/>".
            "<pre>";
            print_r($array); 
            echo "</pre>".
            "END ".$title."<br/>".
            "||---------------------------------||<br/>";

        }else{
             echo $title." is not an array.";
        }
}

Basic usage:

//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);

Results:

PETS
||---------------------------------||

Array
(
    [0] => cat
    [1] => dog
    [2] => bird
    [3] => mouse
    [4] => fish
    [5] => gerbil
)

END PETS
||---------------------------------||

Correct way to initialize HashMap and can HashMap hold different value types?

This is a change made with Java 1.5. What you list first is the old way, the second is the new way.

By using HashMap you can do things like:

HashMap<String, Doohickey> ourMap = new HashMap<String, Doohickey>();

....

Doohickey result = ourMap.get("bob");

If you didn't have the types on the map, you'd have to do this:

Doohickey result = (Doohickey) ourMap.get("bob");

It's really very useful. It helps you catch bugs and avoid writing all sorts of extra casts. It was one of my favorite features of 1.5 (and newer).

You can still put multiple things in the map, just specify it as Map, then you can put any object in (a String, another Map, and Integer, and three MyObjects if you are so inclined).

how to properly display an iFrame in mobile safari

Yeah, you can't constrain the iframe itself with height and width. You should put a div around it. If you control the content in the iframe, you can put some JS within the iframe content that will tell the parent to scroll the div when the touch event is received.

like this:

The JS:

setTimeout(function () {
var startY = 0;
var startX = 0;
var b = document.body;
b.addEventListener('touchstart', function (event) {
    parent.window.scrollTo(0, 1);
    startY = event.targetTouches[0].pageY;
    startX = event.targetTouches[0].pageX;
});
b.addEventListener('touchmove', function (event) {
    event.preventDefault();
    var posy = event.targetTouches[0].pageY;
    var h = parent.document.getElementById("scroller");
    var sty = h.scrollTop;

    var posx = event.targetTouches[0].pageX;
    var stx = h.scrollLeft;
    h.scrollTop = sty - (posy - startY);
    h.scrollLeft = stx - (posx - startX);
    startY = posy;
    startX = posx;
});
}, 1000);

The HTML:

<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="url" />
</div>

If you don't control the iframe content, you can use an overlay over the iframe in a similar manner, but then you can't interact with the iframe contents other than to scroll it - so you can't, for example, click links in the iframe.

It used to be that you could use two fingers to scroll within an iframe, but that doesn't work anymore.

Update: iOS 6 broke this solution for us. I've been attempting to get a new fix for it, but nothing has worked yet. In addition, it is no longer possible to debug javascript on the device since they introduced Remote Web Inspector, which requires a Mac to use.

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

Add Foreign Key to existing table

Simple Steps...

ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)

JavaScript - Use variable in string match

for me anyways, it helps to see it used. just made this using the "re" example:

var analyte_data = 'sample-'+sample_id;
var storage_keys = $.jStorage.index();
var re = new RegExp( analyte_data,'g');  
for(i=0;i<storage_keys.length;i++) { 
    if(storage_keys[i].match(re)) {
        console.log(storage_keys[i]);
        var partnum = storage_keys[i].split('-')[2];
    }
}

Set The Window Position of an application via command line

You'll need an additional utility such as cmdow.exe to accomplish this. Look specifically at the /mov switch. You can either launch your program from cmdow or run it separately and then invoke cmdow to move/resize it as desired.

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

Docker container will automatically stop after "docker run -d"

The centos dockerfile has a default command bash.

That means, when run in background (-d), the shell exits immediately.

Update 2017

More recent versions of docker authorize to run a container both in detached mode and in foreground mode (-t, -i or -it)

In that case, you don't need any additional command and this is enough:

docker run -t -d centos

The bash will wait in the background.
That was initially reported in kalyani-chaudhari's answer and detailed in jersey bean's answer.

vonc@voncvb:~$ d ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
4a50fd9e9189        centos              "/bin/bash"         8 seconds ago       Up 2 seconds                            wonderful_wright

Note that for alpine, Marinos An reports in the comments:

docker run -t -d alpine/git does not keep the process up.
Had to do: docker run --entrypoint "/bin/sh" -it alpine/git


Original answer (2015)

As mentioned in this article:

Instead of running with docker run -i -t image your-command, using -d is recommended because you can run your container with just one command and you don’t need to detach terminal of container by hitting Ctrl + P + Q.

However, there is a problem with -d option. Your container immediately stops unless the commands keep running in foreground.
Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.

The problem is that some application does not run in the foreground. How can we make it easier?

In this situation, you can add tail -f /dev/null to your command.
By doing this, even if your main command runs in the background, your container doesn’t stop because tail is keep running in the foreground.

So this would work:

docker run -d centos tail -f /dev/null

A docker ps would show the centos container still running.

From there, you can attach to it or detach from it (or docker exec some commands).

How to overwrite the previous print to stdout in python?

Simple Version

One way is to use the carriage return ('\r') character to return to the start of the line without advancing to the next line.

Python 3

for x in range(10):
    print(x, end='\r')
print()

Python 2.7 forward compatible

from __future__ import print_function
for x in range(10):
    print(x, end='\r')
print()

Python 2.7

for x in range(10):
    print '{}\r'.format(x),
print

Python 2.0-2.6

for x in range(10):
    print '{0}\r'.format(x),
print

In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.

Line Cleaning

If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K' ('\x1b' = ESC):

for x in range(75):
    print(‘*’ * (75 - x), x, end='\x1b[1K\r')
print()

Pip error: Microsoft Visual C++ 14.0 is required

Pycrypto has vulnerabilities assigned the CVE-2013-7459 number, and the repo hasn't accept PRs since June 23, 2014.

Pycryptodome is a drop-in replacement for the PyCrypto library, which exposes almost the same API as the old PyCrypto, see Compatibility with PyCrypto.

If you haven't install pycrypto yet, you can use pip install pycryptodome to install pycryptodome in which you won't get Microsoft Visual C++ 14.0 issue.

How to remove item from list in C#?

List<T> has two methods you can use.

RemoveAt(int index) can be used if you know the index of the item. For example:

resultlist.RemoveAt(1);

Or you can use Remove(T item):

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

When you are not sure the item really exists you can use SingleOrDefault. SingleOrDefault will return null if there is no item (Single will throw an exception when it can't find the item). Both will throw when there is a duplicate value (two items with the same id).

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

What is Turing Complete?

Fundamentally, Turing-completeness is one concise requirement, unbounded recursion.

Not even bounded by memory.

I thought of this independently, but here is some discussion of the assertion. My definition of LSP provides more context.

The other answers here don't directly define the fundamental essence of Turing-completeness.

parsing JSONP $http.jsonp() response in angular.js

The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":

JSON_CALLBACK(json_response);  // wrong!

Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!

AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:

angular.callbacks._0(json_response);

Change collations of all columns of all tables in SQL Server

Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)

SQL SCRIPT HERE:

BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'DATABASE_DEFAULT';

DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy 
INNER JOIN sys.objects  o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1

OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE tbl_cursor_changed CURSOR FOR
        SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
            , c.name column_name
            , t.Name data_type
            , c.max_length
            , c.column_id
        FROM sys.columns c
        JOIN sys.types t ON c.system_type_id = t.system_type_id
        LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
    ORDER BY c.column_id


    OPEN tbl_cursor_changed 
     FETCH NEXT FROM tbl_cursor_changed
    INTO @row_id, @column_name, @data_type, @max_length, @column_id



    WHILE @@FETCH_STATUS = 0
    BEGIN
    IF (@max_length = -1) SET @max_length = 'MAX';
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            print @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR:'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM tbl_cursor_changed
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE tbl_cursor_changed
    DEALLOCATE tbl_cursor_changed

    FETCH NEXT FROM tbl_cursor
    INTO @schema, @table

END

CLOSE tbl_cursor
DEALLOCATE tbl_cursor

PRINT 'Collation For All Tables Done!'
END

Forbidden You don't have permission to access /wp-login.php on this server

The solution is to add this to the beginning of your .htaccess

<Files wp-login.php>
Order Deny,Allow
Deny from all
Allow from all
</Files>

It's because many hosts were under attack, using the wordpress from their clients.

How do you resize a form to fit its content automatically?

If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.

this.contents.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);

How to copy a file to multiple directories using the gnu cp command

No, cp can copy multiple sources but will only copy to a single destination. You need to arrange to invoke cp multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.

How to make the overflow CSS property work with hidden as value

Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden as well, e.g.:

<div style="overflow: hidden">
  <div style="overflow: hidden">some text that should not overflow<div>
</div>

Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)

How to fade changing background image

This may help

HTML

<div id="textcontainer">        
    <span id="sometext">This is some information </span>
    <div id="container">

    </div>
</div>

CSS

#textcontainer{
    position:relative;
    border:1px solid #000;
    width :300px;
    height:300px;
}
#container{
    background-image :url("http://dcooper.org/gallery/cf_appicon.jpg");
    width :100%;
    height:100%;
}
#sometext{
    position:absolute;
    top:50%;
    left:50%;
}

Js

$('#container').css('opacity','.1');

Extension mysqli is missing, phpmyadmin doesn't work

I faced same issue and resolved it by doing following steps:

  1. First check PHP versions. If you have multiple PHP Versions. Suppose you have PHP versions like php7.0, php7.1 and php 7.2 then

  2. run these commands

For PHP7.0

sudo apt-get install php7.0-mysql
sudo apt-get install php7.0-mysqlnd 

For PHP7.1

sudo apt-get install php7.1-mysql
sudo apt-get install php7.1-mysqlnd 

For PHP7.2

sudo apt-get install php7.2-mysql
sudo apt-get install php7.2-mysqlnd 

For PHP7.3

sudo apt-get install php7.3-mysql
sudo apt-get install php7.3-mysqlnd
  1. Edit the ini file and look for mysqli. Uncomment the line by removing ; for all php versions

    extension=mysqli.so

/etc/php/<php.version>/apache2/php.ini

For PHP7.0

sudo nano /etc/php/7.0/apache2/php.ini

For PHP7.1

sudo nano /etc/php/7.1/apache2/php.ini

For PHP7.2

sudo nano /etc/php/7.2/apache2/php.ini

For PHP7.3

sudo nano /etc/php/7.3/apache2/php.ini

and last restart apache server

sudo /etc/init.d/apache2 restart

Getting Error "Form submission canceled because the form is not connected"

I saw this message using angular, so i just took method="post" and action="" out, and the warning was gone.

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Add support library to Android Studio project

Android no longer downloading the libraries from the SDK manager, it has to be accessed through Google's Maven repository.

You will have to do something similar to this in your build.gradle file:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}



dependencies {
    ...
    compile "com.android.support:support-core-utils:27.0.2"
}

Find more details about the setting up process here and about the different support library revisions here.

How do I set the value property in AngularJS' ng-options?

Instead of using the new 'track by' feature you can simply do this with an array if you want the values to be the same as the text:

<select ng-options="v as v for (k,v) in Array/Obj"></select>

Note the difference between the standard syntax, which will make the values the keys of the Object/Array, and therefore 0,1,2 etc. for an array:

<select ng-options"k as v for (k,v) in Array/Obj"></select>

k as v becomes v as v.

I discovered this just based on common sense looking at the syntax. (k,v) is the actual statement that splits the array/object into key value pairs.

In the 'k as v' statement, k will be the value, and v will be the text option displayed to the user. I think 'track by' is messy and overkill.

ImportError: No module named 'pygame'

I had the same problem and discovered that Pygame doesn't work for Python3 at least on the Mac OS, but I also have Tython2 installed in my computer as you probably do too, so when I use Pygame, I switch the path so that it uses python2 instead of python3. I use Sublime Text as my text editor so I just go to Tools > Build Systems > New Build System and enter the following:

{
    "cmd": ["/usr/local/bin/python", "-u", "$file"],    
}

instead of

{
    "cmd": ["/usr/local/bin/python3", "-u", "$file"],   
}

in my case. And when I'm not using pygame, I simply change the path back so that I can use Python3.

Javascript communication between browser tabs/windows

You can communicate between windows (tabbed or not) if they have a child-parent relationship.

Create and update a child window:

<html>
<head>
<title>Cross window test script</title>
<script>
var i = 0;
function open_and_run() {
    var w2 = window.open("", "winCounter"); 
    var myVar=setInterval(function(){myTimer(w2)},1000);
}

function myTimer(w2) {
    i++;
    w2.document.body.innerHTML="<center><h1>" + i + "</h1><p></center>";
}
</script>
</head>
<body>
Click to open a new window 
<button onclick="open_and_run();">Test This!</button>    
</body>
</html>

Child windows can use the parent object to communicate with the parent that spawned it, so you could control the music player from either window.

See it in action here: https://jsbin.com/cokipotajo/edit?html,js,output

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx


USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee'); 
GO

USE AdventureWorks2012; 
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) 
AS ObjectDefinition; 
GO

EXEC sp_helptext 'HumanResources.vEmployee';

How to dump a dict to a json file?

Also wanted to add this (Python 3.7)

import json

with open("dict_to_json_textfile.txt", 'w') as fout:
    json_dumps_str = json.dumps(a_dictionary, indent=4)
    print(json_dumps_str, file=fout)

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

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

7.1.3.2

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

Bjarne Stroustrup provides a practical example:

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

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

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

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

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


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

First let’s consider a toy example:

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

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

template <typename T>

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

Summary, for the role of using:

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

It cannot be used for:

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

Instead do:

using r = decltype(i);

Naming a set of overloads.

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

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

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

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

The solution for me was to change the .NET framework version in the Application Pools from v4.0 to v2.0 for the Default App Pool:

enter image description here

Java Embedded Databases Comparison

I needed to use Java embedded database in one of my projects and I did lot of research understanding pros and cons of each database. I wrote a blog listing pros and cons of popular embedded java databases (H2, HSQLDB, Derby, ObjectDB, Neo4j, OrientDB), you can have a look at it. I chose H2 as I thought it best suited my requirements. Link for the blog: http://sayrohan.blogspot.in/2012/12/choosing-light-weight-java-database.html Hope it helps!

arranging div one below the other

If you want the two divs to be displayed one above the other, the simplest answer is to remove the float: left;from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.

Alternatively, you could simply add clear:both; to the divs, which will force the floated content to clear previous floats.

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

How do I detect what .NET Framework versions and service packs are installed?

There is an official Microsoft answer to this question at the following knowledge base article:

Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1 How to determine which versions of the .NET Framework are installed and whether service packs have been applied

Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... why would the official Microsoft answer be so misinformed?

How to change theme for AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setMessage("Description");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Kill the previous instance of tomcat or the process that's running on 8080.

Go to terminal and do this:

lsof -i :8080

The output will be something like:

COMMAND   PID   USER      FD   TYPE  DEVICE SIZE/OFF NODE NAME
java    76746   YourName  57u  IPv6 0xd2a83c9c1e75      0t0    TCP *:http-alt (LISTEN)

Kill this process using it's PID:

kill 76746

How can I count all the lines of code in a directory recursively?

I may as well add another OS X entry, this one using plain old find with exec (which I prefer over using xargs, as I have seen odd results from very large find result sets with xargs in the past).

Because this is for OS X, I also added in the filtering to either .h or .m files - make sure to copy all the way to the end!

find ./ -type f -name "*.[mh]" -exec wc -l {}  \; | sed -e 's/[ ]*//g' | cut -d"." -f1 | paste -sd+ - | bc

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

A transport-level error has occurred when receiving results from the server

For me the answer is to upgrade the OS from 2008R2 to 2012R2, the solution of iisreset or restart apppool didn't work for me. I also tried to turn of TCP Chimney Offload setting, but I didn't restart the server because it is a production server, which didn't work either.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

File input 'accept' attribute - is it useful?

Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).

Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.

Upload folder with subfolders using S3 and the AWS console

Execute something similar to the following command:

aws s3 cp local_folder_name s3://s3_bucket_name/local_folder_name/ --recursive

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

*NgIf can create problem here , so either use display none css or easier way is to Use [hidden]="!condition"

How to delete SQLite database from Android programmatically

The SQLiteDatabase.deleteDatabase(File file) static method was added in API 16. If you want to write apps that support older devices, how do you do this?

I tried: file.delete();

but it messes up SQLiteOpenHelper.

Thanks.

NEVER MIND! I later realized you are using Context.deleteDatabase(). The Context one works great and deletes the journal too. Works for me.

Also, I found I needed to call SQLiteOpenHelp.close() before doing the delete, so that I could then use LoaderManager to recreate it.

PHP header redirect 301 - what are the implications?

The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)

After the redirect put exit(); to stop the rest of the script to execute

header("HTTP/1.1 301 Moved Permanently"); 
header("Location: /option-a"); 
exit();

How to browse localhost on Android device?

I needed to see localhost on my android device as well (Samsung S3) as I was developing a Java Web-application.
By far the fastest and easiest way is to go to this link and follow instructions: https://developer.chrome.com/devtools/docs/remote-debugging

* Note: You have to use Google Chrome.*
My summary of the above link:

  • Connect PC with Phone over USB.
  • Turn on Phone's "Developer options" from Settings
  • Go to about:inspect URL in PC's browser
  • Check "Discover USB Devices" (forward Ports if you are using them in your web-application)
  • Copy/paste localhost required link to text field in browser and click Open.

Piece of cake

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

In Maven how to exclude resources from the generated jar?

When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.

Properties files from where? Your main jar? Dependencies?

In the former case, putting resources under src/test/resources as suggested is probably the most straight forward and simplest option.

In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude in the unpackOptions.

How to execute a MySQL command from a shell script?

mysql_config_editor set --login-path=storedPasswordKey --host=localhost --user=root --password

How do I execute a command line with a secure password?? use the config editor!!!

As of mysql 5.6.6 you can store the password in a config file and then execute cli commands like this....

mysql --login-path=storedPasswordKey ....

--login-path replaces variables... host, user AND password. excellent right!

Extract substring in Bash

I love sed's capability to deal with regex groups:

> var="someletters_12345_moreletters.ext"
> digits=$( echo $var | sed "s/.*_\([0-9]\+\).*/\1/p" -n )
> echo $digits
12345

A slightly more general option would be not to assume that you have an underscore _ marking the start of your digits sequence, hence for instance stripping off all non-numbers you get before your sequence: s/[^0-9]\+\([0-9]\+\).*/\1/p.


> man sed | grep s/regexp/replacement -A 2
s/regexp/replacement/
    Attempt to match regexp against the pattern space.  If successful, replace that portion matched with replacement.  The replacement may contain the special  character  &  to
    refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

More on this, in case you're not too confident with regexps:

  • s is for _s_ubstitute
  • [0-9]+ matches 1+ digits
  • \1 links to the group n.1 of the regex output (group 0 is the whole match, group 1 is the match within parentheses in this case)
  • p flag is for _p_rinting

All escapes \ are there to make sed's regexp processing work.

Replace Div Content onclick

EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.


Here is an example of how it could work:

Working jsFiddle Demo

HTML:

<div id="someDiv">
    Once upon a midnight dreary
    <br>While I pondered weak and weary
    <br>Over many a quaint and curious
    <br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />

<input type="hidden" id="vault" />

javascript/jQuery:

//Declare persistent vars outside function
var savText, newText, myState = 0;

$('#mybutt').click(function(){
    if (myState==0){
        savText = $('#someDiv').html(); //save poem data from DIV
        newText = $('#replacementtext').val(); //save data from input field
        $('#replacementtext').val(''); //clear input field
        $('#someDiv').html( newText ); //replace poem with insert field data
        myState = 1; //remember swap has been done once
    } else {
        $('#someDiv').html(savText);
        $('#replacementtext').val(newText); //replace contents
        myState = 0;
    }
});

Calling a function every 60 seconds

There are 2 ways to call-

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

above function will call on every 60 seconds.

Android: Clear the back stack

 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

MySQL: How to reset or change the MySQL root password?

This is the solution for me. I work at Ubuntu 18.04: https://stackoverflow.com/a/46076838/2400373

But is important this change in the last step:

UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='localhost'; 

How to add elements of a string array to a string array list?

public class duplicateArrayList {


    ArrayList al = new ArrayList();
    public duplicateArrayList(Object[] obj) {

        for (int i = 0; i < obj.length; i++) {

            al.add(obj[i]);
        }

        Iterator iter = al.iterator();
        while(iter.hasNext()){

            System.out.print(" "+iter.next());
        }
    }

    public static void main(String[] args) {


    String[] str = {"A","B","C","D"};

    duplicateArrayList dd = new duplicateArrayList(str);

    }

}

How to execute a shell script from C in Linux?

If you're ok with POSIX, you can also use popen()/pclose()

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

int main(void) {
/* ls -al | grep '^d' */
  FILE *pp;
  pp = popen("ls -al", "r");
  if (pp != NULL) {
    while (1) {
      char *line;
      char buf[1000];
      line = fgets(buf, sizeof buf, pp);
      if (line == NULL) break;
      if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
    }
    pclose(pp);
  }
  return 0;
}

Remove and Replace Printed items

Just use CR to go to beginning of the line.

import time
for x in range (0,5):  
    b = "Loading" + "." * x
    print (b, end="\r")
    time.sleep(1)

org.json.simple cannot be resolved

I was facing same issue in my Spring Integration project. I added below JSON dependencies in pom.xml file. It works for me.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
</dependency>

A list of versions can be found here: https://mvnrepository.com/artifact/org.json/json

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got the same error for pandas latest version. Then saw this warning

FutureWarning: 'pandas.tools.plotting.scatter_matrix' is deprecated, import 'pandas.plotting.scatter_matrix' instead.

This shall work for you.

How to add days to the current date?

In SQL Server 2008 and above just do this:

SELECT DATEADD(day, 1, Getdate()) AS DateAdd;

How can I do an OrderBy with a dynamic string parameter?

If you are using plain LINQ-to-objects and don't want to take a dependency on an external library it is not hard to achieve what you want.

The OrderBy() clause accepts a Func<TSource, TKey> that gets a sort key from a source element. You can define the function outside the OrderBy() clause:

Func<Item, Object> orderByFunc = null;

You can then assign it to different values depending on the sort criteria:

if (sortOrder == SortOrder.SortByName)
  orderByFunc = item => item.Name;
else if (sortOrder == SortOrder.SortByRank)
  orderByFunc = item => item.Rank;

Then you can sort:

var sortedItems = items.OrderBy(orderByFunc);

This example assumes that the source type is Item that have properties Name and Rank.

Note that in this example TKey is Object to not constrain the property types that can be sorted on. If the func returns a value type (like Int32) it will get boxed when sorting and that is somewhat inefficient. If you can constrain TKey to a specific value type you can work around this problem.

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

How to run a shell script at startup

Edit the rc.local file using nano or gedit editor and add your scripts in it. File path could be /etc/rc.local or /etc/rc.d/rc.local.

sudo nano /etc/rc.local

This is the edit:

#!/bin/sh
/path-to-your-script/your-scipt-name.sh

once done press ctrl+o to update, pressEnter then ctrl+x.

Make the file executable.

sudo chmod 755 /etc/rc.local

Then initiate the rc-local service to run script during boot.

sudo systemctl start rc-local

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Along the lines of the accepted answer, if you have a JSON text sample you can plug it in to this converter, select your options and generate the C# code.

If you don't know the type at runtime, this topic looks like it would fit.

dynamically deserialize json into any object passed in. c#

Detect Browser Language in PHP

The following script is a modified version of Xeoncross's code (thank you for that Xeoncross) that falls-back to a default language setting if no languages match the supported ones, or if a match is found it replaces the default language setting with a new one according to the language priority.

In this scenario the user's browser is set in order of priority to Spanish, Dutch, US English and English and the application supports English and Dutch only with no regional variations and English is the default language. The order of the values in the "HTTP_ACCEPT_LANGUAGE" string is not important if for some reason the browser does not order the values correctly.

$supported_languages = array("en","nl");
$supported_languages = array_flip($supported_languages);
var_dump($supported_languages); // array(2) { ["en"]=> int(0) ["nl"]=> int(1) }

$http_accept_language = $_SERVER["HTTP_ACCEPT_LANGUAGE"]; // es,nl;q=0.8,en-us;q=0.5,en;q=0.3

preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);

$available_languages = array();

foreach ($matches as $match)
{
    list($language_code,$language_region) = explode('-', $match[1]) + array('', '');

    $priority = isset($match[2]) ? (float) $match[2] : 1.0;

    $available_languages[][$language_code] = $priority;
}

var_dump($available_languages);

/*
array(4) {
    [0]=>
    array(1) {
        ["es"]=>
        float(1)
    }
    [1]=>
    array(1) {
        ["nl"]=>
        float(0.8)
    }
    [2]=>
    array(1) {
        ["en"]=>
        float(0.5)
    }
    [3]=>
    array(1) {
        ["en"]=>
        float(0.3)
    }
}
*/

$default_priority = (float) 0;
$default_language_code = 'en';

foreach ($available_languages as $key => $value)
{
    $language_code = key($value);
    $priority = $value[$language_code];

    if ($priority > $default_priority && array_key_exists($language_code,$supported_languages))
    {
        $default_priority = $priority;
        $default_language_code = $language_code;

        var_dump($default_priority); // float(0.8)
        var_dump($default_language_code); // string(2) "nl"
    }
}

var_dump($default_language_code); // string(2) "nl" 

How do I skip a header from CSV files in Spark?

In PySpark you can use a dataframe and set header as True:

df = spark.read.csv(dataPath, header=True)

How to get the day name from a selected date?

try this:

DateTime.Now.DayOfWeek

Get a UTC timestamp

"... that are independent of their timezone"

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT