Programs & Examples On #Amazon appstore

The Amazon Appstore is a mobile application store for the Google Android operating system, available internationally.

Count rows with not empty value

=counta(range) 
  • counta: "Returns a count of the number of values in a dataset"

    Note: CountA considers "" to be a value. Only cells that are blank (press delete in a cell to blank it) are not counted.

    Google support: https://support.google.com/docs/answer/3093991

  • countblank: "Returns the number of empty cells in a given range"

    Note: CountBlank considers both blank cells (press delete to blank a cell) and cells that have a formula that returns "" to be empty cells.

    Google Support: https://support.google.com/docs/answer/3093403

If you have a range that includes formulae that result in "", then you can modify your formula from

=counta(range)

to:

=Counta(range) - Countblank(range)

EDIT: the function is countblank, not countblanks, the latter will give an error.

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

For me, I started the app from within windows explorer (by double clicking on it). Then it crashed immediately.

I then opened Event Viewer of windows and viewed Application and it displayed full stacktrace of error. The stacktrace showed relation with Bitmap or images. It was then turned out to be due to app icon not found

How to change the font and font size of an HTML input tag?

In your 'head' section, add this code:

<style>
input[type='text'] { font-size: 24px; }
</style>

Or you can only add the:

input[type='text'] { font-size: 24px; }

to a CSS file which can later be included.

You can also change the font face by using the CSS property: font-family

font-family: monospace;

So you can have a CSS code like this:

input[type='text'] { font-size: 24px; font-family: monospace; }

You can find further help at the W3Schools website.

I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.

SQL Query to search schema of all tables

Use this query :

SELECT 
    t.name AS table_name,
    SCHEMA_NAME(schema_id) AS schema_name,
    c.name AS column_name , *
FROM sys.tables AS t
    INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID 
Where 
    ( c.name LIKE '%' + '<ColumnName>' + '%' )
    AND 
    ( t.type = 'U' ) -- Use This To Prevent Selecting System Tables

Youtube - downloading a playlist - youtube-dl

In a shell, & is a special character, advising the shell to start everything up to the & as a process in the background. To avoid this behavior, you can put the URL in quotes. See the youtube-dl FAQ for more information.

Also beware of -citk. With the exception of -i, these options make little sense. See the youtube-dl FAQ for more information. Even -f mp4 looks very strange.

So what you want is:

youtube-dl -i -f mp4 --yes-playlist 'https://www.youtube.com/watch?v=7Vy8970q0Xc&list=PLwJ2VKmefmxpUJEGB1ff6yUZ5Zd7Gegn2'

Alternatively, you can just use the playlist ID:

youtube-dl -i PLwJ2VKmefmxpUJEGB1ff6yUZ5Zd7Gegn2

Distinct by property of class with LINQ

You can implement an IEqualityComparer and use that in your Distinct extension.

class CarEqualityComparer : IEqualityComparer<Car>
{
    #region IEqualityComparer<Car> Members

    public bool Equals(Car x, Car y)
    {
        return x.CarCode.Equals(y.CarCode);
    }

    public int GetHashCode(Car obj)
    {
        return obj.CarCode.GetHashCode();
    }

    #endregion
}

And then

var uniqueCars = cars.Distinct(new CarEqualityComparer());

Error TF30063: You are not authorized to access ... \DefaultCollection

Make sure your password hasn't coincidentally expired exactly on the same day you decided to install a new dev machine.

If you can't even log into TFS using the web interface then this may be the case.

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

How to calculate the angle between a line and the horizontal axis?

import math
from collections import namedtuple


Point = namedtuple("Point", ["x", "y"])


def get_angle(p1: Point, p2: Point) -> float:
    """Get the angle of this line with the horizontal axis."""
    dx = p2.x - p1.x
    dy = p2.y - p1.y
    theta = math.atan2(dy, dx)
    angle = math.degrees(theta)  # angle is in (-180, 180]
    if angle < 0:
        angle = 360 + angle
    return angle

Testing

For testing I let hypothesis generate test cases.

enter image description here

import hypothesis.strategies as s
from hypothesis import given


@given(s.floats(min_value=0.0, max_value=360.0))
def test_angle(angle: float):
    epsilon = 0.0001
    x = math.cos(math.radians(angle))
    y = math.sin(math.radians(angle))
    p1 = Point(0, 0)
    p2 = Point(x, y)
    assert abs(get_angle(p1, p2) - angle) < epsilon

Disable native datepicker in Google Chrome

You could use:

jQuery('input[type="date"]').live('click', function(e) {e.preventDefault();}).datepicker();

Where can I find documentation on formatting a date in JavaScript?

We can do it manually, its pretty straight and simple.

_x000D_
_x000D_
var today = new Date();_x000D_
    _x000D_
    alert("today :"+today);_x000D_
    _x000D_
    var dd = today.getDate();_x000D_
    alert("dd :"+dd);_x000D_
    _x000D_
    var mm = today.getMonth()+1; //January is 0!_x000D_
    alert("mm :"+mm);_x000D_
    _x000D_
    var yyyy = today.getFullYear();_x000D_
    _x000D_
    alert("yyyy :"+yyyy);_x000D_
    _x000D_
    _x000D_
    var hh = today.getHours();_x000D_
    _x000D_
    alert("hh :"+hh);_x000D_
    _x000D_
    var min = today.getMinutes();_x000D_
    _x000D_
   alert("min :"+min);_x000D_
   _x000D_
   var ss = today.getSeconds();_x000D_
   _x000D_
   alert("ss :"+ss);_x000D_
_x000D_
    if(dd<10) {_x000D_
        dd='0'+dd_x000D_
    } _x000D_
_x000D_
    if(mm<10) {_x000D_
        mm='0'+mm_x000D_
    } _x000D_
_x000D_
  //  today = mm+'/'+dd+'/'+yyyy;_x000D_
    // if you want / instead - then add /_x000D_
  _x000D_
  _x000D_
  today = yyyy + "-" + mm + "-" + dd + " " + hh + ":" + mm + ":" + ss;_x000D_
     today = yyyy + "/" + mm + "/" + dd + " " + hh + ":" + mm + ":" + ss;_x000D_
     // use according to your choice 
_x000D_
_x000D_
_x000D_

javascript: using a condition in switch case

You want to use if statements:

if (liCount === 0) {
    setLayoutState('start');
} else if (liCount <= 5) {
    setLayoutState('upload1Row');
} else if (liCount <= 10) {
    setLayoutState('upload2Rows');
}
$('#UploadList').data('jsp').reinitialise();  

CSS: transition opacity on mouse-out?

I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.

The solution was to start the main text elements with an opacity of 0 and use addClass to inject and transition to an opacity of 1. Then removeClass when clicked on again.

I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)

So in it's most basic form...

.slideDown().addClass("load");
.slideUp().removeClass("load");

Thanks for the help everyone.

Get current url in Angular

other.component.ts

So final correct solution is :

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

    @Component({
      selector: 'app-other',
      templateUrl: './other.component.html',
      styleUrls: ['./other.component.css']
    })

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

        ngOnInit() {
            this.href = this.router.url;
            console.log(this.router.url);
        }
    }

Table with table-layout: fixed; and how to make one column wider

The important thing of table-layout: fixed is that the column widths are determined by the first row of the table.

So

if your table structure is as follow (standard table structure)

<table>
  <thead>
      <tr>
          <th> First column </th>
          <th> Second column </th>
          <th> Third column </th>        
      </tr>
  </thead>

   <tbody>
      <tr>
          <td> First column </td>
          <td> Second column </td>
          <td> Third column </td>        
      </tr>
  </tbody>

if you would like to give a width to second column then

<style> 
    table{
        table-layout:fixed;
        width: 100%;
    }

    table tr th:nth-child(2){
       width: 60%;
     }

</style>

Please look that we style the th not the td.

Get the date of next monday, tuesday, etc

You can use Carbon library.

Example: Next week friday

Carbon::parse("friday next week");

Dynamic array in C#

you can use arraylist object from collections class

using System.Collections;

static void Main()
{
  ArrayList arr = new ArrayList();
}

when you want to add elements you can use

arr.Add();

AngularJS ng-class if-else expression

you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'>

Then put your logic in the function itself :

    $scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
     else
         return "ClassC";
    }

I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Please be advised:

JSONP supports only the GET request method.

*Send request by firefox:*

$.ajax({
   type: 'POST',//<<===
   contentType: 'application/json',
   url: url,
   dataType: "json"//<<=============
    ...
});

Above request send by OPTIONS(while ==>type: 'POST')!!!!

$.ajax({
    type: 'POST',//<<===
    contentType: 'application/json',
    url: url,
    dataType: "jsonp"//<<==============
    ...
});

But above request send by GET(while ==>type: 'POST')!!!!

When you are in "cross-domain communication" , pay attention and be careful.

How do I set the background color of Excel cells using VBA?

You can use either:

ActiveCell.Interior.ColorIndex = 28

or

ActiveCell.Interior.Color = RGB(255,0,0)

How can you get the first digit in an int (C#)?

Try this

public int GetFirstDigit(int number) {
  if ( number < 10 ) {
    return number;
  }
  return GetFirstDigit ( (number - (number % 10)) / 10);
}

EDIT

Several people have requested the loop version

public static int GetFirstDigitLoop(int number)
{
    while (number >= 10)
    {
        number = (number - (number % 10)) / 10;
    }
    return number;
}

The developers of this app have not set up this app properly for Facebook Login?

Hemang's answer was right, BUT, there's one extra step you'll need, which is to add a Facebook App ID. (I discovered I was missing this part): enter image description here

Once you've done that in addition to Hemang's answer, you'll be good to go!

cv2.imshow command doesn't work properly in opencv-python

You must use cv2.waitKey(0) after cv2.imshow("window",img). Only then will it work.

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)

PHP function ssh2_connect is not working

I have solved this on ubuntu 16.4 PHP 7.0.27-0+deb9u and nginx

sudo apt install php-ssh2 

What is the fastest way to send 100,000 HTTP requests in Python?

A good approach to solving this problem is to first write the code required to get one result, then incorporate threading code to parallelize the application.

