Programs & Examples On #Fluid layout

A Fluid Layout, sometimes also referred to as a liquid layout, is a CSS technique in which the majority of the page components have percentage widths, and thus adjust to the user's screen resolution.

Fluid width with equally spaced DIVs

in jQuery you might target the Parent directly.

THIS IS USEFUL IF YOU DO NOT KNOW EXACTLY HOW MANY CHILDREN WILL BE ADDED DYNAMICALLY or IF YOU JUST CAN'T FIGURE OUT THEIR NUMBER.

var tWidth=0;

$('.children').each(function(i,e){
tWidth += $(e).width();

///Example: If the Children have a padding-left of 10px;..
//You could do instead:
tWidth += ($(e).width()+10);

})
$('#parent').css('width',tWidth);

This will let the parent grow horizontally as the children are beng added.

NOTE: This assumes that the '.children' have a width and Height Set

Hope that Helps.

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Source - http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

Pros

  • Fixed-width layouts are much easier to use and easier to customize in terms of design.
  • Widths are the same for every browser, so there is less hassle with images, forms, video and other content that are fixed-width.
  • There is no need for min-width or max-width, which isn’t supported by every browser anyway.
  • Even if a website is designed to be compatible with the smallest screen resolution, 800×600, the content will still be wide enough at a larger resolution to be easily legible.

Cons

  • A fixed-width layout may create excessive white space for users with larger screen resolutions, thus upsetting “divine proportion,” the “Rule of Thirds,” overall balance and other design principles.
  • Smaller screen resolutions may require a horizontal scroll bar, depending the fixed layout’s width.
  • Seamless textures, patterns and image continuation are needed to accommodate those with larger resolutions.
  • Fixed-width layouts generally have a lower overall score when it comes to usability.

How to make an element width: 100% minus padding?

Just understand the difference between width:auto; and width:100%; Width:auto; will (AUTO)MATICALLY calculate the width in order to fit the exact given with of the wrapping div including the padding. Width 100% expands the width and adds the padding.

Two divs side by side - Fluid display

You can also use the Grid View its also Responsive its something like this:

#wrapper {
   width: auto;
    height: auto;
    box-sizing: border-box;
    display: grid;
    grid-auto-flow: row;
    grid-template-columns: repeat(6, 1fr);
}

#left{
    text-align: left;
    grid-column: 1/4;
}

#right {
    text-align: right;
    grid-column: 4/6;
}

and the HTML should look like this :

<div id="wrapper">
<div id="left" > ...some awesome stuff </div>
<div id="right" > ...some awesome stuff </div>
</div>

here is a link for more information:

https://www.w3schools.com/css/css_rwd_grid.asp

im quite new but i thougt i could share my little experience

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

Two column div layout with fluid left and fixed right column

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>

The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)

IE6 might need zoom:1 set on the #content div too if you need it's support

Finding which process was killed by Linux OOM killer

Try this out:

grep "Killed process" /var/log/syslog

How do I list all files of a directory?

Another very readable variant for Python 3.4+ is using pathlib.Path.glob:

from pathlib import Path
folder = '/foo'
[f for f in Path(folder).glob('*') if f.is_file()]

It is simple to make more specific, e.g. only look for Python source files which are not symbolic links, also in all subdirectories:

[f for f in Path(folder).glob('**/*.py') if not f.is_symlink()]

How to acces external json file objects in vue.js app

Typescript projects (I have typescript in SFC vue components), need to set resolveJsonModule compiler option to true.

In tsconfig.json:

{
  "compilerOptions": {
    ...
    "resolveJsonModule": true,
    ...
  },
  ...
}

Happy coding :)

(Source https://www.typescriptlang.org/docs/handbook/compiler-options.html)

How to squash all git commits into one?

This worked best for me.

git rebase -X ours -i master

This will git will prefer your feature branch to master; avoiding the arduous merge edits. Your branch needs to be up to date with master.

ours
           This resolves any number of heads, but the resulting tree of the merge is always that of the current
           branch head, effectively ignoring all changes from all other branches. It is meant to be used to
           supersede old development history of side branches. Note that this is different from the -Xours
           option to the recursive merge strategy.

Passing ArrayList through Intent

if you using Generic Array List with Class instead of specific type like

EX:

private ArrayList<Model> aListModel = new ArrayList<Model>();

Here, Model = Class

Receiving Intent Like :

aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);

MUST REMEMBER:

Here Model-class must be implemented like: ModelClass implements Serializable

What is __gxx_personality_v0 for?

Exception handling is included in free standing implementations.

The reason of this is that you possibly use gcc to compile your code. If you compile with the option -### you will notice it is missing the linker-option -lstdc++ when it invokes the linker process . Compiling with g++ will include that library, and thus the symbols defined in it.

When to encode space to plus (+) or %20?

+ means a space only in application/x-www-form-urlencoded content, such as the query part of a URL:

http://www.example.com/path/foo+bar/path?query+name=query+value

In this URL, the parameter name is query name with a space and the value is query value with a space, but the folder name in the path is literally foo+bar, not foo bar.

%20 is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20 and pluses with %2B. This is what eg. encodeURIComponent() does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).

See Also HTML 4.01 Specification application/x-www-form-urlencoded

Zooming MKMapView to fit annotation pins?

You can select which shapes you want to show along with the Annotations.

extension MKMapView {
  func setVisibleMapRectToFitAllAnnotations(animated: Bool = true,
                                            shouldIncludeUserAccuracyRange: Bool = true,
                                            shouldIncludeOverlays: Bool = true,
                                            edgePadding: UIEdgeInsets = UIEdgeInsets(top: 35, left: 35, bottom: 35, right: 35)) {
    var mapOverlays = overlays

    if shouldIncludeUserAccuracyRange, let userLocation = userLocation.location {
      let userAccuracyRangeCircle = MKCircle(center: userLocation.coordinate, radius: userLocation.horizontalAccuracy)
      mapOverlays.append(MKOverlayRenderer(overlay: userAccuracyRangeCircle).overlay)
    }

    if shouldIncludeOverlays {
      let annotations = self.annotations.filter { !($0 is MKUserLocation) }
      annotations.forEach { annotation in
        let cirlce = MKCircle(center: annotation.coordinate, radius: 1)
        mapOverlays.append(cirlce)
      }
    }

    let zoomRect = MKMapRect(bounding: mapOverlays)
    setVisibleMapRect(zoomRect, edgePadding: edgePadding, animated: animated)
  }
}

extension MKMapRect {
  init(bounding overlays: [MKOverlay]) {
    self = .null
    overlays.forEach { overlay in
      let rect: MKMapRect = overlay.boundingMapRect
      self = self.union(rect)
    }
  }
}

How to install Visual Studio 2015 on a different drive

Use VirtualBox. Create a machine on the drive you wish. Enable guest aditions and activate seamless mode.

