Programs & Examples On #Http status

The status code describes the state of the response from the web server.

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

If "validation failure" means that there is some client error in the request, then use HTTP 400 (Bad Request). For instance if the URI is supposed to have an ISO-8601 date and you find that it's in the wrong format or refers to February 31st, then you would return an HTTP 400. Ditto if you expect well-formed XML in an entity body and it fails to parse.

(1/2016): Over the last five years WebDAV's more specific HTTP 422 (Unprocessable Entity) has become a very reasonable alternative to HTTP 400. See for instance its use in JSON API. But do note that HTTP 422 has not made it into HTTP 1.1, RFC-7231.

Richardson and Ruby's RESTful Web Services contains a very helpful appendix on when to use the various HTTP response codes. They say:

400 (“Bad Request”)
Importance: High.
This is the generic client-side error status, used when no other 4xx error code is appropriate. It’s commonly used when the client submits a representation along with a PUT or POST request, and the representation is in the right format, but it doesn’t make any sense. (p. 381)

and:

401 (“Unauthorized”)
Importance: High.
The client tried to operate on a protected resource without providing the proper authentication credentials. It may have provided the wrong credentials, or none at all. The credentials may be a username and password, an API key, or an authentication token—whatever the service in question is expecting. It’s common for a client to make a request for a URI and accept a 401 just so it knows what kind of credentials to send and in what format. [...]

Common HTTPclient and proxy

If your software uses a ProxySelector (for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector for your HttpClient like this:

ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();

And then do your requests as usual:

HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);

Remove empty lines in a text file via grep

Try this: sed -i '/^[ \t]*$/d' file-name

It will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file.

Note: there is a 'space' followed by '\t' inside the square bracket.

The modifier -i will force to write the updated contents back in the file. Without this flag you can see the empty lines got deleted on the screen but the actual file will not be affected.

How to get page content using cURL?

Try This:

$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

PyCharm import external library

Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.

My project is now behaving as I would expect.

These are the windows you would see while following the instructions

AngularJS: factory $http.get JSON file

this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:

menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) { 
    console.log("success!");
    $scope.appetizers = data.appetizers;
        console.log(data.appetizers);
    });    
});

How to add additional libraries to Visual Studio project?

This description is very vague. What did you try, and how did it fail.

To include a library with your project, you have to include it in the modules passed to the linker. The exact steps to do this depend on the tools you are using. That part has nothing to do with the OS.

Now, if you are successfully compiling the library into your app and it doesn't run, that COULD be related to the OS.

Which version of Python do I have installed?

If you are already in a REPL window and don't see the welcome message with the version number, you can use help() to see the major and minor version:

>>>help()
Welcome to Python 3.6's help utility!
...

How can I prevent the backspace key from navigating back?

JavaScript - jQuery way:

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input, textarea")) {
        e.preventDefault();
    }
});

Javascript - the native way, that works for me:

<script type="text/javascript">

//on backspace down + optional callback
function onBackspace(e, callback){
    var key;
    if(typeof e.keyIdentifier !== "undefined"){
        key = e.keyIdentifier;

    }else if(typeof e.keyCode !== "undefined"){
        key = e.keyCode;
    }
    if (key === 'U+0008' || 
        key === 'Backspace' || 
        key === 8) {
                    if(typeof callback === "function"){
                callback();
            }
            return true;
        }
    return false;
}

//event listener
window.addEventListener('keydown', function (e) {

    switch(e.target.tagName.toLowerCase()){
        case "input":
        case "textarea":
        break;
        case "body":
            onBackspace(e,function(){
                e.preventDefault();
            });

        break;
    }
}, true);
</script>

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

Python/BeautifulSoup - how to remove all tags from an element?

it looks like this is the way to do! as simple as that

with this line you are joining together the all text parts within the current element

''.join(htmlelement.find(text=True))

Find the unique values in a column and then sort them

sorted return a new sorted list from the items in iterable.

CODE

import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print sorted(a)

OUTPUT

[1, 2, 3, 6, 8]

Stop floating divs from wrapping

I had a somewhat similar problem where a bounded area consisted of an image in a float:left block and a non-float text block. The area has a fluid width. The text would, by design, wrap up along the right side of the image. The trouble was, the text began with an <h4> tag, the first word of which is the tiny word "From." As I resized the window to a smaller width, the non-floated text would, for a certain range of widths, leave only the word "From" at the top of the wrap area, the rest of the text having been squeezed below the float block. My solution was to make the first word of the tag bigger, by replacing the space that followed it with this code, <span style="opacity:0;">x</span> . The effect was to make the first word, instead of "From", "FromxNextWord", where the "x", being invisible, looked like a space. Now my first word was big enough not to be abandoned by the rest of the text block.

What's the difference between JavaScript and Java?

Everything. They're unrelated languages.

How to set background image of a view?

You want the background color of your main view to be semi-transparent? There's nothing behind it... so nothing will really happen however:

If you want to modify the alpha of any view, use the alpha property:

UIView *someView = [[UIView alloc] init];
...
someView.alpha = 0.8f; //Sets the opacity to 80%
...

Views themselves have the alpha transparency, not just UIColor.

But since your problem is that you can't read text on top of the images... either:

  1. [DESIGN] Reconsider the design/placement of the images. Are they necessary as background images? What about the placement of the labels?
  2. [CODE] It's not exactly the best solution, but what you could do is create a UIView whose frame takes up the entire page and add some alpha transparency to it. This will create an "overlay" of sorts.
UIView *overlay = [[[UIView alloc] init] autorelease];
overlay.frame = self.view.bounds;
overlay.alpha = 0.2f;
[self.view addSubview:overlay];
... Add the rest of the views

Where to change the value of lower_case_table_names=2 on windows xampp

Try adding/editing lower_case_table_names = 2 in my.ini or my.cnf

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

CSS rotation cross browser with jquery.animate()

To do this cross browser including IE7+, you will need to expand the plugin with a transformation matrix. Since vendor prefix is done in jQuery from jquery-1.8+ I will leave that out for the transform property.

$.fn.animateRotate = function(endAngle, options, startAngle)
{
    return this.each(function()
    {
        var elem = $(this), rad, costheta, sintheta, matrixValues, noTransform = !('transform' in this.style || 'webkitTransform' in this.style || 'msTransform' in this.style || 'mozTransform' in this.style || 'oTransform' in this.style),
            anims = {}, animsEnd = {};
        if(typeof options !== 'object')
        {
            options = {};
        }
        else if(typeof options.extra === 'object')
        {
            anims = options.extra;
            animsEnd = options.extra;
        }
        anims.deg = startAngle;
        animsEnd.deg = endAngle;
        options.step = function(now, fx)
        {
            if(fx.prop === 'deg')
            {
                if(noTransform)
                {
                    rad = now * (Math.PI * 2 / 360);
                    costheta = Math.cos(rad);
                    sintheta = Math.sin(rad);
                    matrixValues = 'M11=' + costheta + ', M12=-'+ sintheta +', M21='+ sintheta +', M22='+ costheta;
                    $('body').append('Test ' + matrixValues + '<br />');
                    elem.css({
                        'filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')',
                        '-ms-filter': 'progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\','+matrixValues+')'
                    });
                }
                else
                {
                    elem.css({
                        //webkitTransform: 'rotate('+now+'deg)',
                        //mozTransform: 'rotate('+now+'deg)',
                        //msTransform: 'rotate('+now+'deg)',
                        //oTransform: 'rotate('+now+'deg)',
                        transform: 'rotate('+now+'deg)'
                    });
                }
            }
        };
        if(startAngle)
        {
            $(anims).animate(animsEnd, options);
        }
        else
        {
            elem.animate(animsEnd, options);
        }
    });
};

Note: The parameters options and startAngle are optional, if you only need to set startAngle use {} or null for options.

Example usage:

var obj = $(document.createElement('div'));
obj.on("click", function(){
    obj.stop().animateRotate(180, {
        duration: 250,
        complete: function()
        {
            obj.animateRotate(0, {
                duration: 250
            });
        }
    });
});
obj.text('Click me!');
obj.css({cursor: 'pointer', position: 'absolute'});
$('body').append(obj);

See also this jsfiddle for a demo.

Update: You can now also pass extra: {} in the options. This will make you able to execute other animations simultaneously. For example:

obj.animateRotate(90, {extra: {marginLeft: '100px', opacity: 0.5}});

This will rotate the element 90 degrees, and move it to the right with 100px and make it semi-transparent all at the same time during the animation.

Remove multiple whitespaces

preg_replace('/[\s]+/mu', ' ', $var);

\s already contains tabs and new lines, so this above regex appears to be sufficient.

filedialog, tkinter and opening files

The exception you get is telling you filedialog is not in your namespace. filedialog (and btw messagebox) is a tkinter module, so it is not imported just with from tkinter import *

>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>> 

you should use for example:

>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>

or

>>> import tkinter.filedialog as fdialog

or

>>> from tkinter.filedialog import askopenfilename

So this would do for your browse button:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

enter image description here

How to set editable true/false EditText in Android programmatically?

I did it in a easier way , setEditable and setFocusable false. but you should check this.

How to replicate android:editable="false" in code?

Error: free(): invalid next size (fast):

I encountered a similar error. It was a noob mistake done in a hurry. Integer array without declaring size int a[] then trying to access it. C++ compiler should've caught such an error easily if it were in main. However since this particular int array was declared inside an object, it was being created at the same time as my object (many objects were being created) and the compiler was throwing a free(): invalid next size(normal) error. I thought of 2 explanations for this (please enlighten me if anyone knows more): 1.) This resulted in some random memory being assigned to it but since this wasn't accessible it was freeing up all the other heap memory just trying to find this int. 2.) The memory required by it was practically infinite for a program and to assign this it was freeing up all other memory.