In a perfect world this would simply mean simultaneously starting 100,000 threads which output their results into a dictionary or list for later processing, but in practice you are limited in how many parallel HTTP requests you can issue in this fashion. Locally, you have limits in how many sockets you can open concurrently, how many threads of execution your Python interpreter will allow. Remotely, you may be limited in the number of simultaneous connections if all the requests are against one server, or many. These limitations will probably necessitate that you write the script in such a way as to only poll a small fraction of the URLs at any one time (100, as another poster mentioned, is probably a decent thread pool size, although you may find that you can successfully deploy many more).

You can follow this design pattern to resolve the above issue:

  1. Start a thread which launches new request threads until the number of currently running threads (you can track them via threading.active_count() or by pushing the thread objects into a data structure) is >= your maximum number of simultaneous requests (say 100), then sleeps for a short timeout. This thread should terminate when there is are no more URLs to process. Thus, the thread will keep waking up, launching new threads, and sleeping until your are finished.
  2. Have the request threads store their results in some data structure for later retrieval and output. If the structure you are storing the results in is a list or dict in CPython, you can safely append or insert unique items from your threads without locks, but if you write to a file or require in more complex cross-thread data interaction you should use a mutual exclusion lock to protect this state from corruption.

I would suggest you use the threading module. You can use it to launch and track running threads. Python's threading support is bare, but the description of your problem suggests that it is completely sufficient for your needs.

Finally, if you'd like to see a pretty straightforward application of a parallel network application written in Python, check out ssh.py. It's a small library which uses Python threading to parallelize many SSH connections. The design is close enough to your requirements that you may find it to be a good resource.

Test if object implements interface

A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:

if (serviceType.IsInstanceOfType(service))
{
    // 'service' does implement the 'serviceType' type
}

How to resize array in C++?

  1. Use std::vector or
  2. Write your own method. Allocate chunk of memory using new. with that memory you can expand till the limit of memory chunk.

Saving an image in OpenCV

I use the following code to capture images:

CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
if(!capture) error((char*)"No Capture");
IplImage *img=cvQueryFrame(capture);

I know this works for sure

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to @Boaz's and @vegemite4me's answers....

By implementing ImplicitNamingStrategy you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder during Hibernate's initialization:

metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());

It works for @UniqueConstraint, but not for @Column(unique = true), which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586

Thanks.

Node.js: How to send headers with form data using request module?

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

Safe String to BigDecimal conversion

String value = "1,000,000,000.999999999999999";
BigDecimal money = new BigDecimal(value.replaceAll(",", ""));
System.out.println(money);

Full code to prove that no NumberFormatException is thrown:

import java.math.BigDecimal;

public class Tester {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String value = "1,000,000,000.999999999999999";
        BigDecimal money = new BigDecimal(value.replaceAll(",", ""));
        System.out.println(money);
    }
}

Output

1000000000.999999999999999

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

if anybody unable to update windows online, I suggest you go to http://download.wsusoffline.net/ and download Most recent version.

Then install update generator -> select your operating system. and hit START, just wait few minutes let him download updates and complete all it's process. hope this help.

Image of Offline update generator

How do you uninstall MySQL from Mac OS X?

If you installed mysql through brew then we can use command to uninstall mysql.

$ brew uninstall mysql

Uninstalling /usr/local/Cellar/mysql/5.6.19...

This worked for me.

SQL Server IF EXISTS THEN 1 ELSE 2

What the output that you need, select or print or .. so on.

so use the following code:

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2

How to scroll to specific item using jQuery?

Dead simple. No plugins needed.

var $container = $('div'),
    $scrollTo = $('#row_8');

$container.scrollTop(
    $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
);

// Or you can animate the scrolling:
$container.animate({
    scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
});?

Here is a working example.

Documentation for scrollTop.

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

XPath test if node value is number

There's an amazing type test operator in XPath 2.0 you can use:

<xsl:if test="$number castable as xs:double">
    <!-- implementation -->
</xsl:if>

How do I use setsockopt(SO_REUSEADDR)?

Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :

   SO_REUSEPORT (since Linux 3.9)
          Permits multiple AF_INET or AF_INET6 sockets to be bound to an
          identical socket address.  This option must be set on each
          socket (including the first socket) prior to calling bind(2)
          on the socket.  To prevent port hijacking, all of the
          processes binding to the same address must have the same
          effective UID.  This option can be employed with both TCP and
          UDP sockets.

As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.

You can set theses two options before calling bind like this :

    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
        perror("setsockopt(SO_REUSEADDR) failed");

#ifdef SO_REUSEPORT
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0) 
        perror("setsockopt(SO_REUSEPORT) failed");
#endif

How to trim white spaces of array values in php

Multidimensional-proof solution:

array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Save and close all Internet Explorer windows and then, run Windows Task Manager to end the running processes in background.
  2. Go to Control Panel.
  3. Click Programs and choose the View installed updates instead.
  4. Locate the following Windows Internet Explorer 11 or you can type "Internet Explorer" for a quick search.
  5. Choose the Yes option from the following "Uninstall an update".
  6. Please wait while Windows Internet Explorer 10 is being restored and reconfigured automatically.
  7. Follow the Microsoft Windows wizard to restart your system.

Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.

Excel: Searching for multiple terms in a cell

Try using COUNT function like this

=IF(COUNT(SEARCH({"Romney","Obama","Gingrich"},C1)),1,"")

Note that you don't need the wildcards (as teylyn says) and unless there's a specific reason "1" doesn't need quotes (in fact that makes it a text value)

Can I catch multiple Java exceptions in the same catch clause?

Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice - exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.

Cannot deserialize the current JSON array (e.g. [1,2,3])

You have an array, convert it to an object, something like:

data: [{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]

How to declare or mark a Java method as deprecated?

Use @Deprecated on method. Don't forget about clarifying javadoc field:

/**
 * Does some thing in old style.
 *
 * @deprecated use {@link #new()} instead.  
 */
@Deprecated
public void old() {
// ...
}

How to send email attachments?

This is the code I ended up using:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders


SUBJECT = "Email Data"

msg = MIMEMultipart()
msg['Subject'] = SUBJECT 
msg['From'] = self.EMAIL_FROM
msg['To'] = ', '.join(self.EMAIL_TO)

part = MIMEBase('application', "octet-stream")
part.set_payload(open("text.txt", "rb").read())
Encoders.encode_base64(part)
    
part.add_header('Content-Disposition', 'attachment; filename="text.txt"')

msg.attach(part)

server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())

Code is much the same as Oli's post.

Code based from Binary file email attachment problem post.

Remove URL parameters without refreshing page

To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:

history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is

This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.

How can I add items to an empty set in python

D = {} is a dictionary not set.

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

Use D = set():

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

Xcode iOS 8 Keyboard types not supported

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

 iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

then the software keyboard will be displayed once again.

Disable text input history

<input type="text" autocomplete="off" />

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

One easy way if you have App icon of size 1024 X 1024. just upload it on below site, It will generate icon folder Add AppIcon.appiconset in to your application.

Step 1:

Upload your existing 1024 X 1024 icon on Below Site :

https://makeappicon.com/

Step 2 :

It will send you mail.

Download icon.zip from email.

Step 3 : Drag and Drop AppIcon.appiconset to your application. It will contain all require icon.

It may help you all.

Edit : I am not owner/ promoter of this site. It will save our time.

iOS start Background Thread

Enable NSZombieEnabled to know which object is being released and then accessed. Then check if the getResultSetFromDB: has anything to do with that. Also check if docids has anything inside and if it is being retained.

This way you can be sure there is nothing wrong.

Camera access through browser

In iOS6, Apple supports this via the <input type="file"> tag. I couldn't find a useful link in Apple's developer documentation, but there's an example here.

It looks like overlays and more advanced functionality is not yet available, but this should work for a lot of use cases.

EDIT: The w3c has a spec that iOS6 Safari seems to implement a subset of. The capture attribute is notably missing.

Writing String to Stream and reading it back does not work

Try this "one-liner" from Delta's Blog, String To MemoryStream (C#).

MemoryStream stringInMemoryStream =
   new MemoryStream(ASCIIEncoding.Default.GetBytes("Your string here"));

The string will be loaded into the MemoryStream, and you can read from it. See Encoding.GetBytes(...), which has also been implemented for a few other encodings.

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

this may be a simpler approach:

(DesiredFigure).get_figure().savefig('figure_name.png')

i.e.

dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')

IF... OR IF... in a windows batch file

While dbenham's answer is pretty good, relying on IF DEFINED can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.

While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF with IF /? reveals that,

The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.

In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR check to me, both in regards to underlying logic and readability. For example:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.

If you wanted to have it all on one line, written-wise, you could just chain them together with && like:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

AngularJS format JSON string output

You can use an optional parameter of JSON.stringify()

JSON.stringify(value[, replacer [, space]])

Parameters

  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

"{
    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4
    }
}"

How to import a csv file into MySQL workbench?

In case you have smaller data set, a way to achieve it by GUI is:

  1. Open a query window
  2. SELECT * FROM [table_name]
  3. Select Import from the menu bar
  4. Press Apply on the bottom right below the Result Grid

enter image description here

Reference: http://www.youtube.com/watch?v=tnhJa_zYNVY

How to get full REST request body using Jersey?

Try this using this single code:

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/serviceX")
public class MyClassRESTService {

    @POST
    @Path("/doSomething")   
    public void someMethod(String x) {

        System.out.println(x);
                // String x contains the body, you can process
                // it, parse it using JAXB and so on ...

    }
}

The url for try rest services ends .... /serviceX/doSomething

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

How do I change select2 box height

I had a similar problem, and most of these solutions are close but no cigar. Here is what works in its simplest form:

.select2-selection {
    min-height: 10px !important;
}

You can set the min-height to what ever you want. The height will expand as needed. I personally found the padding a bit unbalanced, and the font too big, so I added those here also.

span with onclick event inside a tag

<a href="http://the.url.com/page.html">
    <span onclick="hide(); return false">Hide me</span>
</a>