Benefits:

  • The ENTIRE installation is on the second drive. will work even with a 32gb ssd. (This is the main selling point, considering that Visual studio with it's additional features exceeds 30gb. If you have the GB to spare this solution is NOT the best for you)
  • Uninstalling or backing up is a breeze. Just delete or move the image file. No system file conflicts and dirty registry in case of a corrupted installation.

Drawbacks:

  • You need a LOT of ram. I use 4GB (out of 8) and 2 (out of 6) cores to run comfortably. Even so it is still slower than a normal installation.
  • Will not work for applications with extensive 3d graphics. If you want to work with forms it's fine but if you want to create a 3d game for android using say xamarin then forget it.
  • Testing the program takes several seconds to compile (minutes for android apps). This may not seem much but during development these seconds do add up.

This is the solution i am using and am very happy with it but i am not your average professional programmer. I just create small windows form applications like file uploaders, chat apps etc. Try it out. It will take some time to setup but this experimentation isn't risky.

How to debug PDO database queries?

Probably what you want to do is use debugDumpParams() on the statement handle. You can run that any time after binding values to the prepared query (no need to execute() the statement).

It doesn't build the prepared statement for you, but it will show your parameters.

Order of execution of tests in TestNG

An answer with an important explanation:

There are two parameters of "TestNG" who are supposed to determine the order of execution the tests:

@Test(dependsOnGroups= "someGroup")

And:

@Test(dependsOnMethods= "someMethod")

In both cases these functions will depend on the method or group,

But the differences:

In this case:

@Test(dependsOnGroups= "someGroup")

The method will be dependent on the whole group, so it is not necessarily that immediately after the execution of the dependent function, this method will also be executed, but it may occur later in the run and even after other tests run.

It is important to note that in case and there is more than one use within the same set of tests in this parameter, this is a safe recipe for problems, because the dependent methods of the entire set of tests will run first and only then the methods that depend on them.

However, in this case:

@Test(dependsOnMethods= "someMethod")

Even if this parameter is used more than once within the same set of tests, the dependent method will still be executed after the dependent method is executed immediately.

Hope it's clearly and help.

Handler vs AsyncTask vs Thread

In my opinion threads aren't the most efficient way of doing socket connections but they do provide the most functionality in terms of running threads. I say that because from experience, running threads for a long time causes devices to be very hot and resource intensive. Even a simple while(true) will heat a phone in minutes. If you say that UI interaction is not important, perhaps an AsyncTask is good because they are designed for long-term processes. This is just my opinion on it.

UPDATE

Please disregard my above answer! I answered this question back in 2011 when I was far less experienced in Android than I am now. My answer above is misleading and is considered wrong. I'm leaving it there because many people commented on it below correcting me, and I've learned my lesson.

There are far better other answers on this thread, but I will at least give me more proper answer. There is nothing wrong with using a regular Java Thread; however, you should really be careful about how you implement it because doing it wrong can be very processor intensive (most notable symptom can be your device heating up). AsyncTasks are pretty ideal for most tasks that you want to run in the background (common examples are disk I/O, network calls, and database calls). However, AsyncTasks shouldn't be used for particularly long processes that may need to continue after the user has closed your app or put their device to standby. I would say for most cases, anything that doesn't belong in the UI thread, can be taken care of in an AsyncTask.

Lotus Notes email as an attachment to another email

Copy the mail as a document link (right click on the mail and you should get this option) and paste it in the new mail. This worked for me

Android Min SDK Version vs. Target SDK Version

For those who want a summary,

android:minSdkVersion

is minimum version till your application supports. If your device has lower version of android , app will not install.

while,

android:targetSdkVersion

is the API level till which your app is designed to run. Means, your phone's system don't need to use any compatibility behaviours to maintain forward compatibility because you have tested against till this API.

Your app will still run on Android versions higher than given targetSdkVersion but android compatibility behaviour will kick in.

Freebie -

android:maxSdkVersion

if your device's API version is higher, app will not install. Ie. this is the max API till which you allow your app to install.

ie. for MinSDK -4, maxSDK - 8, targetSDK - 8 My app will work on minimum 1.6 but I also have used features that are supported only in 2.2 which will be visible if it is installed on a 2.2 device. Also, for maxSDK - 8, this app will not install on phones using API > 8.

At the time of writing this answer, Android documentation was not doing a great job at explaining it. Now it is very well explained. Check it here

How to remove &quot; from my Json in javascript?

i used replace feature in Notepad++ and replaced &quot; (without quotes) with " and result was valid json

Invalid argument supplied for foreach()

More concise extension of @Kris's code

function secure_iterable($var)
{
    return is_iterable($var) ? $var : array();
}

foreach (secure_iterable($values) as $value)
{
     //do stuff...
}

especially for using inside template code

<?php foreach (secure_iterable($values) as $value): ?>
    ...
<?php endforeach; ?>

Set transparent background of an imageview on Android

In your XML set the Background attribute to any colour, White(#FFFFFF) shade or Black(#000000) shade. If you want transparency, just put 80 before the actual hash code:

#80000000

This will change any colour you want to a transparent one.. :)

How to import a JSON file in ECMAScript 6?

I used it installing the plugin "babel-plugin-inline-json-import" and then in .balberc add the plugin.

  1. Install plugin

    npm install --save-dev babel-plugin-inline-json-import

  2. Config plugin in babelrc

    "plugin": [ "inline-json-import" ]

And this is the code where I use it

import es from './es.json'
import en from './en.json'

export const dictionary = { es, en }

jQuery get the name of a select option

 $(this).attr("name") 

means the name of the select tag not option name.

To get option name

 $("#band_type_choices option:selected").attr('name');

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.

Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.

However the overhead of creating the large dataset may offset the benefits of parallel processing...

How to use `@ts-ignore` for a block

If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read into that buffer, and write from that buffer into your socket (you could also use send and recv, which are socket-specific ways of writing and reading data). The outline would look something like this:

while (1) {
    // Read data into buffer.  We may not have enough to fill up buffer, so we
    // store how many bytes were actually read in bytes_read.
    int bytes_read = read(input_file, buffer, sizeof(buffer));
    if (bytes_read == 0) // We're done reading from the file
        break;

    if (bytes_read < 0) {
        // handle errors
    }

    // You need a loop for the write, because not all of the data may be written
    // in one call; write will return how many bytes were written. p keeps
    // track of where in the buffer we are, while we decrement bytes_read
    // to keep track of how many bytes are left to write.
    void *p = buffer;
    while (bytes_read > 0) {
        int bytes_written = write(output_socket, p, bytes_read);
        if (bytes_written <= 0) {
            // handle errors
        }
        bytes_read -= bytes_written;
        p += bytes_written;
    }
}

Make sure to read the documentation for read and write carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue statement, while others mean something is broken and you need to stop.

For sending the file to a socket, there is a system call, sendfile that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap (as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile call but no analogous recvfile.

Beware that sendfile is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).

In Linux 2.6.17, the splice system call was introduced, and as of 2.6.23 is used internally to implement sendfile. splice is a more general purpose API than sendfile. For a good description of splice and tee, see the rather good explanation from Linus himself. He points out how using splice is basically just like the loop above, using read and write, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").

Find integer index of rows with NaN in pandas dataframe

Let the dataframe be named df and the column of interest(i.e. the column in which we are trying to find nulls) is 'b'. Then the following snippet gives the desired index of null in the dataframe:

   for i in range(df.shape[0]):
       if df['b'].isnull().iloc[i]:
           print(i)

How do you remove an invalid remote branch reference from Git?

Only slightly related, but still might be helpful in the same situation as we had - we use a network file share for our remote repository. Last week things were working, this week we were getting the error "Remote origin did not advertise Ref for branch refs/heads/master. This Ref may not exist in the remote or may be hidden by permission settings"

But we believed nothing had been done to corrupt things. The NFS does snapshots so I reviewed each "previous version" and saw that three days ago, the size in MB of the repository had gone from 282MB to 33MB, and about 1,403 new files and 300 folders now existed. I queried my co-workers and one had tried to do a push that day - then cancelled it.

I used the NFS "Restore" functionality to restore it to just before that date and now everythings working fine again. I did try the prune previously, didnt seem to help. Maybe the harsher cleanups would have worked.

Hope this might help someone else one day!

Jay

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

You ran into Eclipse bug 525948 which has already been fixed and which will be published in the upcoming release Oxygen.3 (4.7.3), March 21, 2018.

As workaround, put your test code in a separate project and add the project under test to the modulepath, but do not add a module-info.java to your test project. With your project, class and module naming, it should look something like this:

enter image description here

See also my video that shows Java 9 and JUnit 5 in Eclipse Oxygen.1a in action

Responsively change div size keeping aspect ratio

That's my solution

<div class="main" style="width: 100%;">
    <div class="container">
        <div class="sizing"></div>
        <div class="content"></div>
    </div>
</div>

.main {
    width: 100%;
}
.container {
    width: 30%;
    float: right;
    position: relative;
}
.sizing {
    width: 100%;
    padding-bottom: 50%;
    visibility: hidden;
}
.content {
    width: 100%;
    height: 100%;
    background-color: red;
    position: absolute;
    margin-top: -50%;
}

http://jsfiddle.net/aG4Fs/3/

Get HTML source of WebElement in Selenium WebDriver using Python

I hope this could help: http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html

Here is described Java method:

java.lang.String    getText() 

But unfortunately it's not available in Python. So you can translate the method names to Python from Java and try another logic using present methods without getting the whole page source...

E.g.

 my_id = elem[0].get_attribute('my-id')

Best practice for Django project working directory structure

I don't like to create a new settings/ directory. I simply add files named settings_dev.py and settings_production.py so I don't have to edit the BASE_DIR. The approach below increase the default structure instead of changing it.

mysite/                   # Project
    conf/
        locale/
            en_US/
            fr_FR/
            it_IT/
    mysite/
        __init__.py
        settings.py
        settings_dev.py
        settings_production.py
        urls.py
        wsgi.py
    static/
        admin/
            css/           # Custom back end styles
        css/               # Project front end styles
        fonts/
        images/
        js/
        sass/
    staticfiles/
    templates/             # Project templates
        includes/
            footer.html
            header.html
        index.html
    myapp/                 # Application
        core/
        migrations/
            __init__.py
        templates/         # Application templates
            myapp/
                index.html
        static/
            myapp/
                js/  
                css/
                images/
        __init__.py
        admin.py
        apps.py
        forms.py
        models.py
        models_foo.py
        models_bar.py
        views.py
    templatetags/          # Application with custom context processors and template tags
        __init__.py
        context_processors.py
        templatetags/
            __init__.py
            templatetag_extras.py
    gulpfile.js
    manage.py
    requirements.txt

I think this:

    settings.py
    settings_dev.py
    settings_production.py

is better than this:

    settings/__init__.py
    settings/base.py
    settings/dev.py
    settings/production.py

This concept applies to other files as well.


I usually place node_modules/ and bower_components/ in the project directory within the default static/ folder.

Sometime a vendor/ directory for Git Submodules but usually I place them in the static/ folder.

How to increase font size in NeatBeans IDE?

Alt + scroll wheel will increase / decrease the font size of the main code window

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

Adb install failure: INSTALL_CANCELED_BY_USER

  1. Disable "Verify apps over USB" option under developer mode and try to install again .It should work as pointed out in link https://stackoverflow.com/a/29742394/2559990.

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

I was able to solve the problem by simply adding <AllowedMethod>HEAD</AllowedMethod> to the CORS policy of the S3 Bucket.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

How to pass values between Fragments

As noted at developer site

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

communication between fragments should be done through the associated Activity.

Let's have the following components:

An activity hosts fragments and allow fragments communication

FragmentA first fragment which will send data

FragmentB second fragment which will receive datas from FragmentA

FragmentA's implementation is:

public class FragmentA extends Fragment 
{
    DataPassListener mCallback;
    
    public interface DataPassListener{
        public void passData(String data);
    }

    @Override
    public void onAttach(Context context) 
    {
        super.onAttach(context);
        // This makes sure that the host activity has implemented the callback interface
        // If not, it throws an exception
        try 
        {
            mCallback = (OnImageClickListener) context;
        }
        catch (ClassCastException e) 
        {
            throw new ClassCastException(context.toString()+ " must implement OnImageClickListener");
        }
    }
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        // Suppose that when a button clicked second FragmentB will be inflated
        // some data on FragmentA will pass FragmentB
        // Button passDataButton = (Button).........
        
        passDataButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (view.getId() == R.id.passDataButton) {
                    mCallback.passData("Text to pass FragmentB");
                }
            }
        });
    }
}

MainActivity implementation is:

public class MainActivity extends ActionBarActivity implements DataPassListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (findViewById(R.id.container) != null) {
            if (savedInstanceState != null) {
                return;
            }
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new FragmentA()).commit();
        }
    }
    
    @Override
    public void passData(String data) {
        FragmentB fragmentB = new FragmentB ();
        Bundle args = new Bundle();
        args.putString(FragmentB.DATA_RECEIVE, data);
        fragmentB .setArguments(args);
        getFragmentManager().beginTransaction()
            .replace(R.id.container, fragmentB )
            .commit();
    }
}

FragmentB implementation is:

public class FragmentB extends Fragment{
    final static String DATA_RECEIVE = "data_receive";
    TextView showReceivedData;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_B, container, false);
        showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        Bundle args = getArguments();
        if (args != null) {
            showReceivedData.setText(args.getString(DATA_RECEIVE));
        }
    }
}