A simple:

    int* a;
    class foo{ 
    foo(){
       for(i=0;i<n;i++)
           a=new int[i];
     }

Solved the problem. But it did take a lot of time trying to debug this because the compiler could not "really" find the error.

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

Moving from position A to position B slowly with animation

I don't understand why other answers are about relative coordinates change, not absolute like OP asked in title.

$("#Friends").animate( {top:
  "-=" + (parseInt($("#Friends").css("top")) - 100) + "px"
} );

How to add form validation pattern in Angular 2?

Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.

https://www.npmjs.com/package/ngx-trim-directive https://www.npmjs.com/package/ng2-trim-directive

Thank you.

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

How to change the style of alert box?

I use AlertifyJS to style my dialogues.

_x000D_
_x000D_
alertify.alert('Ready!');_x000D_
alertify.YoutubeDialog || alertify.dialog('YoutubeDialog',function(){_x000D_
    var iframe;_x000D_
    return {_x000D_
        // dialog constructor function, this will be called when the user calls alertify.YoutubeDialog(videoId)_x000D_
        main:function(videoId){_x000D_
            //set the videoId setting and return current instance for chaining._x000D_
            return this.set({ _x000D_
                'videoId': videoId_x000D_
            });_x000D_
        },_x000D_
        // we only want to override two options (padding and overflow)._x000D_
        setup:function(){_x000D_
            return {_x000D_
                options:{_x000D_
                    //disable both padding and overflow control._x000D_
                    padding : !1,_x000D_
                    overflow: !1,_x000D_
                }_x000D_
            };_x000D_
        },_x000D_
        // This will be called once the DOM is ready and will never be invoked again._x000D_
        // Here we create the iframe to embed the video._x000D_
        build:function(){           _x000D_
            // create the iframe element_x000D_
            iframe = document.createElement('iframe');_x000D_
            iframe.frameBorder = "no";_x000D_
            iframe.width = "100%";_x000D_
            iframe.height = "100%";_x000D_
            // add it to the dialog_x000D_
            this.elements.content.appendChild(iframe);_x000D_
_x000D_
            //give the dialog initial height (half the screen height)._x000D_
            this.elements.body.style.minHeight = screen.height * .5 + 'px';_x000D_
        },_x000D_
        // dialog custom settings_x000D_
        settings:{_x000D_
            videoId:undefined_x000D_
        },_x000D_
        // listen and respond to changes in dialog settings._x000D_
        settingUpdated:function(key, oldValue, newValue){_x000D_
            switch(key){_x000D_
               case 'videoId':_x000D_
                    iframe.src = "https://www.youtube.com/embed/" + newValue + "?enablejsapi=1";_x000D_
                break;   _x000D_
            }_x000D_
        },_x000D_
        // listen to internal dialog events._x000D_
        hooks:{_x000D_
            // triggered when the dialog is closed, this is seperate from user defined onclose_x000D_
            onclose: function(){_x000D_
                iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');_x000D_
            },_x000D_
            // triggered when a dialog option gets update._x000D_
            // warning! this will not be triggered for settings updates._x000D_
            onupdate: function(option,oldValue, newValue){_x000D_
                switch(option){_x000D_
                    case 'resizable':_x000D_
                        if(newValue){_x000D_
                            this.elements.content.removeAttribute('style');_x000D_
                            iframe && iframe.removeAttribute('style');_x000D_
                        }else{_x000D_
                            this.elements.content.style.minHeight = 'inherit';_x000D_
                            iframe && (iframe.style.minHeight = 'inherit');_x000D_
                        }_x000D_
                    break;    _x000D_
                }    _x000D_
            }_x000D_
        }_x000D_
    };_x000D_
});_x000D_
//show the dialog_x000D_
alertify.YoutubeDialog('GODhPuM5cEE').set({frameless:true});
_x000D_
<!-- JavaScript -->_x000D_
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>_x000D_
<!-- CSS -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.rtl.min.css"/>
_x000D_
_x000D_
_x000D_

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

Getting the document object of an iframe

For even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

Is Constructor Overriding Possible?

Constructor looks like a method but name should be as class name and no return value.

Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding. Super class name and Sub class names are different.

If you trying to write Super class Constructor in Sub class, then Sub class will treat that as a method not constructor because name should not match with Sub class name. And it will give an compilation error that methods does not have return value. So we should declare as void, then only it will compile.

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

@RequestParam in Spring MVC handling optional parameters

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}

How to launch Windows Scheduler by command-line?

This launches the Scheduled Tasks MMC Control Panel:

%SystemRoot%\system32\taskschd.msc /s

Older versions of windows had a splash screen for the MMC control panel and the /s switch would supress it. It's not needed but doesn't hurt either.

Where Sticky Notes are saved in Windows 10 1607

It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app

Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/

Can .NET load and parse a properties file equivalent to Java Properties class?

Yet another answer (in January 2018) to the old question (in January 2009).

The specification of Java properties file is described in the JavaDoc of java.util.Properties.load(java.io.Reader). One problem is that the specification is a bit complicated than the first impression we may have. Another problem is that some answers here arbitrarily added extra specifications - for example, ; and ' are regarded as starters of comment lines but they should not be. Double/single quotations around property values are removed but they should not be.

The following are points to be considered.

  1. There are two kinds of line, natural lines and logical lines.
  2. A natural line is terminated by \n, \r, \r\n or the end of the stream.
  3. A logical line may be spread out across several adjacent natural lines by escaping the line terminator sequence with a backslash character \.
  4. Any white space at the start of the second and following natural lines in a logical line are discarded.
  5. White spaces are space (, \u0020), tab (\t, \u0009) and form feed (\f, \u000C).
  6. As stated explicitly in the specification, "it is not sufficient to only examine the character preceding a line terminator sequence to decide if the line terminator is escaped; there must be an odd number of contiguous backslashes for the line terminator to be escaped. Since the input is processed from left to right, a non-zero even number of 2n contiguous backslashes before a line terminator (or elsewhere) encodes n backslashes after escape processing."
  7. = is used as the separator between a key and a value.
  8. : is used as the separator between a key and a value, too.
  9. The separator between a key and a value can be omitted.
  10. A comment line has # or ! as its first non-white space characters, meaning leading white spaces before # or ! are allowed.
  11. A comment line cannot be extended to next natural lines even its line terminator is preceded by \.
  12. As stated explicitly in the specification, =, : and white spaces can be embedded in a key if they are escaped by backslashes.
  13. Even line terminator characters can be included using \r and \n escape sequences.
  14. If a value is omitted, an empty string is used as a value.
  15. \uxxxx is used to represent a Unicode character.
  16. A backslash character before a non-valid escape character is not treated as an error; it is silently dropped.

So, for example, if test.properties has the following content:

# A comment line that starts with '#'.
   # This is a comment line having leading white spaces.
! A comment line that starts with '!'.

key1=value1
  key2 : value2
    key3 value3
key\
  4=value\
    4
\u006B\u0065\u00795=\u0076\u0061\u006c\u0075\u00655
\k\e\y\6=\v\a\lu\e\6

\:\ \= = \\colon\\space\\equal

it should be interpreted as the following key-value pairs.

+------+--------------------+
| KEY  | VALUE              |
+------+--------------------+
| key1 | value1             |
| key2 | value2             |
| key3 | value3             |
| key4 | value4             |
| key5 | value5             |
| key6 | value6             |
| : =  | \colon\space\equal |
+------+--------------------+

PropertiesLoader class in Authlete.Authlete NuGet package can interpret the format of the specification. The example code below:

using System;
using System.IO;
using System.Collections.Generic;
using Authlete.Util;

namespace MyApp
{
    class Program
    {
        public static void Main(string[] args)
        {
            string file = "test.properties";
            IDictionary<string, string> properties;

            using (TextReader reader = new StreamReader(file))
            {
                properties = PropertiesLoader.Load(reader);
            }

            foreach (var entry in properties)
            {
                Console.WriteLine($"{entry.Key} = {entry.Value}");
            }
        }
    }
}

will generate this output:

key1 = value1
key2 = value2
key3 = value3
key4 = value4
key5 = value5
key6 = value6
: = = \colon\space\equal

An equivalent example in Java is as follows:

import java.util.*;
import java.io.*;

public class Program
{
    public static void main(String[] args) throws IOException
    {
        String file = "test.properties";
        Properties properties = new Properties();

        try (Reader reader = new FileReader(file))
        {
             properties.load(reader);
        }

        for (Map.Entry<Object, Object> entry : properties.entrySet())
        {
            System.out.format("%s = %s\n", entry.getKey(), entry.getValue());
        }    
    }
}

The source code, PropertiesLoader.cs, can be found in authlete-csharp. xUnit tests for PropertiesLoader are written in PropertiesLoaderTest.cs.

Should I use past or present tense in git commit messages?

Your project should almost always use the past tense. In any case, the project should always use the same tense for consistency and clarity.

I understand some of the other arguments arguing to use the present tense, but they usually don't apply. The following bullet points are common arguments for writing in the present tense, and my response.

  • Writing in the present tense tells someone what applying the commit will do, rather than what you did.

This is the most correct reason one would want to use the present tense, but only with the right style of project. This manner of thinking considers all commits as optional improvements or features, and you are free to decide which commits to keep and which to reject in your particular repository.

This argument works if you are dealing with a truly distributed project. If you are dealing with a distributed project, you are probably working on an open source project. And it is probably a very large project if it is really distributed. In fact, it's probably either the Linux kernel or Git. Since Linux is likely what caused Git to spread and gain in popularity, it's easy to understand why people would consider its style the authority. Yes, the style makes sense with those two projects. Or, in general, it works with large, open source, distributed projects.

