Programs & Examples On #Triangulation

Triangulation is either using angular measurements along a baseline to find the location of points, or splitting a polygon into triangles so that it can be rendered by a graphics library.

CKEditor instance already exists

CKeditor 4.2.1

There is a lot of answers here but for me I needed something more (bit dirty too so if anyone can improve please do). For me MODALs where my issue.

I was rendering the CKEditor in a modal, using Foundation. Ideally I would have destoryed the editor upon closing, however I didn't want to mess with Foundation.

I called delete, I tried remove and another method but this was what I finally settled with.

I was using textarea's to populate not DIVs.

My Solution

//hard code the DIV removal (due to duplication of CKeditors on page however they didn't work)

    $("#cke_myckeditorname").remove();


     if (CKEDITOR.instances['myckeditorname']) {
                delete CKEDITOR.instances['myckeditorname'];
                CKEDITOR.replace('myckeditorname', GetCKEditorSettings());
            } else {
                CKEDITOR.replace('myckeditorname', GetCKEditorSettings());
            }

this was my method to return my specific formatting, which you might not want.

    function GetCKEditorSettings()
    {
       return {
                    linkShowAdvancedTab: false,
                    linkShowTargetTab: false,
                    removePlugins: 'elementspath,magicline',
                    extraAllowedContent: 'hr blockquote div',
                    fontSize_sizes: 'small/8px;normal/12px;large/16px;larger/24px;huge/36px;',
                    toolbar: [
                        ['FontSize'],
                        ['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
                        ['Smiley']
                    ]
                };
    }

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

RESTful Authentication

It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.

The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.

jquery animate .css

If you are needing to use CSS with the jQuery .animate() function, you can use set the duration.

$("#my_image").css({
    'left':'1000px',
    6000, ''
});

We have the duration property set to 6000.

This will set the time in thousandth of seconds: 6 seconds.

After the duration our next property "easing" changes how our CSS happens.

We have our positioning set to absolute.

There are two default ones to the absolute function: 'linear' and 'swing'.

In this example I am using linear.

It allows for it to use a even pace.

The other 'swing' allows for a exponential speed increase.

There are a bunch of really cool properties to use with animate like bounce, etc.

$(document).ready(function(){
    $("#my_image").css({
        'height': '100px',
        'width':'100px',
        'background-color':'#0000EE',
        'position':'absolute'
    });// property than value

    $("#my_image").animate({
        'left':'1000px'
    },6000, 'linear', function(){
        alert("Done Animating");
    });
});

Dark Theme for Visual Studio 2010 With Productivity Power Tools

  1. Install the Visual Studio Color Theme Editor extension:
  2. Make your own color scheme or try: The Dark Expression Blend Color Theme (preview below)
  3. Once you have that, you'll want schemes for the text editor as well. This site has several, including the VS2012 "dark" theme implemented for VS2010.

Visual Studio 2010 with Dark Theme

jQuery - Appending a div to body, the body is the object?

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

Reading Properties file in Java

You can use ResourceBundle class to read the properties file.

ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");

Can't accept license agreement Android SDK Platform 24

I had the Android SDK by installing the Android Studio and got this error too. There's a simple solution from the user guide.

  1. On a machine with Android Studio installed, click Tools > Android > SDK Manager. At the top of the window, note the Android SDK Location.

  2. Navigate to that directory and locate the licenses/ directory inside it.

    (If you do not see a licenses/ directory, return to Android Studio and update your SDK tools, making sure to accept the license agreements. When you return to the Android SDK home directory, you should now see the directory.)

  3. Copy the entire licenses/ directory and paste it into the Android SDK home directory on the machine where you wish to build your projects.

How to check if a file exists in a folder?

This way we can check for an existing file in a particular folder:

 string curFile = @"c:\temp\test.txt";  //Your path
 Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

Start HTML5 video at a particular position when loading?

You can link directly with Media Fragments URI, just change the filename to file.webm#t=50

Here's an example

This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.

SELECT from nothing?

For ClickHouse, the nothing is system.one

SELECT 1 FROM system.one

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

First kill all the hanged instances of httpd, and then try restarting Apache:

service httpd restart

Get Filename Without Extension in Python

You can use stem method to get file name.

Here is an example:

from pathlib import Path

p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file

Find and extract a number from a string

var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
    int val;
    if(int.TryParse(match.Value,out val))
    {
        //val is set
    }
}

What's the difference between Unicode and UTF-8?

Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!

Combine or merge JSON on node.js without jQuery

