Programs & Examples On #Active objects

How to force Sequential Javascript Execution?

I am an old hand at programming and came back recently to my old passion and am struggling to fit in this Object oriented, event driven bright new world and while i see the advantages of the non sequential behavior of Javascript there are time where it really get in the way of simplicity and reusability. A simple example I have worked on was to take a photo (Mobile phone programmed in javascript, HTML, phonegap, ...), resize it and upload it on a web site. The ideal sequence is :

  1. Take a photo
  2. Load the photo in an img element
  3. Resize the picture (Using Pixastic)
  4. Upload it to a web site
  5. Inform the user on success failure

All this would be a very simple sequential program if we would have each step returning control to the next one when it is finished, but in reality :

  1. Take a photo is async, so the program attempt to load it in the img element before it exist
  2. Load the photo is async so the resize picture start before the img is fully loaded
  3. Resize is async so Upload to the web site start before the Picture is completely resized
  4. Upload to the web site is asyn so the program continue before the photo is completely uploaded.

And btw 4 of the 5 steps involve callback functions.

My solution thus is to nest each step in the previous one and use .onload and other similar stratagems, It look something like this :

takeAPhoto(takeaphotocallback(photo) {
  photo.onload = function () {
    resizePhoto(photo, resizePhotoCallback(photo) {
      uploadPhoto(photo, uploadPhotoCallback(status) {
        informUserOnOutcome();
      });
    }); 
  };
  loadPhoto(photo);
});

(I hope I did not make too many mistakes bringing the code to it's essential the real thing is just too distracting)

This is I believe a perfect example where async is no good and sync is good, because contrary to Ui event handling we must have each step finish before the next is executed, but the code is a Russian doll construction, it is confusing and unreadable, the code reusability is difficult to achieve because of all the nesting it is simply difficult to bring to the inner function all the parameters needed without passing them to each container in turn or using evil global variables, and I would have loved that the result of all this code would give me a return code, but the first container will be finished well before the return code will be available.

Now to go back to Tom initial question, what would be the smart, easy to read, easy to reuse solution to what would have been a very simple program 15 years ago using let say C and a dumb electronic board ?

The requirement is in fact so simple that I have the impression that I must be missing a fundamental understanding of Javsascript and modern programming, Surely technology is meant to fuel productivity right ?.

Thanks for your patience

Raymond the Dinosaur ;-)

Convert base64 string to ArrayBuffer

Using TypedArray.from:

Uint8Array.from(atob(base64_string), c => c.charCodeAt(0))

Performance to be compared with the for loop version of Goran.it answer.

React JSX: selecting "selected" on selected <select> option

Use defaultValue to preselect the values for Select.

<Select defaultValue={[{ value: category.published, label: 'Publish' }]} options={statusOptions} onChange={handleStatusChange} />

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

How can I change the Bootstrap default font family using font from Google?

If you have a custom.css file, in there, just do something like:

font-family: "Oswald", Helvetica, Arial, sans-serif!important;

Regular expression: find spaces (tabs/space) but not newlines

As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction

[\s-[\r\n]]

or, including Eiríkr Útlendi's solution, you get

[\s\u3000-[\r\n]]

How do you make sure email you send programmatically is not automatically marked as spam?

I've found that using the recipients real first and last name in the body is a sure fire way of getting through a spam filter.

Slide div left/right using jQuery

The easiest way to do so is using jQuery and animate.css animation library.

Javascript

/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );

/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );


HTML

<div class="example">Some text over here.</div>


Easy enough to implement. Just don't forget to include the animate.css file in the header :)

Listen for key press in .NET console app

Addressing cases that some of the other answers don't handle well:

  • Responsive: direct execution of keypress handling code; avoids the vagaries of polling or blocking delays
  • Optionality: global keypress is opt-in; otherwise the app should exit normally
  • Separation of concerns: less invasive listening code; operates independently of normal console app code.

Many of the solutions on this page involve polling Console.KeyAvailable or blocking on Console.ReadKey. While it's true that the .NET Console is not very cooperative here, you can use Task.Run to move towards a more modern Async mode of listening.

The main issue to be aware of is that, by default, your console thread isn't set up for Async operation--meaning that, when you fall out of the bottom of your main function, instead of awaiting Async completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish full Async support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.

The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.

static void Main(String[] args)
{
    Console.WriteLine("Press any key to prevent exit...");
    var tHold = Task.Run(() => Console.ReadKey(true));

    // ... do your console app activity ...

    if (tHold.IsCompleted)
    {
#if false   // For the 'hold' state, you can simply halt forever...
        Console.WriteLine("Holding.");
        Thread.Sleep(Timeout.Infinite);
#else                            // ...or allow continuing to exit
        while (Console.KeyAvailable)
            Console.ReadKey(true);     // flush/consume any extras
        Console.WriteLine("Holding. Press 'Esc' to exit.");
        while (Console.ReadKey(true).Key != ConsoleKey.Escape)
            ;
#endif
    }
}

How to format DateTime columns in DataGridView?

If it is a windows form Datagrid, you could use the below code to format the datetime for a column

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";

EDIT :

Apart from this, if you need the datetime in AM/PM format, you could use the below code

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

Read next word in java

Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().

On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.

P.S.: Sorry, I don't have right to comment on already given answers.

How do I get the different parts of a Flask request's url?

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

How to set Spinner Default by its Value instead of Position?

If the list you use for the spinner is an object then you can find its position like this

private int selectSpinnerValue( List<Object> ListSpinner,String myString) 
{
    int index = 0;
    for(int i = 0; i < ListSpinner.size(); i++){
      if(ListSpinner.get(i).getValueEquals().equals(myString)){
          index=i;
          break;
      }
    }
    return index;
}

using:

 int index=selectSpinnerValue(ListOfSpinner,StringEquals);
    spinner.setSelection(index,true);

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Automatic prune with Git fetch or pull

git config --global fetch.prune true

To always --prune for git fetch and git pull in all your Git repositories:

git config --global fetch.prune true

This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

[fetch]
    prune = true

git config remote.origin.prune true

To always --prune but from one single repository:

git config remote.origin.prune true
                 #^^^^^^
                 #replace with your repo name

This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