That being said, most projects in source control do not work like this. It is usually incorrect for most repositories. It's a modern way of thinking about a commits: Subversion (SVN) and CVS repositories could barely support this style of repository check-ins. Usually an integration branch handled filtering bad check-ins, but those generally weren't considered "optional" or "nice-to-have features".

In most scenarios, when you are making commits to a source repository, you are writing a journal entry which describes what changed with this update, to make it easier for others in the future to understand why a change was made. It generally isn't an optional change - other people in the project are required to either merge or rebase on it. You don't write a diary entry such as "Dear diary, today I meet a boy and he says hello to me.", but instead you write "I met a boy and he said hello to me."

Finally, for such non-distributed projects, 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository.

  • Consistency. That's how it is in many projects (including git itself). Also git tools that generate commits (like git merge or git revert) do it.

No, I guarantee you that the majority of projects ever logged in a version control system have had their history in the past tense (I don't have references, but it's probably right, considering the present tense argument is new since Git). "Revision" messages or commit messages in the present tense only started making sense in truly distributed projects - see the first point above.

  • People not only read history to know "what happened to this codebase", but also to answer questions like "what happens when I cherry-pick this commit", or "what kind of new things will happen to my code base because of these commits I may or may not merge in the future".

See the first point. 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository. 99.99% beats 0.01%.

  • It's usually shorter

I've never seen a good argument that says use improper tense/grammar because it's shorter. You'll probably only save 3 characters on average for a standard 50 character message. That being said, the present tense on average will probably be a few characters shorter.

  • You can name commits more consistently with titles of tickets in your issue/feature tracker (which don't use past tense, although sometimes future)

Tickets are written as either something that is currently happening (e.g. the app is showing the wrong behavior when I click this button), or something that needs to be done in the future (e.g. the text will need a review by the editor).

History (i.e. commit messages) is written as something that was done in the past (e.g. the problem was fixed).

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

Call Javascript function from URL/address bar

You can use Data URIs. For example: data:text/html,<script>alert('hi');</script>

For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

How to install Python MySQLdb module using pip?

on RHEL 7:

sudo yum install yum-utils mariadb-devel python-pip python-devel gcc

sudo /bin/pip2 install MySQL-python

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

How to check if an app is installed from a web-page on an iPhone?

iOS Safari has a feature that allows you to add a "smart" banner to your webpage that will link either to your app, if it is installed, or to the App Store.

You do this by adding a meta tag to the page. You can even specify a detailed app URL if you want the app to do something special when it loads.

Details are at Apple's Promoting Apps with Smart App Banners page.

The mechanism has the advantages of being easy and presenting a standardized banner. The downside is that you don't have much control over the look or location. Also, all bets are off if the page is viewed in a browser other than Safari.

Github Windows 'Failed to sync this branch'

I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status command Git Shell suggested to push changes as

Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

I did the same as Git Shell suggested (git push) and everything is ok now.

Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.

fatal: Not a git repository (or any of the parent directories):

For example if your Project is in D drive in some folder you have to do something like below as you do in cmd to change directory.

cd D:\someFolder     // if your project is not deep in `D`

And if its within nested folder in D

cd D:\somefolder\someNestedFolder\nestedInNested     // if your project is not deep in `D`

If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.

Add carriage return to a string

string s2 = s1.Replace(",", "," + Environment.NewLine);

Also, just from a performance perspective, here's how the three current solutions I've seen stack up over 100k iterations:

ReplaceWithConstant           - Ms: 328, Ticks: 810908
ReplaceWithEnvironmentNewLine - Ms: 310, Ticks: 766955 
SplitJoin                     - Ms: 483, Ticks: 1192545

ReplaceWithConstant:

string s2 = s1.Replace(",", ",\n");

ReplaceWithEnvironmentNewLine:

string s2 = s1.Replace(",", "," + Environment.NewLine);

SplitJoin:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));

ReplaceWithEnvironmentNewLine and ReplaceWithConstant are within the margin of error of each other, so there's functionally no difference.

Using Environment.NewLine should be preferred over "\n" for the sake readability and consistency similar to using String.Empty instead of "".

C++ unordered_map using a custom class type as the key

For enum type, I think this is a suitable way, and the difference between class is how to calculate hash value.

template <typename T>
struct EnumTypeHash {
  std::size_t operator()(const T& type) const {
    return static_cast<std::size_t>(type);
  }
};

enum MyEnum {};
class MyValue {};

std::unordered_map<MyEnum, MyValue, EnumTypeHash<MyEnum>> map_;

How to append multiple items in one line in Python

use for loop. like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

Suppress command line output

Use this script instead:

@taskkill/f /im test.exe >nul 2>&1
@pause

What the 2>&1 part actually does, is that it redirects the stderr output to stdout. I will explain it better below:

@taskkill/f /im test.exe >nul 2>&1

Kill the task "test.exe". Redirect stderr to stdout. Then, redirect stdout to nul.

@pause

Show the pause message Press any key to continue . . . until someone presses a key.

NOTE: The @ symbol is hiding the prompt for each command. You can save up to 8 bytes this way.

The shortest version of your script could be:
@taskkill/f /im test.exe >nul 2>&1&pause
The & character is used for redirection the first time, and for separating the commands the second time.
An @ character is not needed twice in a line. This code is just 40 bytes, despite the one you've posted being 49 bytes! I actually saved 9 bytes. For a cleaner code look above.

Radio/checkbox alignment in HTML/CSS

@sfjedi

I've created a class and assigned the css values to it.

.radioA{
   vertical-align: middle;
}

It is working and you can check it in the below link. http://jsfiddle.net/gNVsC/ Hope it was useful.

php REQUEST_URI

You can either use regex, or keep on using str_replace.

Eg.

$url = parse_url($_SERVER['REQUEST_URI']);

if ($url != '/') {
    parse_str($url['query']);
    echo $id;
    echo $othervar;
}

Output will be: http://www.testing.com/123/123

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Daniel answer is right on the spot. If you want to query more than one field do this:

Employee.objects.values_list('eng_name','rank')

This will return list of tuples. You cannot use named=Ture when querying more than one field.

Moreover if you know that only one field exists with that info and you know the pk id then do this:

Employee.objects.values_list('eng_name','rank').get(pk=1)

Regex for quoted string with escaping quotes

/(["\']).*?(?<!\\)(\\\\)*\1/is

should work with any quoted string

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Get the distance between two geo points

Just use the following method, pass it lat and long and get distance in meter:

private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
    double R = 6371000f; // Radius of the earth in m
    double dLat = (lat1 - lat2) * Math.PI / 180f;
    double dLon = (lon1 - lon2) * Math.PI / 180f;
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double d = R * c;
    return d;
}

Draw text in OpenGL ES

Look at the "Sprite Text" sample in the GLSurfaceView samples.

What is the "-->" operator in C/C++?

Anyway, we have a "goes to" operator now. "-->" is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.

Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)" on some platforms.

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

Align two inline-blocks left and right on same line

Edit: 3 years has passed since I answered this question and I guess a more modern solution is needed, although the current one does the thing :)

1.Flexbox

It's by far the shortest and most flexible. Apply display: flex; to the parent container and adjust the placement of its children by justify-content: space-between; like this:

.header {
    display: flex;
    justify-content: space-between;
}

Can be seen online here - http://jsfiddle.net/skip405/NfeVh/1073/

Note however that flexbox support is IE10 and newer. If you need to support IE 9 or older, use the following solution:

2.You can use the text-align: justify technique here.

.header {
    background: #ccc; 
    text-align: justify; 

    /* ie 7*/  
    *width: 100%;  
    *-ms-text-justify: distribute-all-lines;
    *text-justify: distribute-all-lines;
}
 .header:after{
    content: '';
    display: inline-block;
    width: 100%;
    height: 0;
    font-size:0;
    line-height:0;
}

h1 {
    display: inline-block;
    margin-top: 0.321em; 

    /* ie 7*/ 
    *display: inline;
    *zoom: 1;
    *text-align: left; 
}

.nav {
    display: inline-block;
    vertical-align: baseline; 

    /* ie 7*/
    *display: inline;
    *zoom:1;
    *text-align: right;
}

The working example can be seen here: http://jsfiddle.net/skip405/NfeVh/4/. This code works from IE7 and above

If inline-block elements in HTML are not separated with space, this solution won't work - see example http://jsfiddle.net/NfeVh/1408/ . This might be a case when you insert content with Javascript.

If we don't care about IE7 simply omit the star-hack properties. The working example using your markup is here - http://jsfiddle.net/skip405/NfeVh/5/. I just added the header:after part and justified the content.

In order to solve the issue of the extra space that is inserted with the after pseudo-element one can do a trick of setting the font-size to 0 for the parent element and resetting it back to say 14px for the child elements. The working example of this trick can be seen here: http://jsfiddle.net/skip405/NfeVh/326/

SQL Error: ORA-00913: too many values

The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.

How to position two divs horizontally within another div

This answer adds to the solutions above to address your last sentence that reads:

how do I ensure that sub-left and sub-right stay within sub-title

The problem is that as the content of sub-left or sub-right expands they will extend below sub-title. This behaviour is designed into CSS but does cause problems for most of us. The easiest solution is to have a div that is styled with the CSS Clear declaration.

