Programs & Examples On #Safari

Safari is Apple's web browser, the default browser on macOS and iOS.

How can I force WebKit to redraw/repaint to propagate style changes?

above suggestions didnt work for me. but the below one does.

Want to change the text inside the anchor dynamically. The word "Search". Created an inner tag "font" with an id attribute. Managed the contents using javascript (below)

Search

script contents:

    var searchText = "Search";
    var editSearchText = "Edit Search";
    var currentSearchText = searchText;

    function doSearch() {
        if (currentSearchText == searchText) {
            $('#pSearch').panel('close');
            currentSearchText = editSearchText;
        } else if (currentSearchText == editSearchText) {
            $('#pSearch').panel('open');
            currentSearchText = searchText;
        }
        $('#searchtxt').text(currentSearchText);
    }

Swift Open Link in Safari

In Swift 2.0:

UIApplication.sharedApplication().openURL(NSURL(string: "http://stackoverflow.com")!)

Safari 3rd party cookie iframe trick no longer working?

You said you were willing to have your users click a button before the content loads. My solution was to have a button open a new browser window. That window sets a cookie for my domain, refreshes the opener and then closes.

So your main script could look like:

<?php if(count($_COOKIE) > 0): ?>
<!--Main Content Stuff-->
<?php else: ?>
<a href="/safari_cookie_fix.php" target="_blank">Click here to load content</a>
<?php endif ?>

Then safari_cookie_fix.php looks like:

<?php
setcookie("safari_test", "1");
?>
<html>
    <head>
        <title>Safari Fix</title>
        <script type="text/javascript" src="/libraries/prototype.min.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    document.observe('dom:loaded', function(){
        window.opener.location.reload();
        window.close();
    })
    </script>
    This window should close automatically
    </body>
</html>

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

NodeJS/express: Cache and 304 status code

Try using private browsing in Safari or deleting your entire cache/cookies.

I've had some similar issues using chrome when the browser thought it had the website in its cache but actually had not.

The part of the http request that makes the server respond a 304 is the etag. Seems like Safari is sending the right etag without having the corresponding cache.

background: fixed no repeat not working on mobile

I've been having the same problem, but now it works. All I had to do was add background-size: cover !important; and it works on my Android device!

The entire code looks like this:

body.page-id-8 #art-main {
  background: #000000 url("link to image") !important;
  background-repeat: no-repeat !important;
  background-position: 50% 50% !important;
  background-attachment: fixed !important;
  background-color: transparent !important;
  background-size: cover !important;
}

Thanks a lot @taylan derinbay and @Vincent!

iPhone Safari Web App opens links in new window

This is slightly adapted version of Sean's which was preventing back button

// this function makes anchor tags work properly on an iphone

$(document).ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
  // For iOS Apps
  $("a").on("click", function(e){

    var new_location = $(this).attr("href");
    if (new_location != undefined && new_location.substr(0, 1) != "#" && new_location!='' && $(this).attr("data-method") == undefined){
      e.preventDefault();
      window.location = new_location;
    }
  });
}

});

Does overflow:hidden applied to <body> work on iPhone Safari?

It does apply, but it only applies to certain elements within the DOM. for example, it won't work on a table, td, or some other elements, but it will work on a <DIV> tag.
eg:

<body>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

Only tested in iOS 4.3.

A minor edit: you may be better off using overflow:scroll so two finger-scrolling does work.

Testing web application on Mac/Safari when I don't own a Mac

For my case (a small, personal project) https://www.lambdatest.com/ was very helpful. Free tier allows for 6 sessions per month.

Firebug like plugin for Safari browser

If you want firebug for Safari, you just have to go to the apple extensions and search for Firebug

Firebug

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Check if the scrollable element is already scrolled to the top when trying to scroll up or to the bottom when trying to scroll down and then preventing the default action to stop the entire page from moving.

var touchStartEvent;
$('.scrollable').on({
    touchstart: function(e) {
        touchStartEvent = e;
    },
    touchmove: function(e) {
        if ((e.originalEvent.pageY > touchStartEvent.originalEvent.pageY && this.scrollTop == 0) ||
            (e.originalEvent.pageY < touchStartEvent.originalEvent.pageY && this.scrollTop + this.offsetHeight >= this.scrollHeight))
            e.preventDefault();
    }
});

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

Works for Safari, Firefox, and IE7 (haven't tried IE8). Simple test:

<button onclick='$("body,html").scrollTop(0);'>  Top </button>

<button onclick='$("body,html").scrollTop(100);'> Middle </button>

<button onclick='$("body,html").scrollTop(250);'> Bottom </button>

Most examples use either one or both, but in reverse order (i.e., "html,body").

Cheers.

(And semantic purists out there, don't bust my chops -- I've been looking for this for weeks, this is a simple example, that validates XHTML strict. Feel free to create 27 layers of abstraction and event binding bloat for your OCD peace of mind. Just please give due credit, since the folks in the jQuery forums, SO, and the G couldn't cough up the goods. Peace out.)

onclick="location.href='link.html'" does not load page in Safari

Give this a go:

<option onclick="parent.location='#5.2'">Bookmark 2</option>

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

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

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

is there a css hack for safari only NOT chrome?

This hack 100% work only for safari 5.1-6.0. I've just tested it with success.

@media only screen and (-webkit-min-device-pixel-ratio: 1) {
     ::i-block-chrome, .yourcssrule {
        your css property
    }
}

Programmatically open new pages on Tabs

It's up to the user whether they want to use new tabs or new windows, it isn't the business of the developer to modify this behaviour. I do not think you can do it.

Pet peeve of mine - I hate it when sites force me to open in a new window / tab - I am quite capable of making that decision for myself. Particularly when they do it in javascript - that is really unhelpful.

removeEventListener on anonymous functions in JavaScript

Possibly not the best solution in terms of what you are asking. I have still not determined an efficient method for removing anonymous function declared inline with the event listener invocation.

I personally use a variable to store the <target> and declare the function outside of the event listener invocation eg:

const target = document.querySelector('<identifier>');

function myFunc(event) { function code; }

target.addEventListener('click', myFunc);

Then to remove the listener:

target.removeEventListener('click', myFunc);

Not the top recommendation you will receive but to remove anonymous functions the only solution I have found useful is to remove then replace the HTML element. I am sure there must be a better vanilla JS method but I haven't seen it yet.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

I had the same issue with a css file instead of javascript. (using the xitami webserver)

what fixed for me was adding under the MIME section of xitami.cfg:

css=text/css

How to remove the border highlight on an input text element

try this css, it work for me

textarea:focus, input:focus{ border: none; }

Firing a Keyboard Event in Safari, using JavaScript

Did you dispatch the event correctly?

function simulateKeyEvent(character) {
  var evt = document.createEvent("KeyboardEvent");
  (evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, character.charCodeAt(0)) 
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

If you use jQuery, you could do:

function simulateKeyPress(character) {
  jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}

Invalid date in safari

This will not work alert(new Date('2010-11-29')); safari have some weird/strict way of processing date format alert(new Date(String('2010-11-29'))); try like this.

(Or)

Using Moment js will solve the issue though, After ios 14 the safari gets even weird

Try this alert(moment(String("2015-12-31 00:00:00")));

Moment JS

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

The above assumes that you have a folder called CSS in the root of your website like this:

http://www.website.com/CSS/Style.css

Disable elastic scrolling in Safari

There are a to of situations where the above CSS solutions do not work. For instance a transparent fixed header and a sticky footer on the same page. To prevent the top bounce in safari messing things and causing flashes on full screen sliders, you can use this.

    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {

        $window.bind('mousewheel', function(e) {

            if (e.originalEvent.wheelDelta / 120 > 0) {

                if ($window.scrollTop() < 2) return false;
            } 
        });

    }

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

Here's a cross browser solution that triggers an event when your selected images are loaded: http://desandro.github.io/imagesloaded/ you can look up the height and width within the imagesLoaded() function.

How to disable phone number linking in Mobile Safari?

This answer trumps everything as of 6-13-2012:

<a href="#" style="color: #666666; 
                   text-decoration: none;
                   pointer-events: none;">
  Boca Raton, FL 33487
</a>

Change the color to whatever matches your text, text decoration removes the underline, pointer events stops it from being viewed like a link in a browser (pointer doesn't change to a hand)

This is perfect for HTML emails on ios and browser.

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

This is not my answer, but I just copied it from https://gist.github.com/anonymous/2388015 just because the answer is awesome and fixes the problem completely. Credit completely goes to the anonymous author.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        if (/iPhone|iPod|iPad/.test(navigator.userAgent))
            $('iframe').wrap(function(){
                var $this = $(this);
                return $('<div />').css({
                    width: $this.attr('width'),
                    height: $this.attr('height'),
                    overflow: 'auto',
                    '-webkit-overflow-scrolling': 'touch'
                });
            });
    })
</script>

How do I make flex box work in safari?

Just try -webkit-flexbox. it's working for safari. webkit-flex safari will not taking.

Disabling same-origin policy in Safari

goto,

Safari -> Preferences -> Advanced

then at the bottom tick Show Develop Menu in menu bar

then in the Develop Menu tick Disable Cross-Origin Restrictions

What is the difference between screenX/Y, clientX/Y and pageX/Y?

I don't like and understand things, which can be explained visually, by words.

enter image description here

Unexpected token ILLEGAL in webkit

This error can also be caused by a javascript line like this one:

navi_elements.style.bottom = 20px;

Notice that the value is not a string.

HTML5 Video tag not working in Safari , iPhone and iPad

Nothing worked for me except for compressing the video to be under 30mb. That did the trick but with very bad compression.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Only tested on Android 4.1.1:

blur event is not a reliable event to test keyboard up and down because the user as the option to explicitly hide the keyboard which does not trigger a blur event on the field that caused the keyboard to show.

resize event however works like a charm if the keyboard comes up or down for any reason.

coffee:

$(window).bind "resize", (event) ->  alert "resize"

fires on anytime the keyboard is shown or hidden for any reason.

Note however on in the case of an android browser (rather than app) there is a retractable url bar which does not fire resize when it is retracted yet does change the available window size.

Video auto play is not working in Safari and Chrome desktop browser

This is because of now chrome is preventing auto play in html5 video, so by default they will not allow auto play. so we can change this settings using chrome flag settings. this is not possible for normal case so i have find another solution. this is working perfect... (add preload="auto")

<video autoplay preload="auto" loop="loop" muted="muted" id="videoBanner" class="videoBanner">
<source src="banner-video.webm" type="video/webm">
<source src="banner-video.mp4" type="video/mp4">
<source src="banner-video.ogg" type="video/ogg">

var herovide = document.getElementById('videoBanner');
       herovide.autoplay=true;
       herovide.load();  

window.open(url, '_blank'); not working on iMac/Safari

To use window.open() in safari you must put it in an element's onclick event attribute.

For example: <button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>

How to Inspect Element using Safari Browser

Press CMD + , than click in show develop menu in menu bar. After that click Option + CMD + i to open and close the inspector

enter image description here

Jquery click not working with ipad

I found that when I made my binding more specific, it began to work on iOS. I had:

$(document).on('click tap', 'span.clickable', function(e){ ... });

When I changed it to:

$("div.content").on('click tap', 'span.clickable', function(e){ ... });

iOS began responding.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url, [ success(data, textStatus) ] )
  • url - A string containing the URL to which the request is sent.

  • success(data, textStatus) - A callback function that is executed if the request succeeds.

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

HTML5 video - show/hide controls programmatically

Here's how to do it:

var myVideo = document.getElementById("my-video")    
myVideo.controls = false;

Working example: https://jsfiddle.net/otnfccgu/2/

See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp

Is it possible to specify proxy credentials in your web.config?

While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:

  <system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="proxyAddress" usesystemdefault="True"/>
    </defaultProxy>
  </system.net>

The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server. If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How to find rows in one table that have no corresponding row in another table

select tableA.id from tableA left outer join tableB on (tableA.id = tableB.id)
where tableB.id is null
order by tableA.id desc 

If your db knows how to do index intersections, this will only touch the primary key index

Datetime format Issue: String was not recognized as a valid DateTime

DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",  
                                           CultureInfo.InvariantCulture);

Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).