[remote "origin"]
    url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    fetch = +refs/heads/*:refs/remotes/origin/*
    prune = true

You can also use --global within the second command or use instead --local within the first command.


git config --global gui.pruneDuringFetch true

If you use git gui you may also be interested by:

git config --global gui.pruneDuringFetch true

that appends:

[gui]
    pruneDuringFetch = true

References

The corresponding documentations from git help config:

--global

  For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

 

--local

  For writing options: write to the repository .git/config file. This is the default behavior.

 

fetch.prune

  If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

 

gui.pruneDuringFetch

  "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

 

remote.<name>.prune

  When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

Composer install error - requires ext_curl when it's actually enabled

on php7 run for example:

> sudo apt-get install php-curl
> sudo apt-get install php-mbstring

for every missing extension. Then:

> sudo apt-get update

and finally (in the project's root folder):

> composer install

How to keep the spaces at the end and/or at the beginning of a String?

There is possible to space with different widths:

<string name="space_demo">|&#x20;|&#x2009;|&#x200A;||</string>

| SPACE | THIN SPACE | HAIR SPACE | no space |

Visualisation:

enter image description here

How can I convert JSON to CSV?

Modified Alec McGail's answer to support JSON with lists inside

    def flattenjson(self, mp, delim="|"):
            ret = []
            if isinstance(mp, dict):
                    for k in mp.keys():
                            csvs = self.flattenjson(mp[k], delim)
                            for csv in csvs:
                                    ret.append(k + delim + csv)
            elif isinstance(mp, list):
                    for k in mp:
                            csvs = self.flattenjson(k, delim)
                            for csv in csvs:
                                    ret.append(csv)
            else:
                    ret.append(mp)

            return ret

Thanks!

How do I measure the execution time of JavaScript code with callbacks?

You could give Benchmark.js a try. It supports many platforms among them also node.js.

When does a process get SIGABRT (signal 6)?

There's another simple cause in case of c++.

std::thread::~thread{
    if((joinable ())
        std::terminate ();
}

i.e. scope of thread ended but you forgot to call either

thread::join();

or

thread::detach();

Angular 2 TypeScript how to find element in Array

Try this

          let val = this.SurveysList.filter(xi => {
        if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
          return xi.Description;
      })

      console.log('Description : ', val );

How to split a string by spaces in a Windows batch file?

one more variation - this looks for the program "cmd.exe" in the current path and reports the first match:

@echo off
setlocal
setlocal enableextensions
setlocal enabledelayedexpansion

set P=%PATH%
:pathloop
for /F "delims=; tokens=1*" %%f in ("!P!") do (
    set F=%%f
    if exist %%f\cmd.exe goto found
    set P=%%g
)
if defined P goto pathloop

echo path of cmd.exe was not found!
goto end

:found
echo found cmd.exe at %F%
goto end

:end

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

Where can I get Google developer key

You should be able to generate a Youtube API key there.

The recommended way to authorize your API call is to use OAuth 2.0 (without API key), as pointed by the documentation an API key is only necessary when using OAuth 1.0 credentials.

The API key for your application can be found in the Google APIs Console in API Access > Simple API.

Test if a string contains a word in PHP?

if (strpos($string, $word) === FALSE) {
   ... not found ...
}

Note that strpos() is case sensitive, if you want a case-insensitive search, use stripos() instead.

Also note the ===, forcing a strict equality test. strpos CAN return a valid 0 if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.

Show empty string when date field is 1/1/1900

select  ISNULL(CONVERT(VARCHAR(23), WorkingDate,121),'') from uv_Employee

Finding rows containing a value (or values) in any column

How about

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

How can I find script's directory?

Try this:

def get_script_path(for_file = None):
    path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
    return path if not for_file else os.path.join(path, for_file)

Input placeholders for Internet Explorer

TO insert the plugin and check the ie is perfectly workedjquery.placeholder.js

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="jquery.placeholder.js"></script>
    <script>
        // To test the @id toggling on password inputs in browsers that don’t support changing an input’s @type dynamically (e.g. Firefox 3.6 or IE), uncomment this:
        // $.fn.hide = function() { return this; }
        // Then uncomment the last rule in the <style> element (in the <head>).
        $(function() {
            // Invoke the plugin
            $('input, textarea').placeholder({customClass:'my-placeholder'});
            // That’s it, really.
            // Now display a message if the browser supports placeholder natively
            var html;
            if ($.fn.placeholder.input && $.fn.placeholder.textarea) {
                html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> and <code>textarea</code> elements.</strong> The plugin won’t run in this case, since it’s not needed. If you want to test the plugin, use an older browser ;)';
            } else if ($.fn.placeholder.input) {
                html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> elements, but not for <code>textarea</code> elements.</strong> The plugin will only do its thang on the <code>textarea</code>s.';
            }
            if (html) {
                $('<p class="note">' + html + '</p>').insertAfter('form');
            }
        });
    </script>

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

How to drop all tables in a SQL Server database?

How about dropping the entire database and then creating it again? This works for me.

DROP DATABASE mydb;
CREATE DATABASE mydb;

Why am I getting error for apple-touch-icon-precomposed.png

If a user from Safari Web browser (Apple devices) visit your site. The browser tries to fetch the site icon if it is not defined in <head> in the following order:

  1. apple-touch-icon-57x57-precomposed.png
  2. apple-touch-icon-57x57.png
  3. apple-touch-icon-precomposed.png
  4. apple-touch-icon.png

To resolve this issue either define an icon for safari web browsers or apple devices. Add something like this to head section of your site:

<link rel="apple-touch-icon" href="/custom_icon.png"/>

If you want to keep <head> clean then upload the icon to root dir of your site with proper name.

The default icon size is 57px.

You can find more details on iOS developer library.

'node' is not recognized as an internal or external command

Everytime I install node.js it needs a reboot and then the path is recognized.

Invert colors of an image in CSS or JavaScript

CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:

_x000D_
_x000D_
img {_x000D_
   -webkit-filter: invert(1);_x000D_
   filter: invert(1);_x000D_
   }
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
_x000D_
_x000D_

Removing duplicates from a String in Java

've an array to know whether a character has already been recorded or not; if not, add that to the string buffer. Please note that I have made it case sensitive; with the int array, you can always make it('ve not done that in this code) to return the number of occurrences too.

private static String removeDuplicates(String s) {

    int [] occurrences = new int[52];
    Arrays.fill(occurrences,0);

    StringBuffer deDupS = new StringBuffer();
    for(int i = 0; i < s.length(); i++) {
        if(s.charAt(i) >= 97) {
            if(occurrences[s.charAt(i) - 97] == 0) {
                deDupS.append(s.charAt(i));
                occurrences[s.charAt(i) - 97]++;
            }
        } else if(s.charAt(i) >= 65) {
            if(occurrences[s.charAt(i) - 65 + 26] == 0) {
                deDupS.append(s.charAt(i));
                occurrences[s.charAt(i) - 65 + 26]++;
            }
        }
    }

    return deDupS.toString();

}

PHP 5 disable strict standards error

Do you want to disable error reporting, or just prevent the user from seeing it? It’s usually a good idea to log errors, even on a production site.

# in your PHP code:
ini_set('display_errors', '0');     # don't show any errors...
error_reporting(E_ALL | E_STRICT);  # ...but do log them

They will be logged to your standard system log, or use the error_log directive to specify exactly where you want errors to go.

Is it possible to use a div as content for Twitter's Popover

Why so complicated? just put this :

data-html='true'

What is the difference between the kernel space and the user space?

The really simplified answer is that the kernel runs in kernel space, and normal programs run in user space. User space is basically a form of sand-boxing -- it restricts user programs so they can't mess with memory (and other resources) owned by other programs or by the OS kernel. This limits (but usually doesn't entirely eliminate) their ability to do bad things like crashing the machine.

The kernel is the core of the operating system. It normally has full access to all memory and machine hardware (and everything else on the machine). To keep the machine as stable as possible, you normally want only the most trusted, well-tested code to run in kernel mode/kernel space.

The stack is just another part of memory, so naturally it's segregated right along with the rest of memory.

How can I stop float left?

A standard approach is to add a clearing div between the two floating block level elements:

<div style="clear:both;"></div>

Git: Remove committed file after push

update: added safer method

preferred method:

  1. check out the previous (unchanged) state of your file; notice the double dash

    git checkout HEAD^ -- /path/to/file
    
  2. commit it:

    git commit -am "revert changes on this file, not finished with it yet"
    
  3. push it, no force needed:

    git push
    
  4. get back to your unfinished work, again do (3 times arrow up):

    git checkout HEAD^ -- /path/to/file
    

effectively 'uncommitting':

To modify the last commit of the repository HEAD, obfuscating your accidentally pushed work, while potentially running into a conflict with your colleague who may have pulled it already, and who will grow grey hair and lose lots of time trying to reconcile his local branch head with the central one:

To remove file change from last commit:

  1. to revert the file to the state before the last commit, do:

    git checkout HEAD^ /path/to/file
    
  2. to update the last commit with the reverted file, do:

    git commit --amend
    
  3. to push the updated commit to the repo, do:

    git push -f
    

Really, consider using the preferred method mentioned before.

Collapsing Sidebar with Bootstrap

EDIT: I've added one more option for bootstrap sidebars.

There are actually three manners in which you can make a bootstrap 3 sidebar. I tried to keep the code as simple as possible.

Fixed sidebar

Here you can see a demo of a simple fixed sidebar I've developed with the same height as the page

Sidebar in a column

I've also developed a rather simple column sidebar that works in a two or three column page inside a container. It takes the length of the longest column. Here you can see a demo

Dashboard

If you google bootstrap dashboard, you can find multiple suitable dashboard, such as this one. However, most of them require a lot of coding. I've developed a dashboard that works without additional javascript (next to the bootstrap javascript). Here is a demo

For all three examples you off course have to include the jquery, bootstrap css, js and theme.css files.

Slidebar

If you want the sidebar to hide on pressing a button this is also possible with only a little javascript.Here is a demo

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

For more solution i have completed the solution of (the great) Tiago Gouvêa exposed before only for strings and arrays

i used md_convert_encoding() function instead of utf8_encode(), it works for me : (12 hours loosed ...)

// this object return me a big array who have multiple arrays imbricated

$get_days = program::get_days($ARR, $client);

// and i use this function for well parsing what the server return *

                function convert_to_utf8_recursively($dat){
                      if( is_string($dat) ){
                         return mb_convert_encoding($dat, 'UTF-8', 'UTF-8');
                      }
                      elseif( is_array($dat) ){
                         $ret = [];
                         foreach($dat as $i => $d){
                           $ret[$i] = convert_to_utf8_recursively($d);
                         }
                         return $ret;
                      }
                      else{
                         return $dat;
                      }
                }

                // use 
                $data = convert_to_utf8_recursively($get_days);
  • what the server return * i talk to that because i test the same code in two different servers the first return me a well formatted json , without any function, as we usually do BUT the second server does not send me back anything if I do not apply this function ...

How does "304 Not Modified" work exactly?

Last-Modified : The last modified date for the requested object

If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.

ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.

If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.

the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:

enter image description here

the server will return 304 when the if statement is False, and browser will use cache.

How should I validate an e-mail address?

Try this simple method which can not accept the email address beginning with digits:

boolean checkEmailCorrect(String Email) {
    if(signupEmail.length() == 0) {
        return false;
    }

    String pttn = "^\\D.+@.+\\.[a-z]+";
    Pattern p = Pattern.compile(pttn);
    Matcher m = p.matcher(Email);

    if(m.matches()) {
        return true;
    }

    return false;
}

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

How to check if command line tools is installed

In macOS Catalina, and possibly some earlier versions, you can find out where the command line tools are installed using:

xcode-select -p a.k.a. xcode-select --print-path

Which will, if it is installed, respond with something like:

/Library/Developer/CommandLineTools

To find out which version you have installed there, you can use:

xcode-select -v a.k.a. xcode-select --version

Which will return something like:

xcode-select version 2370.

However, if you attempt to upgrade it to the latest version, assuming it is installed, using this:

xcode-select --install

You will receive in response:

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

Which rather erroneously gives the impression you need to use Spotlight find something called 'Software Update'. In actual fact, you need to continue in the Terminal, and use this:

softwareupdate -i -a a.k.a. softwareupdate --install --all

Which tries to update everything it can and may well respond with:

Software Update Tool

Finding available software
No new software available.

To find out which versions of the different Apple SDKs are installed on your machine, use this:

xcodebuild -showsdks

How to clear the text of all textBoxes in the form?

I improved/fixed my extension method.

public  static class ControlsExtensions
{
    public static void ClearControls(this Control frm)
    {
        foreach (Control control in frm.Controls)
        {
            if (control is TextBox)
            {
                control.ResetText();
            }

            if (control.Controls.Count > 0)
            {
                control.ClearControls();
            }
        }
    }
}

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

How to reference a local XML Schema file correctly?

Maybe can help to check that the path to the xsd file has not 'strange' characters like 'é', or similar: I was having the same issue but when I changed to a path without the 'é' the error dissapeared.

How can I calculate divide and modulo for integers in C#?

Read two integers from the user. Then compute/display the remainder and quotient,

// When the larger integer is divided by the smaller integer
Console.WriteLine("Enter integer 1 please :");
double a5 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter integer 2 please :");
double b5 = double.Parse(Console.ReadLine());

double div = a5 / b5;
Console.WriteLine(div);

double mod = a5 % b5;
Console.WriteLine(mod);

Console.ReadLine();

Command /usr/bin/codesign failed with exit code 1

What worked for me was to realize that Xcode did not have access to the certificates. Please check that your certs are accessible by Xcode. Go to Keychain Access -> Certificates -> Open the Cert and double click on the private key -> Select Access Control

enter image description here

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

After following the instructions in the other answers, I needed to strip the version from the map file for this to work for me.

Example: Rename

jquery-1.9.1.min.map

to

jquery.min.map

Filter object properties by key in ES6

You can add a generic ofilter (implemented with generic oreduce) so you can easily filter objects the same way you can arrays –

const oreduce = (f, acc, o) =>
  Object
    .entries (o)
    .reduce
      ( (acc, [ k, v ]) => f (acc, v, k, o)
      , acc
      )

const ofilter = (f, o) =>
  oreduce
    ( (acc, v, k, o)=>
        f (v, k, o)
          ? Object.assign (acc, {[k]: v})
          : acc
    , {}
    , o
    )

We can see it working here -

const data =
  { item1: { key: 'a', value: 1 }
  , item2: { key: 'b', value: 2 }
  , item3: { key: 'c', value: 3 }
  }

console.log
  ( ofilter
      ( (v, k) => k !== 'item2'
      , data
      )
      // [ { item1: { key: 'a', value: 1 } }
      // , { item3: { key: 'c', value: 3 } }
      // ]

  , ofilter
      ( x => x.value === 3
      , data
      )
      // [ { item3: { key: 'c', value: 3 } } ]
  )

Verify the results in your own browser below –

_x000D_
_x000D_
const oreduce = (f, acc, o) =>_x000D_
  Object_x000D_
    .entries (o)_x000D_
    .reduce_x000D_
      ( (acc, [ k, v ]) => f (acc, v, k, o)_x000D_
      , acc_x000D_
      )_x000D_
_x000D_
const ofilter = (f, o) =>_x000D_
  oreduce_x000D_
    ( (acc, v, k, o)=>_x000D_
        f (v, k, o)_x000D_
          ? Object.assign (acc, { [k]: v })_x000D_
          : acc_x000D_
    , {}_x000D_
    , o_x000D_
    )_x000D_
_x000D_
const data =_x000D_
  { item1: { key: 'a', value: 1 }_x000D_
  , item2: { key: 'b', value: 2 }_x000D_
  , item3: { key: 'c', value: 3 }_x000D_
  }_x000D_
_x000D_
console.log_x000D_
  ( ofilter_x000D_
      ( (v, k) => k !== 'item2'_x000D_
      , data_x000D_
      )_x000D_
      // [ { item1: { key: 'a', value: 1 } }_x000D_
      // , { item3: { key: 'c', value: 3 } }_x000D_
      // ]_x000D_
_x000D_
  , ofilter_x000D_
      ( x => x.value === 3_x000D_
      , data_x000D_
      )_x000D_
      // [ { item3: { key: 'c', value: 3 } } ]_x000D_
  )
_x000D_
_x000D_
_x000D_

These two functions could be implemented in many ways. I chose to attach to Array.prototype.reduce inside oreduce but you could just as easily write it all from scratch

How do I configure Notepad++ to use spaces instead of tabs?

In my Notepad++ 7.2.2, the Preferences section it's a bit different.

The option is located at: Settings / Preferences / Language / Replace by space as in the Screenshot.

Screenshot of the windows with preferences

How to use random in BATCH script?

here is a example i created for you, it should display a dialog asking you to select a number 1-10, depending on the number you select, it will generate a random number example to a batch file that you named. If you select "1" then you will get a random 1 digit number example. if you select "10" then you will get a random 10 digit number example.

@echo off
color f0
set /p "FileName= Enter Filename (Without Extension) : "
echo @echo off >> %FileName%.bat
echo File Created!
pause
cls
:CommandLine
set /p "calc= ~%ComputerName%: Enter a number to recieve the amount of  random digits :"
if %calc%==genrand_help goto GenerateRandomHelp
if %calc%==1 echo echo %%RANDOM:~-1%% >> %FileName%.bat
if %calc%==2 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat 
if %calc%==3 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%%%RANDOM:~-1%% >>  %FileName%.bat
if %calc%==4 echo echo %%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==5 echo echo %%Random%% >> %FileName%.bat
if %calc%==6 echo echo %%Random%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==7 echo echo %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat 
if %calc%==8 echo echo %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >> %FileName%.bat
if %calc%==9 echo echo  %%Random%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%%%%RANDOM:~-1%% >>  %FileName%.bat
if %calc%==10 echo echo %%Random%%%%Random%% >> %FileName%.bat  
goto CommandLine

Node.js fs.readdir recursive directory search

Check out the final-fs library. It provides a readdirRecursive function:

ffs.readdirRecursive(dirPath, true, 'my/initial/path')
    .then(function (files) {
        // in the `files` variable you've got all the files
    })
    .otherwise(function (err) {
        // something went wrong
    });

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

How to use subList()

I've implemented and tested this one; it should cover most bases:

public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
    int size = list.size();
    if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
        return Collections.emptyList();
    }

    fromIndex = Math.max(0, fromIndex);
    toIndex = Math.min(size, toIndex);

    return list.subList(fromIndex, toIndex);
}

Get the directory from a file path in java (android)

A better way, use getParent() from File Class..

String a="/root/sdcard/Pictures/img0001.jpg"; // A valid file path 
File file = new File(a); 
String getDirectoryPath = file.getParent(); // Only return path if physical file exist else return null

http://developer.android.com/reference/java/io/File.html#getParent%28%29

Converting java date to Sql timestamp

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

This gives me the following output:

 utilDate:Fri Apr 04 12:07:37 MSK 2014
 sqlDate:2014-04-04

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

What is the HTML5 equivalent to the align attribute in table cells?

Add this code into your StyleSheet:

margin-top:80px;

Concatenating date with a string in Excel

This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.

You'll have to do:

= A1 & TEXT(A2, "mm/dd/yyyy")

The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.

Now, you could have a user-defined function:

public function AsDisplayed(byval c as range) as string
  AsDisplayed = c.Text
end function

and then

= A1 & AsDisplayed(A2)

But then there's a bug (feature?) in Excel because of which the .Text property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE instead of what they should.

That is, it's bad either way.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

Login credentials not working with Gmail SMTP

I had already enabled "Allow less secure apps" and my SMPT python program was working perfectly!

But next day it stared giving me "Bad Credentials error (SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted)". I was using the exact same credentials as before and the less secure apps option was also enabled..!

Changed my password again but that also did not help.

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

Note: Had to try multipe times to get this option enabled. Once enabled, I tried connecting after 30mins and it worked..!!!

Hope this helps.

Convert number of minutes into hours & minutes using PHP

The easiest way is :

    gmdate('H:i', $numberOfSeconds * 60)

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

Outputs:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

UILabel text margin

Subclassing is a little cumbersome for such a simple case. An alternative is to simply add the UILabel with no background set to a UIView with the background set. Set the label's x to 10 and make the outer view's size 20 pixels wider than the label.

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

#run 
sudo sendmailconfig

json Uncaught SyntaxError: Unexpected token :

That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

Oracle SQL Developer - tables cannot be seen

Select 'Other Users' from the and select your user(schema), under which you will be able to see your tables and views.

Screenshot

PySpark 2.0 The size or shape of a DataFrame

print((df.count(), len(df.columns)))

is easier for smaller datasets.

However if the dataset is huge, an alternative approach would be to use pandas and arrows to convert the dataframe to pandas df and call shape

spark.conf.set("spark.sql.execution.arrow.enabled", "true")
spark.conf.set("spark.sql.crossJoin.enabled", "true")
print(df.toPandas().shape)

PHP PDO returning single row

Just fetch. only gets one row. So no foreach loop needed :D

$row  = $STH -> fetch();

example (ty northkildonan):

$dbh = new PDO(" --- connection string --- "); 
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
$stmt->execute(); 
$row = $stmt->fetch();

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

What is the difference between const and readonly in C#?

One thing to add to what people have said above. If you have an assembly containing a readonly value (e.g. readonly MaxFooCount = 4; ), you can change the value that calling assemblies see by shipping a new version of that assembly with a different value (e.g. readonly MaxFooCount = 5;)

But with a const, it would be folded into the caller's code when the caller was compiled.

If you've reached this level of C# proficiency, you are ready for Bill Wagner's book, Effective C#: 50 Specific Ways to Improve Your C# Which answers this question in detail, (and 49 other things).

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert string to Title Case in Python?

Note: Why am I providing yet another answer? This answer is based on the title of the question and the notion that camelcase is defined as: a series of words that have been concatenated (no spaces!) such that each of the original words start with a capital letter (the rest being lowercase) excepting the first word of the series (which is completely lowercase). Also it is assumed that "all strings" refers to ASCII character set; unicode would not work with this solution).

simple

Given the above definition, this function

import re
word_regex_pattern = re.compile("[^A-Za-z]+")

def camel(chars):
  words = word_regex_pattern.split(chars)
  return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))

, when called, would result in this manner

camel("San Francisco")  # sanFrancisco
camel("SAN-FRANCISCO")  # sanFrancisco
camel("san_francisco")  # sanFrancisco

less simple

Note that it fails when presented with an already camel cased string!

camel("sanFrancisco")   # sanfrancisco  <-- noted limitation

even less simple

Note that it fails with many unicode strings

camel("México City")    # mXicoCity     <-- can't handle unicode

I don't have a solution for these cases(or other ones that could be introduced with some creativity). So, as in all things that have to do with strings, cover your own edge cases and good luck with unicode!

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Small update: Incase if you get below error in regard to node-sass follow the steps given below.

code EPERM
npm ERR! syscall unlink

steps to solve the issue:

  1. close visual studio
  2. manually remove .node-sass.DELETE from node_modules
  3. open visual studio
  4. npm cache verify
  5. npm install [email protected]

Shortest way to check for null and assign another value if not

You can also do it in your query, for instance in sql server, google ISNULL and CASE built-in functions.

Deleting a local branch with Git

If you have created multiple worktrees with git worktree, you'll need to run git prune before you can delete the branch

node.js Error: connect ECONNREFUSED; response from server

i ran the local mysql database, but not in administrator mode, which threw this error

How to style SVG with external CSS?

One approach you can take is just to use CSS filters to change the appearance of the SVG graphics in the browser.

For example, if you have an SVG graphic that uses a fill color of red within the SVG code, you can turn it purple with a hue-rotate setting of 180 degrees:

#theIdOfTheImgTagWithTheSVGInIt {
    filter: hue-rotate(180deg);
    -webkit-filter: hue-rotate(180deg);
    -moz-filter: hue-rotate(180deg);
    -o-filter: hue-rotate(180deg);
    -ms-filter: hue-rotate(180deg);
}

Experiment with other hue-rotate settings to find the colors you want.

To be clear, the above CSS goes in the CSS that is applied to your HTML document. You are styling the img tag in the HTML code, not styling the code of the SVG.

And note that this won’t work with graphics that have a fill of black or white or gray. You have to have an actual color in there to rotate the hue of that color.

Removing leading and trailing spaces from a string

void removeSpaces(string& str)
{
    /* remove multiple spaces */
    int k=0;
    for (int j=0; j<str.size(); ++j)
    {
            if ( (str[j] != ' ') || (str[j] == ' ' && str[j+1] != ' ' ))
            {
                    str [k] = str [j];
                    ++k;
            }

    }
    str.resize(k);

    /* remove space at the end */   
    if (str [k-1] == ' ')
            str.erase(str.end()-1);
    /* remove space at the begin */
    if (str [0] == ' ')
            str.erase(str.begin());
}