To do this include a CSS statement to define a closing div (can be Clear Left or RIght rather than both, depending on what Float declarations have been used:

#sub_close {clear:both;}

And the HTML becomes:

<div id="sub-title">
<div id="sub-left">Right</div>
<div id="sub-right">Left</div>
<div id="sub-close"></div>
</div>

Sorry, just realized this was posted previously, shouldn't have made that cup of coffee while typing my reply!

@Darko Z: you are right, the best description for the overflow:auto (or overflow:hidden) solution that I have found was in a a post on SitePoint a while ago Simple Clearing of FLoats and there is also a good description in a 456bereastreet article CSS Tips and Tricks Part-2. Have to admit to being too lazy to implement these solutions myself, as the closing div cludge works OK although it is of course very inelegant. So will make an effort from now on to clean up my act.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Hello Googlers from the future.

On MacOS >= High Sierra, the SSH key is no longer saved to the KeyChain because of reasons.

Using ssh-add -K no longer survives restarts as well.

Here are 3 possible solutions.

I've used the first method successfully. I've created a file called config in ~/.ssh:

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa

repaint() in Java

You're doing things in the wrong order.

You need to first add all JComponents to the JFrame, and only then call pack() and then setVisible(true) on the JFrame

If you later added JComponents that could change the GUI's size you will need to call pack() again, and then repaint() on the JFrame after doing so.

What is __future__ in Python used for and how/when to use it, and how it works

With __future__ module's inclusion, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.

E.g., for using context managers, you had to do from __future__ import with_statement in 2.5, as the with keyword was new and shouldn't be used as variable names any longer. In order to use with as a Python keyword in Python 2.5 or older, you will need to use the import from above.

Another example is

from __future__ import division
print 8/7  # prints 1.1428571428571428
print 8//7 # prints 1

Without the __future__ stuff, both print statements would print 1.

The internal difference is that without that import, / is mapped to the __div__() method, while with it, __truediv__() is used. (In any case, // calls __floordiv__().)

Apropos print: print becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.

>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>>

How do I make a "div" button submit the form its sitting in?

To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:

$('#id-of-the-button').click(function() {document.forms[0].submit()});

Which assumes you just have the one form on the page.

Change the size of a JTextField inside a JBorderLayout

From the api on GridLayout:

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).

    JPanel displayPanel = new JPanel();
    // JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
    // JPanel displayPanel = new JPanel( new BorderLayout() );
    // JPanel displayPanel = new JPanel( new GridBagLayout() );

    JTextField titleText = new JTextField( "title" );

    titleText.setPreferredSize( new Dimension( 200, 24 ) );

    // For FlowLayout and GridLayout, uncomment:
    displayPanel.add( titleText );

    // For BorderLayout, uncomment:
    // displayPanel.add( titleText, BorderLayout.NORTH );

    // For GridBagLayout, uncomment:
    // displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
    // 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
    // new Insets( 0, 0, 0, 0 ), 0, 0 ) );

How to show text in combobox when no item selected?

Use the insert method of the combobox to insert the "Please select item" in to 0 index,

comboBox1.Items.Insert(0, "Please select any value");

and add all the items to the combobox after the first index. In the form load set

comboBox1.SelectedIndex = 0;

EDIT:

In form load write the text in to the comboBox1.Text by hardcoding

comboBox1.Text = "Please, select any value";

and in the TextChanged event of the comboBox1 write the following code

 private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex < 0)
            {
                comboBox1.Text = "Please, select any value";
            }
            else
            {
                comboBox1.Text = comboBox1.SelectedText;
            }
        }

jQuery: Scroll down page a set increment (in pixels) on click?

var y = $(window).scrollTop();  //your current y position on the page
$(window).scrollTop(y+150);

await is only valid in async function

"await is only valid in async function"

But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.

How to set back button text in Swift

In the viewDidLoad method of the presenting controller add:

// hide navigation bar title in the next controller
let backButton = UIBarButtonItem(title: "", style:.Plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton

Parse RSS with jQuery

Use jFeed - a jQuery RSS/Atom plugin. According to the docs, it's as simple as:

jQuery.getFeed({
   url: 'rss.xml',
   success: function(feed) {
      alert(feed.title);
   }
});

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

Storing SHA1 hash values in MySQL

So the length is between 10 16-bit chars, and 40 hex digits.

In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.

python pandas convert index to datetime

In my case, my dataframe has the following characteristics

<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to  
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Close   3038 non-null   float64
dtypes: float64(1)
memory usage: 47.5+ KB

enter image description here

The first option data.index = pd.to_datetime(data.index) returned

ParserError: String does not contain a date: ParserError: String does not contain a date:

The second option: data.index.to_datetime() returned

AttributeError: 'Index' object has no attribute 'to_datetime'

It returned

Another option I have tested is. data.index = pd.to_datetime(data.index)

It returned: ParserError: String does not contain a date:

What could be my problem? Thanks

angular.js ng-repeat li items with html content

use ng-bind-html-unsafe

it will apply html with text inside like below:

    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>

How do I add a placeholder on a CharField in Django?

The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It also allows the placeholder to depend on the instance for ModelForms with instance specified.

How do I run a simple bit of code in a new thread?

another option, that uses delegates and the Thread Pool...

assuming 'GetEnergyUsage' is a method that takes a DateTime and another DateTime as input arguments, and returns an Int...

// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime, 
                                            DateTime procDateTime);

// following inside of some client method 
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;                     
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);

Merge two HTML table cells

Set the colspan attribute to 2.

...but please don't use tables for layout.

Can VS Code run on Android?

There is a browser-based implementation of VSC that allows you to run it on a browser on your Android (or any other) device. Check it out here:

https://stackblitz.com/

How to add chmod permissions to file in Git?

According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index sub-command.

To set the flag, use following command:

git update-index --chmod=+x path/to/file

To remove it, use:

git update-index --chmod=-x path/to/file

Under the hood

While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:

  • 100644 for regular files
  • 100755 for executable ones

You can visualize it using ls-file subcommand, with --stage option:

$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0       .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0       my_executable_script.sh

By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode option to false:

git config core.fileMode false

Troubleshooting

If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:

git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file

Bonus

Starting with Git 2.9, you can stage a file AND set the flag in one command:

git add --chmod=+x path/to/file

Does Git Add have a verbose switch

Well, like (almost) every console program for unix-like systems, git does not tell you anything if a command succeeds. It prints out something only if there's something wrong.

However if you want to be sure of what just happened, just type

git status

and see which changes are going to be committed and which not. I suggest you to use this before every commit, just to be sure that you are not forgetting anything.

Since you seem new to git, here is a link to a free online book that introduces you to git. It's very useful, it writes about basics as well as well known different workflows: http://git-scm.com/book

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

I had the same problem. For some reason --initialize did not work. After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.

I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:

https://bugs.mysql.com/bug.php?id=28913

In short words: Add the following line to your my.ini:

innodb_flush_method=normal

I had this problem with mysql 5.7 on Windows.

Python ImportError: No module named wx

Make sure you choose the right project intepreter in the compiler. I used the Pycharm, and I encountered the same problem. And it was solved by choose the right intepreter. Thisvideo may help you.

Find oldest/youngest datetime object in a list

Given a list of dates dates:

Max date is max(dates)

Min date is min(dates)

Configuring IntelliJ IDEA for unit testing with JUnit

If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.

However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.

You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.

A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.

Create Test Intention

Create Test Dialog

You can find more details in the Testing help section of the on-line documentation.

Could pandas use column as index?

You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.

Here is my solution:

  1. Firstly, import pandas as pd: import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

How to add Options Menu to Fragment in Android

If you want to add your menu custom

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_custom, menu);
}

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Conversion failed when converting the nvarchar value ... to data type int

You are trying to concatenate a string and an integer.
You need to cast @ID as a string.
try:

SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))

I want to multiply two columns in a pandas DataFrame and add the result into a new column

For me, this is the clearest and most intuitive:

values = []
for action in ['Sell','Buy']:
    amounts = orders_df['Amounts'][orders_df['Action'==action]].values
    if action == 'Sell':
        prices = orders_df['Prices'][orders_df['Action'==action]].values
    else:
        prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
    values += list(amounts*prices)  
orders_df['Values'] = values

The .values method returns a numpy array allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.

Proper way to rename solution (and directories) in Visual Studio

The only solution which works for me on Visual Studio 2013 in a WEB project:

Lets say I want to rename "project1" to be "project2". Lets say the physical path to my .sln file is: c:\my\path\project1\project1.sln

so the path to my .csproj file as well as the bin and the obj folders should be: c:\my\path\project1\project1\

  1. Open the solution in VS by double clicking the project1.sln file.

  2. In Solution Explorer, right-click the project (NOT the solution!!!), select Rename, and enter a new name.

  3. In Solution Explorer, right-click the project and select Properties. On the Application tab, change the "Assembly name" and "Default namespace".

  4. In the main CS file (or any other code files like Global.asax for example), rename the namespace declaration to use the new name. For this right-click the namespace and select Refactor > Rename enter a new name. For example:

namespace project1

4.1 In Solution Explorer, right-click the project (NOT the solution!!!), select Rename, and enter a new name.

  1. Make sure: the AssemblyTitle and AssemblyProduct in Properties/AssemblyInfo.cs are set to the new name ("project2").

1 [assembly: AssemblyTitle("New Name Here")] 2 [assembly: AssemblyDescription("")] 3 [assembly: AssemblyConfiguration("")] 4 [assembly: AssemblyCompany("")] 5 [assembly: AssemblyProduct("New Name Here")] 6 [assembly: AssemblyCopyright("Copyright © 2013")] 7 [assembly: AssemblyTrademark("")] 8 [assembly: AssemblyCulture("")]

  1. Close the Visual Studio.

  2. Delete bin and obj directories physically.

  3. Rename the parent folder and the source folder to the new name (project2):

In the example: c:\my\path\project1\project1