How to empty/destroy a session in rails?

To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }

how to access iFrame parent page using jquery?

There are multiple ways to do these.

I) Get main parent directly.

for exa. i want to replace my child page to iframe then

var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);

here top.location gets parent directly.

II) get parent one by one,

var element = $('.iframe:visible', window.parent.document);

here if you have more then one iframe, then specify active or visible one.

you also can do like these for getting further parents,

var masterParent = element.parent().parent().parent()

III) get parent by Identifier.

var myWindow = window.top.$("#Identifier")

java.lang.IllegalStateException: Fragment not attached to Activity

i may be late but may help someone ..... The best solution for this is to create a global application class instance and call it in the particular fragment where your activity is not being attached

as like below

icon = MyApplication.getInstance().getString(R.string.weather_thunder);

Here is application class

public class MyApplication extends Application {

    private static MyApplication mInstance;
    private RequestQueue mRequestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }
}

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

You are missing permission to create /var/run/mysqld directory.So please create and give permission as following.

  • mkdir -p /var/run/mysqld
  • chown mysql:mysql /var/run/mysqld

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.

If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.

I would recommend (as far as possible, and depending on the exact size of the figures):

  • Place the figures with [t] (or [h] if you must)
  • Place the figures as near as possible to the "right" place (differs for [t] and [h])
  • Include the figures from separate files with \input, which will make them much easier to move around when you're doing the final tuning

In my experience, this is a big eater-up of non-available time (:-)


In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.

selected value get from db into dropdown select box option using php mysql error

THE EASIEST SOLUTION

It will add an extra in your options but your problem will be solved.

<?php 
    if ($editing == Yes) {
        echo "<option value=\".$MyValue.\" SELECTED>".$MyValue."</option>";
    }
?>

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

Install gitk on Mac

If you happen to already have Fink installed, this worked for me on Yosemite / OS X 10.10.5:

fink install git

Note that as a side effect, other git commands are also using the newer git version (2.5.1) installed by Fink, rather than the version from Apple (2.3.2), which is still there but preempted by my $PATH.

Splitting applicationContext to multiple files

Mike Nereson has this to say on his blog at:

http://blog.codehangover.com/load-multiple-contexts-into-spring/

There are a couple of ways to do this.

1. web.xml contextConfigLocation

Your first option is to load them all into your Web application context via the ContextConfigLocation element. You’re already going to have your primary applicationContext here, assuming you’re writing a web application. All you need to do is put some white space between the declaration of the next context.

  <context-param>
      <param-name> contextConfigLocation </param-name>
      <param-value>
          applicationContext1.xml
          applicationContext2.xml
      </param-value>
  </context-param>

  <listener>
      <listener-class>
          org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>

The above uses carriage returns. Alternatively, yo could just put in a space.

  <context-param>
      <param-name> contextConfigLocation </param-name>
      <param-value> applicationContext1.xml applicationContext2.xml </param-value>
  </context-param>

  <listener>
      <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
  </listener>

2. applicationContext.xml import resource

Your other option is to just add your primary applicationContext.xml to the web.xml and then use import statements in that primary context.

In applicationContext.xml you might have…

  <!-- hibernate configuration and mappings -->
  <import resource="applicationContext-hibernate.xml"/>

  <!-- ldap -->
  <import resource="applicationContext-ldap.xml"/>

  <!-- aspects -->
  <import resource="applicationContext-aspects.xml"/>

Which strategy should you use?

1. I always prefer to load up via web.xml.

Because , this allows me to keep all contexts isolated from each other. With tests, we can load just the contexts that we need to run those tests. This makes development more modular too as components stay loosely coupled, so that in the future I can extract a package or vertical layer and move it to its own module.

2. If you are loading contexts into a non-web application, I would use the import resource.

How to check if directory exists in %PATH%?

A comment to the "addPath" script; When supplying a path with spaces, it throws up.

Example: call addPath "c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin"

yields: 'Files' is not recognized as an internal or external command, operable program or batch file.

How to use SSH to run a local shell script on a remote machine?

Assuming you mean you want to do this automatically from a "local" machine, without manually logging into the "remote" machine, you should look into a TCL extension known as Expect, it is designed precisely for this sort of situation. I've also provided a link to a script for logging-in/interacting via SSH.

https://www.nist.gov/services-resources/software/expect

http://bash.cyberciti.biz/security/expect-ssh-login-script/

When is del useful in Python?

I think one of the reasons that del has its own syntax is that replacing it with a function might be hard in certain cases given it operates on the binding or variable and not the value it references. Thus if a function version of del were to be created a context would need to be passed in. del foo would need to become globals().remove('foo') or locals().remove('foo') which gets messy and less readable. Still I say getting rid of del would be good given its seemingly rare use. But removing language features/flaws can be painful. Maybe python 4 will remove it :)

Forward declaring an enum in C++

I'd do it this way:

[in the public header]

typedef unsigned long E;

void Foo(E e);

[in the internal header]

enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,
  FORCE_32BIT = 0xFFFFFFFF };

By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.

Ruby array to string conversion

I'll join the fun with:

['12','34','35','231'].join(', ')

EDIT:

"'#{['12','34','35','231'].join("', '")}'"

Some string interpolation to add the first and last single quote :P

CSS3 Box Shadow on Top, Left, and Right Only

Adding a separate answer because it is radically different.

You could use rgba and set the alpha channel low (to get transparency) to make your drop shadow less noticeable.

Try something like this (play with the .5)

-webkit-box-shadow: 0px -4px 7px rbga(230, 230, 230, .5);
-moz-box-shadow: 0px -4px 7px rbga(230, 230, 230, .5);
box-shadow: 0px -4px 7px rbga(230, 230, 230, .5);

Hope this helps!

How create table only using <div> tag and Css

A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS

.common_table{
    display:table;
    border-collapse:collapse;
    border:1px solid grey;
    }
.common_table DIV{
    display:table-row;
    border:1px solid grey;
    }
.common_table DIV DIV{
    display:table-cell;
    }

HTML

<DIV class="common_table">
   <DIV><DIV>this is a cell</DIV></DIV>
   <DIV><DIV>this is a cell</DIV></DIV>
</DIV>

Works on Chrome and Firefox

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

Command

:%s/<Ctrl-V><Ctrl-M>/\r/g

Where <Ctrl-V><Ctrl-M> means type Ctrl+V then Ctrl+M.

Explanation

:%s

substitute, % = all lines

<Ctrl-V><Ctrl-M>

^M characters (the Ctrl-V is a Vim way of writing the Ctrl ^ character and Ctrl-M writes the M after the regular expression, resulting to ^M special character)

/\r/

with new line (\r)

g

And do it globally (not just the first occurrence on the line).

When to use @QueryParam vs @PathParam

For resource names and IDs, I use @PathParams. For optional variables, I use @QueryParams

Add leading zeroes/0's to existing Excel values to certain length

I hit this page trying to pad hexadecimal values when I realized that DEC2HEX() provides that very feature for free.

You just need to add a second parameter. For example, tying to turn 12 into 0C
DEC2HEX(12,2) => 0C
DEC2HEX(12,4) => 000C
... and so on

Trying to detect browser close event

Have you tried this code?

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.

One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.

How to skip the OPTIONS preflight request?

setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation

$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);

How to add soap header in java

i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.

Access POST values in Symfony2 request object

Symfony doc to get request data

Finally, the raw data sent with the request body can be accessed using getContent():

$content = $request->getContent();

Row Offset in SQL Server

Following will display 25 records excluding first 50 records works in SQL Server 2012.

SELECT * FROM MyTable ORDER BY ID OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY;

you can replace ID as your requirement

Populate XDocument from String

How about this...?

TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);

This was taken from the MSDN docs for XDocument.Load, found here...

http://msdn.microsoft.com/en-us/library/bb299692.aspx

Align image in center and middle within div

for a long time, i also tried the solution to put the img at the center of the div, but for my case i just need this type of component on ajax loading progress so i simply tried the following solution, hope this helps for you!

<div id="loader" style="position: absolute;top: 0;right: 0;left: 0;bottom: 0;z-index: 1;background: rgba(255,255,255,0.5) url('your_image_url') no-repeat center;background-size: 135px;display: none;"></div>

How do you test that a Python function throws an exception?

I just discovered that the Mock library provides an assertRaisesWithMessage() method (in its unittest.TestCase subclass), which will check not only that the expected exception is raised, but also that it is raised with the expected message:

from testcase import TestCase

import mymod

class MyTestCase(TestCase):
    def test1(self):
        self.assertRaisesWithMessage(SomeCoolException,
                                     'expected message',
                                     mymod.myfunc)

Finish all previous activities

Log in->Home->screen 1->screen 2->screen 3->screen 4->screen 5

on screen 4 (or any other) ->

StartActivity(Log in)
with
FLAG_ACTIVITY_CLEAR_TOP

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

ModelState.IsValid == false, why?

About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41

public bool IsValid {
    get {
        return Values.All(modelState => modelState.Errors.Count == 0);
    }
}

Now, it looks like it can't be. Well, that's for ASP.NET MVC v1.

How do you run multiple programs in parallel from a bash script?

You can use wait:

some_command &
P1=$!
other_command &
P2=$!
wait $P1 $P2