This is the easiest solution.

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Android Supports SSL implementation by default except for Android N (API level 24) and below Android 5.1 (API level 22)
I was getting the error when making the API call below API level 22 devices after implementing SSL at the server side; that was while creating OkHttpClient client object, and fixed by adding connectionSpecs() method OkHttpClient.Builder class.

the error received was

response failure: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8882c00: I/O error during system call, Connection reset by peer

so I fixed this by added the check like

if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
            // Do something for below api level 22
            List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
            if (specsList != null) {
                okb.connectionSpecs(specsList);
            }
        }

Also for the Android N (API level 24); I was getting the error while making the HTTP call like

HTTP FAILED: javax.net.ssl.SSLHandshakeException: Handshake failed

and this is fixed by adding the check for Android 7 particularly, like

if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
            // Do something for naugat ; 7
            okb.connectionSpecs(Collections.singletonList(getSpec()));
        }

So my final OkHttpClient object will be like:

         OkHttpClient client
         HttpLoggingInterceptor httpLoggingInterceptor2 = new
         HttpLoggingInterceptor();
         httpLoggingInterceptor2.setLevel(HttpLoggingInterceptor.Level.BODY);

         OkHttpClient.Builder okb = new OkHttpClient.Builder()
                 .addInterceptor(httpLoggingInterceptor2)
               .addInterceptor(new Interceptor() {
                     @Override
                     public Response intercept(Chain chain) throws IOException {
                         Request request = chain.request();
                         Request request2 = request.newBuilder().addHeader(AUTH_KEYWORD, AUTH_TYPE_JW + " " + password).build();
                         return chain.proceed(request2);
                     }
                 }).connectTimeout(30, TimeUnit.SECONDS)
                 .writeTimeout(30, TimeUnit.SECONDS)
                 .readTimeout(30, TimeUnit.SECONDS);

         if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.N){
             // Do something for naugat ; 7
             okb.connectionSpecs(Collections.singletonList(getSpec()));
         }

         if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
             List<ConnectionSpec> specsList = getSpecsBelowLollipopMR1(okb);
             if (specsList != null) {
                 okb.connectionSpecs(specsList);
             }
         }

         //init client
         client = okb.build();

getSpecsBelowLollipopMR1 function be like,

   private List<ConnectionSpec> getSpecsBelowLollipopMR1(OkHttpClient.Builder okb) {

        try {

            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, null, null);
            okb.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()));

            ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .build();

            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(cs);
            specs.add(ConnectionSpec.COMPATIBLE_TLS);

            return specs;

        } catch (Exception exc) {
            Timber.e("OkHttpTLSCompat Error while setting TLS 1.2"+ exc);

            return null;
        }
    }

The Tls12SocketFactory class will be found in below link (comment by gotev):

https://github.com/square/okhttp/issues/2372


For more support adding some links below this will help you in detail,

https://developer.android.com/training/articles/security-ssl

D/OkHttp: <-- HTTP FAILED: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0x64e3c938: I/O error during system call, Connection reset by peer

OTP (token) should be automatically read from the message

Yes, this is possible now in browsers also. Chrome release this feature in version 84 and above. With the help of WEBOTP API, we can detect OTP on the web for mobile devices.

Here is a Web-OTP integrated code with Angular PWA Apps: https://github.com/Rohit3230/webOtpAutoReadByAngular

Go for live working URL for angular PWA app. https://rohit3230.github.io/webOtpAutoReadByAngular/

compare two list and return not matching items using linq

As an extension method

public static IEnumerable<TSource> AreNotEqual<TSource, TKey, TTarget>(this IEnumerable<TSource> source, Func<TSource, TKey> sourceKeySelector, IEnumerable<TTarget> target, Func<TTarget, TKey> targetKeySelector) 
{
    var targetValues = new HashSet<TKey>(target.Select(targetKeySelector));

    return source.Where(sourceValue => targetValues.Contains(sourceKeySelector(sourceValue)) == false);
}

eg.

public class Customer
{
    public int CustomerId { get; set; }
}

public class OtherCustomer
{
    public int Id { get; set; }
}


var customers = new List<Customer>()
{
    new Customer() { CustomerId = 1 },
    new Customer() { CustomerId = 2 }
};

var others = new List<OtherCustomer>()
{
    new OtherCustomer() { Id = 2 },
    new OtherCustomer() { Id = 3 }
};

var result = customers.AreNotEqual(customer => customer.CustomerId, others, other => other.Id).ToList();

Debug.Assert(result.Count == 1);
Debug.Assert(result[0].CustomerId == 1);

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

How to detect DataGridView CheckBox event change?

following Killercam'answer, My code

private void dgvProducts_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dgvProducts.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

and :

private void dgvProducts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (dgvProducts.DataSource != null)
        {
            if (dgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "True")
            {
                //do something
            }
            else
            {
               //do something
            }
        }
    }

Section vs Article HTML5

I like to stick with the standard meaning of the words used: An article would apply to, well, articles. I would define blog posts, documents, and news articles as articles. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.

Supporting this, the w3c defines an article element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.

Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.

What’s more problematic is that article and section are so very similar. All that separates them is the word “self-contained”. Deciding which element to use would be easy if there were some hard and fast rules. Instead, it’s a matter of interpretation. You can have multiple articles within a section, you can have multiple sections within and article, you can nest sections within sections and articles within sections. It’s up to you to decide which element is the most semantically appropriate in any given situation.

Here is a very good answer to the same question here on SO

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

Why are my PHP files showing as plain text?

Yet another reason (not for this case, but maybe it'll save some nerves for someone) is that in PHP 5.5 short open tags <? phpinfo(); ?> are disabled by default.

So the PHP interpreter would process code within short tags as plain text. In previous versions PHP this feature was enable by default. So the new behaviour can be a little bit mysterious.

Call a stored procedure with parameter in c#

public void myfunction(){
        try
        {
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlcon.Close();
        }
}

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

"Fade" borders in CSS

You could also use box-shadow property with higher value of blur and rgba() color to set opacity level. Sounds like a better choice in your case.

box-shadow: 0 30px 40px rgba(0,0,0,.1);

Passing enum or object through an intent (the best solution)

Most of the answers that are using Parcelable concept here are in Java code. It is easier to do it in Kotlin.

Just annotate your enum class with @Parcelize and implement Parcelable interface.

@Parcelize
enum class ViewTypes : Parcelable {
TITLE, PRICES, COLORS, SIZES
}

How to get screen width and height

    int scrWidth  = getWindowManager().getDefaultDisplay().getWidth();
    int scrHeight = getWindowManager().getDefaultDisplay().getHeight();

Responsive design with media query : screen size?

Take a look at this... http://getbootstrap.com/

For big websites I use Bootstrap and sometimes (for simple websites) I create all the style with some @mediaqueries. It's very simple, just think all the code in percentage.

.container {
max-width: 1200px;
width: 100%;
margin: 0 auto;
}

Inside the container, your structure must have widths in percentage like this...

.col-1 {
width: 40%;
float: left;
}

.col-2 {
width: 60%;
float: left;
}

@media screen and (max-width: 320px) {
.col-1, .col-2 { width: 100%; }
}

In some simple interfaces, if you start to develop the project in this way, you will have great chances to have a fully responsive site using break points only to adjust the flow of objects.

Determine number of pages in a PDF file

I have good success using CeTe Dynamic PDF products. They're not free, but are well documented. They did the job for me.

http://www.dynamicpdf.com/

Mac OS X - EnvironmentError: mysql_config not found

This answer is for MacOS users who did not install from brew but rather from the official .dmg/.pkg. That installer fails to edit your PATH, causing things to break out of the box:

  1. All MySQL commands like mysql, mysqladmin, mysql_config, etc cannot be found, and as a result:
  2. the "MySQL Preference Pane" fails to appear in System Preferences, and
  3. you cannot install any API that communicates with MySQL, including mysqlclient

What you have to do is appending the MySQL bin folder (typically /usr/local/mysql/bin in your PATH by adding this line in your ~/.bash_profile file:

export PATH="/usr/local/mysql/bin/:$PATH"

You should then reload your ~/.bash_profile for the change to take effect in your current Terminal session:

source ~/.bash_profile

Before installing mysqlclient, however, you need to accept the XcodeBuild license:

sudo xcodebuild -license

Follow their directions to sign away your family, after which you should be able to install mysqlclient without issue:

pip install mysqlclient

After installing that, you must do one more thing to fix a runtime bug that ships with MySQL (Dynamic Library libmysqlclient.dylib not found), by adding this line to your system dynamic libraries path:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/:$DYLD_LIBRARY_PATH

Renaming a directory in C#

You should move it:

Directory.Move(source, destination);

Copy a file from one folder to another using vbscripting

Here's an answer, based on (and I think an improvement on) Tester101's answer, expressed as a subroutine, with the CopyFile line once instead of three times, and prepared to handle changing the file name as the copy is made (no hard-coded destination directory). I also found I had to delete the target file before copying to get this to work, but that might be a Windows 7 thing. The WScript.Echo statements are because I didn't have a debugger and can of course be removed if desired.

Sub CopyFile(SourceFile, DestinationFile)

    Set fso = CreateObject("Scripting.FileSystemObject")

    'Check to see if the file already exists in the destination folder
    Dim wasReadOnly
    wasReadOnly = False
    If fso.FileExists(DestinationFile) Then
        'Check to see if the file is read-only
        If fso.GetFile(DestinationFile).Attributes And 1 Then 
            'The file exists and is read-only.
            WScript.Echo "Removing the read-only attribute"
            'Remove the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
            wasReadOnly = True
        End If

        WScript.Echo "Deleting the file"
        fso.DeleteFile DestinationFile, True
    End If

    'Copy the file
    WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
    fso.CopyFile SourceFile, DestinationFile, True

    If wasReadOnly Then
        'Reapply the read-only attribute
        fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
    End If

    Set fso = Nothing

End Sub

Laravel form html with PUT method for PUT routes

Is very easy, you just need to use method_field('PUT') like this:

HTML:

<form action="{{ route('route_name') }}" method="post">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
</form>

or

<form action="{{ route('route_name') }}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Regards!

My Routes are Returning a 404, How can I Fix Them?

you must be using Laravel 5 the command

  class User_Controller extends Controller {
  public $restful = true;
  public function get_index(){
  return View('user.index');
  }
  }

and in routes.php

  Route::get('/', function()
  {
  return view('home.index');
  });

  Route::get('user', function()
  {
  return view('user.index');
  });

Laravel 5 command changes for view and controller see the documentation i was having same error before

Add class to an element in Angular 4

Use [ngClass] and conditionally apply class based on the id.

In your HTML file:

<li>
    <img [ngClass]="{'this-is-a-class': id === 1 }" id="1"  
         src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
    <img [ngClass]="{'this-is-a-class': id === 2 }" id="2"  
         src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>

In your TypeScript file:

addClass(id: any) {
    this.id = id;
}

Allow access permission to write in Program Files of Windows 7

I think there is an alternate solution to all these problems.... Make an two level application. As said above...

1) Launcher which will launch another Main App using code such as (VB)

Call ShellExecute(hwnd, "runas", App.Path & "\MainApp.exe", 0, 0, vbNormalFocus)

2) Main App, which is writing to protected areas, ie Program Files folder