I hope this will help..

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

How to upload a project to Github

How to upload a project to Github from scratch

Follow these steps to project to Github

1) git init

2) git add .

3) git commit -m "Add all my files"

4) git remote add origin https://github.com/yourusername/your-repo-name.git

Upload of project from scratch require git pull origin master.

5) git pull origin master

6) git push origin master

Most efficient way to map function over numpy array

All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray, and you need to retain the shape of array.

I have compare just two, but it will retain the shape of ndarray. I have used the array with 1 million entries for comparison. Here I use square function, which is also inbuilt in numpy and has great performance boost, since there as was need of something, you can use function of your choice.

import numpy, time
def timeit():
    y = numpy.arange(1000000)
    now = time.time()
    numpy.array([x * x for x in y.reshape(-1)]).reshape(y.shape)        
    print(time.time() - now)
    now = time.time()
    numpy.fromiter((x * x for x in y.reshape(-1)), y.dtype).reshape(y.shape)
    print(time.time() - now)
    now = time.time()
    numpy.square(y)  
    print(time.time() - now)

Output

>>> timeit()
1.162431240081787    # list comprehension and then building numpy array
1.0775556564331055   # from numpy.fromiter
0.002948284149169922 # using inbuilt function

here you can clearly see numpy.fromiter works great considering to simple approach, and if inbuilt function is available please use that.

CURRENT_TIMESTAMP in milliseconds

In Mysql 5.7+ you can execute

select current_timestamp(6)

for more details

https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html

"Uncaught Error: [$injector:unpr]" with angular after deployment

I had the same problem but the issue was a different one, I was trying to create a service and pass $scope to it as a parameter.
That's another way to get this error as the documentation of that link says:

Attempting to inject a scope object into anything that's not a controller or a directive, for example a service, will also throw an Unknown provider: $scopeProvider <- $scope error. This might happen if one mistakenly registers a controller as a service, ex.:

angular.module('myModule', [])
       .service('MyController', ['$scope', function($scope) {
        // This controller throws an unknown provider error because
        // a scope object cannot be injected into a service.
}]);

How to convert Set<String> to String[]?

Guava style:

Set<String> myset = myMap.keySet();
FluentIterable.from(mySet).toArray(String.class);

more info: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html

Prompt Dialog in Windows Forms

Here's an example in VB.NET

Public Function ShowtheDialog(caption As String, text As String, selStr As String) As String
    Dim prompt As New Form()
    prompt.Width = 280
    prompt.Height = 160
    prompt.Text = caption
    Dim textLabel As New Label() With { _
         .Left = 16, _
         .Top = 20, _
         .Width = 240, _
         .Text = text _
    }
    Dim textBox As New TextBox() With { _
         .Left = 16, _
         .Top = 40, _
         .Width = 240, _
         .TabIndex = 0, _
         .TabStop = True _
    }
    Dim selLabel As New Label() With { _
         .Left = 16, _
         .Top = 66, _
         .Width = 88, _
         .Text = selStr _
    }
    Dim cmbx As New ComboBox() With { _
         .Left = 112, _
         .Top = 64, _
         .Width = 144 _
    }
    cmbx.Items.Add("Dark Grey")
    cmbx.Items.Add("Orange")
    cmbx.Items.Add("None")
    cmbx.SelectedIndex = 0
    Dim confirmation As New Button() With { _
         .Text = "In Ordnung!", _
         .Left = 16, _
         .Width = 80, _
         .Top = 88, _
         .TabIndex = 1, _
         .TabStop = True _
    }
    AddHandler confirmation.Click, Sub(sender, e) prompt.Close()
    prompt.Controls.Add(textLabel)
    prompt.Controls.Add(textBox)
    prompt.Controls.Add(selLabel)
    prompt.Controls.Add(cmbx)
    prompt.Controls.Add(confirmation)
    prompt.AcceptButton = confirmation
    prompt.StartPosition = FormStartPosition.CenterScreen
    prompt.ShowDialog()
    Return String.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString())
End Function

What does the servlet <load-on-startup> value signify

If the value is <0, the serlet is instantiated when the request comes, else >=0 the container will load in the increasing order of the values. if 2 or more servlets have the same value, then the order of the servlets declared in the web.xml.

How to reset / remove chrome's input highlighting / focus border?

To remove the default focus, use the following in your default .css file :

:focus {outline:none;}

You can then control the focus border color either individually by element, or in the default .css:

:focus {outline:none;border:1px solid red}

Obviously replace red with your chosen hex code.

You could also leave the border untouched and control the background color (or image) to highlight the field:

:focus {outline:none;background-color:red}

:-)

Python: How to keep repeating a program until a specific input is obtained?

Easier way:

#required_number = 18

required_number=input("Insert a number: ")
while required_number != 18
    print("Oops! Something is wrong")
    required_number=input("Try again: ")
if required_number == '18'
    print("That's right!")

#continue the code

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I have a similar issue, have you tried:

proxy.ClientCredentials.Windows.AllowedImpersonationLevel =   
          System.Security.Principal.TokenImpersonationLevel.Impersonation;

how to get data from selected row from datagridview

I was having the same issue and this works excellently.

Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting  
  'Display complete contents in tooltip even though column display cuts off part of it.   
  DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value 
End Sub

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

javascript - match string against the array of regular expressions

You can join all regular expressions into single one. This way the string is scanned only once. Even with a sligthly more complex regular expression.

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';


function matchInArray(str, expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )
    return str.match(fullExpr);

};


if (matchInArray(thisString, thisExpressions)) {
    console.log ("Match!!");
} 

In fact, even with this approach, if you need check the same expression set against multiple strings, this is a few suboptimal because you are building (and compiling) the same regular expression each time the function is called.

Better approach would be to use a function builder like this:

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray_builder(expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )   

    return function (str) {
        return str.match(fullExpr);

    };
};  

var matchInArray = matchInArray_builder(thisExpressions);

if (matchInArray(thisString)) {
    console.log ("Match!!");
} 

Disable a Maven plugin defined in a parent POM

The following works for me when disabling Findbugs in a child POM:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>ID_AS_IN_PARENT</id> <!-- id is necessary sometimes -->
            <phase>none</phase>
        </execution>
    </executions>
</plugin>

Note: the full definition of the Findbugs plugin is in our parent/super POM, so it'll inherit the version and so-on.

In Maven 3, you'll need to use:

 <configuration>
      <skip>true</skip>
 </configuration>

for the plugin.

Operation must use an updatable query. (Error 3073) Microsoft Access

Today in my MS-Access 2003 with an ODBC tabla pointing to a SQL Server 2000 with sa password gave me the same error.
I defined a Primary Key on the table in the SQL Server database, and the issue was gone.

What is the maximum length of a URL in different browsers?

The longest URLs I came across are data URLs

Example image URL from Google image results (11747 characters)

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBhQSERIUExQUFRUUFxcXFhQYFBQXGBgYFhkVGBkVFxUXHCYfGBojGRQVHy8gJCcpLCwsFh4xNTAqNSYrLCkBCQoKDgwOGg8PGiokHyQpLDUqKSwsLCksKSwpKSwsLCwpKSkpLCwpLCksKSwpLCkpLCwsLCkpKSwsLCwsLDQsLP/AABEIAM0A9gMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAABQQGAgMHAQj/xABTEAACAAQCBAcLBgsFBwUAAAABAgADBBESIQUGMUEHEyJRYYGRFBYyVHF0lKGxs9IjNEKS0dMXMzVSYmRypMHj8GOTo7LiJENzosLh8RVTgoPD/8QAGQEBAAMBAQAAAAAAAAAAAAAAAAECAwQF/8QAJxEAAgIBAwMEAgMAAAAAAAAAAAECEQMSITEEE0EiUWGBkfAyceH/2gAMAwEAAhEDEQA/AOiaq6q0b0NGzUlMzNTySWMiUS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NwrpLyWkbmN6t3v9dDCbTPCIZkxmEnDls4y/8A0COVwZ3RypeS+mSk9XJyFsIJ9ov0xzuroFxvLa112dKnMRjo3XtsT4pZZQQQvGWtl0qcoX6w61ibMSYsoowGE/KAgjIj6A2XMbYk06Ms8oyjZIoQZFwlwp2hSUcdIcZnyHKM9I6XqJeAy5gmS3ORmAYwwzKO4355c8KH1iuPxeY34/8ATEd9NXlzUKZTBfwvBZSLMMtucbnEdGpaovKRmtcjlW2XGREeu0U3R+t+GWimVeyi54y1znnbDG5td8/xJ/vB8ERRNloZo0WiuNrt/Y/4n+iPF1z/ALL/ABP9MKILCZF9sApQd1+mESa4DfJJ/wDst/0RtbXUW/En+9/0QLEPT1EqSph3mel/7t4Ig6X0+JqOOLteYreHfYrC3g9MeRJFH//Z

How to play videos in android from assets folder or raw folder?

MainCode

Uri raw_uri=Uri.parse("android.resource://<package_name>/+R.raw.<video_file_name>);

myVideoView=(VideoView)findViewbyID(R.idV.Video_view);

myVideoView.setVideoURI(raw_uri);
myVideoView.setMediaController(new MediaController(this));
myVideoView.start();
myVideoView.requestFocus();

XML

<?xml version="1.0" encoding="utf-8" ?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <VideoView
            android:id="+@/Video_View"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
        />
</LinearLayout>

How to implement the --verbose or -v option into a script?

It might be cleaner if you have a function, say called vprint, that checks the verbose flag for you. Then you just call your own vprint function any place you want optional verbosity.

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

jQuery autocomplete with callback ajax json

$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

Viewing localhost website from mobile device

Another option is http://localtunnel.me/ if you're running NodeJS

npm install -g localtunnel

Start a webserver on any local port such as 8080, and create a tunnel to that port:

lt -p 8080

which will return a public URL for your localhost at randomname.localtunnel.me. You can request your own subdomain if it's available:

lt -p 8080 -s myname

which will return myname.localtunnel.me

How to use if statements in underscore.js templates?

Here is a simple if/else check in underscore.js, if you need to include a null check.

<div class="editor-label">
    <label>First Name : </label>
</div>
<div class="editor-field">
    <% if(FirstName == null) { %>
        <input type="text" id="txtFirstName" value="" />
    <% } else { %>
        <input type="text" id="txtFirstName" value="<%=FirstName%>" />
    <% } %>
</div>

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

Change background color of R plot

Like

par(bg = 'blue')
# Now do plot

Why is the <center> tag deprecated in HTML?

You can still use this with XHTML 1.0 Transitional and HTML 4.01 Transitional if you like. The only other way (best way, in my opinion) is with margins:

<div style="width:200px;margin:auto;">
  <p>Hello World</p>
</div>

Your HTML should define the element, not govern its presentation.

Return string without trailing slash

I'd use a regular expression:

function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}