It assigns the background program PIDs to variables ($! is the last launched process' PID), then the wait command waits for them. It is nice because if you kill the script, it kills the processes too!

How to Select Every Row Where Column Value is NOT Distinct

Just for fun, here's another way:

;with counts as (
    select CustomerName, EmailAddress,
      count(*) over (partition by EmailAddress) as num
    from Customers
)
select CustomerName, EmailAddress
from counts
where num > 1

How to load assemblies in PowerShell?

Make sure you have below features are installed in order

  1. Microsoft System CLR Types for SQL Server
  2. Microsoft SQL Server Shared Management Objects
  3. Microsoft Windows PowerShell Extensions

Also you may need to load

Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll"

How do I convert a Django QuerySet into list of dicts?

You could define a function using model_to_dict as follows:

def queryset_to_list(qs,fields=None, exclude=None):
    my_list=[]
    for x in qs:
        my_list.append(model_to_dict(x,fields=fields,exclude=exclude))
    return my_list

Suppose your Model has following fields

id
name
email

Run following commands in django shell

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_dict(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'[email protected]'},{'id':2, 'name':'xyz', 'email':'[email protected]'}]

Say you want only id and name in the list of queryset dictionary

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_dict(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]

Similarly you can exclude fields in your output.

Android new Bottom Navigation bar or BottomNavigationView

Other alternate library you can try :- https://github.com/Ashok-Varma/BottomNavigation

<com.ashokvarma.bottomnavigation.BottomNavigationBar
    android:layout_gravity="bottom"
    android:id="@+id/bottom_navigation_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

BottomNavigationBar bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);

bottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.ic_home_white_24dp, "Home"))
                .addItem(new BottomNavigationItem(R.drawable.ic_book_white_24dp, "Books"))
                .addItem(new BottomNavigationItem(R.drawable.ic_music_note_white_24dp, "Music"))
                .addItem(new BottomNavigationItem(R.drawable.ic_tv_white_24dp, "Movies & TV"))
                .addItem(new BottomNavigationItem(R.drawable.ic_videogame_asset_white_24dp, "Games"))
                .initialise();

How to display Woocommerce Category image?

Use this code this may help you.i have passed the cat id 17.pass woocommerce cat id and thats it

   <?php
      global $woocommerce;
      global $wp_query;
      $cat_id=17;
      $table_name = $wpdb->prefix . "woocommerce_termmeta";
      $query="SELECT meta_value FROM {$table_name} WHERE `meta_key`='thumbnail_id' and woocommerce_term_id ={$cat_id} LIMIT 0 , 30";
      $result =  $wpdb->get_results($query);

      foreach($result as $result1){
          $img_id= $result1->meta_value;
      }     

      echo '<img src="'.wp_get_attachment_url( $img_id ).'" alt="category image">';
   ?>

Formatting ISODate from Mongodb

you can use mongo query like this yearMonthDayhms: { $dateToString: { format: "%Y-%m-%d-%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

HourMinute: { $dateToString: { format: "%H-%M-%S", date: {$subtract:["$cdt",14400000]}}}

enter image description here

Cannot run Eclipse; JVM terminated. Exit code=13

I had the same error when configuring eclipse.ini to use JRE6. Turns out I caused this error by incorrectly configuring eclipse to use the 64 bit JVM while running a 32 bit version of eclipse 3.7.

The correct configuration required the eclipse.ini -vm argumument to use "C:/Program Files (x86)/" instead of "C:/Program Files/".

Make sure that the JVM version (32/64 bit) you use matches the eclipse version (32/64 bit).

Add common prefix to all cells in Excel

Select the cell you want to be like this, Go To Cell Properties (or CTRL 1) under Number tab in custom enter "X"#

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

Best practice to call ConfigureAwait for all server-side code

I have some general thoughts about the implementation of Task:

  1. Task is disposable yet we are not supposed to use using.
  2. ConfigureAwait was introduced in 4.5. Task was introduced in 4.0.
  3. .NET Threads always used to flow the context (see C# via CLR book) but in the default implementation of Task.ContinueWith they do not b/c it was realised context switch is expensive and it is turned off by default.
  4. The problem is a library developer should not care whether its clients need context flow or not hence it should not decide whether flow the context or not.
  5. [Added later] The fact that there is no authoritative answer and proper reference and we keep fighting on this means someone has not done their job right.

I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).

Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()/Result in your code.

Check if page gets reloaded or refreshed in JavaScript

Here is a method that is supported by nearly all browsers:

if (sessionStorage.getItem('reloaded') != null) {
    console.log('page was reloaded');
} else {
    console.log('page was not reloaded');
}

sessionStorage.setItem('reloaded', 'yes'); // could be anything

It uses SessionStorage to check if the page is opened the first time or if it is refreshed.

In Angular, how to redirect with $location.path as $http.post success callback

it's very easy code .. but hard to fined..

detailsApp.controller("SchoolCtrl", function ($scope, $location) { 
      $scope.addSchool = function () {

        location.href='/ManageSchool/TeacherProfile?ID=' + $scope.TeacherID;
      }
});

Store output of subprocess.Popen call in a string

The accepted answer is still good, just a few remarks on newer features. Since python 3.6, you can handle encoding directly in check_output, see documentation. This returns a string object now:

import subprocess 
out = subprocess.check_output(["ls", "-l"], encoding="utf-8")

In python 3.7, a parameter capture_output was added to subprocess.run(), which does some of the Popen/PIPE handling for us, see the python docs :

import subprocess 
p2 = subprocess.run(["ls", "-l"], capture_output=True, encoding="utf-8")
p2.stdout

How to search for file names in Visual Studio?

Visual Studio 2019:

Menu -> Preferences -> Key Bindings -> Navigate To...

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Disabling SSL Certificate Validation in Spring RestTemplate

You can use this with HTTPClient API.

public RestTemplate getRestTemplateBypassingHostNameVerifcation() {
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);

}

Getting new Twitter API consumer and secret keys

Simply go here: https://dev.twitter.com/apps/new Make sure you have logged in with your Twitter account - then create - even if your just entering random (Test) Content - create your app - afterwards you will receive all the data you require :)

BLOB to String, SQL Server

Found this...

bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'

If you need to know about different options of bcp flags...

http://msdn.microsoft.com/en-us/library/ms162802.aspx

How to split a long array into smaller arrays, with JavaScript

As a supplement to @jyore's answer, and in case you still want to keep the original array:

var originalArray = [1,2,3,4,5,6,7,8];

var splitArray = function (arr, size) {

  var arr2 = arr.slice(0),
      arrays = [];

  while (arr2.length > 0) {
      arrays.push(arr2.splice(0, size));
  }

  return arrays;
}

splitArray(originalArray, 2);
// originalArray is still = [1,2,3,4,5,6,7,8];

How to display Base64 images in HTML?

Seems there is some error in your data URL.

You can use this online base64 encode / base64 decode tool to encode your images for embedding: http://base64online.org/encode/

Check "Format as Data URL" option to format base64 data as URL.

Round float to x decimals?

The Mark Dickinson answer, although complete, didn't work with the float(52.15) case. After some tests, there is the solution that I'm using:

import decimal
        
def value_to_decimal(value, decimal_places):
    decimal.getcontext().rounding = decimal.ROUND_HALF_UP  # define rounding method
    return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))

(The conversion of the 'value' to float and then string is very important, that way, 'value' can be of the type float, decimal, integer or string!)

Hope this helps anyone.

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

How to Set Focus on JTextField?

If the page contains multiple item and like to set the tab sequence and focus I will suggest to use FocusTraversalPolicy.

grabFocus() will not work if you are using FocusTraversalPolicy.

Sample code

int focusNumber = 0;
Component[] focusList;
focusList = new Component[] { game, move, amount, saveButton,
            printButton, editButton, deleteButton, newButton,
            settingsButton };

frame.setFocusTraversalPolicy(new FocusTraversalPolicy() {

        @Override
        public Component getLastComponent(Container aContainer) {
            return focusList[focusList.length - 1];
        }

        @Override
        public Component getFirstComponent(Container aContainer) {
            return focusList[0];
        }

        @Override
        public Component getDefaultComponent(Container aContainer) {
            return focusList[1];
        }

        @Override
        public Component getComponentAfter(Container focusCycleRoot,
                Component aComponent) {
            focusNumber = (focusNumber + 1) % focusList.length;
            if (focusList[focusNumber].isEnabled() == false) {
                getComponentAfter(focusCycleRoot, focusList[focusNumber]);
            }
            return focusList[focusNumber];
        }

        @Override
        public Component getComponentBefore(Container focusCycleRoot,
                Component aComponent) {
            focusNumber = (focusList.length + focusNumber - 1)
                    % focusList.length;
            if (focusList[focusNumber].isEnabled() == false) {
                getComponentBefore(focusCycleRoot, focusList[focusNumber]);
            }
            return focusList[focusNumber];
        }
    });

How to join two sets in one line without using "|"

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Set adb vendor keys

In this case what you can do is : Go in developer options on the device Uncheck "USB Debugging" then check it again A confirmation box should then appear DvxWifiScan

Convert char array to string use C

You can use strcpy but remember to end the array with '\0'

char array[20]; char string[100];

array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);

error: passing xxx as 'this' argument of xxx discards qualifiers

Member functions that do not modify the class instance should be declared as const:

int getId() const {
    return id;
}
string getName() const {
    return name;
}

Anytime you see "discards qualifiers", it's talking about const or volatile.

Android button background color

Why not just use setBackgroundColor(getResources().getColor(R.color.holo_light_green))?

Edit: If you want to have something which looks more like an Android button you are going to want to create a gradient and set it as the background. For an example of this, you can check out this question.

What is a callback URL in relation to an API?

Think of it as a letter. Sometimes you get a letter, say asking you to fill in a form then return the form in a pre-addressed envelope which is in the original envelope that was housing the form.

Once you have finished filling the form in, you put it in the provided return envelop and send it back.

The callbackUrl is like that return envelope. You are basically saying I am sending you this data. Once you are done with it, I am on this callbackUrl waiting for your response. So the API will process the data you have sent then look at the callback to send you the response.

This is useful because sometimes you may take ages to process some data and it makes no sense to have the caller wait for a response. For example, say your API allows users to send documents to it and virus scan them. Then you send a report after. The scan could take maybe 3minutes. The user cannot be waiting for 3minutes. So you acknowledge that you got the document and let the caller get on with other business while you do the scan then use the callbackUrl when done to tell them the result of the scan.

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

Find the similarity metric between two strings

There is a built in.

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

Using it:

>>> similar("Apple","Appel")
0.8
>>> similar("Apple","Mango")
0.0

How to select last two characters of a string

Try this, note that you don't need to specify the end index in substring.

var characters = member.substr(member.length -2);

Is it possible to append Series to rows of DataFrame without making a list first?

DataFrame.append does not modify the DataFrame in place. You need to do df = df.append(...) if you want to reassign it back to the original variable.

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

Can grep show only words that match search pattern?

ripgrep

Here are the example using ripgrep:

rg -o "(\w+)?th(\w+)?"