will be: c:\my\path\project2\project2

  1. Rename the SLN file name by right click on that SLN file forward by Rename.

  2. Then finally open the SLN file (within notepad or any editor) and copy and replace (Ctrl+h) any old name to the new name.

  3. Open VS and click BUILD -> Clean Solution

  4. click Build -> Build solution and then F5 to run...

  5. Note1: If you get something like this: Compilation Error CS0246: The type or namespace name 'project2' could not be found (are you missing a using directive or an assembly reference?)

Source File: c:\Users\Username\AppData\Local\Temp\Temporary ASP.NET Files\root\78dd917f\d0836ce4\App_Web_index.cshtml.a8d08dba.b0mwjmih.0.cs

Then go to the "Temporary ASP.NET Files" folder and delete everything.

  1. Note2: If you are trying to do "save as" to a new named project and to keep also the old one, consider duplicating your db by modifying the connectionStrings in web.config and also by re-starting migrations if you have one in the project.

jQuery autocomplete with callback ajax json

I used the construction of $.each (data [i], function (key, value) But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success

How do you store Java objects in HttpSession?

Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.

If you are going to use the inside servlet do following,

Object obj = new Object();
session.setAttribute("object", obj);

or

HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);

and after setting your attribute by using request or session, use following to access it in the JSP,

<%= request.getAttribute("object")%>

or

<%= session.getAttribute("object")%>

So seems your problem is in the JSP.

If you want use scriptlets it should be as follows,

<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>

Or can use expressions as follows,

<%= session.getAttribute("object")%>

or can use EL as follows, ${object} or ${sessionScope.object}

.htaccess deny from all

You can edit it. The content of the file is literally "Deny from all" which is an Apache directive: http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#deny

Multiple axis line chart in excel

Taking the answer above as guidance;

I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.

Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.

The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.

Thanks to the guy above for the idea!

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

SELECT * 
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

Postgres: INSERT if does not exist already

The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:

ALTER USER user SET search_path to 'name_of_schema';

after these changes "INSERT" will work correctly.

Deleting objects from an ArrayList in Java

First, I'd make sure that this really is a performance bottleneck, otherwise I'd go with the solution that is cleanest and most expressive.

If it IS a performance bottleneck, just try the different strategies and see what's the quickest. My bet is on creating a new ArrayList and puting the desired objects in that one, discarding the old ArrayList.

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

This usually happened if you haven't stopped docker probably.

To resolve

service docker stop
cd /var/run/docker/libcontainerd
rm -rf containerd/*
rm -f docker-containerd.pid
service docker start

then "docker run...." to download your image and start the container as usual

How to set DateTime to null

It looks like you just want:

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
    ? (DateTime?) null
    : DateTime.Parse(dateTimeEnd);

Note that this will throw an exception if dateTimeEnd isn't a valid date.

An alternative would be:

DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
    ? validValue
    : (DateTime?) null;

That will now set the result to null if dateTimeEnd isn't valid. Note that TryParse handles null as an input with no problems.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

just put your script in a file and run that file with 2>/dev/null at the end of command line!

This way, if there is a problem with the command whatsoever, it will not halt your xcode build

in my case I was running just a command to uninstall my previous copy of the app from a connected iphone, so it could give an error if the iphone is not there. To solve it:

$mobiledevice uninstall_app com.my.app 2>/dev/null

Can I use Objective-C blocks as properties?

@property (nonatomic, copy) void (^simpleBlock)(void);
@property (nonatomic, copy) BOOL (^blockWithParamter)(NSString *input);

If you are going to be repeating the same block in several places use a type def

typedef void(^MyCompletionBlock)(BOOL success, NSError *error);
@property (nonatomic) MyCompletionBlock completion;

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

Getting All Variables In Scope

In ECMAScript 6 it's more or less possible by wrapping the code inside a with statement with a proxy object. Note it requires non-strict mode and it's bad practice.

_x000D_
_x000D_
function storeVars(target) {_x000D_
  return new Proxy(target, {_x000D_
    has(target, prop) { return true; },_x000D_
    get(target, prop) { return (prop in target ? target : window)[prop]; }_x000D_
  });_x000D_
}_x000D_
var vars = {}; // Outer variable, not stored._x000D_
with(storeVars(vars)) {_x000D_
  var a = 1;   // Stored in vars_x000D_
  var b = 2;   // Stored in vars_x000D_
  (function() {_x000D_
    var c = 3; // Inner variable, not stored._x000D_
  })();_x000D_
}_x000D_
console.log(vars);
_x000D_
_x000D_
_x000D_

The proxy claims to own all identifiers referenced inside with, so variable assignments are stored in the target. For lookups, the proxy retrieves the value from the proxy target or the global object (not the parent scope). let and const variables are not included.

Inspired by this answer by Bergi.

Check if instance is of a type

Try the following

if (c is TForm) { 
 ...
}

Grouping functions (tapply, by, aggregate) and the *apply family

I recently discovered the rather useful sweep function and add it here for the sake of completeness:

sweep

The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):

Let's say you have a matrix and want to standardize it column-wise:

dataPoints <- matrix(4:15, nrow = 4)

# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)

# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)

# Center the points 
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")

# Return the result
dataPoints_Trans1
##      [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,]  0.5  0.5  0.5
## [4,]  1.5  1.5  1.5

# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")

# Return the result
dataPoints_Trans2
##            [,1]       [,2]       [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,]  0.3872983  0.3872983  0.3872983
## [4,]  1.1618950  1.1618950  1.1618950

NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)

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

simply run following on terminal if you don't have pip installed on your mac.

sudo easy_install pip

download python 3 here: python3

once you're done with these 2 steps, make sure to run the following to verify whether you've installed them successfully.

python3 --version
pip3 --version

phpinfo() is not working on my CentOS server

My solution was uninstalling and installing the PHP instance (7.0 in my case) again:

sudo apt-get purge php7.0
sudo apt-get install php7.0

After that you will need to restart the Apache service:

sudo service apache2 restart

Finally, verify again in your browser with your localhost or IP address.

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

Accessing private member variables from prototype-defined functions

Can't you put the variables in a higher scope?

(function () {
    var privateVariable = true;

    var MyClass = function () {
        if (privateVariable) console.log('readable from private scope!');
    };

    MyClass.prototype.publicMethod = function () {
        if (privateVariable) console.log('readable from public scope!');
    };
}))();

Changing column names of a data frame

The error is caused by the "smart-quotes" (or whatever they're called). The lesson here is, "don't write your code in an 'editor' that converts quotes to smart-quotes".

names(newprice)[1]<-paste(“premium”)  # error
names(newprice)[1]<-paste("premium")  # works

Also, you don't need paste("premium") (the call to paste is redundant) and it's a good idea to put spaces around <- to avoid confusion (e.g. x <- -10; if(x<-3) "hi" else "bye"; x).

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

Get record counts for all tables in MySQL database

SELECT SUM(TABLE_ROWS) 
     FROM INFORMATION_SCHEMA.TABLES 
     WHERE TABLE_SCHEMA = '{your_db}';

Note from the docs though: For InnoDB tables, the row count is only a rough estimate used in SQL optimization. You'll need to use COUNT(*) for exact counts (which is more expensive).

What REALLY happens when you don't free after malloc?

You are absolutely correct in that respect. In small trivial programs where a variable must exist until the death of the program, there is no real benefit to deallocating the memory.

In fact, I had once been involved in a project where each execution of the program was very complex but relatively short-lived, and the decision was to just keep memory allocated and not destabilize the project by making mistakes deallocating it.

That being said, in most programs this is not really an option, or it can lead you to run out of memory.

How to pass an array into a function, and return the results with an array

Try

$waffles = foo($waffles);

Or pass the array by reference, like suggested in the other answers.

In addition, you can add new elements to an array without writing the index, e.g.

$waffles = array(1,2,3); // filling on initialization

or

$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;

On a sidenote, if you want to sum all values in an array, use array_sum()

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include statement so the preprocessor finds it where it already is.

Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find it while following that search pattern.

Alternatively you can change the #include statement so that the preprocessor can find it. You tell us the xyz.cxx file is is in the 'code' folder but you don't tell us where you've put the xyz.h file. Let's say your file structure looks like this...

<some folder>\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\xyz.h"

On the other hand let's say your file structure looks like this...

<some folder>\include\xyz.h
<some folder>\code\xyz.cxx

In that case the #include statement in xyz.cxx should look something like this..

#include "..\include\xyz.h"

Update: On the other other hand as @In silico points out in the comments, if you are using #include <xyz.h> you should probably change it to #include "xyz.h"

Empty set literal?

Just to extend the accepted answer:

From version 2.7 and 3.1 python has got set literal {} in form of usage {1,2,3}, but {} itself still used for empty dict.

Python 2.7 (first line is invalid in Python <2.7)

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>

More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes

Why should I use a pointer rather than the object itself?

One reason for using pointers is to interface with C functions. Another reason is to save memory; for example: instead of passing an object which contains a lot of data and has a processor-intensive copy-constructor to a function, just pass a pointer to the object, saving memory and speed especially if you're in a loop, however a reference would be better in that case, unless you're using an C-style array.

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

Which characters make a URL invalid?

I am implementing old http (0.9, 1.0, 1.1) request and response reader/writer. Request URI is the most problematic place.

You can't just use RFC 1738, 2396 or 3986 as it is. There are many old HTTP clients and servers that allows more characters. So I've made research based on accidentally published webserver access logs: "GET URI HTTP/1.0" 200.

I've found that the following non-standard characters are often used in URI:

\ { } < > | ` ^ "

These characters were described in RFC 1738 as unsafe.

If you want to be compatible with all old HTTP clients and servers - you have to allow these characters in request URI.

Please read more information about this research in oghttp-request-collector.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

Check your project's properties. On the "Application" tab, select your Program class as the Startup object:

alt text

How to silence output in a Bash script?

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

ResourceDictionary in a separate assembly

Check out the pack URI syntax. You want something like this:

<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>

Is it possible to have placeholders in strings.xml for runtime values?

Formatting and Styling

Yes, see the following from String Resources: Formatting and Styling

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

Basic Usage

Note that getString has an overload that uses the string as a format string:

String text = res.getString(R.string.welcome_messages, username, mailCount);

Plurals

If you need to handle plurals, use this:

<plurals name="welcome_messages">
    <item quantity="one">Hello, %1$s! You have a new message.</item>
    <item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>

The first mailCount param is used to decide which format to use (single or plural), the other params are your substitutions:

Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);

See String Resources: Plurals for more details.

How do I make a batch file terminate upon encountering an error?

One minor update, you should change the checks for "if errorlevel 1" to the following...

IF %ERRORLEVEL% NEQ 0 

This is because on XP you can get negative numbers as errors. 0 = no problems, anything else is a problem.

And keep in mind the way that DOS handles the "IF ERRORLEVEL" tests. It will return true if the number you are checking for is that number or higher so if you are looking for specific error numbers you need to start with 255 and work down.

About "*.d.ts" in TypeScript

Worked example for a specific case:

Let's say you have my-module that you're sharing via npm.

You install it with npm install my-module

You use it thus:

import * as lol from 'my-module';

const a = lol('abc', 'def');

The module's logic is all in index.js:

module.exports = function(firstString, secondString) {

  // your code

  return result
}

To add typings, create a file index.d.ts:

declare module 'my-module' {
  export default function anyName(arg1: string, arg2: string): MyResponse;
}

interface MyResponse {
  something: number;
  anything: number;
}

New warnings in iOS 9: "all bitcode will be dropped"

To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9

Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/

How to change cursor from pointer to finger using jQuery?

It is very straight forward

HTML

<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>

jQuery

$(document).ready(function(){
  $('.button').css( 'cursor', 'pointer' );

  // for old IE browsers
  $('.button').css( 'cursor', 'hand' ); 
});

Check it out on JSfiddle

How do I add the Java API documentation to Eclipse?

I just had to dig through this issue myself and succeeded. Contrary to what others have offered as solutions, the path to my happy ending was directly correlated to JavaDoc. No "src.zip" files necessary. My trials and tribulations in the process involved finding the CORRECT JavaDoc to point at. Pointing a Java 1.7 project at Java 8 Javadoc does NOT work. (Even if "jre8" appears to be the only installed JRE available.) Thus, I beat my head against the brick wall unnecessarily.

Window > Preferences > Java > Installed JREs

If the JRE of your project is not listed (as happened to me when I migrated a jre7 project to a new jre8 workspace), you will need to add it here. Click "Add..." and point your Workspace at the desired jre folder. (Mine was C://Program Files/Java/jre7). Then "Edit..." the now-available JRE, select the rt.jar, and click "Javadoc Location..." and aim it at the correct javadoc location. For my use:

For jre7 -- http://docs.oracle.com/javase/7/docs/api/ For jre8 -- http://docs.oracle.com/javase/8/docs/api/

Voila, hover tooltip javadoc is re-enabled. I hope this helps anyone else trying to figure this problem out.

newline in <td title="">

This should now work with Internet Explorer, Firefox v12+ and Chrome 28+

<img src="'../images/foo.gif'" 
  alt="line 1&#013;line 2" title="line 1&#013;line 2">

Try a JavaScript tooltip library for a better result, something like OverLib.

CASE in WHERE, SQL Server

A few ways:

-- Do the comparison, OR'd with a check on the @Country=0 case
WHERE (a.Country = @Country OR @Country = 0)

-- compare the Country field to itself
WHERE a.Country = CASE WHEN @Country > 0 THEN @Country ELSE a.Country END

Or, use a dynamically generated statement and only add in the Country condition if appropriate. This should be most efficient in the sense that you only execute a query with the conditions that actually need to apply and can result in a better execution plan if supporting indices are in place. You would need to use parameterised SQL to prevent against SQL injection.

What is the use of "assert"?

If you ever want to know exactly what a reserved function does in python, type in help(enter_keyword)

Make sure if you are entering a reserved keyword that you enter it as a string.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:

$a=10;
if($a==5) { $user_location='Paris';} else { }
echo $user_location;

The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:

$a=10;
if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
echo $user_location;

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

Round button with text and icon in flutter

The way i usually do it is by embedding a Row inside the Raised button:

class Sendbutton extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return RaisedButton(
          onPressed: () {},
          color: Colors.black,
          textColor: Colors.white,
          child: Row(
            children: <Widget>[
              Text('Send'),
              Icon(Icons.send)
            ],
          ),

        );
      }
    }

How to remove all subviews of a view in Swift?

did you try something like

for o : AnyObject in self.subviews {
     if let v = o as? NSView {
         v.removeFromSuperview()
     }
}

How to resize superview to fit all subviews with autolayout?

You can do this by creating a constraint and connecting it via interface builder

See explanation: Auto_Layout_Constraints_in_Interface_Builder

raywenderlich beginning-auto-layout

AutolayoutPG Articles constraint Fundamentals

@interface ViewController : UIViewController {
    IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
    IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;

connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this

 self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign

I hope this clarifies it.

Select first and last row from grouped data

Just for completeness: You can pass slice a vector of indices:

df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))

which gives

  id stopId stopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      b            1
6  3      a            3

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

Best way to test if a row exists in a MySQL table

At times it is quite handy to get the auto increment primary key (id) of the row if it exists and 0 if it doesn't.

Here's how this can be done in a single query:

SELECT IFNULL(`id`, COUNT(*)) FROM WHERE ...

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

ie8 var w= window.open() - "Message: Invalid argument."

It seems when even using a "valid" custom window name (not _blank, etc.) using window.open to launch a new window, there is still issues. It works fine the first time you click the link, but if you click it again (with the first launched window still up) you receive an "Error: No such interface supported" script debug.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

If statement with String comparison fails

To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:

In Java there are many string comparisons.

String s = "something", t = "maybe something else";
if (s == t)      // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>

Delimiters in MySQL

You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.

Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.

DELIMITER isn't really a MySQL language command, it's a client command.

Example

DELIMITER $$

/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$

/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/ 
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
    
    SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END$$

/*DELIMITER is set to it's default*/
DELIMITER ;