If using Node version >= 4, use Object.assign() (see Ricardo Nolde's answer).

If using Node 0.x, there is the built in util._extend:

var extend = require('util')._extend
var o = extend({}, {name: "John"});
extend(o,  {location: "San Jose"});

It doesn't do a deep copy and only allows two arguments at a time, but is built in. I saw this mentioned on a question about cloning objects in node: https://stackoverflow.com/a/15040626.

If you're concerned about using a "private" method, you could always proxy it:

// myutil.js
exports.extend = require('util')._extend;

and replace it with your own implementation if it ever disappears. This is (approximately) their implementation:

exports.extend = function(origin, add) {
    if (!add || (typeof add !== 'object' && add !== null)){
        return origin;
    }

    var keys = Object.keys(add);
    var i = keys.length;
    while(i--){
        origin[keys[i]] = add[keys[i]];
    }
    return origin;
};

Kafka consumer list

All the consumers per topic

(Replace --zookeeper with --bootstrap-server to get groups stored by newer Kafka clients)

Get all consumers-per-topic as a table of topictabconsumer:

for t in `kafka-consumer-groups.sh --zookeeper <HOST>:2181 --list 2>/dev/null`; do
    echo $t | xargs -I {} sh -c "kafka-consumer-groups.sh --zookeeper <HOST>:2181 --describe --group {} 2>/dev/null | grep ^{} | awk '{print \$2\"\t\"\$1}' "
done > topic-consumer.txt

Make this pairs unique:

cat topic-consumer.txt | sort -u > topic-consumer-u.txt

Get the desired one:

less topic-consumer-u.txt | grep -i <TOPIC>

How to use mod operator in bash?

This might be off-topic. But for the wget in for loop, you can certainly do

curl -O http://example.com/search/link[1-600]

How can I upload fresh code at github?

In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password

Update new Change code into Github

->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

how to implement regions/code collapse in javascript

For VS 2019, this should work without installing anything:

enter image description here

    //#region MyRegion1

    foo() {

    }

    //#endregion

    //#region MyRegion2

    bar() {

    }

    //#endregion

How to draw a custom UIView that is just a circle - iPhone app

Swift 3 - Xcode 8.1

@IBOutlet weak var myView: UIView!

override func viewDidLoad() {
    super.viewDidLoad() 

    let size:CGFloat = 35.0
    myView.bounds = CGRect(x: 0, y: 0, width: size, height: size)
    myView.layer.cornerRadius = size / 2
    myView.layer.borderWidth = 1
    myView.layer.borderColor = UIColor.Gray.cgColor        
}

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

javascript regular expression to not match a word

This is what you are looking for:

^((?!(abc|def)).)*$

the explanation is here: Regular expression to match a line that doesn't contain a word?

Setting up and using environment variables in IntelliJ Idea

In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me

How to export data from Spark SQL to CSV

With the help of spark-csv we can write to a CSV file.

val dfsql = sqlContext.sql("select * from tablename")
dfsql.write.format("com.databricks.spark.csv").option("header","true").save("output.csv")`

How to toggle font awesome icon on click?

You can change the code by using class definition for the i element:

<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>

Then you can switch the classes rapresenting the plus/minus state using toggleClass with multiple classes:

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});

Demo: http://jsfiddle.net/Zcn2u/

How to correctly implement custom iterators and const_iterators?

I don't know if Boost has anything that would help.

My preferred pattern is simple: take a template argument which is equal to value_type, either const qualified or not. If necessary, also a node type. Then, well, everything kind of falls into place.

Just remember to parameterize (template-ize) everything that needs to be, including the copy constructor and operator==. For the most part, the semantics of const will create correct behavior.

template< class ValueType, class NodeType >
struct my_iterator
 : std::iterator< std::bidirectional_iterator_tag, T > {
    ValueType &operator*() { return cur->payload; }

    template< class VT2, class NT2 >
    friend bool operator==
        ( my_iterator const &lhs, my_iterator< VT2, NT2 > const &rhs );

    // etc.

private:
    NodeType *cur;

    friend class my_container;
    my_iterator( NodeType * ); // private constructor for begin, end
};

typedef my_iterator< T, my_node< T > > iterator;
typedef my_iterator< T const, my_node< T > const > const_iterator;

How to get the background color of an HTML element?

Simple solution

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

Now the background color is stored in the new variable.

https://jsfiddle.net/7q1dpeo9/1/

Quoting backslashes in Python string literals

Use a raw string:

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'

Note that although it looks wrong, it's actually right. There is only one backslash in the string foo.

This happens because when you just type foo at the prompt, python displays the result of __repr__() on the string. This leads to the following (notice only one backslash and no quotes around the printed string):

>>> foo = r'baz "\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"

And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:

>>> foo = r'baz \'
  File "<stdin>", line 1
    foo = r'baz \'
                 ^  
SyntaxError: EOL while scanning single-quoted string

Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:

>>> foo = 'baz \\'
>>> print(foo)
baz \

However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the os.path.normpath() function:

myfile = os.path.normpath('c:/folder/subfolder/file.txt')
open(myfile)

This will save a lot of escaping and hair-tearing. This page was handy when going through this a while ago.

Regular expression to get a string between two strings in Javascript

If the data is on multiple lines then you may have to use the following,

/My cow ([\s\S]*)milk/gm

My cow always gives 
milk

Regex 101 example

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

Option to ignore case with .contains method?

I know I'm a little late to the party but in Kotlin you can easily use:

fun Collection<String>.containsIgnoreCase(item: String) = any {
    it.equals(item, ignoreCase = true)
}


val list = listOf("Banana")

println(list.contains("banana"))
println(list.containsIgnoreCase("BaNaNa"))

top -c command in linux to filter processes listed based on processname

You can add filters to top while it is running, just press the o key and then type in a filter expression. For example, to monitor all java processes use the filter expression COMMAND=java. You can add multiple filters by pressing the key again, you can filter by user with the u key, and you can clear all filters with the = key.

Algorithm for Determining Tic Tac Toe Game Over

I just wrote this for my C programming class.

I am posting it because none of the other examples here will work with any size rectangular grid, and any number N-in-a-row consecutive marks to win.

You'll find my algorithm, such as it is, in the checkWinner() function. It doesn't use magic numbers or anything fancy to check for a winner, it simply uses four for loops - The code is well commented so I'll let it speak for itself I guess.

// This program will work with any whole number sized rectangular gameBoard.
// It checks for N marks in straight lines (rows, columns, and diagonals).
// It is prettiest when ROWS and COLS are single digit numbers.
// Try altering the constants for ROWS, COLS, and N for great fun!    

// PPDs come first

    #include <stdio.h>
    #define ROWS 9              // The number of rows our gameBoard array will have
    #define COLS 9              // The number of columns of the same - Single digit numbers will be prettier!
    #define N 3                 // This is the number of contiguous marks a player must have to win
    #define INITCHAR ' '        // This changes the character displayed (a ' ' here probably looks the best)
    #define PLAYER1CHAR 'X'     // Some marks are more aesthetically pleasing than others
    #define PLAYER2CHAR 'O'     // Change these lines if you care to experiment with them


// Function prototypes are next

    int playGame    (char gameBoard[ROWS][COLS]);               // This function allows the game to be replayed easily, as desired
    void initBoard  (char gameBoard[ROWS][COLS]);               // Fills the ROWSxCOLS character array with the INITCHAR character
    void printBoard (char gameBoard[ROWS][COLS]);               // Prints out the current board, now with pretty formatting and #s!
    void makeMove   (char gameBoard[ROWS][COLS], int player);   // Prompts for (and validates!) a move and stores it into the array
    int checkWinner (char gameBoard[ROWS][COLS], int player);   // Checks the current state of the board to see if anyone has won

// The starting line
int main (void)
{
    // Inits
    char gameBoard[ROWS][COLS];     // Our gameBoard is declared as a character array, ROWS x COLS in size
    int winner = 0;
    char replay;

    //Code
    do                              // This loop plays through the game until the user elects not to
    {
        winner = playGame(gameBoard);
        printf("\nWould you like to play again? Y for yes, anything else exits: ");

        scanf("%c",&replay);        // I have to use both a scanf() and a getchar() in
        replay = getchar();         // order to clear the input buffer of a newline char
                                    // (http://cboard.cprogramming.com/c-programming/121190-problem-do-while-loop-char.html)

    } while ( replay == 'y' || replay == 'Y' );

    // Housekeeping
    printf("\n");
    return winner;
}


int playGame(char gameBoard[ROWS][COLS])
{
    int turn = 0, player = 0, winner = 0, i = 0;

    initBoard(gameBoard);

    do
    {
        turn++;                                 // Every time this loop executes, a unique turn is about to be made
        player = (turn+1)%2+1;                  // This mod function alternates the player variable between 1 & 2 each turn
        makeMove(gameBoard,player);
        printBoard(gameBoard);
        winner = checkWinner(gameBoard,player);

        if (winner != 0)
        {
            printBoard(gameBoard);

            for (i=0;i<19-2*ROWS;i++)           // Formatting - works with the default shell height on my machine
                printf("\n");                   // Hopefully I can replace these with something that clears the screen for me

            printf("\n\nCongratulations Player %i, you've won with %i in a row!\n\n",winner,N);
            return winner;
        }

    } while ( turn < ROWS*COLS );                           // Once ROWS*COLS turns have elapsed

    printf("\n\nGame Over!\n\nThere was no Winner :-(\n");  // The board is full and the game is over
    return winner;
}


void initBoard (char gameBoard[ROWS][COLS])
{
    int row = 0, col = 0;

    for (row=0;row<ROWS;row++)
    {
        for (col=0;col<COLS;col++)
        {
            gameBoard[row][col] = INITCHAR;     // Fill the gameBoard with INITCHAR characters
        }
    }

    printBoard(gameBoard);                      // Having this here prints out the board before
    return;                             // the playGame function asks for the first move
}


void printBoard (char gameBoard[ROWS][COLS])    // There is a ton of formatting in here
{                                               // That I don't feel like commenting :P
    int row = 0, col = 0, i=0;                  // It took a while to fine tune
                                                // But now the output is something like:
    printf("\n");                               // 
                                                //    1   2   3
    for (row=0;row<ROWS;row++)                  // 1    |   |
    {                                           //   -----------
        if (row == 0)                           // 2    |   |
        {                                       //   -----------
            printf("  ");                       // 3    |   |

            for (i=0;i<COLS;i++)
            {
                printf(" %i  ",i+1);
            }

            printf("\n\n");
        }

        for (col=0;col<COLS;col++)
        {
            if (col==0)
                printf("%i ",row+1);

            printf(" %c ",gameBoard[row][col]);

            if (col<COLS-1)
                printf("|");
        }

        printf("\n");

        if (row < ROWS-1)
        {
            for(i=0;i<COLS-1;i++)
            {
                if(i==0)
                    printf("  ----");
                else
                    printf("----");
            }

            printf("---\n");
        }
    }

    return;
}


void makeMove (char gameBoard[ROWS][COLS],int player)
{
    int row = 0, col = 0, i=0;
    char currentChar;

    if (player == 1)                    // This gets the correct player's mark
        currentChar = PLAYER1CHAR;
    else
        currentChar = PLAYER2CHAR;

    for (i=0;i<21-2*ROWS;i++)           // Newline formatting again :-(
        printf("\n");

    printf("\nPlayer %i, please enter the column of your move: ",player);
    scanf("%i",&col);
    printf("Please enter the row of your move: ");
    scanf("%i",&row);

    row--;                              // These lines translate the user's rows and columns numbering
    col--;                              // (starting with 1) to the computer's (starting with 0)

    while(gameBoard[row][col] != INITCHAR || row > ROWS-1 || col > COLS-1)  // We are not using a do... while because
    {                                                                       // I wanted the prompt to change
        printBoard(gameBoard);
        for (i=0;i<20-2*ROWS;i++)
            printf("\n");
        printf("\nPlayer %i, please enter a valid move! Column first, then row.\n",player);
        scanf("%i %i",&col,&row);

        row--;                          // See above ^^^
        col--;
    }

    gameBoard[row][col] = currentChar;  // Finally, we store the correct mark into the given location
    return;                             // And pop back out of this function
}


int checkWinner(char gameBoard[ROWS][COLS], int player)     // I've commented the last (and the hardest, for me anyway)
{                                                           // check, which checks for backwards diagonal runs below >>>
    int row = 0, col = 0, i = 0;
    char currentChar;

    if (player == 1)
        currentChar = PLAYER1CHAR;
    else
        currentChar = PLAYER2CHAR;

    for ( row = 0; row < ROWS; row++)                       // This first for loop checks every row
    {
        for ( col = 0; col < (COLS-(N-1)); col++)           // And all columns until N away from the end
        {
            while (gameBoard[row][col] == currentChar)      // For consecutive rows of the current player's mark
            {
                col++;
                i++;
                if (i == N)
                {
                    return player;
                }
            }
            i = 0;
        }
    }

    for ( col = 0; col < COLS; col++)                       // This one checks for columns of consecutive marks
    {
        for ( row = 0; row < (ROWS-(N-1)); row++)
        {
            while (gameBoard[row][col] == currentChar)
            {
                row++;
                i++;
                if (i == N)
                {
                    return player;
                }
            }
            i = 0;
        }
    }

    for ( col = 0; col < (COLS - (N-1)); col++)             // This one checks for "forwards" diagonal runs
    {
        for ( row = 0; row < (ROWS-(N-1)); row++)
        {
            while (gameBoard[row][col] == currentChar)
            {
                row++;
                col++;
                i++;
                if (i == N)
                {
                    return player;
                }
            }
            i = 0;
        }
    }
                                                        // Finally, the backwards diagonals:
    for ( col = COLS-1; col > 0+(N-2); col--)           // Start from the last column and go until N columns from the first
    {                                                   // The math seems strange here but the numbers work out when you trace them
        for ( row = 0; row < (ROWS-(N-1)); row++)       // Start from the first row and go until N rows from the last
        {
            while (gameBoard[row][col] == currentChar)  // If the current player's character is there
            {
                row++;                                  // Go down a row
                col--;                                  // And back a column
                i++;                                    // The i variable tracks how many consecutive marks have been found
                if (i == N)                             // Once i == N
                {
                    return player;                      // Return the current player number to the
                }                                       // winnner variable in the playGame function
            }                                           // If it breaks out of the while loop, there weren't N consecutive marks
            i = 0;                                      // So make i = 0 again
        }                                               // And go back into the for loop, incrementing the row to check from
    }

    return 0;                                           // If we got to here, no winner has been detected,
}                                                       // so we pop back up into the playGame function

// The end!

// Well, almost.

// Eventually I hope to get this thing going
// with a dynamically sized array. I'll make
// the CONSTANTS into variables in an initGame
// function and allow the user to define them.

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

CodeIgniter - return only one row?

If you require to get only one record from database table using codeigniter query then you can do it using row(). we can easily return one row from database in codeigniter.

$data = $this->db->get("items")->row();

How to both read and write a file in C#

you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder

P.S dont forget to add Console.Readline() after this code snippet else console will not appear.

TextWriter tw = new StreamWriter("filename.txt");
        String text = "Hello";
        tw.WriteLine(text);
        tw.Close();

        TextReader tr = new StreamReader("filename.txt");
        Console.WriteLine(tr.ReadLine());
        tr.Close();

Jquery Validate custom error message location

HTML

<form ... id ="GoogleMapsApiKeyForm">
    ...
    <input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
    ....
    <span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
    ...
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Javascript

$(function () {
    $("#GoogleMapsApiKeyForm").validate({
      rules: {
          GoogleMapsAPIKey: {
              required: true
          }
        },
        messages: {
            GoogleMapsAPIKey: 'Google maps api key is required',
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "GoogleMapsAPIKey")
                $("#GoogleMapsAPIKey-errorMsg").html(error);
        },
        submitHandler: function (form) {
           // form.submit(); //if you need Ajax submit follow for rest of code below
        }
    });

    //If you want to use ajax
    $("#GoogleMapsApiKeyForm").submit(function (e) {
        e.preventDefault();
        if (!$("#GoogleMapsApiKeyForm").valid())
            return;

       //Put your ajax call here
    });
});

Shell script to check if file exists

for entry in "/home/loc/etc/"/*
do

   if [ -s /home/loc/etc/$entry ]
   then
       echo "$entry File is available"
   else
       echo "$entry File is not available"
fi
done

Hope it helps

What is the difference between NULL, '\0' and 0?

A byte with a value of 0x00 is, on the ASCII table, the special character called NUL or NULL. In C, since you shouldn't embed control characters in your source code, this is represented in C strings with an escaped 0, i.e., \0.

But a true NULL is not a value. It is the absence of a value. For a pointer, it means the pointer has nothing to point to. In a database, it means there is no value in a field (which is not the same thing as saying the field is blank, 0, or filled with spaces).

The actual value a given system or database file format uses to represent a NULL isn't necessarily 0x00.

How to check for a valid Base64 encoded string

I would suggest creating a regex to do the job. You'll have to check for something like this: [a-zA-Z0-9+/=] You'll also have to check the length of the string. I'm not sure on this one, but i'm pretty sure if something gets trimmed (other than the padding "=") it would blow up.

Or better yet check out this stackoverflow question

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

How to create CSV Excel file C#?

Another good solution to read and write CSV-files is filehelpers (open source).

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

Convert Year/Month/Day to Day of Year in Python

Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:

from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday  # returns 1 for January 1st

When to use static classes in C#

I wrote my thoughts of static classes in an earlier Stack Overflow answer: Class with single method -- best approach?

I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.

Polymorphism

Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.

Interface woes

Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.

Testing

This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.

Fosters blobs

As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.

Parameter creep

To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.

Demanding consumers to create an instance of classes for no reason

One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();

Only a Sith deals in absolutes

Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.

Standards, standards, standards!

Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.

Get name of object or class

All we need:

  1. Wrap a constant in a function (where the name of the function equals the name of the object we want to get)
  2. Use arrow functions inside the object

_x000D_
_x000D_
console.clear();_x000D_
function App(){ // name of my constant is App_x000D_
  return {_x000D_
  a: {_x000D_
    b: {_x000D_
      c: ()=>{ // very important here, use arrow function _x000D_
        console.log(this.constructor.name)_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
}_x000D_
const obj = new App(); // usage_x000D_
_x000D_
obj.a.b.c(); // App_x000D_
_x000D_
// usage with react props etc, _x000D_
// For instance, we want to pass this callback to some component_x000D_
_x000D_
const myComponent = {};_x000D_
myComponent.customProps = obj.a.b.c;_x000D_
myComponent.customProps(); // App
_x000D_
_x000D_
_x000D_

Why should I use IHttpActionResult instead of HttpResponseMessage?

We have the following benefits of using IHttpActionResult over HttpResponseMessage:

  1. By using the IHttpActionResult we are only concentrating on the data to be send not on the status code. So here the code will be cleaner and very easy to maintain.
  2. Unit testing of the implemented controller method will be easier.
  3. Uses async and await by default.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:

Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");

You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.

Bootstrap 4 - Inline List?

Bootstrap4

Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.

<ul class="list-inline">
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>

keyCode values for numeric keypad?

Docs says the order of events related to the onkeyxxx event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

If you use like below code, it fits with also backspace and enter user interactions. After you can do what you want in onKeyPress or onKeyUp events. Code block trigger event.preventDefault function if the value is not number,backspace or enter.

onInputKeyDown = event => {
    const { keyCode } = event;
    if (
      (keyCode >= 48 && keyCode <= 57) ||
      (keyCode >= 96 && keyCode <= 105) ||
      keyCode === 8 || //Backspace key
      keyCode === 13   //Enter key
    ) {
    } else {
      event.preventDefault();
    }
  };

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

Handling click events on a drawable within an EditText

I implemented @aristo_sh answer in Mono.Droid (Xamarin), since it's a delegate anonymous method you can't return true or false you have to take take of e.Event.Handled. I am also hiding the keyboard on click

editText.Touch += (sender, e) => {
                    e.Handled = false;
                    if (e.Event.Action == MotionEventActions.Up)
                    {
                        if (e.Event.RawX >= (bibEditText.Right - (bibEditText.GetCompoundDrawables()[2]).Bounds.Width()))
                        {
                            SearchRunner();
                            InputMethodManager manager = (InputMethodManager)GetSystemService(InputMethodService);
                            manager.HideSoftInputFromWindow(editText.WindowToken, 0);
                            e.Handled = true;
                        }
                    }
                };

AngularJS not detecting Access-Control-Allow-Origin header?

It can also happen when your parameters are wrong in the request. In my case I was working with a API that sent me the message

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401."

when I send wrong username or password with the POST request to login.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Supplement to Iman Mahmoudinasab's answer

For SQL Server 2016, this is where to find the files:

https://www.microsoft.com/en-us/download/details.aspx?id=52676

Note that the files are in the list but you may need to scroll down to see/select it.

From SQL Server 2017 onwards, things change:

"Beginning with SQL Server 2017 SMO is distributed as the Microsoft.SqlServer.SqlManagementObjects NuGet package to allow users to develop applications with SMO."

Source: https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/installing-smo?view=sql-server-2017

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Check whether your config string is okay:

Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999

I just had this issue today, and in my case it was because there was an invisible character in the jpda config parameter.

To be precise, I had dos line endings in my setenv.sh file on tomcat, causing a carriage-return character right after 'dt_socket'

How can I add items to an empty set in python

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

Sleep function in C++

Prior to C++11, there was no portable way to do this.

A portable way is to use Boost or Ace library. There is ACE_OS::sleep(); in ACE.

Check if all checkboxes are selected

I think the easiest way is checking for this condition:

$('.abc:checked').length == $('.abc').length

You could do it every time a new checkbox is checked:

$(".abc").change(function(){
    if ($('.abc:checked').length == $('.abc').length) {
       //do something
    }
});

Simple Pivot Table to Count Unique Values

Excel 2013 can do Count distinct in pivots. If no access to 2013, and it's a smaller amount of data, I make two copies of the raw data, and in copy b, select both columns and remove duplicates. Then make the pivot and count your column b.

Reverse a comparator in Java 8

You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:

Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
        .thenComparingInt(SomeEntity::getProperty2)
        .thenComparing(SomeEntity::getProperty3, reverseOrder());

'float' vs. 'double' precision

Floating point numbers in C use IEEE 754 encoding.

This type of encoding uses a sign, a significand, and an exponent.

Because of this encoding, many numbers will have small changes to allow them to be stored.

Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

How can I group data with an Angular filter?

I originally used Plantface's answer, but I didn't like how the syntax looked in my view.

I reworked it to use $q.defer to post-process the data and return a list on unique teams, which is then uses as the filter.

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

View

<ul>
  <li ng-repeat="team in teams">{{team}}
    <ul>
      <li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li> 
    </ul>
  </li>
</ul>

Controller

app.controller('MainCtrl', function($scope, $q) {

  $scope.players = []; // omitted from SO for brevity

  // create a deferred object to be resolved later
  var teamsDeferred = $q.defer();

  // return a promise. The promise says, "I promise that I'll give you your
  // data as soon as I have it (which is when I am resolved)".
  $scope.teams = teamsDeferred.promise;

  // create a list of unique teams. unique() definition omitted from SO for brevity
  var uniqueTeams = unique($scope.players, 'team');

  // resolve the deferred object with the unique teams
  // this will trigger an update on the view
  teamsDeferred.resolve(uniqueTeams);

});

Deny access to one specific folder in .htaccess

Just put .htaccess into the folder you want to restrict

## no access to this folder

# Apache 2.4
<IfModule mod_authz_core.c>
    Require all denied
</IfModule>

# Apache 2.2
<IfModule !mod_authz_core.c>
    Order Allow,Deny
    Deny from all
</IfModule>

Source: MantisBT sources.

how to remove time from datetime

TSQL

SELECT CONVERT(DATE, GETDATE())         // 2019-09-19
SELECT CAST(GETDATE() AS DATE)          // 2019-09-19
SELECT CONVERT(VARCHAR, GETDATE(), 23)  // 2019-09-19

How to check the gradle version in Android Studio?

You can install andle for gradle version management.

It can help you sync to the latest version almost everything in gradle file.

Simple three step to update all project at once.

1. install:

    $ sudo pip install andle

2. set sdk:

    $ andle setsdk -p <sdk_path>

3. update depedency:

    $ andle update -p <project_path> [--dryrun] [--remote] [--gradle]

--dryrun: only print result in console

--remote: check version in jcenter and mavenCentral

--gradle: check gradle version

See https://github.com/Jintin/andle for more information

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

How to download image using requests

Get a file-like object from the request and copy it to a file. This will also avoid reading the whole thing into memory at once.

import shutil

import requests

url = 'http://example.com/img.png'
response = requests.get(url, stream=True)
with open('img.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Precision String Format Specifier In Swift

Swift 4

let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)

What is a Subclass

If you have the following:

public class A
{
}

public class B extends A
{
}

then B is a subclass of A, B inherits from A. The opposite would be superclass.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

Why does jQuery or a DOM method such as getElementById not find the element?

As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).

However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.

Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.

Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).

How to remove the Flutter debug banner?

  • If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions.

Android Studio

  • Or if you're using Dart DevTools, you can find the same button in the top right corner as well.

Dart DevTools

How do I prevent 'git diff' from using a pager?

You can add an alias to diff with its own pager with pager.alias, like so:

[alias]
  dc = diff
  dsc = diff --staged
[pager]
  dc = cat
  dsc = cat

This will keep the color on and use 'cat' as the pager when invoked at 'git dc'.

Also, things not to do:

  • use --no-pager in your alias. Git (1.8.5.2, Apple Git-48) will complain that you are trying to modify the environment.
  • use a shell with !sh or !git. This will bypass the environment error, above, but it will reset your working directory (for the purposes of this command) to the top-level Git directory, so any references to a local file will not work if you are already in a subdirectory of your repository.

Using a bitmask in C#

I have included an example here which demonstrates how you might store the mask in a database column as an int, and how you would reinstate the mask later on:

public enum DaysBitMask { Mon=0, Tues=1, Wed=2, Thu = 4, Fri = 8, Sat = 16, Sun = 32 }


DaysBitMask mask = DaysBitMask.Sat | DaysBitMask.Thu;
bool test;
if ((mask & DaysBitMask.Sat) == DaysBitMask.Sat)
    test = true;
if ((mask & DaysBitMask.Thu) == DaysBitMask.Thu)
    test = true;
if ((mask & DaysBitMask.Wed) != DaysBitMask.Wed)
    test = true;

// Store the value
int storedVal = (int)mask;

// Reinstate the mask and re-test
DaysBitMask reHydratedMask = (DaysBitMask)storedVal;

if ((reHydratedMask & DaysBitMask.Sat) == DaysBitMask.Sat)
    test = true;
if ((reHydratedMask & DaysBitMask.Thu) == DaysBitMask.Thu)
    test = true;
if ((reHydratedMask & DaysBitMask.Wed) != DaysBitMask.Wed)
    test = true;

Get User's Current Location / Coordinates

import CoreLocation
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    } 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status != .authorizedWhenInUse {return}
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
        let locValue: CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

Because the call to requestWhenInUseAuthorization is asynchronous, the app calls the locationManager function after the user has granted permission or rejected it. Therefore it is proper to place your location getting code inside that function given the user granted permission. This is the best tutorial on this I have found on it.

How to implement infinity in Java?

Only Double and Float type support POSITIVE_INFINITY constant.

How to create an instance of System.IO.Stream stream

Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

CSS: How to position two elements on top of each other, without specifying a height?

Of course, the problem is all about getting your height back. But how can you do that if you don't know the height ahead of time? Well, if you know what aspect ratio you want to give the container (and keep it responsive), you can get your height back by adding padding to another child of the container, expressed as a percentage.

You can even add a dummy div to the container and set something like padding-top: 56.25% to give the dummy element a height that is a proportion of the container's width. This will push out the container and give it an aspect ratio, in this case 16:9 (56.25%).

Padding and margin use the percentage of the width, that's really the trick here.

Best way to style a TextBox in CSS

You can use:

input[type=text]
{
 /*Styles*/
}

Define your common style attributes inside this. and for extra style you can add a class then.

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

How to include js and CSS in JSP with spring MVC

First you need to declare your resources in dispatcher-servlet file like this :

<mvc:resources mapping="/resources/**" location="/resources/folder/" />

Any request with url mapping /resources/** will directly look for /resources/folder/.

Now in jsp file you need to include your css file like this :

<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">

Similarly you can include js files.

Hope this solves your problem.

jQuery: Check if button is clicked

$('input[type="button"]').click(function (e) {
    if (e.target) {
        alert(e.target.id + ' clicked');
    }
});

you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.

Difference between SurfaceView and View?

A SurfaceView is a custom view in Android that can be used to drawn inside it.

The main difference between a View and a SurfaceView is that a View is drawn in the UI Thread, which is used for all the user interaction.

If you want to update the UI rapidly enough and render a good amount of information in it, a SurfaceView is a better choice.

But there are a few technical insides to the SurfaceView:

1. They are not hardware accelerated.

2. Normal views are rendered when you call the methods invalidate or postInvalidate(), but this does not mean the view will be immediately updated (A VSYNC will be sent, and the OS decides when it gets updated. The SurfaceView can be immediately updated.

3. A SurfaceView has an allocated surface buffer, so it is more costly

How to split a string literal across multiple lines in C / Objective-C?

Extending the Quote idea for Objective-C:

#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]

NSString *sql = NSStringMultiline(
    SELECT name, age
    FROM users
    WHERE loggedin = true
);

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

Why use getters and setters/accessors?

We use getters and setters:

  • for reusability
  • to perform validation in later stages of programming

Getter and setter methods are public interfaces to access private class members.


Encapsulation mantra

The encapsulation mantra is to make fields private and methods public.

Getter Methods: We can get access to private variables.

Setter Methods: We can modify private fields.

Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that method

  • better;
  • safer; and
  • faster.

Anywhere a value can be used, a method that returns that value can be added. Instead of:

int x = 1000 - 500

use

int x = 1000 - class_name.getValue();

In layman's terms

Representation of "Person" class

Suppose we need to store the details of this Person. This Person has the fields name, age and sex. Doing this involves creating methods for name, age and sex. Now if we need create another person, it becomes necessary to create the methods for name, age, sex all over again.

Instead of doing this, we can create a bean class(Person) with getter and setter methods. So tomorrow we can just create objects of this Bean class(Person class) whenever we need to add a new person (see the figure). Thus we are reusing the fields and methods of bean class, which is much better.

VBA collection: list of keys

An alternative solution is to store the keys in a separate Collection:

'Initialise these somewhere.
Dim Keys As Collection, Values As Collection

'Add types for K and V as necessary.
Sub Add(K, V) 
Keys.Add K
Values.Add V, K
End Sub

You can maintain a separate sort order for the keys and the values, which can be useful sometimes.

Can the Unix list command 'ls' output numerical chmod permissions?

Closest I can think of (keeping it simple enough) is stat, assuming you know which files you're looking for. If you don't, * can find most of them:

/usr/bin$ stat -c '%a %n' *
755 [
755 a2p
755 a2ps
755 aclocal
...

It handles sticky, suid and company out of the box:

$ stat -c '%a %n' /tmp /usr/bin/sudo
1777 /tmp
4755 /usr/bin/sudo

Overloading and overriding

shadowing = maintains two definitions at derived class and in order to project the base class definition it shadowes(hides)derived class definition and vice versa.

How to merge 2 List<T> and removing duplicate values from it in C#

Union has not good performance : this article describe about compare them with together

var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
        dict[person.Number] = person;
}
var merged = dict.Values.ToList();

Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms

How do I create a URL shortener?

Why not just generate a random string and append it to the base URL? This is a very simplified version of doing this in C#.

static string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
static string baseUrl = "https://google.com/";

private static string RandomString(int length)
{
    char[] s = new char[length];
    Random rnd = new Random();
    for (int x = 0; x < length; x++)
    {
        s[x] = chars[rnd.Next(chars.Length)];
    }
    Thread.Sleep(10);

    return new String(s);
}

Then just add the append the random string to the baseURL:

string tinyURL = baseUrl + RandomString(5);

Remember this is a very simplified version of doing this and it's possible the RandomString method could create duplicate strings. In production you would want to take in account for duplicate strings to ensure you will always have a unique URL. I have some code that takes account for duplicate strings by querying a database table I could share if anyone is interested.

What __init__ and self do in Python?

The 'self' is a reference to the class instance

class foo:
    def bar(self):
            print "hi"

Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:

f = foo()
f.bar()

But it can be passed in as well if the method call isn't in the context of an instance of the class, the code below does the same thing

f = foo()
foo.bar(f)

Interestingly the variable name 'self' is just a convention. The below definition will work exactly the same.. Having said that it is very strong convention which should be followed always, but it does say something about flexible nature of the language

class foo:
    def bar(s):
            print "hi"

How can I declare and use Boolean variables in a shell script?

Revised Answer (Feb 12, 2014)

the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
    echo 'Be careful not to fall off!'
fi

Original Answer

Caveats: https://stackoverflow.com/a/21210966/89391

the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
    echo 'Be careful not to fall off!'
fi

From: Using boolean variables in Bash

The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson's comment about bash builtin true on Jun 2, 2010 only applies to the original answer, not the revised.

Killing a process using Java

With Java 9, we can use ProcessHandle which makes it easier to identify and control native processes:

ProcessHandle
  .allProcesses()
  .filter(p -> p.info().commandLine().map(c -> c.contains("firefox")).orElse(false))
  .findFirst()
  .ifPresent(ProcessHandle::destroy)

where "firefox" is the process to kill.

This:

  • First lists all processes running on the system as a Stream<ProcessHandle>

  • Lazily filters this stream to only keep processes whose launched command line contains "firefox". Both commandLine or command can be used depending on how we want to retrieve the process.

  • Finds the first filtered process meeting the filtering condition.

  • And if at least one process' command line contained "firefox", then kills it using destroy.

No import necessary as ProcessHandle is part of java.lang.

How to make a script wait for a pressed key?

In Python 3 use input():

input("Press Enter to continue...")

In Python 2 use raw_input():

raw_input("Press Enter to continue...")

This only waits for the user to press enter though.

One might want to use msvcrt ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):

import msvcrt as m
def wait():
    m.getch()

This should wait for a key press.

Additional info:

in Python 3 raw_input() does not exist

In Python 2 input(prompt) is equivalent to eval(raw_input(prompt))

How to get the next auto-increment id in mysql

You can get the next auto-increment value by doing:

SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'

Note that you should not use this to alter the table, use an auto_increment column to do that automatically instead.
The problem is that last_insert_id() is retrospective and can thus be guaranteed within the current connection.
This baby is prospective and is therefore not unique per connection and cannot be relied upon.
Only in a single connection database would it work, but single connection databases today have a habit of becoming multiple connection databases tomorrow.

See: SHOW TABLE STATUS

OpenCV with Network Cameras

I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.

#include "cv.h"
#include "highgui.h"
#include <iostream>

int main(int, char**) {
    cv::VideoCapture vcap;
    cv::Mat image;

    const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp"; 
    /* it may be an address of an mjpeg stream, 
    e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */

    //open the video stream and make sure it's opened
    if(!vcap.open(videoStreamAddress)) {
        std::cout << "Error opening video stream or file" << std::endl;
        return -1;
    }

    //Create output window for displaying frames. 
    //It's important to create this window outside of the `for` loop
    //Otherwise this window will be created automatically each time you call
    //`imshow(...)`, which is very inefficient. 
    cv::namedWindow("Output Window");

    for(;;) {
        if(!vcap.read(image)) {
            std::cout << "No frame" << std::endl;
            cv::waitKey();
        }
        cv::imshow("Output Window", image);
        if(cv::waitKey(1) >= 0) break;
    }   
}

Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:

// H.264 stream RTSP address, where 10.10.10.10 is an IP address 
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp

// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp

What's the best way to check if a file exists in C?

Look up the access() function, found in unistd.h. You can replace your function with

if( access( fname, F_OK ) == 0 ) {
    // file exists
} else {
    // file doesn't exist
}

You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)

Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.

How to SUM two fields within an SQL query

The sum function only gets the total of a column. In order to sum two values from different columns, convert the values to int and add them up using the +-Operator

Select (convert(int, col1)+convert(int, col2)) as summed from tbl1

Hope that helps.

CodeIgniter Select Query

When use codeIgniter Framework then refer this active records link. how the data interact with structure and more.

The following functions allow you to build SQL SELECT statements.

Selecting Data

$this->db->get();

Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:

$query = $this->db->get('mytable');

With access to each row

$query = $this->db->get('mytable');

foreach ($query->result() as $row)
{
    echo $row->title;
}

Where clues

$this->db->get_where();

EG:

 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

Select field

$this->db->select('title, content, date');

$query = $this->db->get('mytable');

// Produces: SELECT title, content, date FROM mytable

E.G

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); 
$query = $this->db->get('mytable');

Send response to all clients except sender

use this coding

io.sockets.on('connection', function (socket) {

    socket.on('mousemove', function (data) {

        socket.broadcast.emit('moving', data);
    });

this socket.broadcast.emit() will emit everthing in the function except to the server which is emitting

HTML5 - mp4 video does not play in IE9

Dan has one of the best answers up there and I'd suggest you use html5test.com on your target browsers to see the video formats that are supported.

As stated above, no single format works and what I use is MP4 encoded to H.264, WebM, and a flash fallback. This let's me show video on the following:

Win 7 - IE9, Chrome, Firefox, Safari, Opera

Win XP - IE7, IE8, Chrome, Firefox, Safari, Opera

MacBook OS X - Chrome, Firefox, Safari, Opera

iPad 2, iPad 3

Linux - Android 2.3, Android 3

<video width="980" height="540" controls>
        <source src="images/placeholdername.mp4" type="video/mp4" />
        <source src="images/placeholdername.webm" type="video/webm" />
        <embed src="images/placeholdername.mp4" type="application/x-shockwave-flash" width="980" height="570" allowscriptaccess="always" allowfullscreen="true" autoplay="false"></embed>  <!--IE 8 - add 25-30 pixels to vid height to allow QT player controls-->    
    </video>

Note: The .mp4 video should be coded in h264 basic profile, so that it plays on all mobile devices.

Update: added autoplay="false" to the Flash fallback. This prevents the MP4 from starting to play right away when the page loads on IE8, it will start to play once the play button is pushed.

How do I write the 'cd' command in a makefile?

It is actually executing the command, changing the directory to some_directory, however, this is performed in a sub-process shell, and affects neither make nor the shell you're working from.

If you're looking to perform more tasks within some_directory, you need to add a semi-colon and append the other commands as well. Note that you cannot use newlines as they are interpreted by make as the end of the rule, so any newlines you use for clarity needs to be escaped by a backslash.

For example:

all:
        cd some_dir; echo "I'm in some_dir"; \
          gcc -Wall -o myTest myTest.c

Note also that the semicolon is necessary between every command even though you add a backslash and a newline. This is due to the fact that the entire string is parsed as a single line by the shell. As noted in the comments, you should use '&&' to join commands, which mean they only get executed if the preceding command was successful.

all:
        cd some_dir && echo "I'm in some_dir" && \
          gcc -Wall -o myTest myTest.c

This is especially crucial when doing destructive work, such as clean-up, as you'll otherwise destroy the wrong stuff, should the cd fail for whatever reason.

A common usage though is to call make in the sub directory, which you might want to look into. There's a command line option for this so you don't have to call cd yourself, so your rule would look like this

all:
        $(MAKE) -C some_dir all

which will change into some_dir and execute the Makefile in there with the target "all". As a best practice, use $(MAKE) instead of calling make directly, as it'll take care to call the right make instance (if you, for example, use a special make version for your build environment), as well as provide slightly different behavior when running using certain switches, such as -t.

For the record, make always echos the command it executes (unless explicitly suppressed), even if it has no output, which is what you're seeing.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

Is it possible to get only the first character of a String?

Answering for C++ 14,

Yes, you can get the first character of a string simply by the following code snippet.

string s = "Happynewyear";
cout << s[0];

if you want to store the first character in a separate string,

string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;

List all employee's names and their managers by manager name using an inner join

Your query is close you need to join using the mgr and the empid

on e1.mgr = e2.empid

So the full query is:

select e1.ename Emp,
  e2.eName Mgr
from employees e1
inner join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

If you want to return all rows including those without a manager then you would change it to a LEFT JOIN (for example the president):

select e1.ename Emp,
  e2.eName Mgr
from employees e1
left join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

The president in your sample data will return a null value for the manager because they do not have a manager.

jquery-ui-dialog - How to hook into dialog close event

If I'm understanding the type of window you're talking about, wouldn't $(window).unload() (for the dialog window) give you the hook you need?

(And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then all the ways of closing that window are elements you could register click handers for.)

Edit: Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS. You can hook the X which closes the window by registering a click handler for the element with the class ui-dialog-titlebar-close.

More useful, perhaps, is you tell you how to figure that out quickly. While displaying the dialog, just pop open FireBug and Inspect the elements that can close the window. You'll instantly see how they are defined and that gives you what you need to register the click handlers.

So to directly answer your question, I believe the answer is really "no" -- there's isn't a close event you can hook, but "yes" -- you can hook all the ways to close the dialog box fairly easily and get what you want.

wildcard * in CSS for classes

An alternative solution:

div[class|='tocolor'] will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.

Beware that this won't match

<div class="foo tocolor-">

Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation

[att|=val]

Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)

How is a non-breaking space represented in a JavaScript string?

&nbsp; is a HTML entity. When doing .text(), all HTML entities are decoded to their character values.

Instead of comparing using the entity, compare using the actual raw character:

var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
  x = '';
}

Or you can also create the character from the character code manually it in its Javascript escaped form:

var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
  x = '';
}

More information about String.fromCharCode is available here:

fromCharCode - MDC Doc Center

More information about character codes for different charsets are available here:

Windows-1252 Charset
UTF-8 Charset

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

How do I print a double value with full precision using cout?

Most portably...

#include <limits>

using std::numeric_limits;

    ...
    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << d;

How to line-break from css, without using <br />?

The code can be

<div class="text-class"><span>hello</span><span>How are you</span></div>

CSS would be

.text-class {
     display: flex;
     justify-content: flex-start;
     flex-direction: column;
     align-items: center;
 }

vb.net get file names in directory?

System.IO.Directory.GetFiles() 

could help

Check if value is zero or not null in python

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

How can I set the opacity or transparency of a Panel in WinForms?

As far as I know a Panel can have a transparent color only, you can not control the opacity of the panel. So, you can have some parts of a panel completely transparent but not a 50% to say something.

To use transparency you must define the transparent color property.

phpMyAdmin says no privilege to create database, despite logged in as root user

If you are using Chrome. try some other browser. there where previous posts on this issue saying that phpmyadmin didnot provide privileges for root on chrome.

or try this

name: root

password: password

How to use multiple LEFT JOINs in SQL?

Yes it is possible. You need one ON for each join table.

LEFT JOIN ab
  ON ab.sht = cd.sht
LEFT JOIN aa
  ON aa.sht = cd.sht

Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.

Swift do-try-catch syntax

Create enum like this:

//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}

Create method like:

 func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
    throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
    throw spendingError.limit
}
return morningSpending + eveningSpending
}

Now check error is there or not and handle it:

do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}

jQuery: value.attr is not a function

You are dealing with the raw DOM element .. need to wrap it in a jquery object

console.info("cat_id: ",$(value).attr('cat_id'));

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

[[ ]] double brackets are unsuported under certain version of SunOS and totally unsuported inside function declarations by : GNU bash, version 2.02.0(1)-release (sparc-sun-solaris2.6)

How to output a comma delimited list in jinja python template?

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

Setting the correct PATH for Eclipse

I am using Windows 8.1 environment. I had the same problem while running my first java program after installing Eclipse recently. I had installed java on d drive at d:\java. But Eclipse was looking at the default installation c:\programfiles\java. I did the following:

  1. Modified my eclipse.ini file and added the following after open:

    -vm
    d:\java\jdk1.8.0_161\bin 
    
  2. While creating the java program I have to unselect default build path and then select d:\java.

After this, the program ran well and got the hello world to work.

How can I select an element with multiple classes in jQuery?

For better performance you can use

$('div.a.b')

This will look only through the div elements instead of stepping through all the html elements that you have on your page.

Removing the first 3 characters from a string

Use the substring method of the String class :

String removeCurrency=amount.getText().toString().substring(3);

Remove Elements from a HashSet while Iterating

Here's the more modern streams approach:

myIntegerSet.stream().filter((it) -> it % 2 != 0).collect(Collectors.toSet())

However, this makes a new set, so memory constraints might be an issue if it's a really huge set.

EDIT: previous version of this answer suggested Apache CollectionUtils but that was before steams came about.

Why does multiplication repeats the number several times?

Only when you multiply integer with a string, you will get repetitive string..

You can use int() factory method to create integer out of string form of integer..

>>> int('1') * int('9')
9
>>> 
>>> '1' * 9
'111111111'
>>>
>>> 1 * 9
9
>>> 
>>> 1 * '9'
'9'
  • If both operand is int, you will get multiplication of them as int.
  • If first operand is string, and second is int.. Your string will be repeated that many times, as the value in your integer 2nd operand.
  • If first operand is integer, and second is string, then you will get multiplication of both numbers in string form..

Why use prefixes on member variables in C++ classes

When reading through a member function, knowing who "owns" each variable is absolutely essential to understanding the meaning of the variable. In a function like this:

void Foo::bar( int apples )
{
    int bananas = apples + grapes;
    melons = grapes * bananas;
    spuds += melons;
}

...it's easy enough to see where apples and bananas are coming from, but what about grapes, melons, and spuds? Should we look in the global namespace? In the class declaration? Is the variable a member of this object or a member of this object's class? Without knowing the answer to these questions, you can't understand the code. And in a longer function, even the declarations of local variables like apples and bananas can get lost in the shuffle.

Prepending a consistent label for globals, member variables, and static member variables (perhaps g_, m_, and s_ respectively) instantly clarifies the situation.

void Foo::bar( int apples )
{
    int bananas = apples + g_grapes;
    m_melons = g_grapes * bananas;
    s_spuds += m_melons;
}

These may take some getting used to at first—but then, what in programming doesn't? There was a day when even { and } looked weird to you. And once you get used to them, they help you understand the code much more quickly.

(Using "this->" in place of m_ makes sense, but is even more long-winded and visually disruptive. I don't see it as a good alternative for marking up all uses of member variables.)

A possible objection to the above argument would be to extend the argument to types. It might also be true that knowing the type of a variable "is absolutely essential to understanding the meaning of the variable." If that is so, why not add a prefix to each variable name that identifies its type? With that logic, you end up with Hungarian notation. But many people find Hungarian notation laborious, ugly, and unhelpful.

void Foo::bar( int iApples )
{
    int iBananas = iApples + g_fGrapes;
    m_fMelons = g_fGrapes * iBananas;
    s_dSpuds += m_fMelons;
}

Hungarian does tell us something new about the code. We now understand that there are several implicit casts in the Foo::bar() function. The problem with the code now is that the value of the information added by Hungarian prefixes is small relative to the visual cost. The C++ type system includes many features to help types either work well together or to raise a compiler warning or error. The compiler helps us deal with types—we don't need notation to do so. We can infer easily enough that the variables in Foo::bar() are probably numeric, and if that's all we know, that's good enough for gaining a general understanding of the function. Therefore the value of knowing the precise type of each variable is relatively low. Yet the ugliness of a variable like "s_dSpuds" (or even just "dSpuds") is great. So, a cost-benefit analysis rejects Hungarian notation, whereas the benefit of g_, s_, and m_ overwhelms the cost in the eyes of many programmers.

How can I parse a string with a comma thousand separator to a number?

Replace the comma with an empty string:

_x000D_
_x000D_
var x = parseFloat("2,299.00".replace(",",""))_x000D_
alert(x);
_x000D_
_x000D_
_x000D_

Using str_replace so that it only acts on the first match?

$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace("/$find/",$replace,$string,1);
echo $result;

Git: Create a branch from unstaged/uncommitted changes on master

No need to stash.

git checkout -b new_branch_name

does not touch your local changes. It just creates the branch from the current HEAD and sets the HEAD there. So I guess that's what you want.

--- Edit to explain the result of checkout master ---

Are you confused because checkout master does not discard your changes?

Since the changes are only local, git does not want you to lose them too easily. Upon changing branch, git does not overwrite your local changes. The result of your checkout master is:

M   testing

, which means that your working files are not clean. git did change the HEAD, but did not overwrite your local files. That is why your last status still show your local changes, although you are on master.

If you really want to discard the local changes, you have to force the checkout with -f.

git checkout master -f

Since your changes were never committed, you'd lose them.

Try to get back to your branch, commit your changes, then checkout the master again.

git checkout new_branch
git commit -a -m"edited"
git checkout master
git status

You should get a M message after the first checkout, but then not anymore after the checkout master, and git status should show no modified files.

--- Edit to clear up confusion about working directory (local files)---

In answer to your first comment, local changes are just... well, local. Git does not save them automatically, you must tell it to save them for later. If you make changes and do not explicitly commit or stash them, git will not version them. If you change HEAD (checkout master), the local changes are not overwritten since unsaved.

Edit a text file on the console using Powershell

Not sure if this will benefit anybody, but if you are using Azure CloudShell PowerShell you can just type:

code file.txt

And Visual Studio code will popup with the file to be edit, pretty great.

when I run mockito test occurs WrongTypeOfReturnValue Exception

I recently had this issue. The problem was that the method I was trying to mock had no access modifier. Adding public solved the problem.

How to add rows dynamically into table layout

You are doing it right; every time you need to add a row, simply so new TableRow(), etc. It might be easier for you to inflate the new row from XML though.

How to tell when UITableView has completed ReloadData?

Details

  • Xcode Version 10.2.1 (10E1001), Swift 5

Solution

import UIKit

// MARK: - UITableView reloading functions

protocol ReloadCompletable: class { func reloadData() }

extension ReloadCompletable {
    func run(transaction closure: (() -> Void)?, completion: (() -> Void)?) {
        guard let closure = closure else { return }
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        closure()
        CATransaction.commit()
    }

    func run(transaction closure: (() -> Void)?, completion: ((Self) -> Void)?) {
        run(transaction: closure) { [weak self] in
            guard let self = self else { return }
            completion?(self)
        }
    }

    func reloadData(completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadData() }, completion: closure)
    }
}

// MARK: - UITableView reloading functions

extension ReloadCompletable where Self: UITableView {
    func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadRows(at: indexPaths, with: animation) }, completion: closure)
    }

    func reloadSections(_ sections: IndexSet, with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadSections(sections, with: animation) }, completion: closure)
    }
}

// MARK: - UICollectionView reloading functions

extension ReloadCompletable where Self: UICollectionView {

    func reloadSections(_ sections: IndexSet, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadSections(sections) }, completion: closure)
    }

    func reloadItems(at indexPaths: [IndexPath], completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadItems(at: indexPaths) }, completion: closure)
    }
}

Usage

UITableView

// Activate
extension UITableView: ReloadCompletable { }

// ......
let tableView = UICollectionView()

// reload data
tableView.reloadData { tableView in print(collectionView) }

// or
tableView.reloadRows(at: indexPathsToReload, with: rowAnimation) { tableView in print(tableView) }

// or
tableView.reloadSections(IndexSet(integer: 0), with: rowAnimation) { _tableView in print(tableView) }

UICollectionView

// Activate
extension UICollectionView: ReloadCompletable { }

// ......
let collectionView = UICollectionView()

// reload data
collectionView.reloadData { collectionView in print(collectionView) }

// or
collectionView.reloadItems(at: indexPathsToReload) { collectionView in print(collectionView) }

// or
collectionView.reloadSections(IndexSet(integer: 0)) { collectionView in print(collectionView) }

Full sample

Do not forget to add the solution code here

import UIKit

class ViewController: UIViewController {

    private weak var navigationBar: UINavigationBar?
    private weak var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationItem()
        setupTableView()
    }
}
// MARK: - Activate UITableView reloadData with completion functions

extension UITableView: ReloadCompletable { }

// MARK: - Setup(init) subviews

extension ViewController {

    private func setupTableView() {
        guard let navigationBar = navigationBar else { return }
        let tableView = UITableView()
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.dataSource = self
        self.tableView = tableView
    }

    private func setupNavigationItem() {
        let navigationBar = UINavigationBar()
        view.addSubview(navigationBar)
        self.navigationBar = navigationBar
        navigationBar.translatesAutoresizingMaskIntoConstraints = false
        navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        navigationBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        navigationBar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        let navigationItem = UINavigationItem()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "all", style: .plain, target: self, action: #selector(reloadAllCellsButtonTouchedUpInside(source:)))
        let buttons: [UIBarButtonItem] = [
                                            .init(title: "row", style: .plain, target: self,
                                                  action: #selector(reloadRowButtonTouchedUpInside(source:))),
                                            .init(title: "section", style: .plain, target: self,
                                                  action: #selector(reloadSectionButtonTouchedUpInside(source:)))
                                            ]
        navigationItem.leftBarButtonItems = buttons
        navigationBar.items = [navigationItem]
    }
}

// MARK: - Buttons actions

extension ViewController {

    @objc func reloadAllCellsButtonTouchedUpInside(source: UIBarButtonItem) {
        let elementsName = "Data"
        print("-- Reloading \(elementsName) started")
        tableView?.reloadData { taleView in
            print("-- Reloading \(elementsName) stopped \(taleView)")
        }
    }

    private var randomRowAnimation: UITableView.RowAnimation {
        return UITableView.RowAnimation(rawValue: (0...6).randomElement() ?? 0) ?? UITableView.RowAnimation.automatic
    }

    @objc func reloadRowButtonTouchedUpInside(source: UIBarButtonItem) {
        guard let tableView = tableView else { return }
        let elementsName = "Rows"
        print("-- Reloading \(elementsName) started")
        let indexPathToReload = tableView.indexPathsForVisibleRows?.randomElement() ?? IndexPath(row: 0, section: 0)
        tableView.reloadRows(at: [indexPathToReload], with: randomRowAnimation) { _tableView in
            //print("-- \(taleView)")
            print("-- Reloading \(elementsName) stopped in \(_tableView)")
        }
    }

    @objc func reloadSectionButtonTouchedUpInside(source: UIBarButtonItem) {
        guard let tableView = tableView else { return }
        let elementsName = "Sections"
        print("-- Reloading \(elementsName) started")
        tableView.reloadSections(IndexSet(integer: 0), with: randomRowAnimation) { _tableView in
            //print("-- \(taleView)")
            print("-- Reloading \(elementsName) stopped in \(_tableView)")
        }
    }
}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(Date())"
        return cell
    }
}

Results

enter image description here

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to force the input date format to dd/mm/yyyy?

To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow

<input id="txtDay" type="text" placeholder="DD" />

<input id="txtMonth" type="text" placeholder="MM" />

<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>


  function validateDate() {
    var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);

    if (date == "Invalid Date") {
        alert("jnvalid date");

    }
}

utf-8 special characters not displaying

The problem is because your file are not with the same encoding. First run the following command in all your files:

file -i filename.* 

In order to fix the problem you have to change all your files to uft-8. You can do it with the command iconv:

iconv -f fromcode -t tocode filename > newfilename

Example:

iconv -f iso-8859-1 -t utf-8 index.html > fixed/index.html

After this you can run file -i fixedx/index.html and you will see that your file is now in uft-8

Eclipse DDMS error "Can't bind to local 8600 for debugger"

In addition to adding 127.0.0.1 localhost to your hosts file, make the following changes in Eclipse.

Under

Window -> Preferences -> Android -> DDMS

Set Base local debugger port to 8601

Check the box that says Use ADBHOST and the value should be 127.0.0.1 Thanks to Ben Clayton & Doguhan Uluca in the comments for leading me to a solution.

Some Google keywords:

Ailment or solution for Nexus S Android debugging with the error message: Can't bind to local 8600 for debugger.

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

Edit and Continue: "Changes are not allowed when..."

I ran into this today - turns out that having Debug Info set to pdb-only (or none, I'd imagine) will prevent Edit and Continue from working.

Make sure your Debug Info is set to "full" first!

Project Properties > Build > Advanced > Output > Debug Info

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

Best way to work with dates in Android SQLite

"SELECT  "+_ID+" ,  "+_DESCRIPTION +","+_CREATED_DATE +","+_DATE_TIME+" FROM "+TBL_NOTIFICATION+" ORDER BY "+"strftime(%s,"+_DATE_TIME+") DESC";

How to do case insensitive string comparison?

There are two ways for case insensitive comparison:

  1. Convert strings to upper case and then compare them using the strict operator (===). How strict operator treats operands read stuff at: http://www.thesstech.com/javascript/relational-logical-operators
  2. Pattern matching using string methods:

Use the "search" string method for case insensitive search. Read about search and other string methods at: http://www.thesstech.com/pattern-matching-using-string-methods

<!doctype html>
  <html>
    <head>
      <script>

        // 1st way

        var a = "apple";
        var b = "APPLE";  
        if (a.toUpperCase() === b.toUpperCase()) {
          alert("equal");
        }

        //2nd way

        var a = " Null and void";
        document.write(a.search(/null/i)); 

      </script>
    </head>
</html>

How can I change my Cygwin home folder after installation?

Change your HOME environment variable.

on XP, its right-click My Computer >> Properties >> Advanced >> Environment Variables >> User Variables for >> [select variable HOME] >> edit

Is the ternary operator faster than an "if" condition in Java

For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:

if (i == 0)
{
    a = 10;
    b = 6;
    c = 3;
}
else
{
    a = 5;
    b = 4;
    d = 1;
}

a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6  : 4;
c = (i == 0) ? 3  : 9;
d = (i == 0) ? 12 : 1;

I prefer the latter so that you know you haven't missed an assignment.

What's the best way to store a group of constants that my program uses?

What I like to do is the following (but make sure to read to the end to use the proper type of constants):

internal static class ColumnKeys
{
    internal const string Date = "Date";
    internal const string Value = "Value";
    ...
}

Read this to know why const might not be what you want. Possible type of constants are:

  • const fields. Do not use across assemblies (public or protected) if value might change in future because the value will be hardcoded at compile-time in those other assemblies. If you change the value, the old value will be used by the other assemblies until they are re-compiled.
  • static readonly fields
  • static property without set

Find length (size) of an array in jquery

var array=[];

array.push(array);  //insert the array value using push methods.

for (var i = 0; i < array.length; i++) {    
    nameList += "" + array[i] + "";          //display the array value.                                                             
}

$("id/class").html(array.length);   //find the array length.

How to create standard Borderless buttons (like in the design guideline mentioned)?

For some reason neither style="Widget.Holo.Button.Borderless" nor android:background="?android:attr/selectableItemBackground" worked for me. To be more precise Widget.Holo.Button.Borderless did the job on Android 4.0 but didn't work on Android 2.3.3. What did the trick for me on both versions was android:background="@drawable/transparent" and this XML in res/drawable/transparent.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" >
</shape>

Plain head through the wall approach.

How to get the current location latitude and longitude in android

**The activity should implements LocationListener

In onCreate(), write the following code **

  Boolean network = haveNetworkConnection();
    Log.e("network", "---------->" + network);
    if (!network) {
        Toast.makeText(getApplicationContext(), "Network is not available",
                3000).show();

    }

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.googleMap);
    googleMap = supportMapFragment.getMap();
    googleMap.setMyLocationEnabled(true);


    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);




        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            && !locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {



         TextView title = new TextView(context);
         title.setText("Location Services Not Active");
            title.setBackgroundColor(Color.BLACK);
            title.setPadding(10, 15, 15, 10);
            title.setGravity(Gravity.CENTER);
            title.setTextColor(Color.WHITE);
            title.setTextSize(22);


            AlertDialog.Builder builder = new AlertDialog.Builder(this);




        builder.setCustomTitle(title);


        // builder.setTitle("Location Services Not Active");
        builder.setMessage("Please enable Location Services and GPS");

        builder.setPositiveButton("Turn on",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface,
                            int i) {
                        // Show location settings when the user acknowledges
                        // the alert dialog
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);

                        startActivity(intent);
                        finish();
                    }
                });

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();
                    }
                });

        builder.show();

    }

    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    if (location == null) {
        Toast.makeText(getApplicationContext(), "GPS signal not found",
                3000).show();
    }
    if (location != null) {
        Log.e("locatin", "location--" + location);

        Log.e("latitude at beginning",
                "@@@@@@@@@@@@@@@" + location.getLatitude());
        onLocationChanged(location);
    }

Write a method haveNetworkConnection

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}



@Override
public void onLocationChanged(Location location) {


    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title("Current LOC")
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));


}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}

Requested bean is currently in creation: Is there an unresolvable circular reference?

i encountered this error in quite a stupid way

@Autowired
// private Bean bean;

public void myMethod() {
  return;
}

what happened is that I commented a line for some reason and left the annotation which made spring think that the method needs to be autowired

python BeautifulSoup parsing table

Solved, this is how your parse their html results:

table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")
    if len(cells) == 9:
        summons = cells[1].find(text=True)
        plateType = cells[2].find(text=True)
        vDate = cells[3].find(text=True)
        location = cells[4].find(text=True)
        borough = cells[5].find(text=True)
        vCode = cells[6].find(text=True)
        amount = cells[7].find(text=True)
        print amount

Leave out quotes when copying from cell

Note:The cause of the quotes is that when data moves from excel to clipboard it is fully complying with CSV standards which include quoting values that include tabs, new lines etc (and double-quote characters are replaced with two double-quote characters )

So another approach, especially as in OP's case when tabs/new lines are due to the formula, is to use alternate characters for tabs and hard returns. I use ascii Unit Separator =char(31) for tabs and ascii Record Separator =char(30) for new lines.

Then pasting into text editor will not involve the extra CSV rules and you can do a quick search and replace to convert them back again.

If the tabs/new lines are embedded in the data, you can do a search and replace in excel to convert them.

Whether using formula or changing the data, the key to choosing delimiters is never use characters that can be in the actual data. This is why I recommend the low level ascii characters.

Count number of vector values in range with R

Use which:

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

How to round the corners of a button

For Swift:

button.layer.cornerRadius = 10.0

How do I Merge two Arrays in VBA?

To join Array1 and Array2, create a new array say JointArray

Dim JointArray As Variant
ReDim JointArray(UBound(Array1) + UBound(Array2) + 1) As Variant
For i = 0 To UBound(JointArray)
    If i <= UBound(Array1) Then
    JointArray(i) = Array1(i)
    Else
    JointArray(i) = Array2(i - UBound(Array1) - 1)
    End If
Next

Using iFrames In ASP.NET

You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.

You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server') on the final HTML page that your webform produces when requested.

And you can load a URL into your iframe that is a .aspx page.

But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.

Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?

git with development, staging and production branches

We do it differently. IMHO we do it in an easier way: in master we are working on the next major version.

Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.

To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.

If a new release is coming, we create a side-branch out of master, e.g. release-5 where only bugs get fixed.

Change New Google Recaptcha (v2) Width

For the new version of noCaptcha Recaptcha the following works for me:

<div class="g-recaptcha"
data-sitekey="6LcVkQsTAAAAALqSUcqN1zvzOE8sZkOq2GMBE-RK"
style="transform:scale(0.7);transform-origin:0;-webkit-transform:scale(0.7);
transform:scale(0.7);-webkit-transform-origin:0 0;transform-origin:0 0;"></div>

Ref

Parsing Query String in node.js

You can use the parse method from the URL module in the request callback.

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    response.end('Hello ' + queryData.name + '\n');

  } else {
    response.end("Hello World\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

I suggest you read the HTTP module documentation to get an idea of what you get in the createServer callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.

search in java ArrayList

Customer findCustomerByid(int id){
    for (int i=0; i<this.customers.size(); i++) {
        Customer customer = this.customers.get(i);
        if (customer.getId() == id){
             return customer;
        }
    }
    return null; // no Customer found with this ID; maybe throw an exception
}

What does iterator->second mean?

I'm sure you know that a std::vector<X> stores a whole bunch of X objects, right? But if you have a std::map<X, Y>, what it actually stores is a whole bunch of std::pair<const X, Y>s. That's exactly what a map is - it pairs together the keys and the associated values.

When you iterate over a std::map, you're iterating over all of these std::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

std::map<std::string, int> m = /* fill it */;
auto it = m.begin();

Here, if you now do *it, you will get the the std::pair for the first element in the map.

Now the type std::pair gives you access to its elements through two members: first and second. So if you have a std::pair<X, Y> called p, p.first is an X object and p.second is a Y object.

So now you know that dereferencing a std::map iterator gives you a std::pair, you can then access its elements with first and second. For example, (*it).first will give you the key and (*it).second will give you the value. These are equivalent to it->first and it->second.

Convert form data to JavaScript object with jQuery

I had to shameless self-promote my form library.

transForm.js

It does things like: serialize, deserialize, clear & submit forms.

The reason why I made this is form2js/js2form is not maintained and is not as flexible & fast as I would like. We use it in production because this is form2js/js2form compatible.

How to make grep only match if the entire line matches?

Here is what I do, though using anchors is the best way:

grep -w "ABB.log " a.tmp

MySQL JOIN ON vs USING?

Wikipedia has the following information about USING:

The USING construct is more than mere syntactic sugar, however, since the result set differs from the result set of the version with the explicit predicate. Specifically, any columns mentioned in the USING list will appear only once, with an unqualified name, rather than once for each table in the join. In the case above, there will be a single DepartmentID column and no employee.DepartmentID or department.DepartmentID.

Tables that it was talking about:

enter image description here

The Postgres documentation also defines them pretty well:

The ON clause is the most general kind of join condition: it takes a Boolean value expression of the same kind as is used in a WHERE clause. A pair of rows from T1 and T2 match if the ON expression evaluates to true.

The USING clause is a shorthand that allows you to take advantage of the specific situation where both sides of the join use the same name for the joining column(s). It takes a comma-separated list of the shared column names and forms a join condition that includes an equality comparison for each one. For example, joining T1 and T2 with USING (a, b) produces the join condition ON T1.a = T2.a AND T1.b = T2.b.

Furthermore, the output of JOIN USING suppresses redundant columns: there is no need to print both of the matched columns, since they must have equal values. While JOIN ON produces all columns from T1 followed by all columns from T2, JOIN USING produces one output column for each of the listed column pairs (in the listed order), followed by any remaining columns from T1, followed by any remaining columns from T2.

Using bootstrap with bower

There is a prebuilt bootstrap bower package called bootstrap-css. I think this is what you (and I) were hoping to find.

bower install bootstrap-css

Thanks Nico.

XPath to select element based on childs child value

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

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

to either

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

or

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

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

Sqlite in chrome

Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.

Running the new Intel emulator for Android

For Mac users who want to check whether your processor supports virtualisation, use the maccpuid software and look for VMX. If it is checked then you're good to go.

Download it here

VMX checked is a sign that your processor support virtualisation asked

How can I install a previous version of Python 3 in macOS using homebrew?

What I did was first I installed python 3.7

brew install python3
brew unlink python

then I installed python 3.6.5 using above link

brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb --ignore-dependencies

After that I ran brew link --overwrite python. Now I have all pythons in the system to create the virtual environments.

mian@tdowrick2~ $ python --version
Python 2.7.10
mian@tdowrick2~ $ python3.7 --version
Python 3.7.1
mian@tdowrick2~ $ python3.6 --version
Python 3.6.5

To create Python 3.7 virtual environment.

mian@tdowrick2~ $ virtualenv -p python3.7 env
Already using interpreter /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.7'
New python executable in /Users/mian/env/bin/python3.7
Also creating executable in /Users/mian/env/bin/python
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.7.1
(env) mian@tdowrick2~ $ deactivate

To create Python 3.6 virtual environment

mian@tdowrick2~ $ virtualenv -p python3.6 env
Running virtualenv with interpreter /usr/local/bin/python3.6
Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/mian/env/bin/python3.6
Not overwriting existing python script /Users/mian/env/bin/python (you must use /Users/mian/env/bin/python3.6)
Installing setuptools, pip, wheel...
done.
mian@tdowrick2~ $ source env/bin/activate
(env) mian@tdowrick2~ $ python --version
Python 3.6.5
(env) mian@tdowrick2~ $ 

How to call getClass() from a static method in Java?

Suppose there is a Utility class, then sample code would be -

    URL url = Utility.class.getClassLoader().getResource("customLocation/".concat("abc.txt"));

CustomLocation - if any folder structure within resources otherwise remove this string literal.

Android Spinner : Avoid onItemSelected calls during initialization

create a boolean field

private boolean inispinner;

inside oncreate of the activity

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (!inispinner) {
                inispinner = true;
                return;
            }
            //do your work here
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

convert month from name to number

Try this:

<?php
  $date = date_parse('July');
  var_dump($date['month']);
?>

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

How do I get the HTML code of a web page in PHP?

include_once('simple_html_dom.php');
$url="http://stackoverflow.com/questions/ask";
$html = file_get_html($url);

You can get the whole HTML code as an array (parsed form) using this code Download the 'simple_html_dom.php' file here http://sourceforge.net/projects/simplehtmldom/files/simple_html_dom.php/download

Disable password authentication for SSH

I followed these steps (for Mac).

In /etc/ssh/sshd_config change

#ChallengeResponseAuthentication yes
#PasswordAuthentication yes

to

ChallengeResponseAuthentication no
PasswordAuthentication no

Now generate the RSA key:

ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

(For me an RSA key worked. A DSA key did not work.)

A private key will be generated in ~/.ssh/id_rsa along with ~/.ssh/id_rsa.pub (public key).

Now move to the .ssh folder: cd ~/.ssh

Enter rm -rf authorized_keys (sometimes multiple keys lead to an error).

Enter vi authorized_keys

Enter :wq to save this empty file

Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

Restart the SSH:

sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd

if statements matching multiple values

Using Extension Methods:

public static class ObjectExtension
{
    public static bool In(this object obj, params object[] objects)
    {
        if (objects == null || obj == null)
            return false;
        object found = objects.FirstOrDefault(o => o.GetType().Equals(obj.GetType()) && o.Equals(obj));
        return (found != null);
    }
}

Now you can do this:

string role= "Admin";
if (role.In("Admin", "Director"))
{ 
    ...
} 

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Why is Spring's ApplicationContext.getBean considered bad?

One of the coolest benefits of using something like Spring is that you don't have to wire your objects together. Zeus's head splits open and your classes appear, fully formed with all of their dependencies created and wired-in, as needed. It's magical and fantastic.

The more you say ClassINeed classINeed = (ClassINeed)ApplicationContext.getBean("classINeed");, the less magic you're getting. Less code is almost always better. If your class really needed a ClassINeed bean, why didn't you just wire it in?

That said, something obviously needs to create the first object. There's nothing wrong with your main method acquiring a bean or two via getBean(), but you should avoid it because whenever you're using it, you're not really using all of the magic of Spring.

Declaring variable workbook / Worksheet vba

Lots of answers above! here is my take:

Sub kl()

    Dim wb As Workbook
    Dim ws As Worksheet

    Set ws = Sheets("name")
    Set wb = ThisWorkbook

With ws
    .Select
End With

End Sub

your first (perhaps accidental) mistake as we have all mentioned is "Sheet"... should be "Sheets"

The with block is useful because if you set wb to anything other than the current workbook, it will ececute properly

How to Free Inode Usage?

We faced similar issue recently, In case if a process refers to a deleted file, the Inode shall not be released, so you need to check lsof /, and kill/ restart the process will release the inodes.

Correct me if am wrong here.

How to update a plot in matplotlib?

I have released a package called python-drawnow that provides functionality to let a figure update, typically called within a for loop, similar to Matlab's drawnow.

An example usage:

from pylab import figure, plot, ion, linspace, arange, sin, pi
def draw_fig():
    # can be arbitrarily complex; just to draw a figure
    #figure() # don't call!
    plot(t, x)
    #show() # don't call!

N = 1e3
figure() # call here instead!
ion()    # enable interactivity
t = linspace(0, 2*pi, num=N)
for i in arange(100):
    x = sin(2 * pi * i**2 * t / 100.0)
    drawnow(draw_fig)

This package works with any matplotlib figure and provides options to wait after each figure update or drop into the debugger.

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

Adding elements to an xml file in C#

I've used XDocument.Root.Add to add elements. Root returns XElement which has an Add function for additional XElements

How to get Javascript Select box's selected text

Please try this code:

$("#YourSelect>option:selected").html()

Defined Edges With CSS3 Filter Blur

You can stop the image from overlapping it's edges by clipping the image and applying a wrapper element which sets the blur effect to 0 pixels. This is how it looks like:

HTML

<div id="wrapper">
  <div id="image"></div>
</div>

CSS

#wrapper {
  width: 1024px;
  height: 768px;

  border: 1px solid black;

  // 'blur(0px)' will prevent the wrapped image
  // from overlapping the border
  -webkit-filter: blur(0px);
  -moz-filter: blur(0px);
  -ms-filter: blur(0px);
  filter: blur(0px);
}

#wrapper #image {
  width: 1024px;
  height: 768px;

  background-image: url("../images/cats.jpg");
  background-size: cover;

  -webkit-filter: blur(10px);
  -moz-filter: blur(10px);
  -ms-filter: blur(10px);
  filter: blur(10px);

  // Position 'absolute' is needed for clipping
  position: absolute;
  clip: rect(0px, 1024px, 768px, 0px);
}

Why shouldn't I use "Hungarian Notation"?

I've always thought that a prefix or two in the right place wouldn't hurt. I think if I can impart something useful, like "Hey this is an interface, don't count on specific behaviour" right there, as in IEnumerable, I oughtta do it. Comment can clutter things up much more than just a one or two character symbol.

How to get the entire document HTML as a string?

MS added the outerHTML and innerHTML properties some time ago.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

See quirksmode for browser compatibility for what will work for you. All support innerHTML.

var markup = document.documentElement.innerHTML;
alert(markup);

Check if returned value is not null and if so assign it, in one line, with one method call

Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.

You can use the result variable as your temporary, like this:

dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();

This, however, is hard to read.

Suppress/ print without b' prefix for bytes in Python 3

I am a little late but for Python 3.9.1 this worked for me and removed the -b prefix:

print(outputCode.decode())

Save image from url with curl PHP

Option #1

Instead of picking the binary/raw data into a variable and then writing, you can use CURLOPT_FILE option to directly show a file to the curl for the downloading.

Here is the function:

// takes URL of image and Path for the image as parameter
function download_image1($image_url, $image_file){
    $fp = fopen ($image_file, 'w+');              // open file handle

    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
    fclose($fp);                                  // closing file handle
}

And here is how you should call it:

// test the download function
download_image1("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2", "local_image1.jpg");

Option #2

Now, If you want to download a very large file, that case above function may not become handy. You can use the below function this time for handling a big file. Also, you can print progress(in % or in any other format) if you want. Below function is implemented using a callback function that writes a chunk of data in to the file in to the progress of downloading.

// takes URL of image and Path for the image as parameter
function download_image2($image_url){
    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, "curl_callback");
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
}

/** callback function for curl */
function curl_callback($ch, $bytes){
    global $fp;
    $len = fwrite($fp, $bytes);
    // if you want, you can use any progress printing here
    return $len;
}

And here is how to call this function:

// test the download function
$image_file = "local_image2.jpg";
$fp = fopen ($image_file, 'w+');              // open file handle
download_image2("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2");
fclose($fp);                                  // closing file handle