You'll want to make sure that the variable site is a string, though.

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

Count unique values in a column in Excel

You can add a new formula for unique record count

=IF(COUNTIF($A$2:A2,A2)>1,0,1)

Now you can use a pivot table and get a SUM of unique record count. This solution works best if you have two or more rows where the same value exist, but you want the pivot table to report an unique count.

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this:

Display display   = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width  = displaySize.x;
int height = displaySize.y;

How to pass 2D array (matrix) in a function in C?

Easiest Way in Passing A Variable-Length 2D Array

Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.

#include <stdio.h>

void func(int row, int col, int* matrix){
    int i, j;
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
        }
        printf("\n");
    }
}

int main(){
    int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
    func(2, 3, matrix[0]);

    return 0;
}

Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.

Detecting an "invalid date" Date instance in JavaScript

Here's how I would do it:

if (Object.prototype.toString.call(d) === "[object Date]") {
  // it is a date
  if (isNaN(d.getTime())) {  // d.valueOf() could also work
    // date is not valid
  } else {
    // date is valid
  }
} else {
  // not a date
}

Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:

function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

Run Function After Delay

You can add timeout function in jQuery (Show alert after 3 seconds):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

How to configure Glassfish Server in Eclipse manually

For Eclipse Mars use the similar approach as harshit.

1) Help -> Install New Software
2) Use url: http://download.oracle.com/otn_software/oepe/mars repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse

In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.

During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.

Eclipse 4.5.0 Mars JDK : 1.8

Initialize static variables in C++ class?

If your goal is to initialize the static variable in your header file (instead of a *.cpp file, which you may want if you are sticking to a "header only" idiom), then you can work around the initialization problem by using a template. Templated static variables can be initialized in a header, without causing multiple symbols to be defined.

See here for an example:

Static member initialization in a class template

Using varchar(MAX) vs TEXT on SQL Server

  • Basic Definition

TEXT and VarChar(MAX) are Non-Unicode large Variable Length character data type, which can store maximum of 2147483647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).

  • Which one to Use?

As per MSDN link Microsoft is suggesting to avoid using the Text datatype and it will be removed in a future versions of Sql Server. Varchar(Max) is the suggested data type for storing the large string values instead of Text data type.

  • In-Row or Out-of-Row Storage

Data of a Text type column is stored out-of-row in a separate LOB data pages. The row in the table data page will only have a 16 byte pointer to the LOB data page where the actual data is present. While Data of a Varchar(max) type column is stored in-row if it is less than or equal to 8000 byte. If Varchar(max) column value is crossing the 8000 bytes then the Varchar(max) column value is stored in a separate LOB data pages and row will only have a 16 byte pointer to the LOB data page where the actual data is present. So In-Row Varchar(Max) is good for searches and retrieval.

  • Supported/Unsupported Functionalities

Some of the string functions, operators or the constructs which doesn’t work on the Text type column, but they do work on VarChar(Max) type column.

  1. = Equal to Operator on VarChar(Max) type column
  2. Group by clause on VarChar(Max) type column

    • System IO Considerations

As we know that the VarChar(Max) type column values are stored out-of-row only if the length of the value to be stored in it is greater than 8000 bytes or there is not enough space in the row, otherwise it will store it in-row. So if most of the values stored in the VarChar(Max) column are large and stored out-of-row, the data retrieval behavior will almost similar to the one that of the Text type column.

But if most of the values stored in VarChar(Max) type columns are small enough to store in-row. Then retrieval of the data where LOB columns are not included requires the more number of data pages to read as the LOB column value is stored in-row in the same data page where the non-LOB column values are stored. But if the select query includes LOB column then it requires less number of pages to read for the data retrieval compared to the Text type columns.

Conclusion

Use VarChar(MAX) data type rather than TEXT for good performance.

Source

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

curl Failed to connect to localhost port 80

I also had problem with refused connection on port 80. I didn't use localhost.

curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"

Problem was that I had umlauts äåö in my textfile.txt.

Adding content to a linear layout dynamically?

In your onCreate(), write the following

LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);

view1, view2 and view3 are your TextViews. They're easily created programmatically.

MVC 3: How to render a view without its layout page when loaded via ajax?

In ~/Views/ViewStart.cshtml:

@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

and in the controller:

public ActionResult Index()
{
    return View();
}

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Action Image MVC3 Razor

slide modification changed Helper

     public static IHtmlString ActionImageLink(this HtmlHelper html, string action, object routeValues, string styleClass, string alt)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);
        var anchorBuilder = new TagBuilder("a");
        anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
        anchorBuilder.AddCssClass(styleClass);
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return new HtmlString(anchorHtml);
    }

CSS Class

.Edit {
       background: url('../images/edit.png') no-repeat right;
       display: inline-block;
       height: 16px;
       width: 16px;
      }

Create the link just pass the class name

     @Html.ActionImageLink("Edit", new { id = item.ID }, "Edit" , "Edit") 

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Running a cron every 30 seconds

If you are running a recent Linux OS with SystemD, you can use the SystemD Timer unit to run your script at any granularity level you wish (theoretically down to nanoseconds), and - if you wish - much more flexible launching rules than Cron ever allowed. No sleep kludges required

It takes a bit more to set up than a single line in a cron file, but if you need anything better than "Every minute", it is well worth the effort.

The SystemD timer model is basically this: timers are units that start service units when a timer elapses.

So for every script/command that you want to schedule, you must have a service unit and then an additional timer unit. A single timer unit can include multiple schedules, so you normally wouldn't need more than one timer and one service.

Here is a simple example that logs "Hello World" every 10 seconds:

/etc/systemd/system/helloworld.service:

[Unit]
Description=Say Hello
[Service]
ExecStart=/usr/bin/logger -i Hello World

/etc/systemd/system/helloworld.timer:

[Unit]
Description=Say Hello every 10 seconds
[Timer]
OnBootSec=10
OnUnitActiveSec=10
AccuracySec=1ms
[Install]
WantedBy=timers.target

After setting up these units (in /etc/systemd/system, as described above, for a system-wide setting, or at ~/.config/systemd/user for a user-specific setup), you need to enable the timer (not the service though) by running systemctl enable --now helloworld.timer (the --now flag also starts the timer immediately, otherwise, it will only start after the next boot, or user login).

The [Timer] section fields used here are as follows:

  • OnBootSec - start the service this many seconds after each boot.
  • OnUnitActiveSec - start the service this many seconds after the last time the service was started. This is what causes the timer to repeat itself and behave like a cron job.
  • AccuracySec - sets the accuracy of the timer. Timers are only as accurate as this field sets, and the default is 1 minute (emulates cron). The main reason to not demand the best accuracy is to improve power consumption - if SystemD can schedule the next run to coincide with other events, it needs to wake the CPU less often. The 1ms in the example above is not ideal - I usually set accuracy to 1 (1 second) in my sub-minute scheduled jobs, but that would mean that if you look at the log showing the "Hello World" messages, you'd see that it is often late by 1 second. If you're OK with that, I suggest setting the accuracy to 1 second or more.

As you may have noticed, this timer doesn't mimic Cron all that well - in the sense that the command doesn't start at the beginning of every wall clock period (i.e. it doesn't start on the 10th second on the clock, then the 20th and so on). Instead is just happens when the timer ellapses. If the system booted at 12:05:37, then the next time the command runs will be at 12:05:47, then at 12:05:57, etc. If you are interested in actual wall clock accuracy, then you may want to replace the OnBootSec and OnUnitActiveSec fields and instead set an OnCalendar rule with the schedule that you want (which as far as I understand can't be faster than 1 second, using the calendar format). The above example can also be written as:

OnCalendar=*-*-* *:*:00,10,20,30,40,50

Last note: as you probably guessed, the helloworld.timer unit starts the helloworld.service unit because they have the same name (minus the unit type suffix). This is the default, but you can override that by setting the Unit field for the [Timer] section.

More gory details can be found at:

How to get the focused element with jQuery?

If you want to confirm if focus is with an element then

if ($('#inputId').is(':focus')) {
    //your code
}

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

Docker - a way to give access to a host USB or serial device?

With latest versions of docker, this is enough:

docker run -ti --privileged ubuntu bash

It will give access to all system resources (in /dev for instance)

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Get local IP address

Tested with one or multiple LAN cards and Virtual machines

public static string DisplayIPAddresses()
    {
        string returnAddress = String.Empty;

        // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection)
        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

        foreach (NetworkInterface network in networkInterfaces)
        {
            // Read the IP configuration for each network
            IPInterfaceProperties properties = network.GetIPProperties();

            if (network.NetworkInterfaceType == NetworkInterfaceType.Ethernet &&
                   network.OperationalStatus == OperationalStatus.Up &&
                   !network.Description.ToLower().Contains("virtual") &&
                   !network.Description.ToLower().Contains("pseudo"))
            {
                // Each network interface may have multiple IP addresses
                foreach (IPAddressInformation address in properties.UnicastAddresses)
                {
                    // We're only interested in IPv4 addresses for now
                    if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                        continue;

                    // Ignore loopback addresses (e.g., 127.0.0.1)
                    if (IPAddress.IsLoopback(address.Address))
                        continue;

                    returnAddress = address.Address.ToString();
                    Console.WriteLine(address.Address.ToString() + " (" + network.Name + " - " + network.Description + ")");
                }
            }
        }

       return returnAddress;
    }