I've successfully tried this with windows 7

I'm also developing an app which has online update feature. But it doesn't work in Vista/W7..

I agree with other peoples about Microsoft Policies and Standard Practices.

But my Question is .. 1) How to apply update to an existing application, which probably always remain in Program Files folder. 2) There might be some way to do this, otherwise how goolge updater, antivirus updater or any software updater workes?

I need answer to my questions..... :o

Prof. Rajendra Khope (MIT, Pune, India)

Manually raising (throwing) an exception in Python

In Python3 there are 4 different syntaxes for rasing exceptions:

1. raise exception 
2. raise exception (args) 
3. raise
4. raise exception (args) from original_exception

1. raise exception vs. 2. raise exception (args)

If you use raise exception (args) to raise an exception then the args will be printed when you print the exception object - as shown in the example below.

  #raise exception (args)
    try:
        raise ValueError("I have raised an Exception")
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error I have raised an Exception 



  #raise execption 
    try:
        raise ValueError
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error 

3.raise

raise statement without any arguments re-raises the last exception. This is useful if you need to perform some actions after catching the exception and then want to re-raise it. But if there was no exception before, raise statement raises TypeError Exception.

def somefunction():
    print("some cleaning")

a=10
b=0 
result=None

try:
    result=a/b
    print(result)

except Exception:            #Output ->
    somefunction()           #some cleaning
    raise                    #Traceback (most recent call last):
                             #File "python", line 8, in <module>
                             #ZeroDivisionError: division by zero

4. raise exception (args) from original_exception

This statement is used to create exception chaining in which an exception that is raised in response to another exception can contain the details of the original exception - as shown in the example below.

class MyCustomException(Exception):
pass

a=10
b=0 
reuslt=None
try:
    try:
        result=a/b

    except ZeroDivisionError as exp:
        print("ZeroDivisionError -- ",exp)
        raise MyCustomException("Zero Division ") from exp

except MyCustomException as exp:
        print("MyException",exp)
        print(exp.__cause__)

Output:

ZeroDivisionError --  division by zero
MyException Zero Division 
division by zero

calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

How to check if a json key exists?

A better way, instead of using a conditional like:

if (json.has("club")) {
    String club = json.getString("club"));
 }

is to simply use the existing method optString(), like this:

String club = json.optString("club);

the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.

Ansible playbook shell output

If you need a specific exit status, Ansible provides a way to do that via callback plugins.

Example. It's a very good option if you need a 100% accurate exit status.

If not, you can always use the Debug Module, which is the standard for this cases of use.

Cheers

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Print second last column/field in awk

It's simplest:

 awk '{print $--NF}' 

The reason the original $NF-- didn't work is because the expression is evaluated before the decrement, whereas my prefix decrement is performed before evaluation.

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

How to add image for button in android?

Put your Image in drawable folder. Here my image file name is left.png

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="118dp"
    android:layout_y="95dp"
    android:background="@drawable/left"
    android:onClick="toast"
    android:text=" " />

How do I make text bold in HTML?

You're nearly there!

For a bold text, you should have this: <b> bold text</b> or <strong>bold text</strong> They have the same result.

Working example - JSfiddle

How can I convert String to Int?

As explained in the TryParse documentation, TryParse() returns a Boolean which indicates that a valid number was found:

bool success = Int32.TryParse(TextBoxD1.Text, out val);

if (success)
{
    // Put val in database
}
else
{
    // Handle the case that the string doesn't contain a valid number
}

Advantages of std::for_each over for loop

Like many of the algorithm functions, an initial reaction is to think it's more unreadable to use foreach than a loop. It's been a topic of many flame wars.

Once you get used to the idiom you may find it useful. One obvious advantage is that it forces the coder to separate the inner contents of the loop from the actual iteration functionality. (OK, I think it's an advantage. Other's say you're just chopping up the code with no real benifit).

One other advantage is that when I see foreach, I know that either every item will be processed or an exception will be thrown.

A for loop allows several options for terminating the loop. You can let the loop run its full course, or you can use the break keyword to explicitly jump out of the loop, or use the return keyword to exit the entire function mid-loop. In contrast, foreach does not allow these options, and this makes it more readable. You can just glance at the function name and you know the full nature of the iteration.

Here's an example of a confusing for loop:

for(std::vector<widget>::iterator i = v.begin(); i != v.end(); ++i)
{
   /////////////////////////////////////////////////////////////////////
   // Imagine a page of code here by programmers who don't refactor
   ///////////////////////////////////////////////////////////////////////
   if(widget->Cost < calculatedAmountSofar)
   {
        break;
   }
   ////////////////////////////////////////////////////////////////////////
   // And then some more code added by a stressed out juniour developer
   // *#&$*)#$&#(#)$#(*$&#(&*^$#(*$#)($*#(&$^#($*&#)$(#&*$&#*$#*)$(#*
   /////////////////////////////////////////////////////////////////////////
   for(std::vector<widgetPart>::iterator ip = widget.GetParts().begin(); ip != widget.GetParts().end(); ++ip)
   {
      if(ip->IsBroken())
      {
         return false;
      }
   }
}

How to make Regular expression into non-greedy?

You are right that greediness is an issue:

--A--Z--A--Z--
  ^^^^^^^^^^
     A.*Z

If you want to match both A--Z, you'd have to use A.*?Z (the ? makes the * "reluctant", or lazy).

There are sometimes better ways to do this, though, e.g.

A[^Z]*+Z

This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.

In your case, the regex would be:

/(\[[^\]]++\])/

Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:

/(\[[^\]]+\])/

See also


Quick summary

*   Zero or more, greedy
*?  Zero or more, reluctant
*+  Zero or more, possessive

+   One or more, greedy
+?  One or more, reluctant
++  One or more, possessive

?   Zero or one, greedy
??  Zero or one, reluctant
?+  Zero or one, possessive

Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m} constructs.

Examples in Java:

System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!"));  // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"

System.out.println("xxxxxx".replaceAll("x{3,5}", "Y"));  // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"

How to check if the key pressed was an arrow key in Java KeyListener?

You should be using things like: KeyEvent.VK_UP instead of the actual code.

How are you wanting to refactor it? What is the goal of the refactoring?

How does database indexing work?

Just think of Database Index as Index of a book.

If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast.

Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for.

In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where 0x77129 is the address on the disk where the row data for German Shepherd is stored.

In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.

Python basics printing 1 to 100

x=1 while x<=100: print(x) x=x+3

Why is there no SortedList in Java?

I think all the above do not answer this question due to following reasons,

  1. Since same functionality can be achieved by using other collections such as TreeSet, Collections, PriorityQueue..etc (but this is an alternative which will also impose their constraints i.e. Set will remove duplicate elements. Simply saying even if it does not impose any constraint, it does not answer the question why SortedList was not created by java community)
  2. Since List elements do not implements compare/equals methods (This holds true for Set & Map also where in general items do not implement Comparable interface but when we need these items to be in sorted order & want to use TreeSet/TreeMap,items should implement Comparable interface)
  3. Since List uses indexing & due to sorting it won't work (This can be easily handled introducing intermediate interface/abstract class)

but none has told the exact reason behind it & as I believe these kind of questions can be best answered by java community itself as it will have only one & specific answer but let me try my best to answer this as following,

As we know sorting is an expensive operation and there is a basic difference between List & Set/Map that List can have duplicates but Set/Map can not. This is the core reason why we have got a default implementation for Set/Map in form of TreeSet/TreeMap. Internally this is a Red Black Tree with every operation (insert/delete/search) having the complexity of O(log N) where due to duplicates List could not fit in this data storage structure.

Now the question arises we could also choose a default sorting method for List also like MergeSort which is used by Collections.sort(list) method with the complexity of O(N log N). Community did not do this deliberately since we do have multiple choices for sorting algorithms for non distinct elements like QuickSort, ShellSort, RadixSort...etc. In future there can be more. Also sometimes same sorting algorithm performs differently depending on the data to be sorted. Therefore they wanted to keep this option open and left this on us to choose. This was not the case with Set/Map since O(log N) is the best sorting complexity.

How to select the first element in the dropdown using jquery?

What you want is probably:

$("select option:first-child")

What this code

attr("selected", "selected");

is doing is setting the "selected" attribute to "selected"

If you want the selected options, regardless of whether it is the first-child, the selector is:

$("select").children("[selected]")

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

iPhone SDK on Windows (alternative solutions)

Technically you can write code in a .NET language and use the Mono Framework (http://www.mono-project.com/) to run it on the iPhone. I haven't ever seen someone do this from scratch, but the folks that write the Unity Game Development platform (http://unity3d.com/) use it to make their games iPhone-compatible. The game itself is written in .NET, and then they provide an iPhone shell with the Mono frameworks that allows everything to run on the iPhone. I don't know whether they've contributed all of their modifications to Mono back to the open-source repository, but if you're serious about writing iPhone apps outside the Mac environment, it might be possible.

That said, I think you could dump weeks into getting that to work, and it might be best to invest in a Mac instead :-)

Invoke-customs are only supported starting with android 0 --min-api 26