changing minDate option in JQuery DatePicker not working

There is no need to destroy current instance, just refresh.

$('#datepicker')
    .datepicker('option', 'minDate', new Date)
    .datepicker('refresh');

Rotating a point about another point (2D)

The coordinate system on the screen is left-handed, i.e. the x coordinate increases from left to right and the y coordinate increases from top to bottom. The origin, O(0, 0) is at the upper left corner of the screen.

enter image description here

A clockwise rotation around the origin of a point with coordinates (x, y) is given by the following equations:

enter image description here

where (x', y') are the coordinates of the point after rotation and angle theta, the angle of rotation (needs to be in radians, i.e. multiplied by: PI / 180).

To perform rotation around a point different from the origin O(0,0), let's say point A(a, b) (pivot point). Firstly we translate the point to be rotated, i.e. (x, y) back to the origin, by subtracting the coordinates of the pivot point, (x - a, y - b). Then we perform the rotation and get the new coordinates (x', y') and finally we translate the point back, by adding the coordinates of the pivot point to the new coordinates (x' + a, y' + b).

Following the above description:

a 2D clockwise theta degrees rotation of point (x, y) around point (a, b) is:

Using your function prototype: (x, y) -> (p.x, p.y); (a, b) -> (cx, cy); theta -> angle:

POINT rotate_point(float cx, float cy, float angle, POINT p){

     return POINT(cos(angle) * (p.x - cx) - sin(angle) * (p.y - cy) + cx,
                  sin(angle) * (p.x - cx) + cos(angle) * (p.y - cy) + cy);
}

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I would think that your first question is simply a matter of scope. The ServletContext is a much more broad scoped object (the whole servlet context) than a ServletRequest, which is simply a single request. You might look to the Servlet specification itself for more detailed information.

As to how, I am sorry but I will have to leave that for others to answer at this time.

Responsive web design is working on desktop but not on mobile device

Responsive meta tag

To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>.

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

How to limit text width

Try this:

<style> 
p
{
    width:100px; 
    word-wrap:break-word;
}
</style>

<p>Loremipsumdolorsitamet,consecteturadipiscingelit.Fusce non nisl
non ante malesuada mollis quis ut ipsum. Cum sociis natoque penatibus et magnis dis 
parturient montes, nascetur ridiculus mus. Cras ut adipiscing dolor. Nunc congue, 
tellus vehicula mattis porttitor, justo nisi sollicitudin nulla, a rhoncus lectus lacus 
id turpis. Vivamus diam lacus, egestas nec bibendum eu, mattis eget risus</p>

Visual Studio move project to a different folder

  1. Close your solution in VS2012
  2. Move your project to the new location
  3. Open your solution
  4. Select the project that failed to load
  5. In the Properties tool window, there an editable “File path” entry that allows you to select the new project location
  6. Set the new path
  7. Right click on the project and click reload

can you add HTTPS functionality to a python flask web server?

The top-scoring answer has the right idea, but the API seems to have evolved so that it no longer works as when it was first written, in 2015.

In place of this:

from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')

I used this, with Python 3.7.5:

import ssl
context = ssl.SSLContext()
context.load_cert_chain('fullchain.pem', 'privkey.pem')

and then supplied the SSL context in the Flask.run call as it said:

app.run(…, ssl_context=context)

(My server.crt file is called fullchain.pem and my server.key is called privkey.pem. These files were supplied to me by my LetsEncrypt Certbot.)

How to determine whether an object has a given property in JavaScript

Underscore.js or Lodash

if (_.has(x, "y")) ...

:)

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
        return;
    }
    forward();
}

... or to introduce an else block.

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.

In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.


Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doXxx() {
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.


Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.

protected void doXxx() {
    out.write(bytes);
    // ... 
    forward(); // Fail!
}

This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.


Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2001. For example:

<!DOCTYPE html>
<html lang="en">
    <head>
        ... 
    </head>
    <body>
        ...

        <% sendRedirect(); %>
        
        ...
    </body>
</html>

The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.

Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.


See also:


Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?

Android studio - Failed to find target android-18

Thank you RobertoAV96.

You're my hero. But it's not enough. In my case, I changed both compileSdkVersion, and buildToolsVersion. Now it work. Hope this help

buildscript {
       repositories {
           mavenCentral()
       }
       dependencies {
          classpath 'com.android.tools.build:gradle:0.6.+'
       }
   }
   apply plugin: 'android'

   dependencies {
       compile fileTree(dir: 'libs', include: '*.jar')
   }

   android {
       compileSdkVersion 19
       buildToolsVersion "19"

       sourceSets {
           main {
               manifest.srcFile 'AndroidManifest.xml'
               java.srcDirs = ['src']
               resources.srcDirs = ['src']
               aidl.srcDirs = ['src']
               renderscript.srcDirs = ['src']
               res.srcDirs = ['res']
               assets.srcDirs = ['assets']
           }

           // Move the tests to tests/java, tests/res, etc...
           instrumentTest.setRoot('tests')
           // Move the build types to build-types/<type>
           // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ..
           // This moves them out of them default location under src/<type>/... which would
           // conflict with src/ being used by the main source set.
           // Adding new build types or product flavors should be accompanied
           // by a similar customization.
           debug.setRoot('build-types/debug')
           release.setRoot('build-types/release')
       }
   }

Best way to split string into lines

  • If it looks ugly, just remove the unnecessary ToCharArray call.

  • If you want to split by either \n or \r, you've got two options:

    • Use an array literal – but this will give you empty lines for Windows-style line endings \r\n:

      var result = text.Split(new [] { '\r', '\n' });
      
    • Use a regular expression, as indicated by Bart:

      var result = Regex.Split(text, "\r\n|\r|\n");
      
  • If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions parameter) – use StringSplitOptions.None instead.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

this happened after 27,use targetSdkVersion 26 replace, wait for google fixed it

Why can't C# interfaces contain fields?

Why not just have a Year property, which is perfectly fine?

Interfaces don't contain fields because fields represent a specific implementation of data representation, and exposing them would break encapsulation. Thus having an interface with a field would effectively be coding to an implementation instead of an interface, which is a curious paradox for an interface to have!

For instance, part of your Year specification might require that it be invalid for ICar implementers to allow assignment to a Year which is later than the current year + 1 or before 1900. There's no way to say that if you had exposed Year fields -- far better to use properties instead to do the work here.

How to run (not only install) an android application using .apk file?

First to install your app:

adb install -r path\ProjectName.apk

The great thing about the -r is it works even if it wasn’t already installed.

To launch MainActivity, so you can launch it like:

adb shell am start -n com.other.ProjectName/.MainActivity

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

  1. Create Dockerfile and added commands for creating docker image
  2. Go to directory where we have created Dockfile
  3. execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

List of macOS text editors and code editors

Textmate is state of the Art editor, but if someone is thinking about developing on several platforms without awkward memory eaters monsters like jedit, eclipse, netbeans etc take a look at geany (geany.org). It is free. The only problem the editor has not esthetic look and feel on Mac OS X :)

Create a simple 10 second countdown

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callback and an integer, timeout. When called, setInterval will call the function you give it every timeout milliseconds.

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

function makeAlert(){ 
    alert("Popup window!");
};

setInterval(makeAlert, 500);

However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.

setInterval(function(){ alert("Popup window!"); }, 500);

Once setInterval is called, it will run until you call clearInterval on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.

_x000D_
_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
  if(timeleft <= 0){_x000D_
    clearInterval(downloadTimer);_x000D_
  }_x000D_
  document.getElementById("progressBar").value = 10 - timeleft;_x000D_
  timeleft -= 1;_x000D_
}, 1000);
_x000D_
<progress value="0" max="10" id="progressBar"></progress>
_x000D_
_x000D_
_x000D_

Alternatively, this will create a text countdown.

_x000D_
_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
  if(timeleft <= 0){_x000D_
    clearInterval(downloadTimer);_x000D_
    document.getElementById("countdown").innerHTML = "Finished";_x000D_
  } else {_x000D_
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";_x000D_
  }_x000D_
  timeleft -= 1;_x000D_
}, 1000);
_x000D_
<div id="countdown"></div>
_x000D_
_x000D_
_x000D_

Laravel 5.4 Specific Table Migration

You can only run this command in your terminal

php artisan migrate --path=database/migrations/2020_10_01_164611_create_asset_info_table.php

After migrations you should put the particular file name. or if you have any folder inside migration then just add that folder name after the migration.

Like this

php artisan migrate --path=database/migrations/yourfolder/2020_10_01_164611_create_asset_info_table.php

I hope this will help you a lil bit. Happy Coding.

Determine the number of rows in a range

Function ListRowCount(ByVal FirstCellName as String) as Long
    With thisworkbook.Names(FirstCellName).RefersToRange
        If isempty(.Offset(1,0).value) Then 
            ListRowCount = 1
        Else
            ListRowCount = .End(xlDown).row - .row + 1
        End If
    End With
End Function

But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count

How to fix a collation conflict in a SQL Server query?

I had problems with collations as I had most of the tables with Modern_Spanish_CI_AS, but a few, which I had inherited or copied from another Database, had SQL_Latin1_General_CP1_CI_AS collation.

In my case, the easiest way to solve the problem has been as follows:

  1. I've created a copy of the tables which were 'Latin American, using script table as...
  2. The new tables have obviously acquired the 'Modern Spanish' collation of my database
  3. I've copied the data of my 'Latin American' table into the new one, deleted the old one and renamed the new one.

I hope this helps other users.

Pyinstaller setting icons don't change

pyinstaller --clean --onefile --icon=default.ico Registry.py

It works for Me

Write a file on iOS

May be this is useful to you.

//Method writes a string to a text file
-(void) writeToTextFile{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSUTF8StringEncoding 
                                      error:nil];

}


//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
        //get the documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
        //use simple alert from my library (see previous post for details)
        [ASFunctions alert:content];
        [content release];

}

Extract digits from a string in Java

I have finalized the code for phone numbers +9 (987) 124124.

Unicode characters occupy 4 bytes.

public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

Cloning a private Github repo

In response to mac's answer, you can get your SSH clone URL on your github repo page, by clicking SSH on You can clone with HTTPS, SSH, or Subversion. and copy the URL.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

You should try this code.

 $("#multiple_Package_Ids_checkboxes").on('change', function (e) { 
        var totAmt = 0;
        $.each($(this).find(":selected"), function (i, item) { 
            totAmt += $(item).data("price");
            });
        $("#PackTotAmt").text(totAmt);
    }); 

Creating a new user and password with Ansible

My solution is using lookup and generate password automatically.