What is the difference between single-quoted and double-quoted strings in PHP?

Example of single, double, heredoc, and nowdoc quotes

<?php

    $fname = "David";

    // Single quotes
    echo 'My name is $fname.'; // My name is $fname.

    // Double quotes
    echo "My name is $fname."; // My name is David.

    // Curly braces to isolate the name of the variable
    echo "My name is {$fname}."; // My name is David.

    // Example of heredoc
    echo $foo = <<<abc
    My name is {$fname}
    abc;

        // Example of nowdoc
        echo <<< 'abc'
        My name is "$name".
        Now, I am printing some
    abc;

?>

Preventing twitter bootstrap carousel from auto sliding on page load

add this to your coursel div :

data-interval="false"

Generating random strings with T-SQL

I came across this blog post first, then came up with the following stored procedure for this that I'm using on a current project (sorry for the weird formatting):

CREATE PROCEDURE [dbo].[SpGenerateRandomString]
@sLength tinyint = 10,
@randomString varchar(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE @counter tinyint
DECLARE @nextChar char(1)
SET @counter = 1
SET @randomString = ”

WHILE @counter <= @sLength
BEGIN
SELECT @nextChar = CHAR(48 + CONVERT(INT, (122-48+1)*RAND()))

IF ASCII(@nextChar) not in (58,59,60,61,62,63,64,91,92,93,94,95,96)
BEGIN
SELECT @randomString = @randomString + @nextChar
SET @counter = @counter + 1
END
END
END

Dynamically updating css in Angular 2

The accepted answer is not incorrect.

For grouped styles one can also use the ngStyle directive.

<some-element [ngStyle]="{'font-style': styleExpression, 'font-weight': 12}">...</some-element>

The official docs are here

How To Remove Outline Border From Input Button

Another alternative to restore outline when using the keyboard is to use :focus-visible. However, this doesn't work on IE :https://caniuse.com/?search=focus-visible.

How to remove "disabled" attribute using jQuery?

I think you are trying to toggle the disabled state, in witch case you should use this (from this question):

$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });

Here is a working fiddle.

Convert Python program to C/C++ code?

If the C variant needs x hours less, then I'd invest that time in letting the algorithms run longer/again

"invest" isn't the right word here.

  1. Build a working implementation in Python. You'll finish this long before you'd finish a C version.

  2. Measure performance with the Python profiler. Fix any problems you find. Change data structures and algorithms as necessary to really do this properly. You'll finish this long before you finish the first version in C.

  3. If it's still too slow, manually translate the well-designed and carefully constructed Python into C.

    Because of the way hindsight works, doing the second version from existing Python (with existing unit tests, and with existing profiling data) will still be faster than trying to do the C code from scratch.

This quote is important.

Thompson's Rule for First-Time Telescope Makers
It is faster to make a four-inch mirror and then a six-inch mirror than to make a six-inch mirror.

Bill McKeenan
Wang Institute

How to add a margin to a table row <tr>

This isn't going to be exactly perfect though I was happy to discover that you can control the horizontal and vertical border-spacing separately:

table
{
 border-collapse: separate;
 border-spacing: 0 8px;
}

Detect iPhone/iPad purely by css

Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.

Meanwhile, media queries for device-width, device-height, and device-aspect-ratio have been deprecated, so they may not work in future browser versions. (Source: MDN)

TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.

Can you have if-then-else logic in SQL?

--Similar answer as above for the most part. Code included to test

DROP TABLE table1
GO
CREATE TABLE table1 (project int, customer int, company int, product int, price money)
GO
INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75)
GO
SELECT TOP 1 WITH TIES product
        , price
        , CASE WhereFound WHEN 1 THEN 'Project'
                WHEN 2 THEN 'Customer'
                WHEN 3 THEN 'Company'
            ELSE 'No Match'
            END AS Source
FROM 
    (
     SELECT product, price, 1 as WhereFound FROM table1 where project = 11
     UNION ALL
     SELECT product, price, 2 FROM table1 where customer = 0
     UNION ALL
     SELECT product, price, 3 FROM table1 where company = 30
    ) AS tbl
ORDER BY WhereFound ASC

Kill python interpeter in linux from the terminal

pkill -9 python

should kill any running python process.

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

C#: Dynamic runtime cast

Best I got so far:

dynamic DynamicCast(object entity, Type to)
{
    var openCast = this.GetType().GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
    var closeCast = openCast.MakeGenericMethod(to);
    return closeCast.Invoke(entity, new[] { entity });
}
static T Cast<T>(object entity) where T : class
{
    return entity as T;
}

How to rename a directory/folder on GitHub website?

Go to that directory/folder and then click on the setting. In the section of "Repository name" simply rename it.

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

How do I import an existing Java keystore (.jks) file into a Java installation?

to load a KeyStore, you'll need to tell it the type of keystore it is (probably jceks), provide an inputstream, and a password. then, you can load it like so:

KeyStore ks  = KeyStore.getInstance(TYPE_OF_KEYSTORE);
ks.load(new FileInputStream(PATH_TO_KEYSTORE), PASSWORD);

this can throw a KeyStoreException, so you can surround in a try block if you like, or re-throw. Keep in mind a keystore can contain multiple keys, so you'll need to look up your key with an alias, here's an example with a symmetric key:

SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD));
SecretKey someKey = entry.getSecretKey();

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

How to prevent a click on a '#' link from jumping to top of page?

Just use

<a href="javascript:;" class="someclass">Text</a>

JQUERY

$('.someclass').click(function(e) { alert("action here"); }

jquery how to use multiple ajax calls one after the end of the other

$(document).ready(function(){
 $('#category').change(function(){  
  $("#app").fadeOut();
$.ajax({
type: "POST",
url: "themes/ajax.php",
data: "cat="+$(this).val(),
cache: false,
success: function(msg)
    {
    $('#app').fadeIn().html(msg);
    $('#app').change(function(){    
    $("#store").fadeOut();
        $.ajax({
        type: "POST",
        url: "themes/ajax.php",
        data: "app="+$(this).val(),
        cache: false,
        success: function(ms)
            {
            $('#store').fadeIn().html(ms);

            }
            });// second ajAx
        });// second on change


     }// first  ajAx sucess
  });// firs ajAx
 });// firs on change

});

Can you get the number of lines of code from a GitHub repository?

Hey all this is ridiculously easy...

  1. Create a new branch from your first commit
  2. When you want to find out your stats, create a new PR from main
  3. The PR will show you the number of changed lines - as you're doing a PR from the first commit all your code will be counted as new lines

And the added benefit is that if you don't approve the PR and just leave it in place, the stats (No of commits, files changed and total lines of code) will simply keep up-to-date as you merge changes into main. :) Enjoy.

enter image description here

Read a text file line by line in Qt

Use this code:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

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

In HTML:

<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />

In PHP:

if (isset($_POST["btnSubmit"])){
  // "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
  // "Delete" clicked
}

sql server convert date to string MM/DD/YYYY

That task should be done by the next layer up in your software stack. SQL is a data repository, not a presentation system

You can do it with

CONVERT(VARCHAR(10), fmdate(), 101)

But you shouldn't

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

What exactly are DLL files, and how do they work?

DLLs (Dynamic Link Libraries) contain resources used by one or more applications or services. They can contain classes, icons, strings, objects, interfaces, and pretty much anything a developer would need to store except a UI.

How to add a new row to datagridview programmatically

If the grid is bound against a DataSet / table its better to use a BindingSource like

var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
grid.DataSource = bindingSource;

//Add data to dataTable and then call

bindingSource.ResetBindings(false)    

Why does JSON.parse fail with the empty string?

JSON.parse expects valid notation inside a string, whether that be object {}, array [], string "" or number types (int, float, doubles).

If there is potential for what is parsing to be an empty string then the developer should check for it.

If it was built into the function it would add extra cycles, since built in functions are expected to be extremely performant, it makes sense to not program them for the race case.

#include errors detected in vscode

1.Install Mingw-w64

2.Then Edit environment variables for your account "C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin"

3.Reload

  • For MAC

    1.Open search ,command + shift +P, and run this code “c/c++ edit configurations (ui)”

    2.open file c_cpp_properties.json and update the includePath from "${workspaceFolder}/**" to "${workspaceFolder}/inc"

How to plot multiple functions on the same figure, in Matplotlib?

Just use the function plot as follows

figure()
...
plot(t, a)
plot(t, b)
plot(t, c)

How to make a back-to-top button using CSS and HTML only?

<a href="#">Start of page</a>

"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."

Source

Pressed <button> selector

You could use :focus which will remain the style as long as the user doesn't click elsewhere.

button:active {
    border: 2px solid green;
}

button:focus {
    border: 2px solid red;
}

Convert JsonObject to String

You can use reliable library GSON

private static final Type DATA_TYPE_JSON = 
        new TypeToken<JSONObject>() {}.getType();           
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

Mine was caused by an invalid relationship in the models I was trying to query. Figured out by debugging the response it crashed at the relation.

How to open up a form from another form in VB.NET?

You can also use showdialog

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                      Handles Button3.Click

     dim mydialogbox as new aboutbox1
     aboutbox1.showdialog()

End Sub

What does it mean when an HTTP request returns status code 0?

wininet.dll returns both standard and non-standard status codes that are listed below.

401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed

12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception

For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?

XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.

Find and kill a process in one line using bash and regex

You can use below command to list pid of the command. Use top or better use htop to view all process in linux. Here I want to kill a process named

ps -ef | grep '/usr/lib/something somelocation/some_process.js'  | grep -v grep | awk '{print $2}'

And verify the pid. It must be proper.To kill them use kill command.

sudo kill -9 `ps -ef | grep '/usr/lib/something somelocation/some_process.js'  | grep -v grep | awk '{print $2}'`

Eg:- is from htop process list.

sudo kill -9 `ps -ef | grep '<process>'  | grep -v grep | awk '{print $2}'`

This resolves my issues. Always be prepared to restart process if you accidentally kill a process.

Prevent textbox autofill with previously entered values

This works for me

   <script type="text/javascript">
        var c = document.getElementById("<%=TextBox1.ClientID %>");
        c.select =
        function (event, ui) 
        { this.value = ""; return false; }
    </script>

What is the difference between HTTP status code 200 (cache) vs status code 304?

200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.

304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.

To your last question, I don't know why the two JavaScript files in the same directory are returning different results.

Failed to run sdkmanager --list with Java 9

Define home directories of different JDK versions in your .bashrc or .zshrc:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_14_HOME=$(/usr/libexec/java_home -v14)

First of all use JDK version 8. Put this line the top of sdkmanager file:

export JAVA_HOME=$JAVA_8_HOME

Switch back to JDK version 14. Put this line the bottom of sdkmanager file:

export JAVA_HOME=$JAVA_14_HOME

Byte Array to Image object

According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).