In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_10
    targetCompatibility JavaVersion.VERSION_1_10

}

How to use Oracle ORDER BY and ROWNUM correctly?

An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.

select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo) 
limit 1

My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...

SQLer

Change values of select box of "show 10 entries" of jquery datatable

if you click some button,then change the datatables the displaylenght,you can try this :

 $('.something').click( function () {
var oSettings = oTable.fnSettings();
oSettings._iDisplayLength = 50;
oTable.fnDraw();
});

oTable = $('#example').dataTable();

AWS Lambda import module error in python

My problem was that the .py file and dependencies were not in the zip's "root" directory. e.g the path of libraries and lambda function .py must be:

<lambda_function_name>.py
<name of library>/foo/bar/

not

/foo/bar/<name of library>/foo2/bar2

For example:

drwxr-xr-x  3.0 unx        0 bx stor 20-Apr-17 19:43 boto3/ec2/__pycache__/
-rw-r--r--  3.0 unx      192 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/__init__.cpython-37.pyc
-rw-r--r--  3.0 unx      758 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/deletetags.cpython-37.pyc
-rw-r--r--  3.0 unx      965 bx defX 20-Apr-17 19:43 boto3/ec2/__pycache__/createtags.cpython-37.pyc
-rw-r--r--  3.0 unx     7781 tx defN 20-Apr-17 20:33 download-cs-sensors-to-s3.py

Bootstrap 3 only for mobile

You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only

function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}   
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);
}
}

and

$(document).ready(function() {
$(window).resize(resize);
resize();   

if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
});

Using %s in C correctly - very basic level

Here goes:

char str[] = "This is the end";
char input[100];

printf("%s\n", str);
printf("%c\n", *str);

scanf("%99s", input);

How to serialize an object to XML without getting xmlns="..."?

If you are unable to get rid of extra xmlns attributes for each element, when serializing to xml from generated classes (e.g.: when xsd.exe was used), so you have something like:

<manyElementWith xmlns="urn:names:specification:schema:xsd:one" />

then i would share with you what worked for me (a mix of previous answers and what i found here)

explicitly set all your different xmlns as follows:

Dim xmlns = New XmlSerializerNamespaces()
xmlns.Add("one", "urn:names:specification:schema:xsd:one")
xmlns.Add("two",  "urn:names:specification:schema:xsd:two")
xmlns.Add("three",  "urn:names:specification:schema:xsd:three")

then pass it to the serialize

serializer.Serialize(writer, object, xmlns);

you will have the three namespaces declared in the root element and no more needed to be generated in the other elements which will be prefixed accordingly

<root xmlns:one="urn:names:specification:schema:xsd:one" ... />
   <one:Element />
   <two:ElementFromAnotherNameSpace /> ...

What is Unicode, UTF-8, UTF-16?

Why do we need Unicode?

In the (not too) early days, all that existed was ASCII. This was okay, as all that would ever be needed were a few control characters, punctuation, numbers and letters like the ones in this sentence. Unfortunately, today's strange world of global intercommunication and social media was not foreseen, and it is not too unusual to see English, ???????, ??, ????????, e???????, and ????????? in the same document (I hope I didn't break any old browsers).

But for argument's sake, lets say Joe Average is a software developer. He insists that he will only ever need English, and as such only wants to use ASCII. This might be fine for Joe the user, but this is not fine for Joe the software developer. Approximately half the world uses non-Latin characters and using ASCII is arguably inconsiderate to these people, and on top of that, he is closing off his software to a large and growing economy.

Therefore, an encompassing character set including all languages is needed. Thus came Unicode. It assigns every character a unique number called a code point. One advantage of Unicode over other possible sets is that the first 256 code points are identical to ISO-8859-1, and hence also ASCII. In addition, the vast majority of commonly used characters are representable by only two bytes, in a region called the Basic Multilingual Plane (BMP). Now a character encoding is needed to access this character set, and as the question asks, I will concentrate on UTF-8 and UTF-16.

Memory considerations

So how many bytes give access to what characters in these encodings?

  • UTF-8:
    • 1 byte: Standard ASCII
    • 2 bytes: Arabic, Hebrew, most European scripts (most notably excluding Georgian)
    • 3 bytes: BMP
    • 4 bytes: All Unicode characters
  • UTF-16:
    • 2 bytes: BMP
    • 4 bytes: All Unicode characters

It's worth mentioning now that characters not in the BMP include ancient scripts, mathematical symbols, musical symbols, and rarer Chinese/Japanese/Korean (CJK) characters.

If you'll be working mostly with ASCII characters, then UTF-8 is certainly more memory efficient. However, if you're working mostly with non-European scripts, using UTF-8 could be up to 1.5 times less memory efficient than UTF-16. When dealing with large amounts of text, such as large web-pages or lengthy word documents, this could impact performance.

Encoding basics

Note: If you know how UTF-8 and UTF-16 are encoded, skip to the next section for practical applications.

  • UTF-8: For the standard ASCII (0-127) characters, the UTF-8 codes are identical. This makes UTF-8 ideal if backwards compatibility is required with existing ASCII text. Other characters require anywhere from 2-4 bytes. This is done by reserving some bits in each of these bytes to indicate that it is part of a multi-byte character. In particular, the first bit of each byte is 1 to avoid clashing with the ASCII characters.
  • UTF-16: For valid BMP characters, the UTF-16 representation is simply its code point. However, for non-BMP characters UTF-16 introduces surrogate pairs. In this case a combination of two two-byte portions map to a non-BMP character. These two-byte portions come from the BMP numeric range, but are guaranteed by the Unicode standard to be invalid as BMP characters. In addition, since UTF-16 has two bytes as its basic unit, it is affected by endianness. To compensate, a reserved byte order mark can be placed at the beginning of a data stream which indicates endianness. Thus, if you are reading UTF-16 input, and no endianness is specified, you must check for this.

As can be seen, UTF-8 and UTF-16 are nowhere near compatible with each other. So if you're doing I/O, make sure you know which encoding you are using! For further details on these encodings, please see the UTF FAQ.

Practical programming considerations

Character and String data types: How are they encoded in the programming language? If they are raw bytes, the minute you try to output non-ASCII characters, you may run into a few problems. Also, even if the character type is based on a UTF, that doesn't mean the strings are proper UTF. They may allow byte sequences that are illegal. Generally, you'll have to use a library that supports UTF, such as ICU for C, C++ and Java. In any case, if you want to input/output something other than the default encoding, you will have to convert it first.

Recommended/default/dominant encodings: When given a choice of which UTF to use, it is usually best to follow recommended standards for the environment you are working in. For example, UTF-8 is dominant on the web, and since HTML5, it has been the recommended encoding. Conversely, both .NET and Java environments are founded on a UTF-16 character type. Confusingly (and incorrectly), references are often made to the "Unicode encoding", which usually refers to the dominant UTF encoding in a given environment.

Library support: The libraries you are using support some kind of encoding. Which one? Do they support the corner cases? Since necessity is the mother of invention, UTF-8 libraries will generally support 4-byte characters properly, since 1, 2, and even 3 byte characters can occur frequently. However, not all purported UTF-16 libraries support surrogate pairs properly since they occur very rarely.

Counting characters: There exist combining characters in Unicode. For example the code point U+006E (n), and U+0303 (a combining tilde) forms ñ, but the code point U+00F1 forms ñ. They should look identical, but a simple counting algorithm will return 2 for the first example, 1 for the latter. This isn't necessarily wrong, but may not be the desired outcome either.

Comparing for equality: A, А, and Α look the same, but they're Latin, Cyrillic, and Greek respectively. You also have cases like C and Ⅽ, one is a letter, the other a Roman numeral. In addition, we have the combining characters to consider as well. For more info see Duplicate characters in Unicode.

Surrogate pairs: These come up often enough on SO, so I'll just provide some example links:

Others?:

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

This above does not work because sometimes

$(this).attr('checked') == undefined

adjust your code with

if(!$(this).attr('checked') || $(this).attr('checked') == false){

AngularJS : The correct way of binding to a service properties

I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.

jQuery datepicker, onSelect won't work

The function datepicker is case sensitive and all lowercase. The following however works fine for me:

$(document).ready(function() {
  $('.date-pick').datepicker( {
    onSelect: function(date) {
        alert(date);
    },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1
  });
});

How do I align spans or divs horizontally?

I would do it something like this as it gives you 3 even sized columns, even spacing and (even) scales. Note: This is not tested so it might need tweaking for older browsers.

<style>
html, body {
    margin: 0;
    padding: 0;
}

.content {
    float: left;
    width: 30%;
    border:none;
}

.rightcontent {
    float: right;
    width: 30%;
    border:none
}

.hspacer {
    width:5%;
    float:left;
}

.clear {
    clear:both;
}
</style>

<div class="content">content</div>
<div class="hspacer">&nbsp;</div>
<div class="content">content</div>
<div class="hspacer">&nbsp;</div>
<div class="rightcontent">content</div>
<div class="clear"></div>

Split string into array of character strings

If the original string contains supplementary Unicode characters, then split() would not work, as it splits these characters into surrogate pairs. To correctly handle these special characters, a code like this works:

String[] chars = new String[stringToSplit.codePointCount(0, stringToSplit.length())];
for (int i = 0, j = 0; i < stringToSplit.length(); j++) {
    int cp = stringToSplit.codePointAt(i);
    char c[] = Character.toChars(cp);
    chars[j] = new String(c);
    i += Character.charCount(cp);
}

Reverse a string in Java

As others have pointed out the preferred way is to use:

new StringBuilder(hi).reverse().toString()

But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.

The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.

This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).

public static String reverseString(String s) {
    char[] chars = new char[s.length()];
    boolean twoCharCodepoint = false;
    for (int i = 0; i < s.length(); i++) {
        chars[s.length() - 1 - i] = s.charAt(i);
        if (twoCharCodepoint) {
            swap(chars, s.length() - 1 - i, s.length() - i);
        }
        twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
    }
    return new String(chars);
}

private static void swap(char[] array, int i, int j) {
    char temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
    StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
    sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
    sb.append(".");
    fos.write(sb.toString().getBytes("UTF-16"));
    fos.write("\n".getBytes("UTF-16"));
    fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}