How can I make my flexbox layout take 100% vertical space?

set the wrapper to height 100%

.vwrapper {
  display: flex;
  flex-direction: column;

  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;

  height: 100%;
}

and set the 3rd row to flex-grow

#row3 {
   background-color: green;
   flex: 1 1 auto;
   display: flex;
}

demo

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

How can I copy network files using Robocopy?

You should be able to use Windows "UNC" paths with robocopy. For example:

robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder

Robocopy has the ability to recover from certain types of network hiccups automatically.

Echo newline in Bash prints literal \n

My script:

echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings

Output:

WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:

On my bash script I was getting mad as you until I've just tried:

echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"

Just hit enter where you want to insert that jump. Output now is:

WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:

Convert Map<String,Object> to Map<String,String>

Now that we have Java 8/streams, we can add one more possible answer to the list:

Assuming that each of the values actually are String objects, the cast to String should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.

Map<String,Object> map = new HashMap<>();
Map<String,String> newMap = map.entrySet().stream()
     .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

Trim specific character from a string

The best way to resolve this task is (similar with PHP trim function):

_x000D_
_x000D_
function trim( str, charlist ) {_x000D_
  if ( typeof charlist == 'undefined' ) {_x000D_
    charlist = '\\s';_x000D_
  }_x000D_
  _x000D_
  var pattern = '^[' + charlist + ']*(.*?)[' + charlist + ']*$';_x000D_
  _x000D_
  return str.replace( new RegExp( pattern ) , '$1' )_x000D_
}_x000D_
_x000D_
document.getElementById( 'run' ).onclick = function() {_x000D_
  document.getElementById( 'result' ).value = _x000D_
  trim( document.getElementById( 'input' ).value,_x000D_
  document.getElementById( 'charlist' ).value);_x000D_
}
_x000D_
<div>_x000D_
  <label for="input">Text to trim:</label><br>_x000D_
  <input id="input" type="text" placeholder="Text to trim" value="dfstextfsd"><br>_x000D_
  <label for="charlist">Charlist:</label><br>_x000D_
  <input id="charlist" type="text" placeholder="Charlist" value="dfs"><br>_x000D_
  <label for="result">Result:</label><br>_x000D_
  <input id="result" type="text" placeholder="Result" disabled><br>_x000D_
  <button type="button" id="run">Trim it!</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

P.S.: why i posted my answer, when most people already done it before? Because i found "the best" mistake in all of there answers: all used the '+' meta instead of '*', 'cause trim must remove chars IF THEY ARE IN START AND/OR END, but it return original string in else case.

Sending an Intent to browser to open specific URL

The short version

startActivity(new Intent(Intent.ACTION_VIEW, 
    Uri.parse("http://almondmendoza.com/android-applications/")));

should work as well...

How can I filter a date of a DateTimeField in Django?

This produces the same results as using __year, __month, and __day and seems to work for me:

YourModel.objects.filter(your_datetime_field__startswith=datetime.date(2009,8,22))

Properly embedding Youtube video into bootstrap 3.0 page

This works fine for me...

   .delimitador{
        width:100%;
        margin:auto;
    }
    .contenedor{
        height:0px;
        width:100%;
        /*max-width:560px; /* Así establecemos el ancho máximo (si lo queremos) */
        padding-top:56.25%; /* Relación: 16/9 = 56.25% */
        position:relative;
    }

    iframe{
            position:absolute;
            height:100%;
            width:100%;
            top:0px;
            left:0px;
    }