What design patterns are used in Spring framework?

Spring container generates bean objects depending on the bean scope (singleton, prototype etc..). So this looks like implementing Abstract Factory pattern. In the Spring's internal implementation, I am sure each scope should be tied to specific factory kind class.

ORA-01843 not a valid month- Comparing Dates

I know this is a bit late, but I'm having a similar issue. SQL*Plus executes the query successfully, but Oracle SQL Developer shows the ORA-01843: not a valid month error.

SQL*Plus seems to know that the date I'm using is in the valid format, whereas Oracle SQL Developer needs to be told explicitly what format my date is in.

  • SQL*Plus statement:

    select count(*) from some_table where DATE_TIME_CREATED < '09-12-23';
    

VS

  • Oracle SQL Developer statement:

     select count(*) from some_table where DATE_TIME_CREATED < TO_DATE('09-12-23','RR-MM-DD');
    

How to get visitor's location (i.e. country) using geolocation?

A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I've used and found to be working: (it's the code of my HTML page)

_x000D_
_x000D_
<html>_x000D_
    <body>_x000D_
        <p id="loc"></p>_x000D_
_x000D_
_x000D_
        <script type="text/javascript">_x000D_
            var a = document.getElementById("loc");_x000D_
_x000D_
               function jsonpCallback(data) { _x000D_
             a.innerHTML = "Latitude: " + data.latitude + _x000D_
                              "<br/>Longitude: " + data.longitude + _x000D_
                              "<br/>Country: " + data.address.country; _x000D_
              }_x000D_
        </script>_x000D_
        <script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"_x000D_
                     type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you've written). Therefore, privacy is compromised. So, you should make judicial use of this service.

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

Small change to sam yi's answer (for better readability):

select top 1000 TableID
into #ControlTable 
from dbo.table
where StatusID = 7

declare @TableID int

while exists (select * from #ControlTable)
begin

    select @TableID = (select top 1 TableID
                       from #ControlTable
                       order by TableID asc)

    -- Do something with your TableID

    delete #ControlTable
    where TableID = @TableID

end

drop table #ControlTable

What is Turing Complete?

In the simplest terms, a Turing-complete system can solve any possible computational problem.

One of the key requirements is the scratchpad size be unbounded and that is possible to rewind to access prior writes to the scratchpad.

Thus in practice no system is Turing-complete.

Rather some systems approximate Turing-completeness by modeling unbounded memory and performing any possible computation that can fit within the system's memory.

Creating a folder if it does not exists - "Item already exists"

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

How do I rename all folders and files to lowercase on Linux?

Most of the answers above are dangerous, because they do not deal with names containing odd characters. Your safest bet for this kind of thing is to use find's -print0 option, which will terminate filenames with ASCII NUL instead of \n.

Here is a script, which only alter files and not directory names so as not to confuse find:

find .  -type f -print0 | xargs -0n 1 bash -c \
's=$(dirname "$0")/$(basename "$0");
d=$(dirname "$0")/$(basename "$0"|tr "[A-Z]" "[a-z]"); mv -f "$s" "$d"'

I tested it, and it works with filenames containing spaces, all kinds of quotes, etc. This is important because if you run, as root, one of those other scripts on a tree that includes the file created by

touch \;\ echo\ hacker::0:0:hacker:\$\'\057\'root:\$\'\057\'bin\$\'\057\'bash

... well guess what ...

"Line contains NULL byte" in CSV reader (Python)

Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

How do I mock a static method that returns void with PowerMock?

You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources will throw the exception :

// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception

Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.

doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.


By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.

Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.

Hope that helps.

Regards

AngularJs $http.post() does not send data

Angular

  var payload = $.param({ jobId: 2 });

                this.$http({
                    method: 'POST',
                    url: 'web/api/ResourceAction/processfile',
                    data: payload,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                });

WebAPI 2

public class AcceptJobParams
        {
            public int jobId { get; set; }
        }

        public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
        {
            // do something with fileName parameter

            return Ok();
        }

Hide scroll bar, but while still being able to scroll

This works for me with simple CSS properties:

.container {
    -ms-overflow-style: none;  /* Internet Explorer 10+ */
    scrollbar-width: none;  /* Firefox */
}
.container::-webkit-scrollbar { 
    display: none;  /* Safari and Chrome */
}

For older versions of Firefox, use: overflow: -moz-scrollbars-none;

Google Colab: how to read data from my google drive?

There are many ways to read the files in your colab notebook(**.ipnb), a few are:

  1. Mounting your Google Drive in the runtime's virtual machine.here &, here
  2. Using google.colab.files.upload(). the easiest solution
  3. Using the native REST API;
  4. Using a wrapper around the API such as PyDrive

Method 1 and 2 worked for me, rest I wasn't able to figure out. If anyone could, as others tried in above post please write an elegant answer. thanks in advance.!

First method:

I wasn't able to mount my google drive, so I installed these libraries

# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass

!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

Once the installation & authorization process is finished, you first mount your drive.

!mkdir -p drive
!google-drive-ocamlfuse drive

After installation I was able to mount the google drive, everything in your google drive starts from /content/drive

!ls /content/drive/ML/../../../../path_to_your_folder/

Now you can simply read the file from path_to_your_folder folder into pandas using the above path.

import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')
df.head(5)

you are suppose you use absolute path you received & not using /../..

Second method:

Which is convenient, if your file which you want to read it is present in the current working directory.

If you need to upload any files from your local file system, you could use below code, else just avoid it.!

from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

suppose you have below the folder hierarchy in your google drive:

/content/drive/ML/../../../../path_to_your_folder/

Then, you simply need below code to load into pandas.

import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df

How to prevent line breaks in list items using CSS

You could add this little snippet of code to add a nice "…" to the ending of the line if the content is to large to fit on one line:

li {
  overflow: hidden; 
  text-overflow: ellipsis;
  white-space: nowrap;
}

Grab a segment of an array in Java without creating a new array on heap

The Lists allow you to use and work with subList of something transparently. Primitive arrays would require you to keep track of some kind of offset - limit. ByteBuffers have similar options as I heard.

Edit: If you are in charge of the useful method, you could just define it with bounds (as done in many array related methods in java itself:

doUseful(byte[] arr, int start, int len) {
    // implementation here
}
doUseful(byte[] arr) {
    doUseful(arr, 0, arr.length);
}

It's not clear, however, if you work on the array elements themselves, e.g. you compute something and write back the result?

Sort a list of tuples by 2nd item (integer value)

From python wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

ImageView rounded corners

Based on Nihal's answer ( https://stackoverflow.com/a/42234152/2832027 ), here is a pure XML version that gives a rectangle with rounded corners on API 24 and above. On below API 24, it will show no rounded corners.

Usage:

<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="150dp"
    android:layout_height="200dp"
    android:foreground="@drawable/rounded_corner_mask"/>

rounded_corner_mask.xml

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

    <item
        android:gravity="bottom|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,10 A10,10 0 0,0 10,0 L10,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="bottom|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M0,0 A10,10 0 0,0 10,10 L0,10 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|left">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,0 A10,10 0 0,0 0,10 L0,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

    <item
        android:gravity="top|right">
        <vector xmlns:android="http://schemas.android.com/apk/res/android"
                android:width="@dimen/rounding_radius"
                android:height="@dimen/rounding_radius"
                android:viewportWidth="10.0"
                android:viewportHeight="10.0">
            <path
                android:pathData="M10,10 A10,10 0 0,0 0,0 L10,0 Z"
                android:fillColor="@color/white"/>
        </vector>
    </item>

</layer-list>

What is the main difference between Inheritance and Polymorphism?

If you use JAVA it's as simple as this:

Polymorphism is using inherited methods but "Overriding" them to do something different (or the same if you call super so wouldn't technically be polymorphic).

Correct me if I'm wrong.

iPhone UILabel text soft shadow

This answer to this similar question provides code for drawing a blurred shadow behind a UILabel. The author uses CGContextSetShadow() to generate the shadow for the drawn text.

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

How to fix 'android.os.NetworkOnMainThreadException'?

As Android is working on a single thread, you should not do any network operation on the main thread. There are various ways to avoid this.

Use the following way to perform a network operation

  • Asysnctask: For small operations which don't take much time.
  • Intent Service: For network operation which take a big amount of time.
  • Use a custom library like Volley and Retrofit for handling complex network operations

Never use StrictMode.setThreadPolicy(policy), as it will freeze your UI and is not at all a good idea.

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

How to read from stdin line by line in Node

// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

Check whether a path is valid in Python without creating a file at the path's target

With Python 3, how about:

try:
    with open(filename, 'x') as tempfile: # OSError if file exists or is invalid
        pass
except OSError:
    # handle error here

With the 'x' option we also don't have to worry about race conditions. See documentation here.

Now, this WILL create a very shortlived temporary file if it does not exist already - unless the name is invalid. If you can live with that, it simplifies things a lot.

How to use putExtra() and getExtra() for string data

Intent intent = new Intent(view.getContext(), ApplicationActivity.class);
                        intent.putExtra("int", intValue);
                        intent.putExtra("Serializable", object);
                        intent.putExtra("String", stringValue);
                        intent.putExtra("parcelable", parObject);
                        startActivity(intent);

ApplicationActivity

Intent intent = getIntent();
Bundle bundle = intent.getExtras();

if(bundle != null){
   int mealId = bundle.getInt("int");
   Object object = bundle.getSerializable("Serializable");
   String string = bundle.getString("String");
   T string = <T>bundle.getString("parcelable");
}

How to do a logical OR operation for integer comparison in shell scripting?

This code works for me:

#!/bin/sh

argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
  echo "foo"
else
  echo "bar"
fi

I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.

man test

for more details.

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

What is the difference between precision and scale?

Precision is the number of significant digits. Oracle guarantees the portability of numbers with precision ranging from 1 to 38.

Scale is the number of digits to the right (positive) or left (negative) of the decimal point. The scale can range from -84 to 127.

In your case, ID with precision 6 means it won't accept a number with 7 or more significant digits.

Reference:

http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

That page also has some examples that will make you understand precision and scale.

Is there a way to automatically build the package.json file for Node.js projects

I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.

var fs = require("fs");

function main() {
  fs.readdir("./node_modules", function (err, dirs) {
    if (err) {
      console.log(err);
      return;
    }
    dirs.forEach(function(dir){
      if (dir.indexOf(".") !== 0) {
        var packageJsonFile = "./node_modules/" + dir + "/package.json";
        if (fs.existsSync(packageJsonFile)) {
          fs.readFile(packageJsonFile, function (err, data) {
            if (err) {
              console.log(err);
            }
            else {
              var json = JSON.parse(data);
              console.log('"'+json.name+'": "' + json.version + '",');
            }
          });
        }
      }
    });

  });
}

main();

In my case, the above script outputs:

"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0",   // Remember: remove the comma character in the last line.

Now, you can copy&paste them. Have fun!

What is the difference between background and background-color

background is the shortcut for background-color and few other background related stuffs as below:

background-color
background-image
background-repeat
background-attachment
background-position 

Read the statement below from W3C:

Background - Shorthand property

To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property.

The shorthand property for background is background:

body {
  background: white url("img_tree.png") no-repeat right top;
}

When using the shorthand property the order of the property values is:

background-color
background-image
background-repeat
background-attachment
background-position

It does not matter if one of the property values is missing, as long as the other ones are in this order.

How to link to apps on the app store

A number of answers suggest using 'itms' or 'itms-apps' but this practice is not specifically recommended by Apple. They only offer the following way to open the App Store:

Listing 1 Launching the App Store from an iOS application

NSString *iTunesLink = @"https://itunes.apple.com/us/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

See https://developer.apple.com/library/ios/qa/qa1629/_index.html last updated March, 2014 as of this answer.

For apps that support iOS 6 and above, Apple offers a in-app mechanism for presenting the App Store: SKStoreProductViewController

- (void)loadProductWithParameters:(NSDictionary *)parameters completionBlock:(void (^)(BOOL result, NSError *error))block;

// Example:
SKStoreProductViewController* spvc = [[SKStoreProductViewController alloc] init];
spvc.delegate = self;
[spvc loadProductWithParameters:@{ SKStoreProductParameterITunesItemIdentifier : @(364709193) } completionBlock:^(BOOL result, NSError *error){ 
    if (error)
        // Show sorry
    else
        // Present spvc
}];

Note that on iOS6, the completion block may not be called if there are errors. This appears to be a bug that was resolved in iOS 7.

SQL LIKE condition to check for integer?

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?' 

This will match a title starting with one or more digits and an optional space

How to get the first element of an array?

You can use the combination of reverse then pop. The idea is to reverse the array then pop which will get you the last item in that array.

Be careful as this will modify the original array.

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];_x000D_
var first = fruits.reverse().pop();_x000D_
  _x000D_
console.log('First element -->', first);_x000D_
console.log('Original array -->', fruits);
_x000D_
_x000D_
_x000D_

How to retrieve available RAM from Windows command line?

systeminfo is a command that will output system information, including available memory

Wait until page is loaded with Selenium WebDriver for Python

Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.

import time
from selenium import webdriver

def page_has_loaded(driver, sleep_time = 2):
    '''
    Waits for page to completely load by comparing current page hash values.
    '''

    def get_page_hash(driver):
        '''
        Returns html dom hash
        '''
        # can find element by either 'html' tag or by the html 'root' id
        dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
        # dom = driver.find_element_by_id('root').get_attribute('innerHTML')
        dom_hash = hash(dom.encode('utf-8'))
        return dom_hash

    page_hash = 'empty'
    page_hash_new = ''
    
    # comparing old and new page DOM hash together to verify the page is fully loaded
    while page_hash != page_hash_new: 
        page_hash = get_page_hash(driver)
        time.sleep(sleep_time)
        page_hash_new = get_page_hash(driver)
        print('<page_has_loaded> - page not loaded')

    print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))