How to get just the date part of getdate()?

try this:

select convert (date ,getdate())

or

select CAST (getdate() as DATE)

or

select convert(varchar(10), getdate(),121)

How can I save an image with PIL?

I know that this is old, but I've found that (while using Pillow) opening the file by using open(fp, 'w') and then saving the file will work. E.g:

with open(fp, 'w') as f:
    result.save(f)

fp being the file path, of course.

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

For the record, Dart 2.3 added the ability to use if/else statements in Collection literals. This is now done the following way:

return Column(children: <Widget>[
  Text("hello"),
  if (condition)
     Text("should not render if false"),
  Text("world")
],);

Flutter Issue #28181 - Inline conditional rendering in list

Eclipse Optimize Imports to Include Static Imports

Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to

Window->Preferences->Java->Editor->Content Assist

and check the checkbox for Use static imports (only 1.5 or higher).

This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.

Accessing variables from other functions without using global variables

If another function needs to use a variable you pass it to the function as an argument.

Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.

How to customize Bootstrap 3 tab color

_x000D_
_x000D_
.panel.with-nav-tabs .panel-heading {_x000D_
  padding: 5px 5px 0 5px;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-tabs {_x000D_
  border-bottom: none;_x000D_
}_x000D_
_x000D_
.panel.with-nav-tabs .nav-justified {_x000D_
  margin-bottom: -1px;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DEFAULT ***/_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li>a:focus {_x000D_
  color: #777;_x000D_
  background-color: #ddd;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.active>a:focus {_x000D_
  color: #555;_x000D_
  background-color: #fff;_x000D_
  border-color: #ddd;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f5f5f5;_x000D_
  border-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-default .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #555;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL PRIMARY ***/_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3071a9;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.active>a:focus {_x000D_
  color: #428bca;_x000D_
  background-color: #fff;_x000D_
  border-color: #428bca;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #428bca;_x000D_
  border-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #3071a9;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-primary .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  background-color: #4a9fe9;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL SUCCESS ***/_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #d6e9c6;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.active>a:focus {_x000D_
  color: #3c763d;_x000D_
  background-color: #fff;_x000D_
  border-color: #d6e9c6;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #dff0d8;_x000D_
  border-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #3c763d;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #d6e9c6;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-success .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #3c763d;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL INFO ***/_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #bce8f1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.active>a:focus {_x000D_
  color: #31708f;_x000D_
  background-color: #fff;_x000D_
  border-color: #bce8f1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #d9edf7;_x000D_
  border-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #31708f;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #bce8f1;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-info .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #31708f;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL WARNING ***/_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #faebcc;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.active>a:focus {_x000D_
  color: #8a6d3b;_x000D_
  background-color: #fff;_x000D_
  border-color: #faebcc;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #fcf8e3;_x000D_
  border-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #8a6d3b;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #faebcc;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-warning .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  background-color: #8a6d3b;_x000D_
}_x000D_
_x000D_
_x000D_
/********************************************************************/_x000D_
_x000D_
_x000D_
/*** PANEL DANGER ***/_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>.open>a:focus,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #ebccd1;_x000D_
  border-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.active>a:focus {_x000D_
  color: #a94442;_x000D_
  background-color: #fff;_x000D_
  border-color: #ebccd1;_x000D_
  border-bottom-color: transparent;_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu {_x000D_
  background-color: #f2dede;_x000D_
  /* bg color */_x000D_
  border-color: #ebccd1;_x000D_
  /* border color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a {_x000D_
  color: #a94442;_x000D_
  /* normal text color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {_x000D_
  background-color: #ebccd1;_x000D_
  /* hover bg color */_x000D_
}_x000D_
_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,_x000D_
.with-nav-tabs.panel-danger .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {_x000D_
  color: #fff;_x000D_
  /* active text color */_x000D_
  background-color: #a94442;_x000D_
  /* active bg color */_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">_x000D_
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
<!------ Include the above in your HEAD tag ---------->_x000D_
_x000D_
<div class="container">_x000D_
  <div class="page-header">_x000D_
    <h1>Panels with nav tabs.<span class="pull-right label label-default">:)</span></h1>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-default">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1default" data-toggle="tab">Default 1</a></li>_x000D_
            <li><a href="#tab2default" data-toggle="tab">Default 2</a></li>_x000D_
            <li><a href="#tab3default" data-toggle="tab">Default 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4default" data-toggle="tab">Default 4</a></li>_x000D_
                <li><a href="#tab5default" data-toggle="tab">Default 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1default">Default 1</div>_x000D_
            <div class="tab-pane fade" id="tab2default">Default 2</div>_x000D_
            <div class="tab-pane fade" id="tab3default">Default 3</div>_x000D_
            <div class="tab-pane fade" id="tab4default">Default 4</div>_x000D_
            <div class="tab-pane fade" id="tab5default">Default 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-primary">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1primary" data-toggle="tab">Primary 1</a></li>_x000D_
            <li><a href="#tab2primary" data-toggle="tab">Primary 2</a></li>_x000D_
            <li><a href="#tab3primary" data-toggle="tab">Primary 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4primary" data-toggle="tab">Primary 4</a></li>_x000D_
                <li><a href="#tab5primary" data-toggle="tab">Primary 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1primary">Primary 1</div>_x000D_
            <div class="tab-pane fade" id="tab2primary">Primary 2</div>_x000D_
            <div class="tab-pane fade" id="tab3primary">Primary 3</div>_x000D_
            <div class="tab-pane fade" id="tab4primary">Primary 4</div>_x000D_
            <div class="tab-pane fade" id="tab5primary">Primary 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-success">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1success" data-toggle="tab">Success 1</a></li>_x000D_
            <li><a href="#tab2success" data-toggle="tab">Success 2</a></li>_x000D_
            <li><a href="#tab3success" data-toggle="tab">Success 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4success" data-toggle="tab">Success 4</a></li>_x000D_
                <li><a href="#tab5success" data-toggle="tab">Success 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1success">Success 1</div>_x000D_
            <div class="tab-pane fade" id="tab2success">Success 2</div>_x000D_
            <div class="tab-pane fade" id="tab3success">Success 3</div>_x000D_
            <div class="tab-pane fade" id="tab4success">Success 4</div>_x000D_
            <div class="tab-pane fade" id="tab5success">Success 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-info">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1info" data-toggle="tab">Info 1</a></li>_x000D_
            <li><a href="#tab2info" data-toggle="tab">Info 2</a></li>_x000D_
            <li><a href="#tab3info" data-toggle="tab">Info 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4info" data-toggle="tab">Info 4</a></li>_x000D_
                <li><a href="#tab5info" data-toggle="tab">Info 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1info">Info 1</div>_x000D_
            <div class="tab-pane fade" id="tab2info">Info 2</div>_x000D_
            <div class="tab-pane fade" id="tab3info">Info 3</div>_x000D_
            <div class="tab-pane fade" id="tab4info">Info 4</div>_x000D_
            <div class="tab-pane fade" id="tab5info">Info 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-warning">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1warning" data-toggle="tab">Warning 1</a></li>_x000D_
            <li><a href="#tab2warning" data-toggle="tab">Warning 2</a></li>_x000D_
            <li><a href="#tab3warning" data-toggle="tab">Warning 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4warning" data-toggle="tab">Warning 4</a></li>_x000D_
                <li><a href="#tab5warning" data-toggle="tab">Warning 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1warning">Warning 1</div>_x000D_
            <div class="tab-pane fade" id="tab2warning">Warning 2</div>_x000D_
            <div class="tab-pane fade" id="tab3warning">Warning 3</div>_x000D_
            <div class="tab-pane fade" id="tab4warning">Warning 4</div>_x000D_
            <div class="tab-pane fade" id="tab5warning">Warning 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6">_x000D_
      <div class="panel with-nav-tabs panel-danger">_x000D_
        <div class="panel-heading">_x000D_
          <ul class="nav nav-tabs">_x000D_
            <li class="active"><a href="#tab1danger" data-toggle="tab">Danger 1</a></li>_x000D_
            <li><a href="#tab2danger" data-toggle="tab">Danger 2</a></li>_x000D_
            <li><a href="#tab3danger" data-toggle="tab">Danger 3</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
              <ul class="dropdown-menu" role="menu">_x000D_
                <li><a href="#tab4danger" data-toggle="tab">Danger 4</a></li>_x000D_
                <li><a href="#tab5danger" data-toggle="tab">Danger 5</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <div class="panel-body">_x000D_
          <div class="tab-content">_x000D_
            <div class="tab-pane fade in active" id="tab1danger">Danger 1</div>_x000D_
            <div class="tab-pane fade" id="tab2danger">Danger 2</div>_x000D_
            <div class="tab-pane fade" id="tab3danger">Danger 3</div>_x000D_
            <div class="tab-pane fade" id="tab4danger">Danger 4</div>_x000D_
            <div class="tab-pane fade" id="tab5danger">Danger 5</div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<br/>
_x000D_
_x000D_
_x000D_

How to find pg_config path

check /Library/PostgreSQL/9.3/bin and you should find pg_config

I.E. /Library/PostgreSQL/<version_num>/

ps: you can do the following if you deem it necessary for your pg needs -

create a .profile in your ~ directory

export PG_HOME=/Library/PostgreSQL/9.3
export PATH=$PATH:$PG_HOME/bin

You can now use psql or postgres commands from the terminal, and install psycopg2 or any other dependency without issues, plus you can always just ls $PG_HOME/bin when you feel like peeking at your pg_dir.

What's the most efficient way to erase duplicates and sort a vector?

std::unique only works on consecutive runs of duplicate elements, so you'd better sort first. However, it is stable, so your vector will remain sorted.

Why does this CSS margin-top style not work?

You're actually seeing the top margin of the #inner element collapse into the top edge of the #outer element, leaving only the #outer margin intact (albeit not shown in your images). The top edges of both boxes are flush against each other because their margins are equal.

Here are the relevant points from the W3C spec:

8.3.1 Collapsing margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Adjoining vertical margins collapse [...]

Two margins are adjoining if and only if:

  • both belong to in-flow block-level boxes that participate in the same block formatting context
  • no line boxes, no clearance, no padding and no border separate them
  • both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
    • top margin of a box and top margin of its first in-flow child

You can do any of the following to prevent the margin from collapsing:

The reason the above options prevent the margin from collapsing is because:

  • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  • Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
  • Margins of inline-block boxes do not collapse (not even with their in-flow children).

The left and right margins behave as you expect because:

Horizontal margins never collapse.

Creating a system overlay window (always on top)

Well try my code, atleast it gives you a string as overlay, you can very well replace it with a button or an image. You wont believe this is my first ever android app LOL. Anyways if you are more experienced with android apps than me, please try

  • changing parameters 2 and 3 in "new WindowManager.LayoutParams"
  • try some different event approach

How to add and remove item from array in components in Vue 2

There are few mistakes you are doing:

  1. You need to add proper object in the array in addRow method
  2. You can use splice method to remove an element from an array at particular index.
  3. You need to pass the current row as prop to my-item component, where this can be modified.

You can see working code here.

addRow(){
   this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
   this. itemList.splice(index, 1)
}

Easier way to debug a Windows service

Just put your debugger lunch anywhere and attach Visualstudio on startup

#if DEBUG
    Debugger.Launch();
#endif

Also you need to start VS as Administatrator and you need to allow, that a process can automatically be debugged by a diffrent user (as explained here):

reg add "HKCR\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347}" /v AppIDFlags /t REG_DWORD /d 8 /f

Select parent element of known element in Selenium

Let's consider your DOM as

<a>
    <!-- some other icons and texts -->
    <span>Close</span>
</a>

Now that you need to select parent tag 'a' based on <span> text, then use

driver.findElement(By.xpath("//a[.//span[text()='Close']]"));

Explanation: Select the node based on its child node's value

Submit Button Image

<input type="image" src="path to image" name="submit" />

UPDATE:

For button states, you can use type="submit" and then add a class to it

<input type="submit" name="submit" class="states" />

Then in css, use background images for:

.states{
background-image:url(path to url);
height:...;
width:...;
}

.states:hover{
background-position:...;
}

.states:active{
background-position:...;
}

Best practice to run Linux service as a different user

  • Some daemons (e.g. apache) do this by themselves by calling setuid()
  • You could use the setuid-file flag to run the process as a different user.
  • Of course, the solution you mentioned works as well.

If you intend to write your own daemon, then I recommend calling setuid(). This way, your process can

  1. Make use of its root privileges (e.g. open log files, create pid files).
  2. Drop its root privileges at a certain point during startup.

Check if character is number?

If you are testing single characters, then:

var isDigit = (function() {
    var re = /^\d$/;
    return function(c) {
        return re.test(c);
    }
}());

will return true or false depending on whether c is a digit or not.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.

Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

Operator overloading in Java

Java does not allow operator overloading. The preferred approach is to define a method on your class to perform the action: a.add(b) instead of a + b. You can see a summary of the other bits Java left out from C like languages here: Features Removed from C and C++

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

jQuery Scroll To bottom of the page

$('#pagedwn').bind("click", function () {
        $('html, body').animate({ scrollTop:3031 },"fast");
        return false;
});

This solution worked for me. It is working in Page Scroll Down fastly.

Using Address Instead Of Longitude And Latitude With Google Maps API

Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...

_x000D_
_x000D_
var addressesArray = [_x000D_
  'Address Str.No, Postal Area/city',_x000D_
  //follow this structure_x000D_
]_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
  center: {_x000D_
    lat: 12.7826,_x000D_
    lng: 105.0282_x000D_
  },_x000D_
  zoom: 6,_x000D_
  gestureHandling: 'cooperative'_x000D_
});_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
for (i = 0; i < addressArray.length; i++) {_x000D_
  var address = addressArray[i];_x000D_
  geocoder.geocode({_x000D_
    'address': address_x000D_
  }, function(results, status) {_x000D_
    if (status === 'OK') {_x000D_
      var marker = new google.maps.Marker({_x000D_
        map: map,_x000D_
        position: results[0].geometry.location,_x000D_
        center: {_x000D_
          lat: 12.7826,_x000D_
          lng: 105.0282_x000D_
        },_x000D_
      });_x000D_
    } else {_x000D_
      alert('Geocode was not successful for the following reason: ' + status);_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Capturing image from webcam in java?

There's a pretty nice interface for this in processing, which is kind of a pidgin java designed for graphics. It gets used in some image recognition work, such as that link.

Depending on what you need out of it, you might be able to load the video library that's used there in java, or if you're just playing around with it you might be able to get by using processing itself.

Convert SVG to image (JPEG, PNG, etc.) in the browser

jbeard4 solution worked beautifully.

I'm using Raphael SketchPad to create an SVG. Link to the files in step 1.

For a Save button (id of svg is "editor", id of canvas is "canvas"):

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#editor").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...
});

Clear image on picturebox

I assume you want to clear the Images drawn via PictureBox.

This you would be achieved via a Bitmap object and using Graphics object. you might be doing something like

Graphics graphic = Graphics.FromImage(pictbox.Image);
graphic.Clear(Color.Red) //Color to fill the background and reset the box

Is this what you were looking out?

EDIT

Since you are using the paint method this would cause it to be redrawn every time, I would suggest you to set a flag at the formlevel indicating whether it should or not paint the Picturebox

private bool _shouldDraw = true;
public bool ShouldDraw
{
    get { return _shouldDraw; }
    set { _shouldDraw = value; }
}

In your paint just use

if(ShouldDraw)
  //do your stuff

When you click the button set this property to false and you should be fine.

How to use java.Set

Did you override equals and hashCode in the Block class?

EDIT:

I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

An unhandled exception occurred during the execution of the current web request. ASP.NET

Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.

Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.

Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)

Good luck.

Getting the name of a variable as a string

Maybe this could be useful:

def Retriever(bar):
    return (list(globals().keys()))[list(map(lambda x: id(x), list(globals().values()))).index(id(bar))]

The function goes through the list of IDs of values from the global scope (the namespace could be edited), finds the index of the wanted/required var or function based on its ID, and then returns the name from the list of global names based on the acquired index.

Can I use Homebrew on Ubuntu?

As of February 2018, installing brew on Ubuntu (mine is 17.10) machine is as simple as:

sudo apt install linuxbrew-wrapper

Then, on first brew execution (just type brew --help) you will be asked for two installation options:

me@computer:~/$ brew --help
==> Select the Linuxbrew installation directory
- Enter your password to install to /home/linuxbrew/.linuxbrew (recommended)
- Press Control-D to install to /home/me/.linuxbrew
- Press Control-C to cancel installation
[sudo] password for me:

For recommended option type your password (if your current user is in sudo group), or, if you prefer installing all the dependencies in your own home folder, hit Ctrl+D. Enjoy.

How do I build a graphical user interface in C++?

Since I've already been where you are right now, I think I can "answer" you.

The fact is there is no easy way to make a GUI. GUI's are highly dependent on platform and OS specific code, that's why you should start reading your target platform/OS documentation on window management APIs. The good thing is: there are plenty of libraries that address these limitations and abstract architecture differences into a single multi-platform API. Those suggested before, GTK and Qt, are some of these libraries.

But even these are a little too complicated, since lots of new concepts, data types, namespaces and classes are introduced, all at once. For this reason, they use to come bundled with some GUI WYSIWYG editor. They pretty much make programming software with GUIs possible.

To sum it up, there are also non free "environments" for GUI development such as Visual Studio from Microsoft. For those with Delphi experience backgrounds, Visual Studio may be more familiar. There are also free alternatives to the full Visual Studio environment supplied from Microsoft: Visual Studio Express, which is more than enough for starting on GUI development.

How do I use the built in password reset/change views with my own templates

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

Can I use jQuery to check whether at least one checkbox is checked?

if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }

List all the files and folders in a Directory with PHP recursive function

My proposal without ugly "foreach" control structures is

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$allFiles = array_filter(iterator_to_array($iterator), function($file) {
    return $file->isFile();
});

You may only want to extract the filepath, which you can do so by:

array_keys($allFiles);

Still 4 lines of code, but more straight forward than using a loop or something.

How to view user privileges using windows cmd?

Mark Russinovich wrote a terrific tool called AccessChk that lets you get this information from the command line. No installation is necessary.

http://technet.microsoft.com/en-us/sysinternals/bb664922.aspx

For example:

accesschk.exe /accepteula -q -a SeServiceLogonRight

Returns this for me:

IIS APPPOOL\DefaultAppPool
IIS APPPOOL\Classic .NET AppPool
NT SERVICE\ALL SERVICES

By contrast, whoami /priv and whoami /all were missing some entries for me, like SeServiceLogonRight.

Binding Listbox to List<object> in WinForms

You're looking for the DataSource property:

List<SomeType> someList = ...;
myListBox.DataSource = someList;

You should also set the DisplayMember property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString().

Datetime BETWEEN statement not working in SQL Server

You don't have any error in either of your queries. My guess is the following:

  • No records exists between 2013-10-17' and '2013-10-18'
  • the records the second query returns you exist after '2013-10-18'

Collections sort(List<T>,Comparator<? super T>) method example

To use Collections sort(List,Comparator) , you need to create a class that implements Comparator Interface, and code for the compare() in it, through Comparator Interface

You can do something like this:

class StudentComparator implements Comparator
{
    public int compare (Student s1 Student s2)
    {
        // code to compare 2 students
    }
}

To sort do this:

 Collections.sort(List,new StudentComparator())

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016

Step 1: Right button mouse > Select "Edit Top 200 Rows"

Edit top 200 rows

Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)