---
- hosts: 'all'
  remote_user: root
  gather_facts: no
  vars:
    deploy_user: deploy
    deploy_password: "{{ lookup('password', '/tmp/password chars=ascii_letters') }}"

  tasks:
    - name: Create deploy user
      user:
        name: "{{ deploy_user }}"
        password: "{{ deploy_password | password_hash('sha512') }}"

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

As everyone has mentioned http.server module is equivalent to python -m SimpleHTTPServer.
But as a warning from https://docs.python.org/3/library/http.server.html#module-http.server

Warning: http.server is not recommended for production. It only implements basic security checks.

Usage

http.server can also be invoked directly using the -m switch of the interpreter.

python -m http.server

The above command will run a server by default on port number 8000. You can also give the port number explicitly while running the server

python -m http.server 9000

The above command will run an HTTP server on port 9000 instead of 8000.

By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1

or

python -m http.server 8000 -b 127.0.0.1

Python 3.8 version also supports IPv6 in the bind argument.

Directory Binding

By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

Directory binding is introduced in python 3.7

VB.NET Connection string (Web.Config, App.Config)

I don't know if this still is an issue, but i prefere just to use the My.Settings in my code.

Visual Studio generates a simple class with functions for reading settings from the app.config file.

You can simply access it using My.Settings.ConnectionString.

    Using Context As New Data.Context.DataClasses()
        Context.Connection.ConnectionString = My.Settings.ConnectionString
    End Using

How to fit in an image inside span tag?

Try this.

<span style="padding-right:3px; padding-top: 3px; display:inline-block;">

<img class="manImg" src="images/ico_mandatory.gif"></img>

</span>

Android ImageView setImageResource in code

You can use this code:

// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];

// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...

// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
   if(countriesId[i][0].equals(countryCode))
      break;
}
// Now "i" is the index of the country

img.setImageResource(Integer.parseInt(countriesId[i][1]));

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

CodeIgniter removing index.php from url

on your htaccess use this,

RewriteEngine On
RewriteBase /root_folder_name/
RewriteCond %{REQUEST_URI} ^system.*
RewriteCond $1 !^(index\.php|images|js|uploads|css|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Hope this helps.

Scheduling recurring task in Android

Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:

A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.

So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.

How to left align a fixed width string?

This one worked in my python script:

print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s"  % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

"Rate This App"-link in Google Play store app on the phone

Play Store Rating

 btn_rate_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                // To count with Play market backstack, After pressing back button,
                // to taken back to our application, we need to add following flags to intent.
                goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                        Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                        Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                try {
                    startActivity(goToMarket);
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
                }
            }
        });

dpi value of default "large", "medium" and "small" text views android

To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?

Like biegleux already said:

  • small represents 14sp
  • medium represents 18sp
  • large represents 22sp

If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml file in your values folder and define the text size there with the following 3 lines:

<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>

Here is an example for a TextView with large text from the dimens.xml file:

<TextView
  android:id="@+id/hello_world"
  android:text="hello world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="@dimen/text_size_large"/>

How can you sort an array without mutating the original array?

Anyone who wants to do a deep copy (e.g. if your array contains objects) can use:

let arrCopy = JSON.parse(JSON.stringify(arr))

Then you can sort arrCopy without changing arr.

arrCopy.sort((obj1, obj2) => obj1.id > obj2.id)

Please note: this can be slow for very large arrays.

Detect whether there is an Internet connection available on Android

Probably I have found myself:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();

Typescript Date Type?

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

According to me @Html.RenderPartial() has faster execution than @Html.Partial() due to Html.RenderPartial gives a quick response to Output.

Because when I use @Html.Partial(), my website takes more time to load compared to @Html.RenderPartial()

Explain the concept of a stack frame in a nutshell

Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.

There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.

CSS Circular Cropping of Rectangle Image

The accepted answer probably works for some situations, but it depends on the ratio of the rectangle and any predetermined styles.

I use this method because it's more compatible than solutions only using object-fit:

_x000D_
_x000D_
.image-cropper {
   width: 150px;
   height: 150px;
   position: relative;
   overflow: hidden;
   border-radius: 50%;
   border:2px solid #f00;
}

/* Common img styles in web dev environments */
img {
   height: auto;
   max-width: 100%;
}

/* Center image inside of parent */
img.center {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

/* For horizontal rectangles */
img.horizontal {
   height: 100%;
   width: auto;
   max-width: 9999px; /* max-content fall back */
   max-width: max-content;
}
_x000D_
<div class="image-cropper">
  <img src="https://via.placeholder.com/300x600" class="center" />
</div>

<div class="image-cropper">
  <img src="https://via.placeholder.com/600x300" class="horizontal center" />
</div>
_x000D_
_x000D_
_x000D_

If you run the snippet you can see, for horizontal rectangles we add another class .horizontal.

We override max-width to allow the img to go larger than 100% of the width. This preserves the aspect ratio, preventing the image from stretching.

However, the image will not be centered and that's where the .centered class comes in. It uses a great centering trick to absolute position the image in the center both vertically and horizontally.

More information on the centering at CSS Tricks

More than likely you won't always know what ratio the image will be, so this is why I'd suggest using javascript to target the img and add the .horizontal class if needed.

Here is a stack overflow answer that would work

Start a fragment via Intent within a Fragment

Try this it may help you:

private void changeFragment(Fragment targetFragment){

    getSupportFragmentManager()
         .beginTransaction()
         .replace(R.id.main_fragment, targetFragment, "fragment")
         .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
         .commit();

}

How can you make a custom keyboard in Android?

System keyboard

This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone. If you want to make a keyboard that will only be used within your own app, then see my other answer.

The example below will look like this. You can modify it for any keyboard layout.

enter image description here

The following steps show how to create a working custom system keyboard. As much as possible I tried to remove any unnecessary code. If there are other features that you need, I provided links to more help at the end.

1. Start a new Android project

I named my project "Custom Keyboard". Call it whatever you want. There is nothing else special here. I will just leave the MainActivity and "Hello World!" layout as it is.

2. Add the layout files

Add the following two files to your app's res/layout folder:

  • keyboard_view.xml
  • key_preview.xml

keyboard_view.xml

This view is like a container that will hold our keyboard. In this example there is only one keyboard, but you could add other keyboards and swap them in and out of this KeyboardView.

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>

key_preview.xml

The key preview is a layout that pops up when you press a keyboard key. It just shows what key you are pressing (in case your big, fat fingers are covering it). This isn't a multiple choice popup. For that you should check out the Candidates view.

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@android:color/white"
    android:textColor="@android:color/black"
    android:textSize="30sp">
</TextView>

3. Add supporting xml files

Create an xml folder in your res folder. (Right click res and choose New > Directory.)

Then add the following two xml files to it. (Right click the xml folder and choose New > XML resource file.)

  • number_pad.xml
  • method.xml

number_pad.xml

This is where it starts to get more interesting. This Keyboard defines the layout of the keys.

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>

Here are some things to note:

  • keyWidth: This is the default width of each key. The 20%p means that each key should take up 20% of the width of the parent. It can be overridden by individual keys, though, as you can see happened with the Delete and Enter keys in the third row.
  • keyHeight: It is hard coded here, but you could use something like @dimen/key_height to set it dynamically for different screen sizes.
  • Gap: The horizontal and vertical gap tells how much space to leave between keys. Even if you set it to 0px there is still a small gap.
  • codes: This can be a Unicode or custom code value that determines what happens or what is input when the key is pressed. See keyOutputText if you want to input a longer Unicode string.
  • keyLabel: This is the text that is displayed on the key.
  • keyEdgeFlags: This indicates which edge the key should be aligned to.
  • isRepeatable: If you hold down the key it will keep repeating the input.

method.xml

This file tells the system the input method subtypes that are available. I am just including a minimal version here.

<?xml version="1.0" encoding="utf-8"?>
<input-method
    xmlns:android="http://schemas.android.com/apk/res/android">

    <subtype
        android:imeSubtypeMode="keyboard"/>

</input-method>

4. Add the Java code to handle key input

Create a new Java file. Let's call it MyInputMethodService. This file ties everything together. It handles input received from the keyboard and sends it on to whatever view is receiving it (an EditText, for example).

public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {

    @Override
    public View onCreateInputView() {
        // get the KeyboardView and add our Keyboard layout to it
        KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
        Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
        keyboardView.setKeyboard(keyboard);
        keyboardView.setOnKeyboardActionListener(this);
        return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) {

        InputConnection ic = getCurrentInputConnection();
        if (ic == null) return;
        switch (primaryCode) {
            case Keyboard.KEYCODE_DELETE:
                CharSequence selectedText = ic.getSelectedText(0);
                if (TextUtils.isEmpty(selectedText)) {
                    // no selection, so delete previous character
                    ic.deleteSurroundingText(1, 0);
                } else {
                    // delete the selection
                    ic.commitText("", 1);
                }
                break;
            default:
                char code = (char) primaryCode;
                ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}

Notes:

  • The OnKeyboardActionListener listens for keyboard input. It is also requires all those empty methods in this example.
  • The InputConnection is what is used to send input to another view like an EditText.

5. Update the manifest

I put this last rather than first because it refers to the files we already added above. To register your custom keyboard as a system keyboard, you need to add a service section to your AndroidManifest.xml file. Put it in the application section after activity.

<manifest ...>
    <application ... >
        <activity ... >
            ...
        </activity>

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">
            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>
            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>
        </service>

    </application>
</manifest>

That's it! You should be able to run your app now. However, you won't see much until you enable your keyboard in the settings.

6. Enable the keyboard in Settings

Every user who wants to use your keyboard will have to enable it in the Android settings. For detailed instructions on how to do that, see the following link:

Here is a summary:

  • Go to Android Settings > Languages and input > Current keyboard > Choose keyboards.
  • You should see your Custom Keyboard on the list. Enable it.
  • Go back and choose Current keyboard again. You should see your Custom Keyboard on the list. Choose it.

Now you should be able to use your keyboard anywhere that you can type in Android.

Further study

The keyboard above is usable, but to create a keyboard that other people will want to use you will probably have to add more functionality. Study the links below to learn how.

Going On

Don't like how the standard KeyboardView looks and behaves? I certainly don't. It looks like it hasn't been updated since Android 2.0. How about all those custom keyboards in the Play Store? They don't look anything like the ugly keyboard above.

The good news is that you can completely customize your own keyboard's look and behavior. You will need to do the following things:

  1. Create your own custom keyboard view that subclasses ViewGroup. You could fill it with Buttons or even make your own custom key views that subclass View. If you use popup views, then note this.
  2. Add a custom event listener interface in your keyboard. Call its methods for things like onKeyClicked(String text) or onBackspace().
  3. You don't need to add the keyboard_view.xml, key_preview.xml, or number_pad.xml described in the directions above since these are all for the standard KeyboardView. You will handle all these UI aspects in your custom view.
  4. In your MyInputMethodService class, implement the custom keyboard listener that you defined in your keyboard class. This is in place of KeyboardView.OnKeyboardActionListener, which is no longer needed.
  5. In your MyInputMethodService class's onCreateInputView() method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener to this.

Structs data type in php?

I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:

http://code.activestate.com/recipes/577160-php-struct-port/

One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:

$z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
//accessing values as properties
$y = (object)$z;
echo $y->foo;

I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.

If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)

Setting selected option in laravel form

Setting selected option is very simple in laravel form :

{{ Form::select('number', [0, 1, 2], 2) }}

Output will be :

<select name="number">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2" selected="selected">2</option>
</select>

Problem in running .net framework 4.0 website on iis 7.0

After mapping of Application follow these steps

Open IIS Click on Applications Pools Double click on website Change Manage pipeline mode to "classic" click Ok.

Ow change .Net Framework Version to Lower version

Then click Ok

Where is NuGet.Config file located in Visual Studio project?

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

How do I convert from BLOB to TEXT in MySQL?

phpMyAdmin screenshot Using phpMyAdmin you can also set the options to show BLOB content and show complete text.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I had the same problem, when suddenly any test didn't appeared on Test Explorer window. I has the updated version of "NUnit3TestAdapter"

and after lots of searches and efforts, I found that I need set the following values in project properties: [In Solution Explorer window: right click on Project > Properties] Under Build tab, set Platform=x64, and set Platform target=x86 or Any CPU Build the project and all tests will be appear on Test Explorer window.

Important note: I came to a solution after seeing the next msg in the output window:

"Test run will use DLL(s) built for framework Framework45 and platform X86. Following DLL(s) will not be part of run: AutomationTests.dll is built for Framework Framework45 and Platform X64."

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

Removing unwanted table cell borders with CSS

You may also want to add

table td { border:0; }

the above is equivalent to setting cellpadding="0"

it gets rid of the padding automatically added to cells by browsers which may depend on doctype and/or any CSS used to reset default browser styles

ReactNative: how to center text?

const styles = StyleSheet.create({
        navigationView: {
        height: 44,
        width: '100%',
        backgroundColor:'darkgray',
        justifyContent: 'center', 
        alignItems: 'center' 
    },
    titleText: {
        fontSize: 20,
        fontWeight: 'bold',
        color: 'white',
        textAlign: 'center',
    },
})


render() {
    return (
        <View style = { styles.navigationView }>
            <Text style = { styles.titleText } > Title name here </Text>
        </View>
    )

}

Select box arrow style

Browsers and OS's determine the style of the select boxes in most cases, and it's next to impossible to alter them with CSS alone. You'll have to look into replacement methods. The main trick is to apply appearance: none which lets you override some of the styling.

My favourite method is this one:

http://cssdeck.com/item/265/styling-select-box-with-css3

It doesn't replace the OS select menu UI element so all the problems related to doing that are non-existant (not being able to break out of the browser window with a long list being the main one).

Good luck :)

Getting a list of associative array keys

You can use: Object.keys(obj)

Example:

_x000D_
_x000D_
var dictionary = {
  "cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  "dogs": [4, 5, 6, 3, 2]
};

// Get the keys
var keys = Object.keys(dictionary);

console.log(keys);
_x000D_
_x000D_
_x000D_

See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. Object.keys() contains a code snippet that you can add if Object.keys() is not supported in your browser.

Multiple radio button groups in one form

This is very simple you need to keep different names of every radio input group.

_x000D_
_x000D_
      <input type="radio" name="price">Thousand<br>_x000D_
      <input type="radio" name="price">Lakh<br>_x000D_
      <input type="radio" name="price">Crore_x000D_
      _x000D_
      </br><hr>_x000D_
_x000D_
      <input type="radio" name="gender">Male<br>_x000D_
      <input type="radio" name="gender">Female<br>_x000D_
      <input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_

Format Float to n decimal places

You may also pass the float value, and use:

String.format("%.2f", floatValue);

Documentation

jQuery Ajax PUT with parameters

You can use the PUT method and pass data that will be included in the body of the request:

let data = {"key":"value"}

$.ajax({
    type: 'PUT',
    url: 'http://example.com/api',
    contentType: 'application/json',
    data: JSON.stringify(data), // access in body
}).done(function () {
    console.log('SUCCESS');
}).fail(function (msg) {
    console.log('FAIL');
}).always(function (msg) {
    console.log('ALWAYS');
});

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

jQuery returning "parsererror" for ajax request

The problem

window.JSON.parse raises an error in $.parseJSON function.

<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>

My solution

Overloading JQuery using requirejs tool.

<pre>
define(['jquery', 'jquery.overload'], function() { 
    //Loading jquery.overload
});
</pre>

jquery.overload.js file content

<pre>
define(['jquery'],function ($) { 

    $.parseJSON: function( data ) {
        // Attempt to parse using the native JSON parser first
        /**  THIS RAISES Parsing ERROR
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }
        **/

        if ( data === null ) {
            return data;
        }

        if ( typeof data === "string" ) {

            // Make sure leading/trailing whitespace is removed (IE can't handle it)
            data = $.trim( data );

            if ( data ) {
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                    .replace( rvalidtokens, "]" )
                    .replace( rvalidbraces, "")) ) {

                    return ( new Function( "return " + data ) )();
                }
            }
        }

        $.error( "Invalid JSON: " + data );
    }

    return $;

});
</pre>

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