Conda command is not recognized on Windows 10

The newest version of the Anaconda installer for Windows will also install a windows launcher for "Anaconda Prompt" and "Anaconda Powershell Prompt". If you use one of those instead of the regular windows cmd shell, the conda command, python etc. should be available by default in this shell.

enter image description here

What does "TypeError 'xxx' object is not callable" means?

The action occurs when you attempt to call an object which is not a function, as with (). For instance, this will produce the error:

>>> a = 5
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Class instances can also be called if they define a method __call__

One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0) instead of [0]

How to detect shake event with android?

Google helps a lot.

/* The following code was written by Matthew Wiggins
 * and is released under the APACHE 2.0 license
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 */
package com.hlidskialf.android.hardware;

import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.content.Context;
import java.lang.UnsupportedOperationException;

public class ShakeListener implements SensorListener 
{
  private static final int FORCE_THRESHOLD = 350;
  private static final int TIME_THRESHOLD = 100;
  private static final int SHAKE_TIMEOUT = 500;
  private static final int SHAKE_DURATION = 1000;
  private static final int SHAKE_COUNT = 3;

  private SensorManager mSensorMgr;
  private float mLastX=-1.0f, mLastY=-1.0f, mLastZ=-1.0f;
  private long mLastTime;
  private OnShakeListener mShakeListener;
  private Context mContext;
  private int mShakeCount = 0;
  private long mLastShake;
  private long mLastForce;

  public interface OnShakeListener
  {
    public void onShake();
  }

  public ShakeListener(Context context) 
  { 
    mContext = context;
    resume();
  }

  public void setOnShakeListener(OnShakeListener listener)
  {
    mShakeListener = listener;
  }

  public void resume() {
    mSensorMgr = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
    if (mSensorMgr == null) {
      throw new UnsupportedOperationException("Sensors not supported");
    }
    boolean supported = mSensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME);
    if (!supported) {
      mSensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
      throw new UnsupportedOperationException("Accelerometer not supported");
    }
  }

  public void pause() {
    if (mSensorMgr != null) {
      mSensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
      mSensorMgr = null;
    }
  }

  public void onAccuracyChanged(int sensor, int accuracy) { }

  public void onSensorChanged(int sensor, float[] values) 
  {
    if (sensor != SensorManager.SENSOR_ACCELEROMETER) return;
    long now = System.currentTimeMillis();

    if ((now - mLastForce) > SHAKE_TIMEOUT) {
      mShakeCount = 0;
    }

    if ((now - mLastTime) > TIME_THRESHOLD) {
      long diff = now - mLastTime;
      float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000;
      if (speed > FORCE_THRESHOLD) {
        if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
          mLastShake = now;
          mShakeCount = 0;
          if (mShakeListener != null) { 
            mShakeListener.onShake(); 
          }
        }
        mLastForce = now;
      }
      mLastTime = now;
      mLastX = values[SensorManager.DATA_X];
      mLastY = values[SensorManager.DATA_Y];
      mLastZ = values[SensorManager.DATA_Z];
    }
  }

}

Destroy or remove a view in Backbone.js

Without knowing all the information... You could bind a reset trigger to your model or controller:

this.bind("reset", this.updateView);

and when you want to reset the views, trigger a reset.

For your callback, do something like:

updateView: function() {
  view.remove();
  view.render();
};

gradle build fails on lint task

With 0.7.0 there comes extended support for Lint, however, it does not work always properly. (Eg. the butterknife library)

Solution is to disable aborting build on found lint errors

I took the inspiration from https://android.googlesource.com/platform/tools/base/+/e6a5b9c7c1bca4da402de442315b5ff1ada819c7

(implementation: https://android.googlesource.com/platform/tools/base/+/e6a5b9c7c1bca4da402de442315b5ff1ada819c7/build-system/gradle/src/main/groovy/com/android/build/gradle/internal/model/DefaultAndroidProject.java )

(discussion: https://plus.google.com/+AndroidDevelopers/posts/ersS6fMLxw1 )

android {
  // your build config
  defaultConfig { ... }
  signingConfigs { ... }
  compileOptions { ... }
  buildTypes { ... }
  // This is important, it will run lint checks but won't abort build
  lintOptions {
      abortOnError false
  }
}

And if you need to disable just particular Lint rule and keep the build failing on others, use this:

/*
 * Use only 'disable' or only 'enable', those configurations exclude each other
 */
android {
  lintOptions {
    // use this line to check all rules except those listed
    disable 'RuleToDisable', 'SecondRuleToDisable'
    // use this line to check just listed rules
    enable 'FirstRuleToCheck', 'LastRuleToCheck'
  }
}

A potentially dangerous Request.Path value was detected from the client (*)

For me, I am working on .net 4.5.2 with web api 2.0, I have the same error, i set it just by adding requestPathInvalidCharacters="" in the requestPathInvalidCharacters you have to set not allowed characters else you have to remove characters that cause this problem.

<system.web>
     <httpRuntime targetFramework="4.5.2" requestPathInvalidCharacters="" />
     <pages  >
      <namespaces>
     ....
 </namespaces>
    </pages> 
  </system.web>

**Note that it is not a good practice, may be a post with this parameter as attribute of an object is better or try to encode the special character. -- After searching on best practice for designing rest api, i found that in search, sort and paginnation, we have to handle the query parameter like this

/companies?search=Digital%26Mckinsey

and this solve the problem when we encode & and remplace it on the url by %26 any way, on the server we receive the correct parameter Digital&Mckinsey

this link may help on best practice of designing rest web api https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9

Is it possible to use JS to open an HTML select to show its option list?

Unfortunately there's a simple answer to this question, and it's "No"

How can I remove a button or make it invisible in Android?

First make the button invisible in xml file.Then set button visible in java code if needed.

Button resetButton=(Button)findViewById(R.id.my_button_del);
resetButton.setVisibility(View.VISIBLE); //To set visible

Xml:

<Button
android:text="Delete"
android:id="@+id/my_button_del"
android:layout_width="72dp" 
android:layout_height="40dp"
android:visibility="invisible"/>

How do I escape a single quote in SQL Server?

Many of us know that the Popular Method of Escaping Single Quotes is by Doubling them up easily like below.

PRINT 'It''s me, Arul.';

Doubling the Single Quotes Method

we are going to look on some other alternate ways of escaping the single quotes.

1.UNICODE Characters

39 is the UNICODE character of Single Quote. So we can use it like below.

PRINT 'Hi,it'+CHAR(39)+'s Arul.';
PRINT 'Helo,it'+NCHAR(39)+'s Arul.';

UNICODE Characters

2.QUOTED_IDENTIFIER

Another simple and best alternate solution is to use QUOTED_IDENTIFIER. When QUOTED_IDENTIFIER is set to OFF, the strings can be enclosed in double quotes. In this scenario, we don’t need to escape single quotes. So,this way would be very helpful while using lot of string values with single quotes. It will be very much helpful while using so many lines of INSERT/UPDATE scripts where column values having single quotes.

SET QUOTED_IDENTIFIER OFF;
PRINT "It's Arul."
SET QUOTED_IDENTIFIER ON;

QUOTE_IDENTIFIER

CONCLUSION

The above mentioned methods are applicable to both AZURE and On Premises .

JavaScript loop through json array?

Your JSON should look like this:

var json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "[email protected]"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "[email protected]"
}];