Navigate to Query Designer > Pane > SQL

Step 3: Modify the query

Modify the query

Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)

enter image description here

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

setting global sql_mode in mysql

For Temporary change use following command

set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 

For permanent change : go to config file /etc/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf and add following lines then restart mysql service

[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

php stdClass to array

This function worked for me:

function cvf_convert_object_to_array($data) {

    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }
    else {
        return $data;
    }
}

Reference: http://carlofontanos.com/convert-stdclass-object-to-array-in-php/

Uncaught ReferenceError: jQuery is not defined

For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.

AngularJS: factory $http.get JSON file

I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.

By default IIS Express restricted access to local files (like json).

But, first: JSON have JavaScript syntax.

Second: javascript files is allowed.

So:

  1. rename JSON to JS (data.json->data.js).

  2. correct load command ($http.get('App/data.js').success(function (data) {...

  3. load script data.js to page (<script src="App/data.js"></script>)

Next use loaded data an usual manner. It is just workaround, of course.

Extension exists but uuid_generate_v4 fails

#1 Re-install uuid-ossp extention in an exact schema:

SET search_path TO public;
DROP EXTENSION IF EXISTS "uuid-ossp";

CREATE EXTENSION "uuid-ossp" SCHEMA public;

If this is a fresh installation you can skip SET and DROP. Credits to @atomCode (details)

After this, you should see uuid_generate_v4() function IN THE RIGHT SCHEMA (when execute \df query in psql command-line prompt).

#2 Use fully-qualified names (with schemaname. qualifier):

CREATE TABLE public.my_table (
    id uuid DEFAULT public.uuid_generate_v4() NOT NULL,

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.

$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database

database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like

$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);

and then pass that field into function $fields

$table is the name of the table in which you want to store the data..

function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
    //extracting extension of uploaded file
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $arrayimage["name"]);
    $extension = end($temp);

    //validating image
    if ((($arrayimage["type"] == "image/gif")
    || ($arrayimage["type"] == "image/jpeg")
    || ($arrayimage["type"] == "image/jpg")
    || ($arrayimage["type"] == "image/pjpeg")
    || ($arrayimage["type"] == "image/x-png")
    || ($arrayimage["type"] == "image/png"))

    //check image size

    && ($arrayimage["size"] < 20000000)

    //check iamge extension in above created extension array
    && in_array($extension, $allowedExts)) 
    {
        if ($arrayimage["error"] > 0) 
        {
            echo "Error: " . $arrayimage["error"] . "<br>";
        } 
        else 
        {
            echo "Upload: " . $arrayimage["name"] . "<br>";
            echo "Type: " . $arrayimage["type"] . "<br>";
            echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
            echo "Stored in: ".$arrayimage['tmp_name']."<br>";

            //check if file is exist in folder of not
            if (file_exists($dir."/".$arrayimage["name"])) 
            {
                echo $arrayimage['name'] . " already exists. ";
            } 
            else 
            {
                //extracting database fields and value
                foreach($fields as $key=>$val)
                {
                    $f[]=$key;
                    $v[]=$val;
                    $fi=implode(",",$f);
                    $value=implode("','",$v);
                }
                //dynamic sql for inserting data into any table
                $sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
                //echo $sql;
                $imginsquery=mysql_query($sql);
                move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
                echo "<br> Stored in: " .$dir ."/ Folder <br>";

            }
        }
    } 
    //if file not match with extension
    else 
    {
        echo "Invalid file";
    }
}
//function imageUpload ends here
}