Print Html template in Angular 2 (ng-print in Angular 2)

EDIT: updated the snippets for a more generic approach

Just as an extension to the accepted answer,

For getting the existing styles to preserve the look 'n feel of the targeted component, you can:

  1. make a query to pull the <style> and <link> elements from the top-level document

  2. inject it into the HTML string.

To grab a HTML tag:

private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string
{
    const htmlStr: string[] = [];
    const elements = document.getElementsByTagName(tagName);
    for (let idx = 0; idx < elements.length; idx++)
    {
        htmlStr.push(elements[idx].outerHTML);
    }

    return htmlStr.join('\r\n');
}

Then in the existing snippet:

const printContents = document.getElementById('print-section').innerHTML;
const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');

const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
    <html>
        <head>
            <title>Print tab</title>
            ${linksHtml}
            ${stylesHtml}
            ^^^^^^^^^^^^^ add them as usual to the head
        </head>
        <body onload="window.print(); window.close()">
            ${printContents}
        </body>
    </html>
    `
);
popupWin.document.close();

Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap, MaterialDesign, Bulma) it should look like a snippet of the existing screen

powershell - list local users and their groups

Use this to get an array with the local users and the groups they are member of:

Get-LocalUser | 
    ForEach-Object { 
        $user = $_
        return [PSCustomObject]@{ 
            "User"   = $user.Name
            "Groups" = Get-LocalGroup | Where-Object {  $user.SID -in ($_ | Get-LocalGroupMember | Select-Object -ExpandProperty "SID") } | Select-Object -ExpandProperty "Name"
        } 
    }

To get an array with the local groups and their members:

Get-LocalGroup | 
    ForEach-Object {
        $group = $_
        return [PSCustomObject]@{ 
            "Group"   = $group.Name
            "Members" = $group | Get-LocalGroupMember | Select-Object -ExpandProperty "Name"
        } 
    } 

Sound alarm when code finishes

import subprocess

subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

How do I monitor all incoming http requests?

Using Wireshark..

I have not tried this: http://wiki.wireshark.org/CaptureSetup/Loopback

If that works, you could then filter for http/http contains GET/http contains POST traffic.

You might have to run two Wireshark instances, one capturing local, and one capturing remote. I'm not sure.

Combining two sorted lists in Python

People seem to be over complicating this.. Just combine the two lists, then sort them:

>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..or shorter (and without modifying l1):

>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.

If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of datetime objects)

Using the timeit.Timer().repeat() (which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb's solution, and sorted(l1+l2) is substantially quicker:

merge_sorted_lists took..

[9.7439379692077637, 9.8844599723815918, 9.552299976348877]

sorted(l1+l2) took..

[2.860386848449707, 2.7589840888977051, 2.7682540416717529]

What is the Swift equivalent to Objective-C's "@synchronized"?

In the "Understanding Crashes and Crash Logs" session 414 of the 2018 WWDC they show the following way using DispatchQueues with sync.

In swift 4 should be something like the following:

class ImageCache {
    private let queue = DispatchQueue(label: "sync queue")
    private var storage: [String: UIImage] = [:]
    public subscript(key: String) -> UIImage? {
        get {
          return queue.sync {
            return storage[key]
          }
        }
        set {
          queue.sync {
            storage[key] = newValue
          }
        }
    }
}

Anyway you can also make reads faster using concurrent queues with barriers. Sync and async reads are performed concurrently and writing a new value waits for previous operations to finish.

class ImageCache {
    private let queue = DispatchQueue(label: "with barriers", attributes: .concurrent)
    private var storage: [String: UIImage] = [:]

    func get(_ key: String) -> UIImage? {
        return queue.sync { [weak self] in
            guard let self = self else { return nil }
            return self.storage[key]
        }
    }

    func set(_ image: UIImage, for key: String) {
        queue.async(flags: .barrier) { [weak self] in
            guard let self = self else { return }
            self.storage[key] = image
        }
    }
}

Kotlin unresolved reference in IntelliJ

In my case, it was a misconfigured IntelliJ instance.

Project Structure -> SDKs -> Remove and add the Java SDK again

How do I access the $scope variable in browser's console using AngularJS?

I've used angular.element($(".ng-scope")).scope(); in the past and it works great. Only good if you have only one app scope on the page, or you can do something like:

angular.element($("div[ng-controller=controllerName]")).scope(); or angular.element(document.getElementsByClassName("ng-scope")).scope();

.gitignore exclude folder but include specific subfolder

Just another example of walking down the directory structure to get exactly what you want. Note: I didn't exclude Library/ but Library/**/*

# .gitignore file
Library/**/*
!Library/Application Support/
!Library/Application Support/Sublime Text 3/
!Library/Application Support/Sublime Text 3/Packages/
!Library/Application Support/Sublime Text 3/Packages/User/
!Library/Application Support/Sublime Text 3/Packages/User/*macro
!Library/Application Support/Sublime Text 3/Packages/User/*snippet
!Library/Application Support/Sublime Text 3/Packages/User/*settings
!Library/Application Support/Sublime Text 3/Packages/User/*keymap
!Library/Application Support/Sublime Text 3/Packages/User/*theme
!Library/Application Support/Sublime Text 3/Packages/User/**/
!Library/Application Support/Sublime Text 3/Packages/User/**/*macro
!Library/Application Support/Sublime Text 3/Packages/User/**/*snippet
!Library/Application Support/Sublime Text 3/Packages/User/**/*settings
!Library/Application Support/Sublime Text 3/Packages/User/**/*keymap
!Library/Application Support/Sublime Text 3/Packages/User/**/*theme

> git add Library

> git status

On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   Library/Application Support/Sublime Text 3/Packages/User/Default (OSX).sublime-keymap
    new file:   Library/Application Support/Sublime Text 3/Packages/User/ElixirSublime.sublime-settings
    new file:   Library/Application Support/Sublime Text 3/Packages/User/Package Control.sublime-settings
    new file:   Library/Application Support/Sublime Text 3/Packages/User/Preferences.sublime-settings
    new file:   Library/Application Support/Sublime Text 3/Packages/User/RESTer.sublime-settings
    new file:   Library/Application Support/Sublime Text 3/Packages/User/SublimeLinter/Monokai (SL).tmTheme
    new file:   Library/Application Support/Sublime Text 3/Packages/User/TextPastryHistory.sublime-settings
    new file:   Library/Application Support/Sublime Text 3/Packages/User/ZenTabs.sublime-settings
    new file:   Library/Application Support/Sublime Text 3/Packages/User/adrian-comment.sublime-macro
    new file:   Library/Application Support/Sublime Text 3/Packages/User/json-pretty-generate.sublime-snippet
    new file:   Library/Application Support/Sublime Text 3/Packages/User/raise-exception.sublime-snippet
    new file:   Library/Application Support/Sublime Text 3/Packages/User/trailing_spaces.sublime-settings

How to send email attachments?

Here is the modified version from Oli for python 3

import smtplib
from pathlib import Path
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders


def send_mail(send_from, send_to, subject, message, files=[],
              server="localhost", port=587, username='', password='',
              use_tls=True):
    """Compose and send email with provided info and attachments.

    Args:
        send_from (str): from name
        send_to (list[str]): to name(s)
        subject (str): message title
        message (str): message body
        files (list[str]): list of file paths to be attached to email
        server (str): mail server host name
        port (int): port number
        username (str): server auth username
        password (str): server auth password
        use_tls (bool): use TLS mode
    """
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(message))

    for path in files:
        part = MIMEBase('application', "octet-stream")
        with open(path, 'rb') as file:
            part.set_payload(file.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="{}"'.format(Path(path).name))
        msg.attach(part)

    smtp = smtplib.SMTP(server, port)
    if use_tls:
        smtp.starttls()
    smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

Android and Facebook share intent

I found out you can only share either Text or Image, not both using Intents. Below code shares only Image if exists, or only Text if Image does not exits. If you want to share both, you need to use Facebook SDK from here.

If you use other solution instead of below code, don't forget to specify package name com.facebook.lite as well, which is package name of Facebook Lite. I haven't test but com.facebook.orca is package name of Facebook Messenger if you want to target that too.

You can add more methods for sharing with WhatsApp, Twitter ...

public class IntentShareHelper {

    /**
     * <b>Beware,</b> this shares only image if exists, or only text if image does not exits. Can't share both
     */
    public static void shareOnFacebook(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");

        if (fileUri != null) {
            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setType("image/*");
        }

        boolean facebookAppFound = false;
        List<ResolveInfo> matches = appCompatActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo info : matches) {
            if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana") ||
                info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.lite")) {
                intent.setPackage(info.activityInfo.packageName);
                facebookAppFound = true;
                break;
            }
        }

        if (facebookAppFound) {
            appCompatActivity.startActivity(intent);
        } else {
            showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
        }
    }

    public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}

    private static void showWarningDialog(Context context, String message) {
        new AlertDialog.Builder(context)
                .setMessage(message)
                .setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .create().show();
    }
}

For getting Uri from File, use below class:

public class UtilityFile {
    public static @Nullable Uri getUriFromFile(Context context, @Nullable File file) {
        if (file == null)
            return null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return Uri.fromFile(file);
        }
    }

    // Returns the URI path to the Bitmap displayed in specified ImageView       
    public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        Bitmap bmp = null;
        if (drawable instanceof BitmapDrawable) {
            bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        } else {
            return null;
        }
        // Store image to default external storage directory
        Uri bmpUri = null;
        try {
            // Use methods on Context to access package-specific directories on external storage.
            // This way, you don't need to request external read/write permission.
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

            bmpUri = getUriFromFile(context, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }    
}

For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents

What is a simple command line program or script to backup SQL server databases?

I found this on a Microsoft Support page http://support.microsoft.com/kb/2019698.

It works great! And since it came from Microsoft, I feel like it's pretty legit.

Basically there are two steps.

  1. Create a stored procedure in your master db. See msft link or if it's broken try here: http://pastebin.com/svRLkqnq
  2. Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.

    sqlcmd -S YOUR_SERVER_NAME\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='C:\SQL_Backup\', @backupType='F'"  1>c:\SQL_Backup\backup.log            
    

Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\SQL_Backup

Code-first vs Model/Database-first

I think one of the Advantages of code first is that you can back up all the changes you've made to a version control system like Git. Because all your tables and relationships are stored in what are essentially just classes, you can go back in time and see what the structure of your database was before.

How do I make the text box bigger in HTML/CSS?

Try this:

#signin input {
    background-color:#FFF;
    height: 1.5em;
    /* or */
    line-height: 1.5em;
}

How can I compile a Java program in Eclipse without running it?

Right click on Yourproject(in project Explorer)-->Build Project

It will compile all files in your project and updates your build folder, all without running.

Calling a function when ng-repeat has finished

If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:

const dereg = scope.$watch('$$childTail.$last', last => {
    if (last) {
        dereg();
        // do yr stuff -- you may still need a $timeout here
    }
});

This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.

What is the difference between up-casting and down-casting with respect to class variable

I know this question asked quite long time ago but for the new users of this question. Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator

  • There's no need to upcast manually, it happens on its own:

    Mammal m = (Mammal)new Cat(); equals to Mammal m = new Cat();

  • But downcasting must always be done manually:

    Cat c1 = new Cat();      
    Animal a = c1;      //automatic upcasting to Animal
    Cat c2 = (Cat) a;    //manual downcasting back to a Cat
    

Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException. This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.

 Cat c1 = new Cat();         
    Animal a = c1;       //upcasting to Animal
    if(a instanceof Cat){ // testing if the Animal is a Cat
        System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");        
        Cat c2 = (Cat)a;
    }

For more information please read this article

Efficiently sorting a numpy array in descending order?

>>> a=np.array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

>>> np.sort(a)
array([2, 2, 4, 4, 4, 4, 5, 6, 7, 8])

>>> -np.sort(-a)
array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Live search through table rows

This one is Best in my case

https://www.w3schools.com/jquery/jquery_filters.asp

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

How do I make a dotted/dashed line in Android?

By using this class you can apply "dashed and underline" effect to multiple lines text. to use DashPathEffect you have to turn off hardwareAccelerated of your TextView(though DashPathEffect method has a problem with long text). you can find my sample project here: https://github.com/jintoga/Dashed-Underlined-TextView/blob/master/Untitled.png.

public class DashedUnderlineSpan implements LineBackgroundSpan, LineHeightSpan {

    private Paint paint;
    private TextView textView;
    private float offsetY;
    private float spacingExtra;

    public DashedUnderlineSpan(TextView textView, int color, float thickness, float dashPath,
                               float offsetY, float spacingExtra) {
        this.paint = new Paint();
        this.paint.setColor(color);
        this.paint.setStyle(Paint.Style.STROKE);
        this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0));
        this.paint.setStrokeWidth(thickness);
        this.textView = textView;
        this.offsetY = offsetY;
        this.spacingExtra = spacingExtra;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
        fm.ascent -= spacingExtra;
        fm.top -= spacingExtra;
        fm.descent += spacingExtra;
        fm.bottom += spacingExtra;
    }

    @Override
    public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int lineNum = textView.getLineCount();
        for (int i = 0; i < lineNum; i++) {
            Layout layout = textView.getLayout();
            canvas.drawLine(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    this.paint);
        }
    }
}

Result:

dashed underline

How to cherry-pick multiple commits

To apply J. B. Rainsberger and sschaef's comments to specifically answer the question... To use a cherry-pick range on this example:

git checkout a
git cherry-pick b..f

or

git checkout a
git cherry-pick c^..f

Permission denied on CopyFile in VBS

for me adding / worked at the end of location of folder. Hence, if you are copying into folder, don't forget to put /

Reference alias (calculated in SELECT) in WHERE clause

It's actually possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A cross join doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does - and treats nulls more transparently.

SELECT
    vars.BalanceDue
FROM
    Entity e
OUTER APPLY (
    SELECT
        -- variables   
        BalanceDue = e.EntityTypeId,
        Variable2 = ...some..long..complex..expression..etc...
    ) vars
WHERE
    vars.BalanceDue > 0

Kudos to Syed Mehroz Alam.

How to change MenuItem icon in ActionBar programmatically

Instead of getViewById(), use

MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);

replacing the Menu.FIRST with your menu item id.

How can I add some small utility functions to my AngularJS application?

You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.

function doSomething( a, b ) {
    return a + b;
};

angular.module('moduleName',[])
    // Define
    .constant('$doSomething', doSomething)
    // Usage
    .controller( 'SomeController', function( $doSomething ) {
        $scope.added = $doSomething( 100, 200 );
    })
;

Can you use Microsoft Entity Framework with Oracle?

In case you don't know it already, Oracle has released ODP.NET which supports Entity Framework. It doesn't support code first yet though.

http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

combining results of two select statements

You can use a Union.

This will return the results of the queries in separate rows.

First you must make sure that both queries return identical columns.

Then you can do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

UNION

SELECT tableA.Id, tableA.Name,  '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM 
[tableC] 
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name

As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.

SO

You can use a Join

If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...

You could do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 


INNER JOIN 
  (SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans 
   FROM [tableC] 
   RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id 
   GROUP BY tableA.Id, tableA.Name) AS query2 
ON query2.Id = tableA.Id

GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

Are nested try/except blocks in Python a good programming practice?

In Python it is easier to ask for forgiveness than permission. Don't sweat the nested exception handling.

(Besides, has* almost always uses exceptions under the cover anyway.)

How to print React component on click of a button?

If you're looking to print specific data that you already have access to, whether it's from a Store, AJAX, or available elsewhere, you can leverage my library react-print.

https://github.com/captray/react-print

It makes creating print templates much easier (assuming you already have a dependency on react). You just need to tag your HTML appropriately.

This ID should be added higher up in your actual DOM tree to exclude everything except the "print mount" below.

<div id="react-no-print"> 

This is where your react-print component will mount and wrap your template that you create:

<div id="print-mount"></div>

An example looks something like this:

var PrintTemplate = require('react-print');
var ReactDOM = require('react-dom');
var React = require('react');

var MyTemplate = React.createClass({
    render() {
        return (
            <PrintTemplate>
                <p>Your custom</p>
                <span>print stuff goes</span>
                <h1>Here</h1>
            </PrintTemplate>
        );
    }
});

ReactDOM.render(<MyTemplate/>, document.getElementById('print-mount'));

It's worth noting that you can create new or utilize existing child components inside of your template, and everything should render fine for printing.

How do I insert multiple checkbox values into a table?

I think you should $_POST[][], i tried it and it work :)), tks

How to center a <p> element inside a <div> container?

Centered and middled content ?

Do it this way :

<table style="width:100%">
    <tr>
        <td valign="middle" align="center">Table once ruled centering</td>
    </tr>
</table>

I fiddled it here

Ha, let me guess .. you want DIVs ..

just make your first outter DIV behave like a table-cell then style it with vertical align:middle;

<div>
    <p>I want this paragraph to be at the center, but I can't.</p>
</div>

div {
    width:500px;
    height:100px;
    background-color:aqua;
    text-align:center;
    /*  there it is */
    display:table-cell;
    vertical-align:middle;
}

jsfiddle.net/9Mk64/

How to include header files in GCC search path?

The -I directive does the job:

gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c 

JQuery show and hide div on mouse click (animate)

Use slideToggle(500) function with a duration in milliseconds for getting a better effect.

Sample Html

<body>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">2.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details ">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">3.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
</body>

In your js file, if you need child propagation for the animation then remove the second click event function and its codes.

$(document).ready(function(){
    $(".js--growth-step").click(function(event){
       $(this).children(".step-details").slideToggle(500);
         return false;
    });
//for stoping child to manipulate the animation
    $(".js--growth-step .step-details").click(function(event) {
        event.stopPropagation();
   });
});

android get all contacts

public class MyActivity extends Activity 
                        implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int CONTACTS_LOADER_ID = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(CONTACTS_LOADER_ID,
                                      null,
                                      this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.

        if (id == CONTACTS_LOADER_ID) {
            return contactsLoader();
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        //The framework will take care of closing the
        // old cursor once we return.
        List<String> contacts = contactsFromCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
    }

    private  Loader<Cursor> contactsLoader() {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts

        String[] projection = {                                  // The columns to return for each row
                ContactsContract.Contacts.DISPLAY_NAME
        } ;

        String selection = null;                                 //Selection criteria
        String[] selectionArgs = {};                             //Selection criteria
        String sortOrder = null;                                 //The sort order for the returned rows

        return new CursorLoader(
                getApplicationContext(),
                contactsUri,
                projection,
                selection,
                selectionArgs,
                sortOrder);
    }

    private List<String> contactsFromCursor(Cursor cursor) {
        List<String> contacts = new ArrayList<String>();

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();

            do {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contacts.add(name);
            } while (cursor.moveToNext());
        }

        return contacts;
    }

}

and do not forget

<uses-permission android:name="android.permission.READ_CONTACTS" />

Permanently hide Navigation Bar in an activity

After watching the DevBytes video (by Roman Nurik) and reading the very last line in the docs, which says:

Note: If you like the auto-hiding behavior of IMMERSIVE_STICKY but need to show your own UI controls as well, just use IMMERSIVE combined with Handler.postDelayed() or something similar to re-enter immersive mode after a few seconds.

the answer, radu122 gave, worked for me. Just setup a handler and your will be good to go.

Here is the code which works for me:

@Override
protected void onResume() {
    super.onResume();
    executeDelayed();
}


private void executeDelayed() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // execute after 500ms
            hideNavBar();
        }
    }, 500);
}


private void hideNavBar() {
    if (Build.VERSION.SDK_INT >= 19) {
        View v = getWindow().getDecorView();
        v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }
}

Google says "after a few seconds" - but I want to provide this functionality as soon as possible. Maybe I will change the value later, if I have to, I will update this answer.

How to redirect both stdout and stderr to a file

Use:

command >>log_file 2>>log_file

Are the shift operators (<<, >>) arithmetic or logical in C?

Well, I looked it up on wikipedia, and they have this to say:

C, however, has only one right shift operator, >>. Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.

So it sounds like it depends on your compiler. Also in that article, note that left shift is the same for arithmetic and logical. I would recommend doing a simple test with some signed and unsigned numbers on the border case (high bit set of course) and see what the result is on your compiler. I would also recommend avoiding depending on it being one or the other since it seems C has no standard, at least if it is reasonable and possible to avoid such dependence.

onclick open window and specific size

<a style="cursor:pointer"
  onclick=" window.open('http://YOUR.URL.TARGET','',' scrollbars=yes,menubar=no,width=500, resizable=yes,toolbar=no,location=no,status=no')">Your text</a>

What is the Auto-Alignment Shortcut Key in Eclipse?

Want to format it automatically when you save the file???

then Goto Window > Preferences > Java > Editor > Save Actions

and configure your save actions.

Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc

Giving graphs a subtitle in matplotlib

As mentioned here, uou can use matplotlib.pyplot.text objects in order to achieve the same result:

plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)

Getting the difference between two sets

Adding a solution which I've recently used myself and haven't seen mentioned here. If you have Apache Commons Collections available then you can use the SetUtils#difference method:

// Returns all the elements of test2 which are not in test1
SetUtils.difference(test2, test1) 

Note that according to the documentation the returned set is an unmodifiable view:

Returns a unmodifiable view containing the difference of the given Sets, denoted by a \ b (or a - b). The returned view contains all elements of a that are not a member of b.

Full documentation: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/SetUtils.html#difference-java.util.Set-java.util.Set-

How to implement a binary search tree in Python?

I find the solutions a bit clumsy on the insert part. You could return the root reference and simplify it a bit:

def binary_insert(root, node):
    if root is None:
        return node
    if root.data > node.data:
        root.l_child = binary_insert(root.l_child, node)
    else:
        root.r_child = binary_insert(root.r_child, node)
    return root

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

I fixed this problem by explicitly installing g++:

sudo apt-get install g++

Problem was encountered on Ubuntu 12.04 while installing pandas. (Thanks perilbrain.)

Get current application physical path within Application_Start

Best choice is using

AppDomain.CurrentDomain.BaseDirectory

because it's in the system namespace and there is no dependency to system.web

this way your code will be more portable

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Password masking console application

This masks the password with a red square, then reverts back to the original colours once the password has been entered.

It doesn't stop the user from using copy/paste to get the password, but if it's more just about stopping someone looking over your shoulder, this is a good quick solution.

Console.Write("Password ");
ConsoleColor origBG = Console.BackgroundColor; // Store original values
ConsoleColor origFG = Console.ForegroundColor;

Console.BackgroundColor = ConsoleColor.Red; // Set the block colour (could be anything)
Console.ForegroundColor = ConsoleColor.Red;

string Password = Console.ReadLine(); // read the password

Console.BackgroundColor= origBG; // revert back to original
Console.ForegroundColor= origFG;

What is *.o file?

You've gotten some answers, and most of them are correct, but miss what (I think) is probably the point here.

My guess is that you have a makefile you're trying to use to create an executable. In case you're not familiar with them, makefiles list dependencies between files. For a really simple case, it might have something like:

myprogram.exe: myprogram.o
    $(CC) -o myprogram.exe myprogram.o

myprogram.o: myprogram.cpp
    $(CC) -c myprogram.cpp

The first line says that myprogram.exe depends on myprogram.o. The second line tells how to create myprogram.exe from myprogram.o. The third and fourth lines say myprogram.o depends on myprogram.cpp, and how to create myprogram.o from myprogram.cpp` respectively.