You can loop over the Array like this:

for(var i = 0; i < json.length; i++) {
    var obj = json[i];

    console.log(obj.id);
}

Or like this (suggested from Eric) be careful with IE support

json.forEach(function(obj) { console.log(obj.id); });

Reactjs: Unexpected token '<' Error

in my case, i had failed to include the type attribute on my script tag.

<script type="text/jsx">

How can I disable the UITableView selection?

While this is the best and easiest solution to prevent a row from showing the highlight during selection

cell.selectionStyle = UITableViewCellSelectionStyleNone;

I'd like to also suggest that it's occasionally useful to briefly show that the row has been selected and then turning it off. This alerts the users with a confirmation of what they intended to select:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     [tableView deselectRowAtIndexPath:indexPath animated:NO];
...
}

How to get date in BAT file

%date% will give you the date.

%time% will give you the time.

The date and time /t commands may give you more detail.

Java Hashmap: How to get key from value?

For Android development targeting API < 19, Vitalii Fedorenko one-to-one relationship solution doesn't work because Objects.equals isn't implemented. Here's a simple alternative:

public <K, V> K getKeyByValue(Map<K, V> map, V value) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
            if (value.equals(entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

Java Singleton and Synchronization

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance ;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}

Confusing "duplicate identifier" Typescript error message

This is because of the combination of two things:

  • tsconfig not having any files section. From http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

    If no "files" property is present in a tsconfig.json, the compiler defaults to including all files in the containing directory and subdirectories. When a "files" property is specified, only those files are included.

  • Including typescript as an npm dependency : node_modules/typescript/ This means that all of typescript gets included .... there is an implicitly included lib.d.ts in your project anyways (http://basarat.gitbook.io/typescript/content/docs/types/lib.d.ts.html) and its conflicting with the one that ships with the NPM version of typescript.

Fix

Either list files or include explicitly https://basarat.gitbook.io/typescript/docs/project/files.html

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

I had the same problem and I solved it with the following steps

  1. Help > Install New Software...
  2. Select "Eclipse Web Tools Platform Repository (http://download.eclipse.org/webtools/updates)" from the "Work with" drop-down.
  3. Select "Web Tools Platform (WTP)" and "Project Provided Components".

Complete all the installation steps and restart Eclipse. You'll see a bunch of servers when you try to add a server runtime environment.

Input placeholders for Internet Explorer

Placeholdr is a super-lightweight drop-in placeholder jQuery polyfill that I wrote. It's less than 1 KB minified.

I made sure that this library addresses both of your concerns:

  1. Placeholdr extends the jQuery $.fn.val() function to prevent unexpected return values when text is present in input fields as a result of Placeholdr. So if you stick with the jQuery API for accessing your fields' values, you won't need to change a thing.

  2. Placeholdr listens for form submits, and it removes the placeholder text from fields so that the server simply sees an empty value.

Again, my goal with Placeholdr is to provide a simple drop-in solution to the placeholder issue. Let me know on Github if there's anything else you'd be interested in having Placeholdr support.

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Inserting a Python datetime.datetime object into MySQL

If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

# make the record for the passed link info
sql_stmt = "INSERT INTO snippet_links (" + \
    "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
    "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"

sql_data = ( title, link, str(publish_date), \
             author, posted_by, \
             str(coco_id), str(link_id) )

try:
    dbc.execute(sql_stmt, sql_data )
except Exception, e:
    ...

Returning an array using C

You can do it using heap memory (through malloc() invocation) like other answers reported here, but you must always manage the memory (use free() function everytime you call your function). You can also do it with a static array:

char* returnArrayPointer() 
{
static char array[SIZE];

// do something in your array here

return array; 
}

You can than use it without worrying about memory management.

int main() 
{
char* myArray = returnArrayPointer();
/* use your array here */
/* don't worry to free memory here */
}

In this example you must use static keyword in array definition to set to application-long the array lifetime, so it will not destroyed after return statement. Of course, in this way you occupy SIZE bytes in your memory for the entire application life, so size it properly!

HTML: How to center align a form

Try this : Set the width of the form as 20% by:
width : 20%;
now if the entire canvas is 100 %, the centre is at 50%. So to align the centre of the form at the centre, 50-(20/2) = 40. therefore set your left margin as 40% by doing this :
left : 40%;

Why does using an Underscore character in a LIKE filter give me all the results?

As you want to specifically search for a wildcard character you need to escape that

This is done by adding the ESCAPE clause to your LIKE expression. The character that is specified with the ESCAPE clause will "invalidate" the following wildcard character.

You can use any character you like (just not a wildcard character). Most people use a \ because that is what many programming languages also use

So your query would result in:

select * 
from Manager
where managerid LIKE '\_%' escape '\'
and managername like '%\_%' escape '\';

But you can just as well use any other character:

select * 
from Manager
where managerid LIKE '#_%' escape '#'
and managername like '%#_%' escape '#';

Here is an SQLFiddle example: http://sqlfiddle.com/#!6/63e88/4

Testing if a site is vulnerable to Sql Injection

A login page isn't the only part of a database-driven website that interacts with the database.

Any user-editable input which is used to construct a database query is a potential entry point for a SQL injection attack. The attacker may not necessarily login to the site as an admin through this attack, but can do other things. They can change data, change server settings, etc. depending on the nature of the application's interaction with the database.

Appending a ' to an input is usually a pretty good test to see if it generates an error or otherwise produces unexpected behavior on the site. It's an indication that the user input is being used to build a raw query and the developer didn't expect a single quote, which changes the query structure.

Keep in mind that one page may be secure against SQL injection while another one may not. The login page, for example, may be hardened against such attacks. But a different page elsewhere in the site might be wide open. So, for example, if one wanted to login as an admin then one can use the SQL injection on that other page to change the admin password. Then return to the perfectly non-SQL-injectable login page and login as the admin.

"Gradle Version 2.10 is required." Error

Important:

If you are getting this when you run:
gradle build
from command line you have to use:
gradlew build
instead so that you will use gradle wrapper to downloaded the appropriate gradle version needed by the app.

When you execute gradle build you are using the global gradle installed on your system.

How do I configure Maven for offline development?

You have two options for this:

1.) make changes in the settings.xml add this in first tag

<localRepository>C:/Users/admin/.m2/repository</localRepository>

2.) use the -o tag for offline command.

mvn -o clean install -DskipTests=true
mvn -o jetty:run

How to use a TRIM function in SQL Server

LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'

I think you're missing a ) on both of the trims. Some SQL versions support just TRIM which does both L and R trims...

Redis: Show database size/size for keys

The solution from the comments deserves it's own answer:

redis-cli --bigkeys

How to add the JDBC mysql driver to an Eclipse project?

Try to insert this:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

before getting the JDBC Connection.

Draw Circle using css alone

yup.. here's my code:

<style>
  .circle{
     width: 100px;
     height: 100px;
     border-radius: 50%;
     background-color: blue
  }
</style>
<div class="circle">
</div>

Displaying the build date

You could launch an extra step in the build process that writes a date stamp to a file which can then be displayed.

On the projects properties tab look at the build events tab. There is an option to execute a pre or post build command.

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

I ran into this issue today. None of these answers provided the fix. I needed to do the following commands (found here https://stackoverflow.com/a/20141146/633107) for my mysql service to start:

sudo /etc/init.d/mysql stop
cd /var/lib/mysql/
ls ib_logfile*
mv ib_logfile0 ib_logfile0.bak
mv ib_logfile1 ib_logfile1.bak
... etc ...
/etc/init.d/mysql restart

This was partly indicated by the following errors in /var/log/mysql/error.log:

140319 11:58:21 InnoDB: Completed initialization of buffer pool
InnoDB: Error: log file ./ib_logfile0 is of different size 0 50331648 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
140319 11:58:21 [ERROR] Plugin 'InnoDB' init function returned error.
140319 11:58:21 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
140319 11:58:21 [ERROR] Unknown/unsupported storage engine: InnoDB
140319 11:58:21 [ERROR] Aborting

I also saw the disk full error, but only when running commands without sudo. If the permissions check fails, it reports disk full (even when your partition is not even close to full).

How to get the process ID to kill a nohup process?

About losing your putty: often the ps ... | awk/grep/perl/... process gets matched, too! So the old school trick is like this

ps -ef | grep -i [n]ohup 

That way the regex search doesn't match the regex search process!

Converting milliseconds to a date (jQuery/JavaScript)

/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.