//imageFunctions class ends here

you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code

Using request.setAttribute in a JSP page

The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.

Simple way to convert datarow array to datatable

Incase anyone needs it in VB.NET:

Dim dataRow as DataRow
Dim yourNewDataTable as new datatable
For Each dataRow In yourArray
     yourNewDataTable.ImportRow(dataRow)
Next

How to find longest string in the table column data

For Postgres:

SELECT column
FROM table
WHERE char_length(column) = (SELECT max(char_length(column)) FROM table )

This will give you the string itself,modified for postgres from @Thorsten Kettner answer

Installed SSL certificate in certificate store, but it's not in IIS certificate list

The certutil -repairstore command mentioned in other answers worked for me, but if your certificate is in the "Web Hosting" store and you don't want to move it, the real (internal) name of the "Web Hosting" store is "WebHosting", for anyone following the steps mentioned here.

Powershell 2 copy-item which creates a folder if doesn't exist

Yes, add the -Force parameter.

copy-item $from $to -Recurse -Force

Construct pandas DataFrame from items in nested dictionary

A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict, using the option orient='index':

user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
                  'Category 2': {'att_1': 23, 'att_2': 'another'}},
             15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
                  'Category 2': {'att_1': 30, 'att_2': 'bar'}}}

pd.DataFrame.from_dict({(i,j): user_dict[i][j] 
                           for i in user_dict.keys() 
                           for j in user_dict[i].keys()},
                       orient='index')


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

An alternative approach would be to build your dataframe up by concatenating the component dataframes:

user_ids = []
frames = []

for user_id, d in user_dict.iteritems():
    user_ids.append(user_id)
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

pd.concat(frames, keys=user_ids)

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

How do I auto-resize an image to fit a 'div' container?

object-fit

It turns out there's another way to do this.

<img style='height: 100%; width: 100%; object-fit: contain'/>

will do the work. It's CSS 3 stuff.

Fiddle: http://jsfiddle.net/mbHB4/7364/

PowerShell: Run command from script's directory

This would work fine.

Push-Location $PSScriptRoot

Write-Host CurrentDirectory $CurDir

How to import a JSON file in ECMAScript 6?

In TypeScript or using Babel, you can import json file in your code.

// Babel

import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

Reference: https://hackernoon.com/import-json-into-typescript-8d465beded79

Change old commit message on Git

It says:

When you save and exit the editor, it will rewind you back to that last commit in that list and drop you on the command line with the following message:

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

It does not mean:

type again git rebase -i HEAD~3

Try to not typing git rebase -i HEAD~3 when exiting the editor, and it should work fine.
(otherwise, in your particular situation, a git rebase -i --abort might be needed to reset everything and allow you to try again)


As Dave Vogt mentions in the comments, git rebase --continue is for going to the next task in the rebasing process, after you've amended the first commit.

Also, Gregg Lind mentions in his answer the reword command of git rebase:

By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

If you just want to edit the commit message for a commit, replace the command "pick" with the command "reword", since Git1.6.6 (January 2010).

It does the same thing ‘edit’ does during an interactive rebase, except it only lets you edit the commit message without returning control to the shell. This is extremely useful.
Currently if you want to clean up your commit messages you have to:

$ git rebase -i next

Then set all the commits to ‘edit’. Then on each one:

# Change the message in your editor.
$ git commit --amend
$ git rebase --continue

Using ‘reword’ instead of ‘edit’ lets you skip the git-commit and git-rebase calls.

Simple C example of doing an HTTP POST and consuming the response

Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:

memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
    printf("RESPONSE: %s\n", response);
    // HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
    memset(response, 0, sizeof(response));
    bytes = recv(sockfd, response, 1024, 0);
    if (bytes < 0)
        printf("ERROR reading response from socket");
    if (bytes == 0)
        break;
    received+=bytes;
} while (1); 

How to change visibility of layout programmatically

TextView view = (TextView) findViewById(R.id.textView);
view.setText("Add your text here");
view.setVisibility(View.VISIBLE);

summing two columns in a pandas dataframe

df['variance'] = df.loc[:,['budget','actual']].sum(axis=1)

Regular expression for not allowing spaces in the input field

Use + plus sign (Match one or more of the previous items),

var regexp = /^\S+$/

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

How do I navigate to a parent route from a child route?

None of this worked for me ... Here is my code with the back function :

import { Router } from '@angular/router';
...
constructor(private router: Router) {}
...
back() {
   this.router.navigate([this.router.url.substring(0, this.router.url.lastIndexOf('/'))]);
}

this.router.url.substring(0, this.router.url.lastIndexOf('/') --> get the last part of the current url after the "/" --> get the current route.

How can I check for "undefined" in JavaScript?

I personally use

myVar === undefined

Warning: Please note that === is used over == and that myVar has been previously declared (not defined).


I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)

Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"

Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?

If you follow this rule, good for you: you aren't a hypocrite.

The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout because someone can

window.setTimeout = function () {
    alert("Got you now!");
};

Bottom line, the "it can be redefined" argument to not use a raw === undefined is bogus.

(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)


Also, like the typeof approach, this technique can "detect" undeclared variables:

if (window.someVar === undefined) {
    doSomething();
}

But both these techniques leak in their abstraction. I urge you not to use this or even

if (typeof myVar !== "undefined") {
    doSomething();
}

Consider:

var iAmUndefined;

To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).

if ("myVar" in window) {
    doSomething();
}

But wait! There's more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:

encodeURIComponent() 

and in PHP:

urldecode($_POST['field']);

What is an Android PendingIntent?

A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code. To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().

Changing permissions via chmod at runtime errors with "Operation not permitted"

This is a tricky question.

There a set of problems about file permissions. If you can do this at the command line

$ sudo chown myaccount /path/to/file

then you have a standard permissions problem. Make sure you own the file and have permission to modify the directory.

If you cannnot get permissions, then you have probably mounted a FAT-32 filesystem. If you ls -l the file, and you find it is owned by root and a member of the "plugdev" group, then you are certain its the issue. FAT-32 permissions are set at the time of mounting, using the line of /etc/fstab file. You can set the uid/gid of all the files like this:

UUID=C14C-CE25  /big            vfat    utf8,umask=007,uid=1000,gid=1000 0       1

Also, note that the FAT-32 won't take symbolic links.

Wrote the whole thing up at http://www.charlesmerriam.com/blog/2009/12/operation-not-permitted-and-the-fat-32-system/

JavaScript listener, "keypress" doesn't detect backspace?

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

How to print VARCHAR(MAX) using Print Statement?

You can use this

declare @i int = 1
while Exists(Select(Substring(@Script,@i,4000))) and (@i < LEN(@Script))
begin
     print Substring(@Script,@i,4000)
     set @i = @i+4000
end

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

Google Maps API: open url by clicking on marker

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    window.location.href = marker.url;
  }
})(marker, i));

Inline functions in C#?

No, there is no such construct in C#, but the .NET JIT compiler could decide to do inline function calls on JIT time. But i actually don't know if it is really doing such optimizations.
(I think it should :-))

Git undo local branch delete

If you know the last SHA1 of the branch, you can try

git branch branchName <SHA1>

You can find the SHA1 using git reflog, described in the solution --defect link--.