It'll match all words matching th.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

If B is a Boolean array, write

B = B*1

(A bit code golfy.)

Jquery, set value of td in a table?

From:

it could be:

.html()

In an HTML document, .html() can be used to get the contents of any element.

.text()

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements.

.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

How can I get the last character in a string?

 var myString = "Test3";
 alert(myString[myString.length-1])

here is a simple fiddle

http://jsfiddle.net/MZEqD/

How to install a specific JDK on Mac OS X?

The easiest way is to use Homebrew. Install Homebrew and then:

brew tap caskroom/versions
brew cask install java7

You can list all available versions using the following command: brew cask search java

Flattening a shallow list in Python

Off the top of my head, you can eliminate the lambda:

reduce(list.__add__, map(list, [mi.image_set.all() for mi in list_of_menuitems]))

Or even eliminate the map, since you've already got a list-comp:

reduce(list.__add__, [list(mi.image_set.all()) for mi in list_of_menuitems])

You can also just express this as a sum of lists:

sum([list(mi.image_set.all()) for mi in list_of_menuitems], [])

How to set JAVA_HOME in Mac permanently?

add following

setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Home

in your ~/.login file:

Get Base64 encode file-data from Input Form

It's entirely possible in browser-side javascript.

The easy way:

The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,), but that's no biggie. This would take all the fun out though.

The hard way:

If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer(). This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.

There are two methods:

  • Convert to string and use the built-in btoa or similar
    • I haven't tested all cases, but works for me- just get the char-codes
  • Convert directly from a Uint8Array to base64

I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.

What I do now:

The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):

function uint8ToString(buf) {
    var i, length, out = '';
    for (i = 0, length = buf.length; i < length; i += 1) {
        out += String.fromCharCode(buf[i]);
    }
    return out;
}

From there, just do:

var base64 = btoa(uint8ToString(yourUint8Array));

Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:

window.open("data:application/octet-stream;base64," + base64);

This will download it as a file.

Other info:

To get the data as a Uint8Array, look at the MDN docs:

Enabling CORS in Cloud Functions for Firebase

I have a little addition to @Andreys answer to his own question.

It seems that you do not have to call the callback in the cors(req, res, cb) function, so you can just call the cors module at the top of your function, without embedding all your code in the callback. This is much quicker if you want to implement cors afterwards.

exports.exampleFunction = functions.https.onRequest((request, response) => {
    cors(request, response, () => {});
    return response.send("Hello from Firebase!");
});

Do not forget to init cors as mentioned in the opening post:

const cors = require('cors')({origin: true});

How do you sort a dictionary by value?

Required namespace : using System.Linq;

Dictionary<string, int> counts = new Dictionary<string, int>();
counts.Add("one", 1);
counts.Add("four", 4);
counts.Add("two", 2);
counts.Add("three", 3);

Order by desc :

foreach (KeyValuePair<string, int> kvp in counts.OrderByDescending(key => key.Value))
{
// some processing logic for each item if you want.
}

Order by Asc :

foreach (KeyValuePair<string, int> kvp in counts.OrderBy(key => key.Value))
{
// some processing logic for each item if you want.
}

Parsing JSON object in PHP using json_decode

You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.

How do I enable EF migrations for multiple contexts to separate databases?

To update database type following codes in PowerShell...

Update-Database -context EnrollmentAppContext

*if more than one databases exist only use this codes,otherwise not necessary..

How to clear/delete the contents of a Tkinter Text widget?

from Tkinter import *

app = Tk()

# Text Widget + Font Size
txt = Text(app, font=('Verdana',8))
txt.pack()

# Delete Button
btn = Button(app, text='Delete', command=lambda: txt.delete(1.0,END))
btn.pack()

app.mainloop()

Here's an example of txt.delete(1.0,END) as mentioned.

The use of lambda makes us able to delete the contents without defining an actual function.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How can I parse a YAML file in Python

I use ruamel.yaml. Details & debate here.

from ruamel import yaml

with open(filename, 'r') as fp:
    read_data = yaml.load(fp)

Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use

from ruamel import yaml

instead of

import yaml

and it will fix most of your problems.

EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.

How to create virtual column using MySQL SELECT?

You can add virtual columns as

SELECT '1' as temp

But if you tries to put where condition to additionally generated column, it wont work and will show an error message as the column doesn't exist.

We can solve this issue by returning sql result as a table.ie,

SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1

How to make HTML table cell editable?

Try this code.

$(function () {
 $("td").dblclick(function () {
    var OriginalContent = $(this).text();

    $(this).addClass("cellEditing");
    $(this).html("<input type="text" value="&quot; + OriginalContent + &quot;" />");
    $(this).children().first().focus();

    $(this).children().first().keypress(function (e) {
        if (e.which == 13) {
            var newContent = $(this).val();
            $(this).parent().text(newContent);
            $(this).parent().removeClass("cellEditing");
        }
    });

 $(this).children().first().blur(function(){
    $(this).parent().text(OriginalContent);
    $(this).parent().removeClass("cellEditing");
 });
 });
});

You can also visit this link for more details :

how to change namespace of entire project?

In asp.net is more to do, to get completely running under another namespace.

  • Copy your source folder and rename it to your new project name.
  • Open it and Replace all by Ctrl + H and be sure to include all Replace everything
  • Press F2 on your Projectname and rename it to your new project name
  • go to your project properties and adjust it, coz everything has gone and you need to make a new Debug Profile Profile to Create
  • All dependencies have now an exclamation mark - restart visual studio
  • Clean your solution and Run it and it should work :)

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

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

WordPress overrides PHP's memory limit to 256M, with the assumption that whatever it was set to before is going to be too low to render the dashboard. You can override this by defining WP_MAX_MEMORY_LIMIT in wp-config.php:

define( 'WP_MAX_MEMORY_LIMIT' , '512M' );

I agree with DanFromGermany, 256M is really a lot of memory for rendering a dashboard page. Changing the memory limit is really putting a bandage on the problem.

node.js Error: connect ECONNREFUSED; response from server

From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).

The problem might be you have not created server on your local machine which listens to port 8000.

For that you have to set up server on localhost which can serve your request.

  1. Create server.js

    var express = require('express');
    var app = express();
    
    app.get('/', function (req, res) {
      res.send('Hello World!'); // This will serve your request to '/'.
    });
    
    app.listen(8000, function () {
      console.log('Example app listening on port 8000!');
     });
    
  2. Run server.js : node server.js

  3. Run file that contains code to make request.

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Eclipse won't compile/run java file

Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.

If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

What is href="#" and why is it used?

The problem with using href="#" for an empty link is that it will take you to the top of the page which may not be the desired action. To avoid this, for older browsers or non-HTML5 doctypes, use

<a href="javascript:void(0)">Goes Nowhere</a>

Delete a database in phpMyAdmin

select database on the left side. Then on the right-central top you can find Operations. In that go for remove database (DROP). That's all.

Navigation Controller Push View Controller

UIViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboardId"];
[self.navigationController pushViewController:vc animated:YES];

An invalid XML character (Unicode: 0xc) was found

You can filter all 'invalid' chars with a custom FilterReader class:

public class InvalidXmlCharacterFilter extends FilterReader {

    protected InvalidXmlCharacterFilter(Reader in) {
        super(in);
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        int read = super.read(cbuf, off, len);
        if (read == -1) return read;

        for (int i = off; i < off + read; i++) {
            if (!XMLChar.isValid(cbuf[i])) cbuf[i] = '?';
        }
        return read;
    }
}

And run it like this:

InputStream fileStream = new FileInputStream(xmlFile);
Reader reader = new BufferedReader(new InputStreamReader(fileStream, charset));
InvalidXmlCharacterFilter filter = new InvalidXmlCharacterFilter(reader);
InputSource is = new InputSource(filter);
xmlReader.parse(is);

Hibernate: flush() and commit()

One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.

Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.

How to list all dates between two dates

You can use a numbers table:

DECLARE @Date1 DATE, @Date2 DATE
SET @Date1 = '20150528'
SET @Date2 = '20150531'

SELECT DATEADD(DAY,number+1,@Date1) [Date]
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY,number+1,@Date1) < @Date2

Results:

+------------+
¦    Date    ¦
¦------------¦
¦ 2015-05-29 ¦
¦ 2015-05-30 ¦
+------------+

Replace a string in a file with nodejs

You could process the file while being read by using streams. It's just like using buffers but with a more convenient API.

var fs = require('fs');
function searchReplaceFile(regexpFind, replace, cssFileName) {
    var file = fs.createReadStream(cssFileName, 'utf8');
    var newCss = '';

    file.on('data', function (chunk) {
        newCss += chunk.toString().replace(regexpFind, replace);
    });

    file.on('end', function () {
        fs.writeFile(cssFileName, newCss, function(err) {
            if (err) {
                return console.log(err);
            } else {
                console.log('Updated!');
            }
    });
});

searchReplaceFile(/foo/g, 'bar', 'file.txt');

Compare 2 arrays which returns difference

/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                    difference.push(array1[i]);
        }
    }

    return difference;
}   

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

phpMyAdmin - config.inc.php configuration?

Run This Query:


*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
> 
> -- --------------------------------------------------------
> 
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin`   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> --    'pma'@localhost;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__bookmark`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__bookmark` (   `id` int(10) unsigned
> NOT NULL auto_increment,   `dbase` varchar(255) NOT NULL default '',  
> `user` varchar(255) NOT NULL default '',   `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '',   `query` text NOT NULL, 
> PRIMARY KEY  (`id`) )   COMMENT='Bookmarks'   DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__column_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__column_info` (   `id` int(5) unsigned
> NOT NULL auto_increment,   `db_name` varchar(64) NOT NULL default '', 
> `table_name` varchar(64) NOT NULL default '',   `column_name`
> varchar(64) NOT NULL default '',   `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `transformation` varchar(255)
> NOT NULL default '',   `transformation_options` varchar(255) NOT NULL
> default '',   `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',  
> PRIMARY KEY  (`id`),   UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) )   COMMENT='Column information
> for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__history`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__history` (   `id` bigint(20) unsigned
> NOT NULL auto_increment,   `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '',   `table` varchar(64) NOT NULL
> default '',   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP,   `sqlquery` text NOT NULL,   PRIMARY KEY  (`id`), 
> KEY `username` (`username`,`db`,`table`,`timevalue`) )   COMMENT='SQL
> history for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__pdf_pages`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` (   `db_name` varchar(64)
> NOT NULL default '',   `page_nr` int(10) unsigned NOT NULL
> auto_increment,   `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '',   PRIMARY KEY  (`page_nr`),   KEY `db_name`
> (`db_name`) )   COMMENT='PDF relation pages for phpMyAdmin'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__recent`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__recent` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Recently accessed tables'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__favorite`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__favorite` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Favorite tables'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_uiprefs`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` (   `username`
> varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,   `table_name`
> varchar(64) NOT NULL,   `prefs` text NOT NULL,   `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP,   PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__relation`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__relation` (   `master_db` varchar(64)
> NOT NULL default '',   `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '',   `foreign_db`
> varchar(64) NOT NULL default '',   `foreign_table` varchar(64) NOT
> NULL default '',   `foreign_field` varchar(64) NOT NULL default '',  
> PRIMARY KEY  (`master_db`,`master_table`,`master_field`),   KEY
> `foreign_field` (`foreign_db`,`foreign_table`) )   COMMENT='Relation
> table'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_coords`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_coords` (   `db_name`
> varchar(64) NOT NULL default '',   `table_name` varchar(64) NOT NULL
> default '',   `pdf_page_number` int(11) NOT NULL default '0',   `x`
> float unsigned NOT NULL default '0',   `y` float unsigned NOT NULL
> default '0',   PRIMARY KEY  (`db_name`,`table_name`,`pdf_page_number`)
> )   COMMENT='Table coordinates for phpMyAdmin PDF output'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_info` (   `db_name` varchar(64)
> NOT NULL default '',   `table_name` varchar(64) NOT NULL default '',  
> `display_field` varchar(64) NOT NULL default '',   PRIMARY KEY 
> (`db_name`,`table_name`) )   COMMENT='Table information for
> phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__tracking`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__tracking` (   `db_name` varchar(64)
> NOT NULL,   `table_name` varchar(64) NOT NULL,   `version` int(10)
> unsigned NOT NULL,   `date_created` datetime NOT NULL,  
> `date_updated` datetime NOT NULL,   `schema_snapshot` text NOT NULL,  
> `schema_sql` text,   `data_sql` longtext,   `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL,   `tracking_active`
> int(1) unsigned NOT NULL default '1',   PRIMARY KEY 
> (`db_name`,`table_name`,`version`) )   COMMENT='Database changes
> tracking for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__userconfig`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__userconfig` (   `username`
> varchar(64) NOT NULL,   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   `config_data` text
> NOT NULL,   PRIMARY KEY  (`username`) )   COMMENT='User preferences
> storage for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__users`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__users` (   `username` varchar(64) NOT
> NULL,   `usergroup` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`usergroup`) )   COMMENT='Users and their assignments to
> user groups'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__usergroups`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__usergroups` (   `usergroup`
> varchar(64) NOT NULL,   `tab` varchar(64) NOT NULL,   `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N',   PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) )   COMMENT='User groups with configured
> menu items'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__navigationhiding`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` (   `username`
> varchar(64) NOT NULL,   `item_name` varchar(64) NOT NULL,  
> `item_type` varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,  
> `table_name` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )  
> COMMENT='Hidden items of navigation tree'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__savedsearches`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` (   `id` int(5)
> unsigned NOT NULL auto_increment,   `username` varchar(64) NOT NULL
> default '',   `db_name` varchar(64) NOT NULL default '',  
> `search_name` varchar(64) NOT NULL default '',   `search_data` text
> NOT NULL,   PRIMARY KEY  (`id`),   UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> )   COMMENT='Saved searches'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__central_columns`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__central_columns` (   `db_name`
> varchar(64) NOT NULL,   `col_name` varchar(64) NOT NULL,   `col_type`
> varchar(64) NOT NULL,   `col_length` text,   `col_collation`
> varchar(64) NOT NULL,   `col_isNull` boolean NOT NULL,   `col_extra`
> varchar(255) default '',   `col_default` text,   PRIMARY KEY
> (`db_name`,`col_name`) )   COMMENT='Central list of columns'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__designer_settings`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` (   `username`
> varchar(64) NOT NULL,   `settings_data` text NOT NULL,   PRIMARY KEY
> (`username`) )   COMMENT='Settings related to Designer'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__export_templates`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__export_templates` (   `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT,   `username` varchar(64) NOT NULL,  
> `export_type` varchar(10) NOT NULL,   `template_name` varchar(64) NOT
> NULL,   `template_data` text NOT NULL,   PRIMARY KEY (`id`),   UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> )   COMMENT='Saved export templates'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*

Open This File :

C:\xampp\phpMyAdmin\config.inc.php

Clear and Past this Code :

> --------------------------------------------------------- <?php /**  * Debian local configuration file  *  * This file overrides the settings
> made by phpMyAdmin interactive setup  * utility.  *  * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz  *  * NOTE:
> do not add security sensitive data to this file (like passwords)  *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still  * want to do this, make sure to properly secure the access to
> this file  * (also on the filesystem level).  */ /**  * Server(s)
> configuration  */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1].  Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
>     /* Authentication type */
>     $cfg['Servers'][$i]['auth_type'] = 'cookie';
>     /* Server parameters */
>     if (empty($dbserver)) $dbserver = 'localhost';
>     $cfg['Servers'][$i]['host'] = $dbserver;
>     if (!empty($dbport)) {
>         $cfg['Servers'][$i]['connect_type'] = 'tcp';
>         $cfg['Servers'][$i]['port'] = $dbport;
>     }
>     //$cfg['Servers'][$i]['compress'] = false;
>     /* Select mysqli if your server has it */
>     $cfg['Servers'][$i]['extension'] = 'mysqli';
>     /* Optional: User for advanced features */
>     $cfg['Servers'][$i]['controluser'] = $dbuser;
>     $cfg['Servers'][$i]['controlpass'] = $dbpass;
>     /* Optional: Advanced phpMyAdmin features */
>     $cfg['Servers'][$i]['pmadb'] = $dbname;
>     $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
>     $cfg['Servers'][$i]['relation'] = 'pma_relation';
>     $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
>     $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
>     $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
>     $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
>     $cfg['Servers'][$i]['history'] = 'pma_history';
>     $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
>     /* Uncomment the following to enable logging in to passwordless accounts,
>      * after taking note of the associated security risks. */
>     // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
>     /* Advance to next server for rest of config */
>     $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';  
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /*  * End of servers
> configuration  */ /*  * Directories for saving/loading files from
> server  */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';

------------------------------------------

i Solve My Problem Through this Method

Limitations of SQL Server Express

You can't install Integration Services with it. Express does not support Integration Services. So if you want build say SSIS-packages you'll need at least Standard Edition.

See more here.

What's the difference between an element and a node in XML?

A Node is a part of the DOM tree, an Element is a particular type of Node

e.g. <foo> This is Text </foo>

You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node

When to use 'raise NotImplementedError'?

Consider if instead it was:

class RectangularRoom(object):
    def __init__(self, width, height):
        pass

    def cleanTileAtPosition(self, pos):
        pass

    def isTileCleaned(self, m, n):
        pass

and you subclass and forget to tell it how to isTileCleaned() or, perhaps more likely, typo it as isTileCLeaned(). Then in your code, you'll get a None when you call it.

  • Will you get the overridden function you wanted? Definitely not.
  • Is None valid output? Who knows.
  • Is that intended behavior? Almost certainly not.
  • Will you get an error? It depends.

raise NotImplmentedError forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.

Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).

On a CSS hover event, can I change another div's styling?

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

Javascript add leading zeroes to date

Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.

Number.prototype.padLeft = function(base,chr){
        var  len = (String(base || 10).length - String(this).length)+1;
        return len > 0? new Array(len).join(chr || '0')+this : this;
    }

var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');

jQuery if Element has an ID?

Simply use:

$(".parent a[id]");

Troubleshooting misplaced .git directory (nothing to commit)

Don't try commiting / adding files. Just run the following 2 commands (:

    git remote add origin http://xyzremotedir/xyzgitproject.git
    git push origin master

Javascript: How to check if a string is empty?

This should work:

if (variable === "") {

}

Parse XLSX with Node and create json

here's angular 5 method version of this with unminified syntax for those who struggling with that y, z, tt in accepted answer. usage: parseXlsx().subscribe((data)=> {...})

parseXlsx() {
    let self = this;
    return Observable.create(observer => {
        this.http.get('./assets/input.xlsx', { responseType: 'arraybuffer' }).subscribe((data: ArrayBuffer) => {
            const XLSX = require('xlsx');
            let file = new Uint8Array(data);
            let workbook = XLSX.read(file, { type: 'array' });
            let sheetNamesList = workbook.SheetNames;

            let allLists = {};
            sheetNamesList.forEach(function (sheetName) {
                let worksheet = workbook.Sheets[sheetName];
                let currentWorksheetHeaders: object = {};
                let data: Array<any> = [];
                for (let cellName in worksheet) {//cellNames example: !ref,!margins,A1,B1,C1

                    //skipping serviceCells !margins,!ref
                    if (cellName[0] === '!') {
                        continue
                    };

                    //parse colName, rowNumber, and getting cellValue
                    let numberPosition = self.getCellNumberPosition(cellName);
                    let colName = cellName.substring(0, numberPosition);
                    let rowNumber = parseInt(cellName.substring(numberPosition));
                    let cellValue = worksheet[cellName].w;// .w is XLSX property of parsed worksheet

                    //treating '-' cells as empty on Spot Indices worksheet
                    if (cellValue.trim() == "-") {
                        continue;
                    }

                    //storing header column names
                    if (rowNumber == 1 && cellValue) {
                        currentWorksheetHeaders[colName] = typeof (cellValue) == "string" ? cellValue.toCamelCase() : cellValue;
                        continue;
                    }

                    //creating empty object placeholder to store current row
                    if (!data[rowNumber]) {
                        data[rowNumber] = {}
                    };

                    //if header is date - for spot indices headers are dates
                    data[rowNumber][currentWorksheetHeaders[colName]] = cellValue;

                }

                //dropping first two empty rows
                data.shift();
                data.shift();
                allLists[sheetName.toCamelCase()] = data;
            });

            this.parsed = allLists;

            observer.next(allLists);
            observer.complete();
        })
    });
}

Sum of Numbers C++

First, you have two variables of the same name i. This calls for confusion.

Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.

How To Auto-Format / Indent XML/HTML in Notepad++

  1. Install Xml Tools plug-in on notepad++: Open the menu plugins-plugins Admin, then search for XML Tools, click on the upper right corner to install . Use shortcut keys Ctrl + Alt + Shift + B
  2. Use online sites, such as XML Formatter

How to define dimens.xml for every different screen size in android?

Use Scalable DP

Although making a different layout for different screen sizes is theoretically a good idea, it can get very difficult to accommodate for all screen dimensions, and pixel densities. Having over 20+ different dimens.xml files as suggested in the above answers, is not easy to manage at all.

How To Use:

To use sdp:

  1. Include implementation 'com.intuit.sdp:sdp-android:1.0.5' in your build.gradle,
  2. Replace any dp value such as 50dp with a @dimen/50_sdp like so:

    <TextView
     android:layout_width="@dimen/_50sdp"
     android:layout_height="@dimen/_50sdp"
     android:text="Hello World!" />
    

How It Works:

sdp scales with the screen size because it is essentially a huge list of different dimens.xml for every possible dp value.

enter image description here

See It In Action:

Here it is on three devices with widely differing screen dimensions, and densities:

enter image description here

Note that the sdp size unit calculation includes some approximation due to some performance and usability constraints.

Property 'value' does not exist on type EventTarget in TypeScript

The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.

How can I return two values from a function in Python?

def test():
    r1 = 1
    r2 = 2
    r3 = 3
    return r1, r2, r3

x,y,z = test()
print x
print y
print z


> test.py 
1
2
3

Why is $$ returning the same id as the parent process?

  1. Parentheses invoke a subshell in Bash. Since it's only a subshell it might have the same PID - depends on implementation.
  2. The C program you invoke is a separate process, which has its own unique PID - doesn't matter if it's in a subshell or not.
  3. $$ is an alias in Bash to the current script PID. See differences between $$ and $BASHPID here, and right above that the additional variable $BASH_SUBSHELL which contains the nesting level.

How do I remove a submodule?

Since git1.8.3 (April 22d, 2013):

There was no Porcelain way to say "I no longer am interested in this submodule", once you express your interest in a submodule with "submodule init".
"submodule deinit" is the way to do so.

The deletion process also uses git rm (since git1.8.5 October 2013).

Summary

The 3-steps removal process would then be:

0. mv a/submodule a/submodule_tmp

1. git submodule deinit -f -- a/submodule    
2. rm -rf .git/modules/a/submodule
3. git rm -f a/submodule
# Note: a/submodule (no trailing slash)

# or, if you want to leave it in your working tree and have done step 0
3.   git rm --cached a/submodule
3bis mv a/submodule_tmp a/submodule

Explanation

rm -rf: This is mentioned in Daniel Schroeder's answer, and summarized by Eonil in the comments:

This leaves .git/modules/<path-to-submodule>/ unchanged.
So if you once delete a submodule with this method and re-add them again, it will not be possible because repository already been corrupted.


git rm: See commit 95c16418:

Currently using "git rm" on a submodule removes the submodule's work tree from that of the superproject and the gitlink from the index.
But the submodule's section in .gitmodules is left untouched, which is a leftover of the now removed submodule and might irritate users (as opposed to the setting in .git/config, this must stay as a reminder that the user showed interest in this submodule so it will be repopulated later when an older commit is checked out).

Let "git rm" help the user by not only removing the submodule from the work tree but by also removing the "submodule.<submodule name>" section from the .gitmodules file and stage both.


git submodule deinit: It stems from this patch:

With "git submodule init" the user is able to tell git they care about one or more submodules and wants to have it populated on the next call to "git submodule update".
But currently there is no easy way they can tell git they do not care about a submodule anymore and wants to get rid of the local work tree (unless the user knows a lot about submodule internals and removes the "submodule.$name.url" setting from .git/config together with the work tree himself).

Help those users by providing a 'deinit' command.
This removes the whole submodule.<name> section from .git/config either for the given submodule(s) (or for all those which have been initialized if '.' is given).
Fail if the current work tree contains modifications unless forced.
Complain when for a submodule given on the command line the url setting can't be found in .git/config, but nonetheless don't fail.

This takes care if the (de)initialization steps (.git/config and .git/modules/xxx)

Since git1.8.5, the git rm takes also care of the:

  • 'add' step which records the url of a submodule in the .gitmodules file: it is need to removed for you.
  • the submodule special entry (as illustrated by this question): the git rm removes it from the index:
    git rm --cached path_to_submodule (no trailing slash)
    That will remove that directory stored in the index with a special mode "160000", marking it as a submodule root directory.

If you forget that last step, and try to add what was a submodule as a regular directory, you would get error message like:

git add mysubmodule/file.txt 
Path 'mysubmodule/file.txt' is in submodule 'mysubmodule'

Note: since Git 2.17 (Q2 2018), git submodule deinit is no longer a shell script.
It is a call to a C function.

See commit 2e61273, commit 1342476 (14 Jan 2018) by Prathamesh Chavan (pratham-pc).
(Merged by Junio C Hamano -- gitster -- in commit ead8dbe, 13 Feb 2018)

git ${wt_prefix:+-C "$wt_prefix"} submodule--helper deinit \
  ${GIT_QUIET:+--quiet} \
  ${prefix:+--prefix "$prefix"} \
  ${force:+--force} \
  ${deinit_all:+--all} "$@"

How to concatenate strings in twig

The operator you are looking for is Tilde (~), like Alessandro said, and here it is in the documentation:

~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is 'John') Hello John!. – http://twig.sensiolabs.org/doc/templates.html#other-operators

And here is an example somewhere else in the docs:

{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}

{{ greeting ~ name|lower }}   {# Hello fabien #}

{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}

Child element click event trigger the parent click event

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).

Syntax:

Here is the simple syntax to use this method:

event.stopPropagation() 

Example:

$("div").click(function(event) {
    alert("This is : " + $(this).prop('id'));

    // Comment the following to see the difference
    event.stopPropagation();
});?

How to create custom button in Android using XML Styles

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

   <solid 
       android:color="#ffffffff"/>

   <size 
       android:width="@dimen/shape_circle_width"
        android:height="@dimen/shape_circle_height"/>
</shape>

1.add this in your drawable

2.set as background to your button

Convert to binary and keep leading zeros in Python

You can use zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2)

prints:

01
10
100

I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable... e.g. - x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.

How to split a list by comma not space

kent$  echo "Hello,World,Questions,Answers,bash shell,script"|awk -F, '{for (i=1;i<=NF;i++)print $i}'
Hello
World
Questions
Answers
bash shell
script

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

Newline in JLabel

Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.

http://www.jidesoft.com/articles/StyledLabel.pdf

display HTML page after loading complete

you can also go for this.... this will only show the HTML section once javascript has loaded.

<!-- Adds the hidden style and removes it when javascript has loaded -->
<style type="text/css">
    .hideAll  {
        visibility:hidden;
     }
</style>

<script type="text/javascript">
    $(window).load(function () {
        $("#tabs").removeClass("hideAll");
    });
</script>

<div id="tabs" class="hideAll">
   ##Content##
</div>

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

I was trying to add a new connection in VS2015. None of the suggestions here worked. Suspecting some sort of a bug in the wizard, especially since SSMS was able to connect just fine, I decided to try and trick it. It worked!

  1. Instead of adding the connection, use "Create new SQL Server Database". Enter your server name and a random name for the new DB, e.g. "test".

  2. Assuming this succeeds, open Server Explorer in VS, locate the connection in Data Connections, right-click it and select Modify Connection.

  3. Change "test" (from step 1) to the name of the existing database you want to connect to. Click "Test Connection". This time it should work!

  4. Delete the temporary database you created in step 1.

How to parse a month name (string) to an integer for comparison in C#?

You could do something like this:

Convert.ToDate(month + " 01, 1900").Month

How does Google calculate my location on a desktop?

I know you can look up IP address to get approximate location, but it's not always accurate. Perhaps they're using that?

update:

Typically, your browser uses information about the Wi-Fi access points around you to estimate your location. If no Wi-Fi access points are in range, or your computer doesn't have Wi-Fi, it may resort to using your computer's IP address to get an approximate location.

Input text dialog Android

I found it cleaner and more reusable to extend AlertDialog.Builder to create a custom dialog class. This is for a dialog that asks the user to input a phone number. A preset phone number can also be supplied by calling setNumber() before calling show().

InputSenderDialog.java

public class InputSenderDialog extends AlertDialog.Builder {

    public interface InputSenderDialogListener{
        public abstract void onOK(String number);
        public abstract void onCancel(String number);
    }

    private EditText mNumberEdit;

    public InputSenderDialog(Activity activity, final InputSenderDialogListener listener) {
        super( new ContextThemeWrapper(activity, R.style.AppTheme) );

        @SuppressLint("InflateParams") // It's OK to use NULL in an AlertDialog it seems...
        View dialogLayout = LayoutInflater.from(activity).inflate(R.layout.dialog_input_sender_number, null);
        setView(dialogLayout);

        mNumberEdit = dialogLayout.findViewById(R.id.numberEdit);

        setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onOK(String.valueOf(mNumberEdit.getText()));

            }
        });

        setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                if( listener != null )
                    listener.onCancel(String.valueOf(mNumberEdit.getText()));
            }
        });
    }

    public InputSenderDialog setNumber(String number){
        mNumberEdit.setText( number );
        return this;
    }

    @Override
    public AlertDialog show() {
        AlertDialog dialog = super.show();
        Window window = dialog.getWindow();
        if( window != null )
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        return dialog;
    }
}

dialog_input_sender_number.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="10dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:paddingBottom="20dp"
        android:text="Input phone number"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <TextView
        android:id="@+id/numberLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/title"
        app:layout_constraintLeft_toLeftOf="parent"
        android:text="Phone number" />

    <EditText
        android:id="@+id/numberEdit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/numberLabel"
        app:layout_constraintLeft_toLeftOf="parent"
        android:inputType="phone" >
        <requestFocus />
    </EditText>

</android.support.constraint.ConstraintLayout>

Usage:

new InputSenderDialog(getActivity(), new InputSenderDialog.InputSenderDialogListener() {
    @Override
    public void onOK(final String number) {
        Log.d(TAG, "The user tapped OK, number is "+number);
    }

    @Override
    public void onCancel(String number) {
        Log.d(TAG, "The user tapped Cancel, number is "+number);
    }
}).setNumber(someNumberVariable).show();

Oracle Convert Seconds to Hours:Minutes:Seconds

For the comment on the answer by vogash, I understand that you want something like a time counter, thats because you can have more than 24 hours. For this you can do the following:

select to_char(trunc(xxx/3600)) || to_char(to_date(mod(xxx, 86400),'sssss'),':mi:ss') as time
from dual;

xxx are your number of seconds.

The first part accumulate the hours and the second part calculates the remaining minutes and seconds. For example, having 150023 seconds it will give you 41:40:23.

But if you always want have hh24:mi:ss even if you have more than 86000 seconds (1 day) you can do:

select to_char(to_date(mod(xxx, 86400),'sssss'),'hh24:mi:ss') as time 
from dual;

xxx are your number of seconds.

For example, having 86402 seconds it will reset the time to 00:00:02.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Some security config and you are ready with swagger open to all

For Swagger V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

For Swagger V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/v3/api-docs",  
            "/swagger-resources/**", 
            "/swagger-ui/**",
             };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

Input placeholders for Internet Explorer

In looking at the "Web Forms : input placeholder" section of HTML5 Cross Browser Polyfills, one I saw was jQuery-html5-placeholder.

I tried the demo out with IE9, and it looks like it wraps your <input> with a span and overlays a label with the placeholder text.

<label>Text:
  <span style="position: relative;">
    <input id="placeholder1314588474481" name="text" maxLength="6" type="text" placeholder="Hi Mom">
    <label style="font: 0.75em/normal sans-serif; left: 5px; top: 3px; width: 147px; height: 15px; color: rgb(186, 186, 186); position: absolute; overflow-x: hidden; font-size-adjust: none; font-stretch: normal;" for="placeholder1314588474481">Hi Mom</label>
  </span>
</label>

There are also other shims there, but I didn't look at them all. One of them, Placeholders.js, advertises itself as "No dependencies (so no need to include jQuery, unlike most placeholder polyfill scripts)."

Edit: For those more interested in "how" that "what", How to create an advanced HTML5 placeholder polyfill which walks through the process of creating a jQuery plugin that does this.

Also, see keep placeholder on focus in IE10 for comments on how placeholder text disappears on focus with IE10, which differs from Firefox and Chrome. Not sure if there is a solution for this problem.

Using SSH keys inside docker container

You can pass the authorised keys in to your container using a shared folder and set permissions using a docker file like this:

FROM ubuntu:16.04
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
EXPOSE 22
RUN cp /root/auth/id_rsa.pub /root/.ssh/authorized_keys
RUN rm -f /root/auth
RUN chmod 700 /root/.ssh
RUN chmod 400 /root/.ssh/authorized_keys
RUN chown root. /root/.ssh/authorized_keys
CMD /usr/sbin/sshd -D

And your docker run contains something like the following to share an auth directory on the host (holding the authorised_keys) with the container then open up the ssh port which will be accessable through port 7001 on the host.

-d -v /home/thatsme/dockerfiles/auth:/root/auth -–publish=127.0.0.1:7001:22

You may want to look at https://github.com/jpetazzo/nsenter which appears to be another way to open a shell on a container and execute commands within a container.

How to test the `Mosquitto` server?

In separate terminal windows do the following:

  1. Start the broker:

    mosquitto
    
  2. Start the command line subscriber:

    mosquitto_sub -v -t 'test/topic'
    
  3. Publish test message with the command line publisher:

    mosquitto_pub -t 'test/topic' -m 'helloWorld'
    

As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:

test/topic helloWorld

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

413 Request Entity Too Large - File Upload Issue

I add the changes directly to my virtualhost instead the global config of nginx, like this:

   server {
     client_max_body_size 100M;
     ...
   }

And then I change the params in php.ini, like the comments above:

   max_input_time = 24000
   max_execution_time = 24000
   upload_max_filesize = 12000M
   post_max_size = 24000M
   memory_limit = 12000M

and what you can not forget is to restart nginx and php-fpm, in centos 7 is like this:

  systemctl restart nginx
  systemctl restart php-fpm

MVC Razor @foreach

When people say don't put logic in views, they're usually referring to business logic, not rendering logic. In my humble opinion, I think using @foreach in views is perfectly fine.

ps command doesn't work in docker container

ps is not installed in the base wheezy image. Try this from within the container:

RUN apt-get update && apt-get install -y procps

Convert ascii char[] to hexadecimal char[] in C

void atoh(char *ascii_ptr, char *hex_ptr,int len)
{
    int i;

    for(i = 0; i < (len / 2); i++)
    {

        *(hex_ptr+i)   = (*(ascii_ptr+(2*i)) <= '9') ? ((*(ascii_ptr+(2*i)) - '0') * 16 ) :  (((*(ascii_ptr+(2*i)) - 'A') + 10) << 4);
        *(hex_ptr+i)  |= (*(ascii_ptr+(2*i)+1) <= '9') ? (*(ascii_ptr+(2*i)+1) - '0') :  (*(ascii_ptr+(2*i)+1) - 'A' + 10);

    }


}

How to add Headers on RESTful call using Jersey Client API

String sBodys="Body";
HashMap<String,String> headers= new HashMap<>();
Client c = Client.create();
WebResource resource = c.resource("http://consulta/rs");
WebResource.Builder builder = resource.accept(MediaType.APPLICATION_JSON);
builder.type(MediaType.APPLICATION_JSON);
if(headers!=null){
      LOGGER.debug("se setean los headers");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
          LOGGER.debug("key: "+entry.getKey());
          LOGGER.debug("value: "+entry.getValue());
          builder.header(key, value);
      }
  }
ClientResponse response = builder.post(ClientResponse.class,sBodys);

Wpf control size to content?

I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.

To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:

<Grid Margin="0,60,10,200">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <controls1:HelpPanel x:Name="HelpInfoPanel"
                         Visibility="Visible"
                         Width="570"
                         HorizontalAlignment="Right"
                         ItemsSource="{Binding HelpItems}"
                         Background="#FF313131" />
</Grid>

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

List supported SSL/TLS versions for a specific OpenSSL build

You can not check for version support via command line. Best option would be checking OpenSSL changelog.

Openssl versions till 1.0.0h supports SSLv2, SSLv3 and TLSv1.0. From Openssl 1.0.1 onward support for TLSv1.1 and TLSv1.2 is added.

psql: FATAL: Peer authentication failed for user "dev"

Peer authentication means that postgres asks the operating system for your login name and uses this for authentication. To login as user "dev" using peer authentication on postgres, you must also be the user "dev" on the operating system.

You can find details to the authentication methods in the Postgresql documentation.

Hint: If no authentication method works anymore, disconnect the server from the network and use method "trust" for "localhost" (and double check that your server is not reachable through the network while method "trust" is enabled).

How can I print the contents of a hash in Perl?

Easy:

print "$_ $h{$_}\n" for (keys %h);

Elegant, but actually 30% slower (!):

while (my ($k,$v)=each %h){print "$k $v\n"}

Submitting a form on 'Enter' with jQuery?

In HTML codes:

<form action="POST" onsubmit="ajax_submit();return false;">
    <b>First Name:</b> <input type="text" name="firstname" id="firstname">
    <br>
    <b>Last Name:</b> <input type="text" name="lastname" id="lastname">
    <br>
    <input type="submit" name="send" onclick="ajax_submit();">
</form>

In Js codes:

function ajax_submit()
{
    $.ajax({
        url: "submit.php",
        type: "POST",
        data: {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            // another codes when result is success
        }
    });
}

Laravel Eloquent - distinct() and count() not working properly together

You can use the following way to get the unique data as per your need as follows,

$data = $ad->getcodes()->get()->unique('email');

$count = $data->count();

Hope this will work.

Maven Jacoco Configuration - Exclude classes/packages from report not working

you can configure the coverage exclusion in the sonar properties, outside of the configuration of the jacoco plugin:

...
<properties>
    ....
    <sonar.exclusions>
        **/generated/**/*,
        **/model/**/*
    </sonar.exclusions>
    <sonar.test.exclusions>
        src/test/**/*
    </sonar.test.exclusions>
    ....
    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
    <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
    <sonar.coverage.exclusions>
        **/generated/**/*,
        **/model/**/*
    </sonar.coverage.exclusions>
    <jacoco.version>0.7.5.201505241946</jacoco.version>
    ....
</properties>
....

and remember to remove the exclusion settings from the plugin

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

How to get all options of a select using jQuery?

If you're looking for all options with some selected text then the below code will work.

$('#test').find("select option:contains('B')").filter(":selected");

React Native - Image Require Module using Dynamic Names

To dynamic image using require

this.state={
       //defualt image
       newimage: require('../../../src/assets/group/kids_room3.png'),
       randomImages=[
         {
            image:require('../../../src/assets/group/kids_room1.png')
          },
         {
            image:require('../../../src/assets/group/kids_room2.png')
          }
        ,
         {
            image:require('../../../src/assets/group/kids_room3.png')
          }
        
        
        ]

}

when press the button-(i select image random number betwenn 0-2))

let setImage=>(){
//set new dynamic image 
this.setState({newimage:this.state.randomImages[Math.floor(Math.random() * 3)];
})
}

view

<Image
        style={{  width: 30, height: 30 ,zIndex: 500 }}
        
        source={this.state.newimage}
      />

How to make a view with rounded corners?

In case you want to round some specific corner.

fun setCorners() {
        
        val mOutlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View, outline: Outline) {

                val left = 0
                val top = 0;
                val right = view.width
                val bottom = view.height
                val cornerRadiusDP = 16f
                val cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, cornerRadiusDP, resources.displayMetrics).toInt()

                // all corners
                outline.setRoundRect(left, top, right, bottom, cornerRadius.toFloat())

                /* top corners
                outline.setRoundRect(left, top, right, bottom+cornerRadius, cornerRadius.toFloat())*/

                /* bottom corners
                outline.setRoundRect(left, top - cornerRadius, right, bottom, cornerRadius.toFloat())*/

                /* left corners
                outline.setRoundRect(left, top, right + cornerRadius, bottom, cornerRadius.toFloat())*/

                /* right corners
                outline.setRoundRect(left - cornerRadius, top, right, bottom, cornerRadius.toFloat())*/

                /* top left corner
                outline.setRoundRect(left , top, right+ cornerRadius, bottom + cornerRadius, cornerRadius.toFloat())*/

                /* top right corner
                outline.setRoundRect(left - cornerRadius , top, right, bottom + cornerRadius, cornerRadius.toFloat())*/

                /* bottom left corner
                outline.setRoundRect(left, top - cornerRadius, right + cornerRadius, bottom, cornerRadius.toFloat())*/

                /* bottom right corner
                outline.setRoundRect(left - cornerRadius, top - cornerRadius, right, bottom, cornerRadius.toFloat())*/

            }
        }

        myView.apply {
            outlineProvider = mOutlineProvider
            clipToOutline = true
        }
    }

How can I escape a double quote inside double quotes?

Store the double quote character in a variable:

dqt='"'
echo "Double quotes ${dqt}X${dqt} inside a double quoted string"

Output:

Double quotes "X" inside a double quoted string

How to clear mysql screen console in windows?

SQL> clear scr

This command clears the screen in MYSQL

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

I fixed this problem.The device system version is older then the sdk minSdkVersion? I just modified the minSdkVersion from android_L to 19 to target my nexus 4.4.4.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'
    }
}
apply plugin: 'com.android.application'

repositories {
    jcenter()
}

android {
    **compileSdkVersion 'android-L'** modified to 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.antwei.uiframework.ui"
        minSdkVersion 14
        targetSdkVersion 'L'
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    **compile 'com.android.support:support-v4:21.+'** modified to compile 'com.android.support:support-v4:20.0.0'
}

how to modified the value by ide. select file->Project Structure -> Facets -> android-gradle and then modified the compile Sdk Version from android_L to 19

sorry I don't have enough reputation to add pictures

How to parse a JSON string into JsonNode in Jackson?

import com.github.fge.jackson.JsonLoader;
JsonLoader.fromString("{\"k1\":\"v1\"}")
== JsonNode = {"k1":"v1"}

What is the easiest way to install BLAS and LAPACK for scipy?

For Debian Jessie and Stretch installing the following packages resolves the issue:

sudo apt install libblas3 liblapack3 liblapack-dev libblas-dev

Your next issue is very likely going to be a missing Fortran compiler, resolve this by installing it like this:

sudo apt install gfortran

If you want an optimized scipy, you can also install the optional libatlas-base-dev package:

sudo apt install libatlas-base-dev

Source


If you have any issue with a missing Python.h file like this:

Python.h: No such file or directory

Then have a look at this post: https://stackoverflow.com/a/21530768/209532

Call a Class From another class

Class2 class2 = new Class2();

Instead of calling the main, perhaps you should call individual methods where and when you need them.

Why catch and rethrow an exception in C#?

It depends what you are doing in the catch block, and if you are wanting to pass the error on to the calling code or not.

You might say Catch io.FileNotFoundExeption ex and then use an alternative file path or some such, but still throw the error on.

Also doing Throw instead of Throw Ex allows you to keep the full stack trace. Throw ex restarts the stack trace from the throw statement (I hope that makes sense).

Is it possible to log all HTTP request headers with Apache?

If you're interested in seeing which specific headers a remote client is sending to your server, and you can cause the request to run a CGI script, then the simplest solution is to have your server script dump the environment variables into a file somewhere.

e.g. run the shell command "env > /tmp/headers" from within your script

Then, look for the environment variables that start with HTTP_...

You will see lines like:

HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_CACHE_CONTROL=max-age=0

Each of those represents a request header.

Note that the header names are modified from the actual request. For example, "Accept-Language" becomes "HTTP_ACCEPT_LANGUAGE", and so on.

How to break out from a ruby block?

I wanted to just be able to break out of a block - sort of like a forward goto, not really related to a loop. In fact, I want to break of of a block that is in a loop without terminating the loop. To do that, I made the block a one-iteration loop:

for b in 1..2 do
    puts b
    begin
        puts 'want this to run'
        break
        puts 'but not this'
    end while false
    puts 'also want this to run'
end

Hope this helps the next googler that lands here based on the subject line.

Can I use git diff on untracked files?

I believe you can diff against files in your index and untracked files by simply supplying the path to both files.

git diff --no-index tracked_file untracked_file

How to give a delay in loop execution using Qt

As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members

  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members

Reading an Excel file in python using pandas

This is much simple and easy way.

import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)

check out documentation full details http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html

FutureWarning: The sheetname keyword is deprecated for newer Pandas versions, use sheet_name instead.

Add new element to an existing object

Just do myFunction.foo = "bar" and it will add it. myFunction is the name of the object in this case.

Visual Studio 2015 installer hangs during install?

I had the same issue. It would hang immediately, as soon as it said "Applying Microsoft Visual Studio 2015." There was only a small sliver in the progress bar. I even let the install run overnight. There was no disk activity or CPU usage from the installer.

What finally worked was to kill the process in Task Manager and restart the computer. As soon as I rebooted, the installer opened up automatically and completed successfully.

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

(13: Permission denied) while connecting to upstream:[nginx]

13-permission-denied-while-connecting-to-upstreamnginx on centos server -

setsebool -P httpd_can_network_connect 1

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

The defaultSelected attribute is not settable, it's just for informational purposes:

Quote:

The defaultSelected property returns the default value of the selected attribute.
This property returns true if an option is selected by default, otherwise it returns false.

I think you want:

$('option[value=valueToSelect]', newOption).attr('selected', 'selected');

I.e. set the selected attribute of the option you want to select.


Without trying to fix your code, here's roughly how I would do it:

function buildSelect(options, default) {
    // assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
    //        default = 'value1'

    var $select = $('<select></select>');
    var $option;

    for (var val in options) {
        $option = $('<option value="' + val + '">' + options[val] + '</option>');
        if (val == default) {
            $option.attr('selected', 'selected');
        }
        $select.append($option);
    }

    return $select;
}

You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.

Paging with LINQ for objects

   ( for o in objects
    where ...
    select new
   {
     A=o.a,
     B=o.b
   })
.Skip((page-1)*pageSize)
.Take(pageSize)

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

jQuery selectors on custom data attributes using HTML5

$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"

$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"

Look in to jQuery Selectors :contains is a selector

here is info on the :contains selector

Magento Product Attribute Get Value

Please see Daniel Kocherga's answer, as it'll work for you in most cases.

In addition to that method to get the attribute's value, you may sometimes want to get the label of a select or multiselect. In that case, I have created this method which I store in a helper class:

/**
 * @param int $entityId
 * @param int|string|array $attribute atrribute's ids or codes
 * @param null|int|Mage_Core_Model_Store $store
 *
 * @return bool|null|string
 * @throws Mage_Core_Exception
 */
public function getAttributeRawLabel($entityId, $attribute, $store=null) {
    if (!$store) {
        $store = Mage::app()->getStore();
    }

    $value = (string)Mage::getResourceModel('catalog/product')->getAttributeRawValue($entityId, $attribute, $store);
    if (!empty($value)) {
        return Mage::getModel('catalog/product')->getResource()->getAttribute($attribute)->getSource()->getOptionText($value);
    }

    return null;
}

Split function equivalent in T-SQL?

This simple CTE will give what's needed:

DECLARE @csv varchar(max) = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15';
--append comma to the list for CTE to work correctly
SET @csv = @csv + ',';
--remove double commas (empty entries)
SET @csv = replace(@csv, ',,', ',');
WITH CteCsv AS (
    SELECT CHARINDEX(',', @csv) idx, SUBSTRING(@csv, 1, CHARINDEX(',', @csv) - 1) [Value]
    UNION ALL
    SELECT CHARINDEX(',', @csv, idx + 1), SUBSTRING(@csv, idx + 1, CHARINDEX(',', @csv, idx + 1) - idx - 1) FROM CteCsv
    WHERE CHARINDEX(',', @csv, idx + 1) > 0
)

SELECT [Value] FROM CteCsv

Why would $_FILES be empty when uploading files to PHP?

I was empty $_FILES because after <form enctype="multipart/form-data" method="post"> i placed

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

Initial code was like

<span class="span_left">Photos (gif/jpg/jpeg/png) </span>
<form enctype="multipart/form-data" method="post">
<input name="files[]" type="file" id="upload_file" />
<input type="button" id="upload" value="Upload photo" />
</form>

I decided to modify and

<div>
<span class="span_left">Photos (gif/jpg/jpeg/png) </span>
<form enctype="multipart/form-data" method="post">
</div>
<div style="clear:both"></div>
<input name="files[]" type="file" id="upload_file" />
<input type="button" id="upload" value="Upload photo" />
</form>
<div style="clear:both"></div>

So conclusion is that after <form enctype="multipart/form-data" method="post"> must be <input name, type, id and must not be <div> or some other tags

In my situation correct code was

<div>
<span class="span_left">Photos (gif/jpg/jpeg/png) </span>
</div>
<div style="clear:both"></div>
<form enctype="multipart/form-data" method="post">
<input name="files[]" type="file" id="upload_file" />
<input type="button" id="upload" value="Upload photo" />
</form>
<div style="clear:both"></div>

Best way to include CSS? Why use @import?

There is almost no reason to use @import as it loads every single imported CSS file separately and can slow your site down significantly. If you are interested in the optimal way to deal with CSS(when it comes to page speed), this is how you should deal with all your CSS code:

  • Open all your CSS files and copy the code of every single file
  • Paste all the code in between a single STYLE tag in the HTML header of your page
  • Never use CSS @import or separate CSS files to deliver CSS unless you have a large amount of code or there is a specific need to.

More detailed information here: http://www.giftofspeed.com/optimize-css-delivery/

The reason the above works best is because it creates less requests for the browser to deal with and it can immediately start rendering the CSS instead of downloading separate files.

Inserting a value into all possible locations in a list

Simplest is use list[i:i]

    a = [1,2, 3, 4]
    a[2:2] = [10]

Print a to check insertion

    print a
    [1, 2, 10, 3, 4]

Convert Mat to Array/Vector in OpenCV

byte * matToBytes(Mat image)
{
   int size = image.total() * image.elemSize();
   byte * bytes = new byte[size];  //delete[] later
   std::memcpy(bytes,image.data,size * sizeof(byte));
}

How to read embedded resource text file

In Visual Studio you can directly embed access to a file resource via the Resources tab of the Project properties ("Analytics" in this example). visual studio screen shot - Resources tab

The resulting file can then be accessed as a byte array by

byte[] jsonSecrets = GoogleAnalyticsExtractor.Properties.Resources.client_secrets_reporter;

Should you need it as a stream, then ( from https://stackoverflow.com/a/4736185/432976 )

Stream stream = new MemoryStream(jsonSecrets)

Visual Studio 2010 always thinks project is out of date, but nothing has changed

If you are using the command-line MSBuild command (not the Visual Studio IDE), for example if you are targetting AppVeyor or you just prefer the command line, you can add this option to your MSBuild command line:

/fileLoggerParameters:LogFile=MyLog.log;Append;Verbosity=diagnostic;Encoding=UTF-8

As documented here (warning: usual MSDN verbosity). When the build finishes, search for the string will be compiled in the log file created during the build, MyLog.log.

Wait until all jQuery Ajax requests are done?

jQuery allows you to specify if you want the ajax request to be asynchronous or not. You can simply make the ajax requests synchronous and then the rest of the code won't execute until they return.

For example:

jQuery.ajax({ 
    async: false,
    //code
});

How to increment variable under DOS?

Indeed, set in DOS has no option to allow for arithmetic. You could do a giant lookup table, though:

if %COUNTER%==249 set COUNTER=250
...
if %COUNTER%==3 set COUNTER=4
if %COUNTER%==2 set COUNTER=3
if %COUNTER%==1 set COUNTER=2
if %COUNTER%==0 set COUNTER=1

Powershell send-mailmessage - email to multiple recipients

$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"

is type of string you need pass to send-mailmessage a string[] type (an array):

[string[]]$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

I think that not casting to string[] do the job for the coercing rules of powershell:

$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

is object[] type but can do the same job.

List all sequences in a Postgres db 8.1 with SQL

select sequence_name, (xpath('/row/last_value/text()', xml_count))[1]::text::int as last_value
from (
    select sequence_schema,
            sequence_name,         
            query_to_xml(format('select last_value from %I.%I', sequence_schema, sequence_name), false, true, '') as xml_count
    from information_schema.sequences
    where sequence_schema = 'public'
) new_table order by last_value desc;

Regular expression for floating point numbers

what you need is:

[\-\+]?[0-9]*(\.[0-9]+)?

I escaped the "+" and "-" sign and also grouped the decimal with its following digits since something like "1." is not a valid number.

The changes will allow you to match integers and floats. for example:

0
+1
-2.0
2.23442