and then

<div class="delimitador">
<div class="contenedor">
// youtube code 
</div>
</div>

Error Installing Homebrew - Brew Command Not Found

This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.

Compare two DataFrames and output their differences side-by-side

import pandas as pd
import io

texts = ['''\
id   Name   score                    isEnrolled                        Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.11                     False                           Graduated
113  Zoe    4.12                     True       ''',

         '''\
id   Name   score                    isEnrolled                        Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.21                     False                           Graduated
113  Zoe    4.12                     False                         On vacation''']


df1 = pd.read_fwf(io.StringIO(texts[0]), widths=[5,7,25,21,20])
df2 = pd.read_fwf(io.StringIO(texts[1]), widths=[5,7,25,21,20])
df = pd.concat([df1,df2]) 

print(df)
#     id  Name  score isEnrolled               Comment
# 0  111  Jack   2.17       True  He was late to class
# 1  112  Nick   1.11      False             Graduated
# 2  113   Zoe   4.12       True                   NaN
# 0  111  Jack   2.17       True  He was late to class
# 1  112  Nick   1.21      False             Graduated
# 2  113   Zoe   4.12      False           On vacation

df.set_index(['id', 'Name'], inplace=True)
print(df)
#           score isEnrolled               Comment
# id  Name                                        
# 111 Jack   2.17       True  He was late to class
# 112 Nick   1.11      False             Graduated
# 113 Zoe    4.12       True                   NaN
# 111 Jack   2.17       True  He was late to class
# 112 Nick   1.21      False             Graduated
# 113 Zoe    4.12      False           On vacation

def report_diff(x):
    return x[0] if x[0] == x[1] else '{} | {}'.format(*x)

changes = df.groupby(level=['id', 'Name']).agg(report_diff)
print(changes)

prints

                score    isEnrolled               Comment
id  Name                                                 
111 Jack         2.17          True  He was late to class
112 Nick  1.11 | 1.21         False             Graduated
113 Zoe          4.12  True | False     nan | On vacation

Can’t delete docker image with dependent child images

THIS COMMAND REMOVES ALL IMAGES (USE WITH CAUTION)

Have you tried to use --force

sudo docker rmi $(sudo docker images -aq) --force

This above code run like a charm even doe i had the same issue

Kill process by name?

this worked for me in windows 7

import subprocess
subprocess.call("taskkill /IM geckodriver.exe")

Difference between Spring MVC and Struts MVC

The main difference between struts & spring MVC is about the difference between Aspect Oriented Programming (AOP) & Object oriented programming (OOP).

Spring makes application loosely coupled by using Dependency Injection.The core of the Spring Framework is the IoC container.

OOP can do everything that AOP does but different approach. In other word, AOP complements OOP by providing another way of thinking about program structure.

Practically, when you want to apply same changes for many files. It should be exhausted work with Struts to add same code for tons of files. Instead Spring write new changes somewhere else and inject to the files.

Some related terminologies of AOP is cross-cutting concerns, Aspect, Dependency Injection...

Replace comma with newline in sed on MacOS?

If your sed usage tends to be entirely substitution expressions (as mine tends to be), you can also use perl -pe instead

$ echo 'foo,bar,baz' | perl -pe 's/,/,\n/g'
foo,
bar,
baz

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Quick easy way to migrate SQLite3 to MySQL?

Here is a python script, built off of Shalmanese's answer and some help from Alex martelli over at Translating Perl to Python

I'm making it community wiki, so please feel free to edit, and refactor as long as it doesn't break the functionality (thankfully we can just roll back) - It's pretty ugly but works

use like so (assuming the script is called dump_for_mysql.py:

sqlite3 sample.db .dump | python dump_for_mysql.py > dump.sql

Which you can then import into mysql

note - you need to add foreign key constrains manually since sqlite doesn't actually support them

here is the script:

#!/usr/bin/env python

import re
import fileinput

def this_line_is_useless(line):
    useless_es = [
        'BEGIN TRANSACTION',
        'COMMIT',
        'sqlite_sequence',
        'CREATE UNIQUE INDEX',
        'PRAGMA foreign_keys=OFF',
    ]
    for useless in useless_es:
        if re.search(useless, line):
            return True

def has_primary_key(line):
    return bool(re.search(r'PRIMARY KEY', line))

searching_for_end = False
for line in fileinput.input():
    if this_line_is_useless(line):
        continue

    # this line was necessary because '');
    # would be converted to \'); which isn't appropriate
    if re.match(r".*, ''\);", line):
        line = re.sub(r"''\);", r'``);', line)

    if re.match(r'^CREATE TABLE.*', line):
        searching_for_end = True

    m = re.search('CREATE TABLE "?(\w*)"?(.*)', line)
    if m:
        name, sub = m.groups()
        line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
        line = line % dict(name=name, sub=sub)
    else:
        m = re.search('INSERT INTO "(\w*)"(.*)', line)
        if m:
            line = 'INSERT INTO %s%s\n' % m.groups()
            line = line.replace('"', r'\"')
            line = line.replace('"', "'")
    line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
    line = line.replace('THIS_IS_TRUE', '1')
    line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
    line = line.replace('THIS_IS_FALSE', '0')

    # Add auto_increment if it is not there since sqlite auto_increments ALL
    # primary keys
    if searching_for_end:
        if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
            line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
        # replace " and ' with ` because mysql doesn't like quotes in CREATE commands 
        if line.find('DEFAULT') == -1:
            line = line.replace(r'"', r'`').replace(r"'", r'`')
        else:
            parts = line.split('DEFAULT')
            parts[0] = parts[0].replace(r'"', r'`').replace(r"'", r'`')
            line = 'DEFAULT'.join(parts)

    # And now we convert it back (see above)
    if re.match(r".*, ``\);", line):
        line = re.sub(r'``\);', r"'');", line)

    if searching_for_end and re.match(r'.*\);', line):
        searching_for_end = False

    if re.match(r"CREATE INDEX", line):
        line = re.sub('"', '`', line)

    if re.match(r"AUTOINCREMENT", line):
        line = re.sub("AUTOINCREMENT", "AUTO_INCREMENT", line)

    print line,

Access POST values in Symfony2 request object

Symfony 2.2

this solution is deprecated since 2.3 and will be removed in 3.0, see documentation

$form->getData();

gives you an array for the form parameters

from symfony2 book page 162 (Chapter 12: Forms)

[...] sometimes, you may just want to use a form without a class, and get back an array of the submitted data. This is actually really easy:

public function contactAction(Request $request) {
  $defaultData = array('message' => 'Type your message here');
  $form = $this->createFormBuilder($defaultData)
  ->add('name', 'text')
  ->add('email', 'email')
  ->add('message', 'textarea')
  ->getForm();
  if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);
    // data is an array with "name", "email", and "message" keys
    $data = $form->getData();
  }
  // ... render the form
}

You can also access POST values (in this case "name") directly through the request object, like so:

$this->get('request')->request->get('name');

Be advised, however, that in most cases using the getData() method is a better choice, since it returns the data (usually an object) after it's been transformed by the form framework.

When you want to access the form token, you have to use the answer of Problematic $postData = $request->request->get('contact'); because the getData() removes the element from the array


Symfony 2.3

since 2.3 you should use handleRequest instead of bindRequest:

 $form->handleRequest($request);

see documentation

Modify request parameter with servlet filter

Try request.setAttribute("param",value);. It worked fine for me.

Please find this code sample:

private void sanitizePrice(ServletRequest request){
        if(request.getParameterValues ("price") !=  null){
            String price[] = request.getParameterValues ("price");

            for(int i=0;i<price.length;i++){
                price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
                System.out.println(price[i]);
            }
            request.setAttribute("price", price);
            //request.getParameter("numOfBooks").re
        }
    }

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Example:

contents of the ae.csv file:

"Date, xpto 14"
"code","number","year","C"
"blab","15885","2016","Y"
"aeea","15883","1982","E"
"xpto","15884","1986","B"
"jrgg","15885","1400","A"

CREATE TABLE Tabletmp (  
    rec VARCHAR(9) 
);

For put only column 3:

LOAD DATA INFILE '/local/ae.csv' 
INTO TABLE Tabletmp
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 2 LINES
(@col1, @col2, @col3, @col4, @col5)
set rec = @col3;


select * from Tabletmp;
    2016
    1982
    1986
    1400

How to transfer paid android apps from one google account to another google account

Google has this to say on transferring data between accounts.

http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304

It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.

It's conveniently titled: "Moving Product Data"

http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582

PHP foreach change original array values