My guess is that in your case, you have a makefile like the one above that was created for gcc. The problem you're running into is that you're using it with MS VC instead of gcc. As it happens, MS VC uses ".obj" as the extension for its object files instead of ".o".

That means when make (or its equivalent built into the IDE in your case) tries to build the program, it looks at those lines to try to figure out how to build myprogram.exe. To do that, it sees that it needs to build myprogram.o, so it looks for the rule that tells it how to build myprogram.o. That says it should compile the .cpp file, so it does that.

Then things break down -- the VC++ compiler produces myprogram.obj instead of myprogram.o as the object file, so when it tries to go to the next step to produce myprogram.exe from myprogram.o, it finds that its attempt at creating myprogram.o simply failed. It did what the rule said to do, but that didn't produce myprogram.o as promised. It doesn't know what to do, so it quits and give you an error message.

The cure for that specific problem is probably pretty simple: edit the make file so all the object files have an extension of .obj instead of .o. There's room for a lot of question whether that will fix everything though -- that may be all you need, or it may simply lead to other (probably more difficult) problems.

How to decide when to use Node.js?

There is nothing like Silver Bullet. Everything comes with some cost associated with it. It is like if you eat oily food, you will compromise your health and healthy food does not come with spices like oily food. It is individual choice whether they want health or spices as in their food. Same way Node.js consider to be used in specific scenario. If your app does not fit into that scenario you should not consider it for your app development. I am just putting my thought on the same:

When to use Node.JS

  1. If your server side code requires very few cpu cycles. In other world you are doing non blocking operation and does not have heavy algorithm/Job which consumes lots of CPU cycles.
  2. If you are from Javascript back ground and comfortable in writing Single Threaded code just like client side JS.

When NOT to use Node.JS

  1. Your server request is dependent on heavy CPU consuming algorithm/Job.

Scalability Consideration with Node.JS

  1. Node.JS itself does not utilize all core of underlying system and it is single threaded by default, you have to write logic by your own to utilize multi core processor and make it multi threaded.

Node.JS Alternatives

There are other option to use in place of Node.JS however Vert.x seems to be pretty promising and has lots of additional features like polygot and better scalability considerations.