Use foreach($fields as &$field){ - so you will work with the original array.

Here is more about passing by reference.

SQlite - Android - Foreign key syntax

You have to define your TASK_CAT column first and then set foreign key on it.

private static final String TASK_TABLE_CREATE = "create table "
        + TASK_TABLE + " (" 
        + TASK_ID + " integer primary key autoincrement, " 
        + TASK_TITLE + " text not null, " 
        + TASK_NOTES + " text not null, "
        + TASK_DATE_TIME + " text not null,"
        + TASK_CAT + " integer,"
        + " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";

More information you can find on sqlite foreign keys doc.

jQuery UI Accordion Expand/Collapse All

I tried the old-fashioned version, of just adjusting aria-* and CSS attributes like many of these older answers, but eventually gave up and just did a conditional fake-click. Works a beaut':

HTML:

<a href="#" onclick="expandAll();"
  title="Expand All" alt="Expand All"><img
    src="/images/expand-all-icon.png"/></a>
<a href="#" onclick="collapseAll();"
  title="Collapse All" alt="Collapse All"><img
    src="/images/collapse-all-icon.png"/></a>

Javascript:

async function expandAll() {
  let heads = $(".ui-accordion-header");
  heads.each((index, el) => {
    if ($(el).hasClass("ui-accordion-header-collapsed") === true)
      $(el).trigger("click");
  });
}

async function collapseAll() {
  let heads = $(".ui-accordion-header");
  heads.each((index, el) => {
    if ($(el).hasClass("ui-accordion-header-collapsed") === false)
      $(el).trigger("click");
  });
}


(The HTML newlines are placed in those weird places to prevent whitespace in the presentation.)

Returning string from C function

Either allocate the string on the stack on the caller side and pass it to your function:

void getStr(char *wordd, int length) {
    ...
}

int main(void) {
    char wordd[10 + 1];
    getStr(wordd, sizeof(wordd) - 1);
    ...
}

Or make the string static in getStr:

char *getStr(void) {
    static char wordd[10 + 1];
    ...
    return wordd;
}

Or allocate the string on the heap:

char *getStr(int length) {
    char *wordd = malloc(length + 1);
    ...
    return wordd;
}

How to Get Element By Class in JavaScript?

This code should work in all browsers.

function replaceContentInContainer(matchClass, content) {
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
                > -1) {
            elems[i].innerHTML = content;
        }
    }
}

The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.

jsFiddle Example, using Vanilla JS (i.e. no framework)

How to limit file upload type file size in PHP?

var sizef = document.getElementById('input-file-id').files[0].size;
                if(sizef > 210000){
                    alert('sorry error');
                }else {
                    //action
                }   

PHP Curl UTF-8 Charset

First method (internal function)

The best way I have tried before is to use urlencode(). Keep in mind, don't use it for the whole url; instead, use it only for the needed parts. For example, a request that has two 'text-fa' and 'text-en' fields and they contain a Persian and an English text, respectively, you might only need to encode the Persian text, not the English one.

Second Method (using cURL function)

However, there are better ways if the range of characters have to be encoded is more limited. One of these ways is using CURLOPT_ENCODING, by passing it to curl_setopt():

curl_setopt($ch, CURLOPT_ENCODING, "");

How to sort mongodb with pymongo

TLDR: Aggregation pipeline is faster as compared to conventional .find().sort().

Now moving to the real explanation. There are two ways to perform sorting operations in MongoDB:

  1. Using .find() and .sort().
  2. Or using the aggregation pipeline.

As suggested by many .find().sort() is the simplest way to perform the sorting.

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

However, this is a slow process compared to the aggregation pipeline.

Coming to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:

  1. $match (optional step)
  2. $sort

NOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort() method.

Here's an example of the aggregation pipeline.

db.collection_name.aggregate([{
    "$match": {
        # your query - optional step
    }
},
{
    "$sort": {
        "field_1": pymongo.ASCENDING,
        "field_2": pymongo.DESCENDING,
        ....
    }
}])

Try this method yourself, compare the speed and let me know about this in the comments.

Edit: Do not forget to use allowDiskUse=True while sorting on multiple fields otherwise it will throw an error.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :

connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
       Initial Catalog=databaseName;
       User ID=theuser if u use it;
       Password=thepassword if u use it;
       integrated security=true(if u don t use user and pass; else change it false)"

Without to knowing your instance, I could help with this one. Hope it helped

Calculate the mean by group

We already have tons of options to get mean by group, adding one more from mosaic package.

mosaic::mean(speed~dive, data = df)
#dive1 dive2 
#0.579 0.440 

This returns a named numeric vector, if needed a dataframe we can wrap it in stack

stack(mosaic::mean(speed~dive, data = df))

#  values   ind
#1  0.579 dive1
#2  0.440 dive2

data

set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
                 speed=runif(10))

Size of character ('a') in C/C++

In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:

void foo(char c)
{
    puts("char");
}
void foo(int i)
{
    puts("int");
}
int main()
{
    foo('i');
    return 0;
}

Output:

char

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.

Drawing Isometric game worlds

Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)

..  ..  01  ..  ..
  ..  06  02  ..
..  11  07  03  ..
  16  12  08  04
21  17  13  09  05
  22  18  14  10
..  23  19  15  ..
  ..  24  20  ..
..  ..  25  ..  ..

And by diamond you mean:

..  ..  ..  ..  ..
  01  02  03  04
..  05  06  07  ..
  08  09  10  11
..  12  13  14  ..
  15  16  17  18
..  19  20  21  ..
  22  23  24  25
..  ..  ..  ..  ..

The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.

How do I consume the JSON POST data in an Express application

@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).

In my case I needed to force content-type: text/plain to be parsed as json.

If you cannot change the content-type of the request, try using the following code:

app.use(express.json({type: '*/*'}));

Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:

app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
  // echo json
  res.json(req.body);
});

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

javascript filter array of objects

_x000D_
_x000D_
var names = [{_x000D_
        name: "Joe",_x000D_
        age: 20,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Mike",_x000D_
        age: 50,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Joe",_x000D_
        age: 45,_x000D_
        email: "[email protected]"_x000D_
    }_x000D_
];_x000D_
const res = _.filter(names, (name) => {_x000D_
    return name.name == "Joe" && name.age < 30;_x000D_
_x000D_
});_x000D_
console.log(res);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
_x000D_
_x000D_

What is the purpose of willSet and didSet in Swift?

I do not know C#, but with a little guesswork I think I understand what

foo : int {
    get { return getFoo(); }
    set { setFoo(newValue); }
}

does. It looks very similar to what you have in Swift, but it's not the same: in Swift you do not have the getFoo and setFoo. That is not a little difference: it means you do not have any underlying storage for your value.

Swift has stored and computed properties.

A computed property has get and may have set (if it's writable). But the code in the getter and setter, if they need to actually store some data, must do it in other properties. There is no backing storage.

A stored property, on the other hand, does have backing storage. But it does not have get and set. Instead it has willSet and didSet which you can use to observe variable changes and, eventually, trigger side effects and/or modify the stored value. You do not have willSet and didSet for computed properties, and you do not need them because for computed properties you can use the code in set to control changes.

Calling a PHP function from an HTML form in the same file

Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.

The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.

Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.

<?php
    function test() {
        header("Content-Type: text/xml");
        echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
    }
    if(isset($_GET["user"])){
        test();
    } else {
?><html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
            function do_ajax() {
                if(window.XMLHttpRequest){
                    xmlhttp=new XMLHttpRequest();
                } else {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function(){
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        var xmlDoc = xmlhttp.responseXML;
                        data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
                        mydiv = document.getElementById("Test");
                        mydiv.appendChild(document.createTextNode(data));
                        mydiv.appendChild(document.createElement("br"));
                    }
                }
                xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
                xmlhttp.send();
            }
        </script>
    </head>
    <body>
        <form action="test.php" method="post">
            <input type="text" name="user" placeholder="enter a text" id="username"/>
            <input type="button" value="submit" onclick="do_ajax()" />
        </form>
        <div id="Test"></div>
    </body>
</html><?php } ?>

Center image in div horizontally

I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/

How to delete object?

Use a collection that is a static property of your Car class. Every time you create a new instance of a Car, store the reference in this collection.

To destroy all Cars, just set all items to null.

Which .NET Dependency Injection frameworks are worth looking into?

I can recommend Ninject. It's incredibly fast and easy to use but only if you don't need XML configuration, else you should use Windsor.

Search a whole table in mySQL for a string

If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).

Right click any database or table and select "Find text on server".

All the matches are shown in a separate tab for each table - very nice.

Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!

Understanding generators in Python

First of all, the term generator originally was somewhat ill-defined in Python, leading to lots of confusion. You probably mean iterators and iterables (see here). Then in Python there are also generator functions (which return a generator object), generator objects (which are iterators) and generator expressions (which are evaluated to a generator object).

According to the glossary entry for generator it seems that the official terminology is now that generator is short for "generator function". In the past the documentation defined the terms inconsistently, but fortunately this has been fixed.

It might still be a good idea to be precise and avoid the term "generator" without further specification.

SQLAlchemy: print the actual query

I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:

borrowed from: https://gist.github.com/gsakkis/4572159

The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:

# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime

from sqlalchemy.orm import Query


try:
    basestring
except NameError:
    basestring = str


def render_query(statement, dialect=None):
    """
    Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement.
    WARNING: This method of escaping is insecure, incomplete, and for debugging
    purposes only. Executing SQL statements with inline-rendered user values is
    extremely insecure.
    Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
    """
    if isinstance(statement, Query):
        if dialect is None:
            dialect = statement.session.bind.dialect
        statement = statement.statement
    elif dialect is None:
        dialect = statement.bind.dialect

    class LiteralCompiler(dialect.statement_compiler):

        def visit_bindparam(self, bindparam, within_columns_clause=False,
                            literal_binds=False, **kwargs):
            return self.render_literal_value(bindparam.value, bindparam.type)

        def render_array_value(self, val, item_type):
            if isinstance(val, list):
                return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
            return self.render_literal_value(val, item_type)

        def render_literal_value(self, value, type_):
            if isinstance(value, long):
                return str(value)
            elif isinstance(value, (basestring, date, datetime, timedelta)):
                return "'%s'" % str(value).replace("'", "''")
            elif isinstance(value, list):
                return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
            return super(LiteralCompiler, self).render_literal_value(value, type_)

    return LiteralCompiler(dialect, statement).process(statement)

Tested to two levels of nested arrays.

Select mySQL based only on month and year

You can do like this:

$q="SELECT * FROM projects WHERE Year(Date) = '$year' and Month(Date) = '$month'";