Programs & Examples On #Satellite image

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

How to trap the backspace key using jQuery?

Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .

$('html').on('keydown' , function(event) {

        if(! $(event.target).is('input')) {
            console.log(event.which);
           //event.preventDefault();
           if(event.which == 8) {
            //  alert('backspace pressed');
            return false;
         }
        }
});

returning false => both event.preventDefault and event.stopPropagation are in effect .

SQL multiple column ordering

The other answers lack a concrete example, so here it goes:

Given the following People table:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826

If you execute the query below:

SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC

The result set will look like this:

 FirstName |  LastName   |  YearOfBirth
----------------------------------------
  Thomas   | More        |   1478
  Thomas   | Jefferson   |   1826
  Thomas   | Alva Edison |   1847
  Benjamin | Franklin    |   1706

Reading specific columns from a text file in python

It may help:

import csv
with open('csv_file','r') as f:
    # Printing Specific Part of CSV_file
    # Printing last line of second column
    lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
    print(lines[-1][1])
    # For printing a range of rows except 10 last rows of second column
    for i in range(len(lines)-10):
        print(lines[i][1])

How do you check if a certain index exists in a table?

A slight deviation from the original question however may prove useful for future people landing here wanting to DROP and CREATE an index, i.e. in a deployment script.

You can bypass the exists check simply by adding the following to your create statement:

CREATE INDEX IX_IndexName
ON dbo.TableName
WITH (DROP_EXISTING = ON);

Read more here: CREATE INDEX (Transact-SQL) - DROP_EXISTING Clause

N.B. As mentioned in the comments, the index must already exist for this clause to work without throwing an error.

Minimum and maximum value of z-index?

Z-Index only works for elements that have position: relative; or position: absolute; applied to them. If that's not the problem we'll need to see an example page to be more helpful.

EDIT: The good doctor has already put the fullest explanation but the quick version is that the minimum is 0 because it can't be a negative number and the maximum - well, you'll never really need to go above 10 for most designs.

How to make a query with group_concat in sql server

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , STUFF((
          SELECT ',' + T.maskdetail
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH('')), 1, 1, '') as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
Group by  A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname

remove first element from array and return the array minus the first element

This should remove the first element, and then you can return the remaining:

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
    _x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
_x000D_
_x000D_

As others have suggested, you could also use slice(1);

_x000D_
_x000D_
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
  _x000D_
alert(myarray.slice(1));
_x000D_
_x000D_
_x000D_

Wordpress - Images not showing up in the Media Library

Did you ever change the directory of your Wordpress install?

I had a problem with not finding my uploaded images after changing the Wordpress location on my server. In Wordpress, I went to Dashboard-> Settings -> Media and changed the uploads folder in the "Store uploads in this folder" field.

Select All as default value for Multivalue parameter

It works better

CREATE TABLE [dbo].[T_Status](
   [Status] [nvarchar](20) NULL
) ON [PRIMARY]

GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO

DECLARE @GetStatus nvarchar(20) = null
--DECLARE @GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE  [Status] = CASE WHEN (isnull(@GetStatus, '')='') THEN [Status]
ELSE @GetStatus END

Difference between ${} and $() in Bash

  1. your understanding is right. For detailed info on {} see bash ref - parameter expansion

  2. 'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.

With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done in essence manage everything about the iteration yourself

Asyncio.gather vs asyncio.wait

I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:

result=loop.run_until_complete(asyncio.wait([
        say('first hello', 2),
        say('second hello', 1),
        say('third hello', 4)
    ]))

Whereas grouping in gather() is done by just specifying multiple coroutines:

result=loop.run_until_complete(asyncio.gather(
        say('first hello', 2),
        say('second hello', 1),
        say('third hello', 4)
    ))

Python display text with font & color?

There are 2 possibilities. In either case PyGame has to be initialized by pygame.init.

import pygame
pygame.init()

Use either the pygame.font module and create a pygame.font.SysFont or pygame.font.Font object. render() a pygame.Surface with the text and blit the Surface to the screen:

my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))

Or use the pygame.freetype module. Create a pygame.freetype.SysFont() or pygame.freetype.Font object. render() a pygame.Surface with the text or directly render_to() the text to the screen:

my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))

See also Text and font


Minimal pygame.font example: repl.it/@Rabbid76/PyGame-Text

import pygame

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    window.blit(text, text.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()

Minimal pygame.freetype example: repl.it/@Rabbid76/PyGame-FreeTypeText

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

ft_font = pygame.freetype.SysFont('Times New Roman', 80)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    text_rect = ft_font.get_rect('Hello World')
    text_rect.center = window.get_rect().center
    ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
    pygame.display.flip()

pygame.quit()
exit()

Custom header to HttpClient request

Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

using Newtonsoft.Json;
...

var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("https://api.clickatell.com/rest/message"),
        Headers = { 
            { HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
            { HttpRequestHeader.Accept.ToString(), "application/json" },
            { "X-Version", "1" }
        },
        Content = new StringContent(JsonConvert.SerializeObject(svm))
    };

var response = client.SendAsync(httpRequestMessage).Result;

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

How to show shadow around the linearlayout in Android?

One possible solution is using nine patch image like this http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

OR

I have done this in the following way. This is my main layout in which round_corner.xml and drop_shadow.xml used as background resource. round_corner_two is same like round_corner.xml only the color attribute is different. copy the round_corner.xml,drop_shadow.xml and round_conere_two.xml into drawable folder.

<RelativeLayout
    android:id="@+id/facebook_id"
    android:layout_width="250dp"
    android:layout_height="52dp"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="28dp"
    android:background="@drawable/round_corner" >

    <LinearLayout
        android:id="@+id/shadow_id"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_margin="1dp"
        android:background="@drawable/drop_shadow" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_marginBottom="2dp"
            android:background="@drawable/round_corner_two"
            android:gravity="center"
            android:text="@string/fb_butn_text"
            android:textColor="@color/white" >
        </TextView>
    </LinearLayout>
</RelativeLayout>

round_corner.xml:

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

<!-- view background color -->
<solid
    android:color="#ffffff" >
</solid>

<!-- view border color and width -->
<stroke
    android:width="0dp"
    android:color="#3b5998" >
</stroke>

<!-- If you want to add some padding -->
<padding
    android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp"    >
</padding>

<!-- Here is the corner radius -->
<corners
    android:radius="10dp"   >
</corners>

</shape>

drop_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
    <shape 
        android:shape="rectangle">
    <solid android:color="@android:color/darker_gray" />
    <corners android:radius="12dp"/>
    </shape>
</item>
<item android:right="1dp" android:left="1dp" android:bottom="5dp">
    <shape 
        android:shape="rectangle">
    <solid android:color="@android:color/white"/>
    <corners android:radius="5dp"/>
    </shape>
</item>
</layer-list>

Add target="_blank" in CSS

Another way to use target="_blank" is:

onclick="this.target='_blank'"

Example:

<a href="http://www.url.com" onclick="this.target='_blank'">Your Text<a>

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

Javascript - Regex to validate date format

Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.

Note supplied date format and date string go hand in hand.

    <script type="text/javascript">
function validate(format) {

    if(isAfterCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is after the current date.');
    } else {
        alert('Date is not after the current date.');
    }
    if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is before current date.');
    } else {
        alert('Date is not before current date.');
    }
    if(isCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is current date.');
    } else {
        alert('Date is not a current date.');
    }
    if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Start/Effective Date cannot be greater than End/Expiration Date');
    } else {
        alert('Valid dates...');
    }
    if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('End/Expiration Date cannot be less than Start/Effective Date');
    } else {
        alert('Valid dates...');
    }
    if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Dates are equals...');
    } else {
        alert('Dates are not equals...');
    }
    if (isDate(document.getElementById('start').value, format)) {
        alert('Is valid date...');
    } else {
        alert('Is invalid date...');
    }
}

/**
 * This method gets the year index from the supplied format
 */
function getYearIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'YYYY'
            || tokens[0] === 'yyyy') {
        return 0;
    } else if (tokens[1]=== 'YYYY'
            || tokens[1] === 'yyyy') {
        return 1;
    } else if (tokens[2] === 'YYYY'
            || tokens[2] === 'yyyy') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the year string located at the supplied index
 */
function getYear(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the month index from the supplied format
 */
function getMonthIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'MM'
            || tokens[0] === 'mm') {
        return 0;
    } else if (tokens[1] === 'MM'
            || tokens[1] === 'mm') {
        return 1;
    } else if (tokens[2] === 'MM'
            || tokens[2] === 'mm') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the month string located at the supplied index
 */
function getMonth(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the date index from the supplied format
 */
function getDateIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'DD'
            || tokens[0] === 'dd') {
        return 0;
    } else if (tokens[1] === 'DD'
            || tokens[1] === 'dd') {
        return 1;
    } else if (tokens[2] === 'DD'
            || tokens[2] === 'dd') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the date string located at the supplied index
 */
function getDate(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method returns true if date1 is before date2 else return false
 */
function isBefore(date1, date2, format) {
    // Validating if date1 date is greater than the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        > new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is after date2 else return false
 */
function isAfter(date1, date2, format) {
    // Validating if date2 date is less than the date1 date
    if (new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()
        < new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        ) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is equals to date2 else return false
 */
function isEquals(date1, date2, format) {
    // Validating if date1 date is equals to the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        === new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;
}

/**
 * This method validates and returns true if the supplied date is 
 * equals to the current date.
 */
function isCurrentDate(date, format) {
    // Validating if the supplied date is the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        === new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is before the current date.
 */
function isBeforeCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        < new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is after the current date.
 */
function isAfterCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        > new Date(new Date().getFullYear(),
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method splits the supplied date OR format based 
 * on non alpha numeric characters in the supplied string.
 */
function splitDateFormat(dateFormat) {
    // Spliting the supplied string based on non characters
    return dateFormat.split(/\W/);
}

/*
 * This method validates if the supplied value is a valid date.
 */
function isDate(date, format) {                
    // Validating if the supplied date string is valid and not a NaN (Not a Number)
    if (!isNaN(new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))))) {                    
        return true;
    } 
    return false;                                      
}

Below is the HTML snippet

    <input type="text" name="start" id="start" size="10" value="05/31/2016" />
    <br/> 
    <input type="text" name="end" id="end" size="10" value="04/28/2016" />
    <br/>
    <input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />

Android, How to limit width of TextView (and add three dots at the end of text)?

You can limit your textview's number of characters and add (...) after the text. Suppose You need to show 5 letters only and thereafter you need to show (...), Just do the following :

String YourString = "abcdefghijk";

if(YourString.length()>5){

YourString  =  YourString.substring(0,4)+"...";

your_text_view.setText(YourString);
}else{

 your_text_view.setText(YourString); //Dont do any change

}

a little hack ^_^. Though its not a good solution. But a work around which worked for me :D

EDIT: I have added check for less character as per your limited no. of characters.

Viewing unpushed Git commits

one way of doing things is to list commits that are available on one branch but not another.

git log ^origin/master master

What's the proper value for a checked attribute of an HTML checkbox?

It's pretty crazy town that the only way to make checked false is to omit any values. With Angular 1.x, you can do this:

  <input type="radio" ng-checked="false">

which is a lot more sane, if you need to make it unchecked.

How to get base URL in Web API controller?

First you get full URL using HttpContext.Current.Request.Url.ToString(); then replace your method url using Replace("user/login", "").

Full code will be

string host = HttpContext.Current.Request.Url.ToString().Replace("user/login", "")

Return different type of data from a method in java?

This can be one of the solution. But your present solution is good enough. You can also add new variables and still keep it clean, which cannot be done with present code.

private static final int INDEX_OF_STRING_PARAM = 0;
private static final int INDEX_OF_INT_PARAM = 1;

public static Object[] myMethod() {
    Object[] values = new Object[2];
    values[INDEX_OF_STRING_PARAM] = "value";
    values[INDEX_OF_INT_PARAM] = 12;
    return values;
}

Comment out HTML and PHP together

PHP parser will search your entire code for <?php (or <? if short_open_tag = On), so HTML comment tags have no effect on PHP parser behavior & if you don't want to parse your PHP code, you have to use PHP commenting directives(/* */ or //).

Set focus on TextBox in WPF from view model

I know this question has been answered a thousand times over by now, but I made some edits to Anvaka's contribution that I think will help others that had similar issues that I had.

Firstly, I changed the above Attached Property like so:

public static class FocusExtension
{
    public static readonly DependencyProperty IsFocusedProperty = 
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension), new FrameworkPropertyMetadata(IsFocusedChanged){BindsTwoWayByDefault = true});

    public static bool? GetIsFocused(DependencyObject element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }

        return (bool?)element.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject element, bool? value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }

        element.SetValue(IsFocusedProperty, value);
    }

    private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var fe = (FrameworkElement)d;

        if (e.OldValue == null)
        {
            fe.GotFocus += FrameworkElement_GotFocus;
            fe.LostFocus += FrameworkElement_LostFocus;
        }

        if (!fe.IsVisible)
        {
            fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
        }

        if (e.NewValue != null && (bool)e.NewValue)
        {
            fe.Focus();
        }
    }

    private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var fe = (FrameworkElement)sender;
        if (fe.IsVisible && (bool)fe.GetValue(IsFocusedProperty))
        {
            fe.IsVisibleChanged -= fe_IsVisibleChanged;
            fe.Focus();
        }
    }

    private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
    {
        ((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
    }

    private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
    {
        ((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
    }
}

My reason for adding the visibility references were tabs. Apparently if you used the attached property on any other tab outside of the initially visible tab, the attached property didn't work until you manually focused the control.

The other obstacle was creating a more elegant way of resetting the underlying property to false when it lost focus. That's where the lost focus events came in.

<TextBox            
    Text="{Binding Description}"
    FocusExtension.IsFocused="{Binding IsFocused}"/>

If there's a better way to handle the visibility issue, please let me know.

Note: Thanks to Apfelkuacha for the suggestion of putting the BindsTwoWayByDefault in the DependencyProperty. I had done that long ago in my own code, but never updated this post. The Mode=TwoWay is no longer necessary in the WPF code due to this change.

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

ADD instruction copies files or folders from a local or remote source and adds them to the container's file system. It used to copy local files, those must be in the working directory. ADD instruction unpacks local .tar files to the destination image directory.

Example

ADD http://someserver.com/filename.pdf /var/www/html

COPY copies files from the working directory and adds them to the container's file system. It is not possible to copy a remote file using its URL with this Dockerfile instruction.

Example

COPY Gemfile Gemfile.lock ./
COPY ./src/ /var/www/html/

Generate C# class from XML

I realise that this is a rather old post and you have probably moved on.

But I had the same problem as you so I decided to write my own program.

The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.

It is in no way elegant but it did the job for me.

You can get it here: Please make suggestions if you like it.

SimpleXmlToCode

Printing prime numbers from 1 through 100

this is my approach from a simple blog:

//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;

int main()
{
int a = 2;       //start from 2
long long int b = 1000;     //ends at 1000

for (int i = a; i <= b; i++)
{

 for (int j = 2; j <= i; j++)
 {
    if (!(i%j)&&(i!=j))    //Condition for not prime
        {
            break;
        }

    if (j==i)             //condition for Prime Numbers
        {
              cout << i << endl;

        }
 }
}
}

- See more at: http://www.programmingtunes.com/generation-of-prime-numbers-c/#sthash.YoWHqYcm.dpuf

How to implode array with key and value without foreach in PHP

For create mysql where conditions from array

$sWheres = array('item1'  => 'object1',
                 'item2'  => 'object2',
                 'item3'  => 1,
                 'item4'  => array(4,5),
                 'item5'  => array('object3','object4'));
$sWhere = '';
if(!empty($sWheres)){
    $sWhereConditions = array();
    foreach ($sWheres as $key => $value){
        if(!empty($value)){
            if(is_array($value)){
                $value = array_filter($value); // For remove blank values from array
                if(!empty($value)){
                    array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
                    $sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
                }
            }else{
                $sWhereConditions[] = sprintf("%s='%s'", $key, $value);
            }
        }
    }
    if(!empty($sWhereConditions)){
        $sWhere .= "(".implode(' AND ', $sWhereConditions).")";
    }
}
echo $sWhere;  // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))

Exit from app when click button in android phonegap?

Try this code.

<!DOCTYPE HTML>
<html>
  <head>
    <title>PhoneGap</title>

        <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>      
        <script type="text/javascript" charset="utf-8">

            function onLoad()
            {
                  document.addEventListener("deviceready", onDeviceReady, true);
            }

            function exitFromApp()
             {
                navigator.app.exitApp();
             }

        </script>

    </head>

    <body onload="onLoad();">
       <button name="buttonClick" onclick="exitFromApp()">Click Me!</button>
    </body>
</html>

Replace src="cordova-1.5.0.js" with your phonegap js .

How to delete a record in Django models?

if you want to delete one instance then write the code

entry= Account.objects.get(id= 5)
entry.delete()

if you want to delete all instance then write the code

entries= Account.objects.all()
entries.delete()

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:

python -V

I hope it helps

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

Add the last 2 entries of /proc/meminfo, they give you the exact memory present on the host.

Example:

DirectMap4k:       10240 kB
DirectMap2M:     4184064 kB

10240 + 4184064 = 4194304 kB = 4096 MB.

How to run a function in jquery

function doosomething ()
{
  //Doo something
}


$(function () {


  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

How can I pass command-line arguments to a Perl program?

Depends on what you want to do. If you want to use the two arguments as input files, you can just pass them in and then use <> to read their contents.

If they have a different meaning, you can use GetOpt::Std and GetOpt::Long to process them easily. GetOpt::Std supports only single-character switches and GetOpt::Long is much more flexible. From GetOpt::Long:

use Getopt::Long;
my $data   = "file.dat";
my $length = 24;
my $verbose;
$result = GetOptions ("length=i" => \$length,    # numeric
                    "file=s"   => \$data,      # string
                    "verbose"  => \$verbose);  # flag

Alternatively, @ARGV is a special variable that contains all the command line arguments. $ARGV[0] is the first (ie. "string1" in your case) and $ARGV[1] is the second argument. You don't need a special module to access @ARGV.

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

ssh script returns 255 error

This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.

ssh returns 255 when an error occurred or 255 is returned by the remote script:

 EXIT STATUS

     ssh exits with the exit status of the remote command or
     with 255 if an error occurred.

Usually you would an error message something similar to:

ssh: connect to host host.domain.com port 22: No route to host

Or

ssh: connect to host HOSTNAME port 22: Connection refused

Check-list:

  • What happens if you run the ssh command directly from the command line?

  • Are you able to ping that machine?

  • Does the remote has ssh installed?

  • If installed, then is the ssh service running?

Remove border from IFrame

Use the HTML iframe frameborder Attribute

http://www.w3schools.com/tags/att_iframe_frameborder.asp

Note: use frameBorder (cap B) for IE, otherwise will not work. But, the iframe frameborder attribute is not supported in HTML5. So, Use CSS instead.

<iframe src="http://example.org" width="200" height="200" style="border:0">

you can also remove scrolling using scrolling attribute http://www.w3schools.com/tags/att_iframe_scrolling.asp

<iframe src="http://example.org" width="200" height="200" scrolling="no" style="border:0">

Also you can use seamless attribute which is new in HTML5. The seamless attribute of the iframe tag is only supported in Opera, Chrome and Safari. When present, it specifies that the iframe should look like it is a part of the containing document (no borders or scrollbars). As of now, The seamless attribute of the tag is only supported in Opera, Chrome and Safari. But in near future it will be the standard solution and will be compatible with all browsers. http://www.w3schools.com/tags/att_iframe_seamless.asp

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

Can you 'exit' a loop in PHP?

All of these are good answers, but I would like to suggest one more that I feel is a better code standard. You may choose to use a flag in the loop condition that indicates whether or not to continue looping and avoid using break all together.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
$length = count($arr);
$found = false;
for ($i = 0; $i < $length && !$found; $i++) {
    $val = $arr[$i];
    if ($val == 'stop') {
        $found = true; // this will cause the code to 
                       // stop looping the next time 
                       // the condition is checked
    }
    echo "$val<br />\n";
}

I consider this to be better code practice because it does not rely on the scope that break is used. Rather, you define a variable that indicates whether or not to break a specific loop. This is useful when you have many loops that may or may not be nested or sequential.

angular-cli server - how to proxy API requests to another server?

We can find the proxy documentation for Angular-CLI over here:

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

After setting up a file called proxy.conf.json in your root folder, edit your package.json to include the proxy config on ng start. After adding "start": "ng serve --proxy-config proxy.conf.json" to your scripts, run npm start and not ng serve, because that will ignore the flag setup in your package.json.

current version of angular-cli: 1.1.0

Converting a string to an integer on Android

Use regular expression:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

output:

i=123;
j=123;
k=123;

How to access custom attributes from event object in React?

You can access data attributes something like this

event.target.dataset.tag

PHP cURL custom headers

Use the following Syntax

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate',
    'Accept-Language: en-US,en;q=0.5',
    'Cache-Control: no-cache',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Host: www.example.com',
    'Referer: http://www.example.com/index.php', //Your referrer address
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0',
    'X-MicrosoftAjax: Delta=true'
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

curl_close ($ch);

print  $server_output ;

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Use component from another module

SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.

Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.

1st: Export the component in the module which contains it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

2nd: In the module where you want to use TaskCardComponent:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
   CommonModule,
   MdCardModule
   ],
  providers: [],
  exports:[ MdCardModule ] <== this line
})
export class TaskModule{}

Like this the second module imports the first module which imports and exports the component.

When we import the module in the second module we need to export it again. Now we can use the first component in the second module.

How to SSH to a VirtualBox guest externally through a host?

Change the adapter type in VirtualBox to bridged, and set the guest to use DHCP or set a static IP address outside of the bounds of DHCP. This will cause the Virtual Machine to act like a normal guest on your home network. You can then port forward.

R dates "origin" must be supplied

My R use 1970-01-01:

>as.Date(15103, origin="1970-01-01")
[1] "2011-05-09"

and this matches the calculation from

>as.numeric(as.Date(15103, origin="1970-01-01"))

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Also worth noting that if you have two factor authentication enabled, you'll need to setup an application specific password to use in place of your email account's password.

You can generate an application specific password by following these instructions: https://support.google.com/accounts/answer/185833

Then set $mail->Password to your application specific password.

jQuery remove special characters from string and more

Remove/Replace all special chars in Jquery :

If

str = My name is "Ghanshyam" and from "java" background

and want to remove all special chars (") then use this

str=str.replace(/"/g,' ')

result:

My name is Ghanshyam and from java background

Where g means Global

Detect click outside element

I use this code:

show-hide button

 <a @click.stop="visualSwitch()"> show hide </a>

show-hide element

<div class="dialog-popup" v-if="visualState" @click.stop=""></div>

script

data () { return {
    visualState: false,
}},
methods: {
    visualSwitch() {
        this.visualState = !this.visualState;
        if (this.visualState)
            document.addEventListener('click', this.visualState);
        else
            document.removeEventListener('click', this.visualState);
    },
},

Update: remove watch; add stop propagation

What's the difference between session.persist() and session.save() in Hibernate?

This question has some good answers about different persistence methods in Hibernate. To answer your question directly, with save() the insert statement is executed immediately regardless of transaction state. It returns the inserted key so you can do something like this:

long newKey = session.save(myObj);

So use save() if you need an identifier assigned to the persistent instance immediately.

With persist(), the insert statement is executed in a transaction, not necessarily immediately. This is preferable in most cases.

Use persist() if you don't need the insert to happen out-of-sequence with the transaction and you don't need the inserted key returned.

How can I find the latitude and longitude from address?

public GeoPoint getLocationFromAddress(String strAddress){

Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;

try {
    address = coder.getFromLocationName(strAddress,5);
    if (address==null) {
       return null;
    }
    Address location=address.get(0);
    location.getLatitude();
    location.getLongitude();

    p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
                      (double) (location.getLongitude() * 1E6));

    return p1;
    }
}

strAddress is a string containing the address. The address variable holds the converted addresses.

How to change the foreign key referential action? (behavior)

You can simply use one query to rule them all: ALTER TABLE products DROP FOREIGN KEY oldConstraintName, ADD FOREIGN KEY (product_id, category_id) REFERENCES externalTableName (foreign_key_name, another_one_makes_composite_key) ON DELETE CASCADE ON UPDATE CASCADE

Maven: Non-resolvable parent POM

I had similar problem at my work.

Building the parent project without dependency created parent_project.pom file in the .m2 folder.

Then add the child module in the parent POM and run Maven build.

<modules>
    <module>module1</module>
    <module>module2</module>
    <module>module3</module>
    <module>module4</module>
</modules>

Can I recover a branch after its deletion in Git?

First go to git batch the move to your project like :

cd android studio project
cd Myproject
then type :
git reflog

You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha. another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.

Apache Spark: The number of cores vs. the number of executors

There is a small issue in the First two configurations i think. The concepts of threads and cores like follows. The concept of threading is if the cores are ideal then use that core to process the data. So the memory is not fully utilized in first two cases. If you want to bench mark this example choose the machines which has more than 10 cores on each machine. Then do the bench mark.

But dont give more than 5 cores per executor there will be bottle neck on i/o performance.

So the best machines to do this bench marking might be data nodes which have 10 cores.

Data node machine spec: CPU: Core i7-4790 (# of cores: 10, # of threads: 20) RAM: 32GB (8GB x 4) HDD: 8TB (2TB x 4)

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Python: How to create a unique file name?

In case you need short unique IDs as your filename, try shortuuid, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.

>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22

compared to

>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'

MySQL LIKE IN()?

You can use like this too:

SELECT * FROM fiberbox WHERE fiber IN('140 ', '1938 ', '1940 ')

Figure out size of UILabel based on String in Swift

For multiline text this answer is not working correctly. You can build a different String extension by using UILabel

extension String {
func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat {
    let label =  UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.text = self
    label.font = font
    label.sizeToFit()

    return label.frame.height
 }
}

The UILabel gets a fixed width and the .numberOfLines is set to 0. By adding the text and calling .sizeToFit() it automatically adjusts to the correct height.

Code is written in Swift 3

How to validate domain name in PHP?

use checkdnsrr http://php.net/manual/en/function.checkdnsrr.php

$domain = "stackoverflow.com";

checkdnsrr($domain , "A");

//returns true if has a dns A record, false otherwise

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

try this

echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";

how to convert a string to a bool

I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:

    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };


        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: " 
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }

What is the memory consumption of an object in Java?

It appears that every object has an overhead of 16 bytes on 32-bit systems (and 24-byte on 64-bit systems).

http://algs4.cs.princeton.edu/14analysis/ is a good source of information. One example among many good ones is the following.

enter image description here

http://www.cs.virginia.edu/kim/publicity/pldi09tutorials/memory-efficient-java-tutorial.pdf is also very informative, for example:

enter image description here

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Well as the stack trace says, you would need to set the protected mode settings to same for all zones in IE. Read the why here : http://jimevansmusic.blogspot.in/2012/08/youre-doing-it-wrong-protected-mode-and.html

and a quick how to from the same link : "In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone"

How to use relative paths without including the context root name?

Instead using entire link we can make as below (solution concerns jsp files)

With JSTL we can make it like: To link resource like css, js:

     <link rel="stylesheet" href="${pageContext.request.contextPath}/style/sample.css" />
     <script src="${pageContext.request.contextPath}/js/sample.js"></script>   

To simply make a link:

     <a id=".." class=".." href="${pageContext.request.contextPath}/jsp/sample.jsp">....</a>

It's worth to get familiar with tags

   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

There is also jsp method to do it like below, but better way like above:

   <link rel="stylesheet" href="<%=request.getContextPath()%>/style/sample.css" />
   <script type="text/javascript" src="<%=request.getContextPath()%>/js/sample.js"></script>

To simply make a link:

   <a id=".." class=".." href="<%=request.getContextPath()%>/jsp/sample.jsp">....</a>

Double free or corruption after queue::push

Let's talk about copying objects in C++.

Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.

Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.

When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.

Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.

How do I fix it?

The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:

Test(const Test& other){
    myArray = new int[10];
    memcpy( myArray, other.myArray, 10 );
}

Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.

We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:

Test& operator= (const Test& other){
    if (this != &other) {
        memcpy( myArray, other.myArray, 10 );
    }
    return *this;
}

The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.

Best algorithm for detecting cycles in a directed graph

If you can't add a "visited" property to the nodes, use a set (or map) and just add all visited nodes to the set unless they are already in the set. Use a unique key or the address of the objects as the "key".

This also gives you the information about the "root" node of the cyclic dependency which will come in handy when a user has to fix the problem.

Another solution is to try to find the next dependency to execute. For this, you must have some stack where you can remember where you are now and what you need to do next. Check if a dependency is already on this stack before you execute it. If it is, you've found a cycle.

While this might seem to have a complexity of O(N*M) you must remember that the stack has a very limited depth (so N is small) and that M becomes smaller with each dependency that you can check off as "executed" plus you can stop the search when you found a leaf (so you never have to check every node -> M will be small, too).

In MetaMake, I created the graph as a list of lists and then deleted every node as I executed them which naturally cut down the search volume. I never actually had to run an independent check, it all happened automatically during normal execution.

If you need a "test only" mode, just add a "dry-run" flag which disables the execution of the actual jobs.

What is a web service endpoint?

In past projects I worked on, the endpoint was a relative property. That is to say it may or may not have been appended to, but it always contained the protocol://host:port/partOfThePath.

If the service being called had a dynamic part to it, for example a ?param=dynamicValue, then that part would get added to the endpoint. But many times the endpoint could be used as is without having to be amended.

Whats important to understand is what an endpoint is not and how it helps. For example an alternative way to pass the information stored in an endpoint would be to store the different parts of the endpoint in separate properties. For example:

hostForServiceA=someIp
portForServiceA=8080
pathForServiceA=/some/service/path
hostForServiceB=someIp
portForServiceB=8080
pathForServiceB=/some/service/path

Or if the same host and port across multiple services:

host=someIp
port=8080
pathForServiceA=/some/service/path
pathForServiceB=/some/service/path

In those cases the full URL would need to be constructed in your code as such:

String url = "http://" + host + ":" + port + pathForServiceA  + "?" + dynamicParam + "=" + dynamicValue;

In contract this can be stored as an endpoint as such

serviceAEndpoint=http://host:port/some/service/path?dynamicParam=

And yes many times we stored the endpoint up to and including the '='. This lead to code like this:

String url = serviceAEndpoint + dynamicValue;

Hope that sheds some light.

Seconds CountDown Timer

Hey please add code in your project,it is easy and i think will solve your problem.

    int count = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        count--;
        if (count != 0 && count > 0)
        {
            label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
        }
        else
        {
            label1.Text = "game over";

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1;

        timer1.Tick += new EventHandler(timer1_Tick);

    }

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

How to take MySQL database backup using MySQL Workbench?

Sever > Data Export

enter image description here

Select database, and start export

enter image description here

How to check String in response body with mockMvc

String body = mockMvc.perform(bla... bla).andReturn().getResolvedException().getMessage()

This should give you the body of the response. "Username already taken" in your case.

How to write a switch statement in Ruby

Since switch case always returns a single object, we can directly print its result:

puts case a
     when 0
        "It's zero"
     when 1
        "It's one"
     end

Using Mockito, how do I verify a method was a called with a certain argument?

Building off of Mamboking's answer:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:

ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");

If that assumption was wrong, and the argument to save() is a collection of some kind, it would be only slightly different:

ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);

You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.

printing out a 2-D array in Matrix format

public static void printMatrix(double[][] matrix) {
    for (double[] row : matrix) {
        for (double element : row) {
            System.out.printf("%5.1f", element);
        }
        System.out.println();
    }
}

Function Call

printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});

Output:

  2.0  0.0  0.0
  0.0  2.0  0.0
  0.0  0.0  3.0

In console:

Console Output

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

This problem happened with me when I used jQUery Fancybox inside a website with many others jQuery plugins. When I used the LightBox (site here) instead of Fancybox, the problem is gone.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Change

 mAdapter = new RecordingsListAdapter(this, recordings);

to

 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

Is there a way to catch the back button event in javascript?

I have created a solution which may be of use to some people. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

"No backupset selected to be restored" SQL Server 2012

I think I get the award for the most bone headed reason to get this error. In the Restore Database dialog, the database dropdown under Source is gray and I thought it was disabled. I skipped down to the database dropdown under Destination thinking it was the source and made a selection. Doing this will cause this error message to be displayed.

What does upstream mean in nginx?

If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.

background-image: url("images/plaid.jpg") no-repeat; wont show up

You may debug using two ways:

  1. Press CTRL+U to view page Source . Press CTRL+F to find "mystyles.css" in source . click on mystyles.css link and check if it is not showing "404 not found".

  2. You can INSPECT ELEMENT IN FIRBUG and set path to Image ,Set Image height and width because sometimes image doesnt show up.

Hope this may works !!.

How is CountDownLatch used in Java Multithreading?

One good example of when to use something like this is with Java Simple Serial Connector, accessing serial ports. Typically you'll write something to the port, and asyncronously, on another thread, the device will respond on a SerialPortEventListener. Typically, you'll want to pause after writing to the port to wait for the response. Handling the thread locks for this scenario manually is extremely tricky, but using Countdownlatch is easy. Before you go thinking you can do it another way, be careful about race conditions you never thought of!!

Pseudocode:

CountDownLatch latch;
void writeData() { 
   latch = new CountDownLatch(1);
   serialPort.writeBytes(sb.toString().getBytes())
   try {
      latch.await(4, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
   }
}
class SerialPortReader implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR()){//If data is available
            byte buffer[] = serialPort.readBytes(event.getEventValue());
            latch.countDown();
         }
     }
}

Convert string to a variable name

The function you are looking for is get():

assign ("abc",5)
get("abc")

Confirming that the memory address is identical:

getabc <- get("abc")
pryr::address(abc) == pryr::address(getabc)
# [1] TRUE

Reference: R FAQ 7.21 How can I turn a string into a variable?

How to print a query string with parameter values when using Hibernate

All of the answers here are helpful, but if you're using a Spring application context XML to setup your session factory, setting the log4j SQL level variable only gets you part of the way there, you also have to set the hibernate.show_sql variable in the app context itself to get Hibernate to start actually showing the values.

ApplicationContext.xml has:

<property name="hibernateProperties">
            <value>
            hibernate.jdbc.batch_size=25
            ... <!-- Other parameter values here -->
            hibernate.show_sql=true
            </value>
 </property>

And your log4j file needs

log4j.logger.org.hibernate.SQL=DEBUG

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

If you are using "n" library @ https://github.com/tj/n . Do the following

  echo $NODE_PATH

If node path is empty, then

sudo n latest    - sudo is optional depending on your system

After switching Node.js versions using n, npm may not work properly.

curl -0 -L https://npmjs.com/install.sh | sudo sh
echo NODE_PATH

You should see your Node Path now. Else, it might be something else

How to read data from java properties file using Spring Boot

i would suggest the following way:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

Please initialize the log4j system properly warning

From the link in the error message:

This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments. Also see FAQ: Why can't log4j find my properties in a J2EE or WAR application?.

The configuration file cannot be found. Are you using xml or a property file??

Also, use logback!

.war vs .ear file

From GeekInterview:

In J2EE application, modules are packaged as EAR, JAR, and WAR based on their functionality

JAR: EJB modules which contain enterprise java beans (class files) and EJB deployment descriptor are packed as JAR files with .jar extension

WAR: Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as a JAR file with .war (web archive) extension

EAR: All the above files (.jar and .war) are packaged as a JAR file with .ear (enterprise archive) extension and deployed into Application Server.

How to set width of a div in percent in JavaScript?

Also you can use .prop() and it should be better because

Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

$(elem).prop('width', '100%');
$(elem).prop('height', '100%');

Catching access violation exceptions?

A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.

how to change the dist-folder path in angular-cli after 'ng build'

Angular CLI now uses environment files to do this.

First, add an environments section to the angular-cli.json

Something like :

{
  "apps": [{
      "environments": {
        "prod": "environments/environment.prod.ts"
      }
    }]
}

And then inside the environment file (environments/environment.prod.ts in this case), add something like :

export const environment = {
  production: true,
  "output-path": "./whatever/dist/"
};

now when you run :

ng build --prod

it will output to the ./whatever/dist/ folder.

How to search for an element in a golang slice

You can use sort.Slice() plus sort.Search()

type Person struct {
    Name string
}

func main() {
    crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}

    sort.Slice(crowd, func(i, j int) bool {
        return crowd[i].Name <= crowd[j].Name
    })

    needle := "Benni"
    idx := sort.Search(len(crowd), func(i int) bool {
        return string(crowd[i].Name) >= needle
    })

    if crowd[idx].Name == needle {
        fmt.Println("Found:", idx, crowd[idx])
    } else {
        fmt.Println("Found noting: ", idx)
    }
}

See: https://play.golang.org/p/47OPrjKb0g_c

Best practice to return errors in ASP.NET Web API

For me I usually send back an HttpResponseException and set the status code accordingly depending on the exception thrown and if the exception is fatal or not will determine whether I send back the HttpResponseException immediately.

At the end of the day it's an API sending back responses and not views, so I think it's fine to send back a message with the exception and status code to the consumer. I currently haven't needed to accumulate errors and send them back as most exceptions are usually due to incorrect parameters or calls etc.

An example in my app is that sometimes the client will ask for data, but there isn't any data available so I throw a custom NoDataAvailableException and let it bubble to the Web API app, where then in my custom filter which captures it sending back a relevant message along with the correct status code.

I am not 100% sure on what's the best practice for this, but this is working for me currently so that's what I'm doing.

Update:

Since I answered this question a few blog posts have been written on the topic:

https://weblogs.asp.net/fredriknormen/asp-net-web-api-exception-handling

(this one has some new features in the nightly builds) https://docs.microsoft.com/archive/blogs/youssefm/error-handling-in-asp-net-webapi

Update 2

Update to our error handling process, we have two cases:

  1. For general errors like not found, or invalid parameters being passed to an action we return a HttpResponseException to stop processing immediately. Additionally for model errors in our actions we will hand the model state dictionary to the Request.CreateErrorResponse extension and wrap it in a HttpResponseException. Adding the model state dictionary results in a list of the model errors sent in the response body.

  2. For errors that occur in higher layers, server errors, we let the exception bubble to the Web API app, here we have a global exception filter which looks at the exception, logs it with ELMAH and tries to make sense of it setting the correct HTTP status code and a relevant friendly error message as the body again in a HttpResponseException. For exceptions that we aren't expecting the client will receive the default 500 internal server error, but a generic message due to security reasons.

Update 3

Recently, after picking up Web API 2, for sending back general errors we now use the IHttpActionResult interface, specifically the built in classes for in the System.Web.Http.Results namespace such as NotFound, BadRequest when they fit, if they don't we extend them, for example a NotFound result with a response message:

public class NotFoundWithMessageResult : IHttpActionResult
{
    private string message;

    public NotFoundWithMessageResult(string message)
    {
        this.message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotFound);
        response.Content = new StringContent(message);
        return Task.FromResult(response);
    }
}

How To fix white screen on app Start up?

Just mention the transparent theme to the starting activity in the AndroidManifest.xml file.

Like:

<activity
        android:name="first Activity Name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" >
 <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
 </activity>

and extend that screen with Activity class in place of AppCompatActivity.

like :

public class SplashScreenActivity extends Activity{

  ----YOUR CODE GOES HERE----
}

How to convert int to float in python?

In Python 3 this is the default behavior, but if you aren't using that you can import division like so:

>>> from __future__ import division
>>> 144/314
0.4585987261146497

Alternatively you can cast one of the variables to a float when doing your division which will do the same thing

sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))

How can I see what has changed in a file before committing to git?

Remember, you're committing changes, not files.

For this reason, it's very rare that I don't use git add -p (or the magit equivalent) to add my changes.

Wait for all promises to resolve

I want the all to resolve when all the chains have been resolved.

Sure, then just pass the promise of each chain into the all() instead of the initial promises:

$q.all([one.promise, two.promise, three.promise]).then(function() {
    console.log("ALL INITIAL PROMISES RESOLVED");
});

var onechain   = one.promise.then(success).then(success),
    twochain   = two.promise.then(success),
    threechain = three.promise.then(success).then(success).then(success);

$q.all([onechain, twochain, threechain]).then(function() {
    console.log("ALL PROMISES RESOLVED");
});

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

How can I force users to access my page over HTTPS instead of HTTP?

You shouldn't for security reasons. Especially if cookies are in play here. It leaves you wide open to cookie-based replay attacks.

Either way, you should use Apache control rules to tune it.

Then you can test for HTTPS being enabled and redirect as-needed where needed.

You should redirect to the pay page only using a FORM POST (no get), and accesses to the page without a POST should be directed back to the other pages. (This will catch the people just hot-jumping.)

http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/

Is a good place to start, apologies for not providing more. But you really should shove everything through SSL.

It's over-protective, but at least you have less worries.

How do I ignore ampersands in a SQL script running from SQL Plus?

I resolved with the code below:

set escape on

and put a \ beside & in the left 'value_\&_intert'

Att

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

Checking password match while typing

The onkeyup event does "work" as you intend:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
function checkPasswordMatch() {
    var password = $("#txtNewPassword").val();
    var confirmPassword = $("#txtConfirmPassword").val();

    if (password != confirmPassword)
        $("#divCheckPasswordMatch").html("Passwords do not match!");
    else
        $("#divCheckPasswordMatch").html("Passwords match.");
}
//--></script>
</head>
<body>

<div class="td">
    <input type="password" id="txtNewPassword" />
</div>
<div class="td">
    <input type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();" />
</div>
    <div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>

</body>
</html>

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

How to list records with date from the last 10 days?

Just generalising the query if you want to work with any given date instead of current date:

SELECT Table.date
  FROM Table 
  WHERE Table.date > '2020-01-01'::date - interval '10 day'

Change header text of columns in a GridView

I Think this Works:

 testGV.HeaderRow.Cells[0].Text="Date"

Android selector & text color

And selector is the answer here as well.

Search for bright_text_dark_focused.xml in the sources, add to your project under res/color directory and then refer from the TextView as

android:textColor="@color/bright_text_dark_focused"

jQuery SVG vs. Raphael

Oh Raphael has moved on significantly since June. There is a new charting library that can work with it and these are very eye catching. Raphael also supports full SVG path syntax and is incorporating really advanced path methods. Come see 1.2.8+ at my site (Shameless plug) and then bounce over to the Dmitry's site from there. http://www.irunmywebsite.com/raphael/raphaelsource.html

Android Studio does not show layout preview

Please (change com.android.support:appcompat-v7:28.0.0-alpha3) or (com.android.support:appcompat-v7:28.0.0-rc02) to (com.android.support:appcompat-v7:28.0.0-alpha1) in build.gradle (Module: App).

Next click File -> Invalidate Caches / Restart

Need internet access.

It works for me Windows 10 and in Ubuntu 18.04.1 LTS

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

type checking in javascript

A variable will never be an integer type in JavaScript — it doesn't distinguish between different types of Number.

You can test if the variable contains a number, and if that number is an integer.

(typeof foo === "number") && Math.floor(foo) === foo

If the variable might be a string containing an integer and you want to see if that is the case:

foo == parseInt(foo, 10)

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I'm using n (Node version management)

You can install it in two ways

brew install n

or

npm install -g n

You can switch between different version of node and io. Here's an example from my current env when I call n without params:

$ n

  io/3.3.1
  node/0.12.7
  node/4.0.0
  node/5.0.0
? node/5.10.1 

How to find which columns contain any NaN value in Pandas dataframe

In datasets having large number of columns its even better to see how many columns contain null values and how many don't.

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))

For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.

Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)

Note: Above code removes all of your null values. If you want null values, process them before.

server error:405 - HTTP verb used to access this page is not allowed

I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Qt C++ will show this error when you change a class such that it now inherits from QObject (ie so that it can now use signals/slots). Running qmake -r will call moc and fix this problem.

If you are working with others via some sort of version control, you will want to make some change to your .pro file (ie add/remove a blank line). When everyone else gets your changes and runs make, make will see that the .pro file has changed and automatically run qmake. This will save your teammates from repeating your frustration.

How to align a <div> to the middle (horizontally/width) of the page

Simple http://jsfiddle.net/8pd4qx5r/

html {
  display: table;
  height: 100%;
  width: 100%;
}

body {
  display: table-cell;
  vertical-align: middle;
}

.content {
  margin: 0 auto;
  width: 260px;
  text-align: center;
  background: pink;
}

The requested resource does not support HTTP method 'GET'

In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.

[Route("Documents/{id}")]   <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)
{
  ..
}

Javascript date.getYear() returns 111 in 2011?

From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear() is the way to go. If you're really wanting to use getYear() add 1900 to it.

var now = new Date(),
    year = now.getYear() + 1900;

Dart: mapping a list (list.map)

you can use

moviesTitles.map((title) => Tab(text: title)).toList()

example:

    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) => Tab(text: title)).toList()
      ,
    ),

Android Pop-up message

sample code show custom dialog in kotlin:

fun showDlgFurtherDetails(context: Context,title: String?, details: String?) {

    val dialog = Dialog(context)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.dlg_further_details)
    dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    val lblService = dialog.findViewById(R.id.lblService) as TextView
    val lblDetails = dialog.findViewById(R.id.lblDetails) as TextView
    val imgCloseDlg = dialog.findViewById(R.id.imgCloseDlg) as ImageView

    lblService.text = title
    lblDetails.text = details
    lblDetails.movementMethod = ScrollingMovementMethod()
    lblDetails.isScrollbarFadingEnabled = false
    imgCloseDlg.setOnClickListener {
        dialog.dismiss()
    }
    dialog.show()
}

Check if element found in array c++

C++ has NULL as well, often the same as 0 (pointer to address 0x00000000).

Do you use NULL or 0 (zero) for pointers in C++?

So in C++ that null check would be:

 if (!foo)
    cout << "not found";

Calling javascript function in iframe

objectframe.contentWindow.Reset() you need reference to the top level element in the frame first.

PHP - remove <img> tag from string

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

SQL Query Where Date = Today Minus 7 Days

DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))

Pandas dataframe get first row of each group

I'd suggest to use .nth(0) rather than .first() if you need to get the first row.

The difference between them is how they handle NaNs, so .nth(0) will return the first row of group no matter what are the values in this row, while .first() will eventually return the first not NaN value in each column.

E.g. if your dataset is :

df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
            'value'  : ["first","second","third", np.NaN,
                        "second","first","second","third",
                        "fourth","first","second"]})

>>> df.groupby('id').nth(0)
    value
id        
1    first
2    NaN
3    first
4    first

And

>>> df.groupby('id').first()
    value
id        
1    first
2    second
3    first
4    first

Is there a simple way to delete a list element by value?

Here's how to do it inplace (without list comprehension):

def remove_all(seq, value):
    pos = 0
    for item in seq:
        if item != value:
           seq[pos] = item
           pos += 1
    del seq[pos:]

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

I was experiencing a similar error message that I noticed in the Windows Event Viewer that read:

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Reason: Failed to open the explicitly specified database. [CLIENT: local machine]

The solution that resolved my problem was:

  1. Login to SqlExpress via SQL Server Management Studio
  2. Go to the "Security" directory of the database
  3. Right-click the Users directory
  4. Select "New User..."
  5. Add 'NT AUTHORITY\NETWORK SERVICE' as a new user
  6. In the Data Role Membership area, select db_owner
  7. Click OK

Here's a screenshot of the above: Screenshot of adding new user Network Service as db_owner to SqlExpress

Add an element to an array in Swift

From page 143 of The Swift Programming Language:

You can add a new item to the end of an array by calling the array’s append method

Alternatively, add a new item to the end of an array with the addition assignment operator (+=)

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

How to create an empty array in PHP with predefined size?

Possibly related, if you want to initialize and fill an array with a range of values, use PHP's (wait for it...) range function:

$a = range(1, 5);  // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

How can I read comma separated values from a text file in Java?

Use OpenCSV for reliability. Split should never be used for these kind of things. Here's a snippet from a program of my own, it's pretty straightforward. I check if a delimiter character was specified and use this one if it is, if not I use the default in OpenCSV (a comma). Then i read the header and fields

CSVReader reader = null;
try {
    if (delimiter > 0) {
        reader = new CSVReader(new FileReader(this.csvFile), this.delimiter);
    }
    else {
        reader = new CSVReader(new FileReader(this.csvFile));
    }

    // these should be the header fields
    header = reader.readNext();
    while ((fields = reader.readNext()) != null) {
        // more code
    }
catch (IOException e) {
    System.err.println(e.getMessage());
}

How to delete parent element using jQuery

I have stumbled upon this problem for one hour. After an hour, I tried debugging and this helped:

$('.list').on('click', 'span', (e) => {
  $(e.target).parent().remove();
});

HTML:

<ul class="list">
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
  <li class="task">some text<span>X</span></li>
</ul>

How can I enable cURL for an installed Ubuntu LAMP stack?

First thing to do: Check for the PHP version your machine is running.

Command Line: php -version

This will show something like this (in my case):

PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS ) Copyright (c) 1997-2016 The PHP Group

If you are using PHP 5.x.x => run command: sudo apt-get install php5-curl

If PHP 7.x.x => run command (in my case): sudo apt-get install php7.0-curl

Enable this extension by running:

sudo gedit /etc/php/7.0/cli/php.ini

And in the file "php.ini" search for keyword "curl" to find this line below and change it from

;extension=php_curl.dll

To:

extension=php_curl.dll

Next, save your file "php.ini".

Finally, in your command line, restart your server by running: sudo service apache2 restart.

Will iOS launch my app into the background if it was force-quit by the user?

For iOS13

For background pushes in iOS13, you must set below parameters:

apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms 

Background PUSHES The video link: https://developer.apple.com/videos/play/wwdc2019/707/

How do I implement a callback in PHP?

I cringe every time I use create_function() in php.

Parameters are a coma separated string, the whole function body in a string... Argh... I think they could not have made it uglier even if they tried.

Unfortunately, it is the only choice when creating a named function is not worth the trouble.

C++ int to byte array

Int to byte and vice versa.

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);


int num = 0;
for(int i = 0; i < 4; i++)
 {
 num <<= 8;
 num |= bytes[i];
 }


printf("number %d",num);

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

"Port 4200 is already in use" when running the ng serve command

For Ubndu 18.04 sudo lsof -t -i tcp:3000 | xargs kill -9

Its happen when port was unsucessfully terminated so this command will terminat it 4200 or 3000 or3300 any

Filter dataframe rows if value in column is in a set list of values

Use the isin method:

rpt[rpt['STK_ID'].isin(stk_list)]

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

There's a pretty good write up in the Adobe KB's on 'wmode' and other attributes with regards to their effect on presentation and performance.

http://kb2.adobe.com/cps/127/tn_12701.html

jQuery detect if string contains something

You can use javascript's indexOf function.

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
   alert(str2 + " found");
}

T-SQL: Looping through an array of known values

You can try as below :

declare @list varchar(MAX), @i int
select @i=0, @list ='4,7,12,22,19,'

while( @i < LEN(@list))
begin
    declare @item varchar(MAX)
    SELECT  @item = SUBSTRING(@list,  @i,CHARINDEX(',',@list,@i)-@i)
    select @item

     --do your stuff here with @item 
     exec p_MyInnerProcedure @item 

    set @i = CHARINDEX(',',@list,@i)+1
    if(@i = 0) set @i = LEN(@list) 
end

Bootstrap: wider input field

There is also a smaller one yet called "input-mini".

Return value in a Bash function

As an add-on to others' excellent posts, here's an article summarizing these techniques:

  • set a global variable
  • set a global variable, whose name you passed to the function
  • set the return code (and pick it up with $?)
  • 'echo' some data (and pick it up with MYVAR=$(myfunction) )

Returning Values from Bash Functions

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

Get Memory Usage in Android

Since the OP asked about CPU usage AND memory usage (accepted answer only shows technique to get cpu usage), I'd like to recommend the ActivityManager class and specifically the accepted answer from this question: How to get current memory usage in android?

How to inspect Javascript Objects

How about alert(JSON.stringify(object)) with a modern browser?

In case of TypeError: Converting circular structure to JSON, here are more options: How to serialize DOM node to JSON even if there are circular references?

The documentation: JSON.stringify() provides info on formatting or prettifying the output.

How to mark-up phone numbers?

I used tel: for my project.

It worked in Chrome, Firefox, IE9&8, Chrome mobile and the mobile Browser on my Sony Ericsson smartphone.

But callto: did not work in the mobile Browsers.

How to convert a String to CharSequence?

That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:

    List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
    List<CharSequence> result;
    
//    result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
    result = input.stream().collect(Collectors.toList());
    
    System.out.println(result);

Random row selection in Pandas dataframe

Below line will randomly select n number of rows out of the total existing row numbers from the dataframe df without replacement.

df=df.take(np.random.permutation(len(df))[:n])

Javascript getElementsByName.value not working

document.getElementsByName("name") will get several elements called by same name . document.getElementsByName("name")[Number] will get one of them. document.getElementsByName("name")[Number].value will get the value of paticular element.

The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.

ERROR in ./node_modules/css-loader?

My case:

Missing node-sass in package.json

Solution:

  1. npm i --save node-sass@latest
  2. remove node-modules folder
  3. npm i
  4. check "@angular-devkit/build-angular": "^0.901.0" version in package.json

How to unpack pkl file?

Generally

Your pkl file is, in fact, a serialized pickle file, which means it has been dumped using Python's pickle module.

To un-pickle the data you can:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

For the MNIST data set

Note gzip is only needed if the file is compressed:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

Where each set can be further divided (i.e. for the training set):

train_x, train_y = train_set

Those would be the inputs (digits) and outputs (labels) of your sets.

If you want to display the digits:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

The other alternative would be to look at the original data:

http://yann.lecun.com/exdb/mnist/

But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle. As you've seen, it's very easy. ;-)

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

It seems that you can transfer your Certificates and Provisioning profiles from one machine to the other, so if you are having issues in setting up your certificate and/or profiles because you migrated your Dev machine, have a look at this:

how to transfer xcode certificates between macs

Getting the inputstream from a classpath resource (XML file)

That depends on where exactly the XML file is. Is it in the sources folder (in the "default package" or the "root") or in the same folder as the class?

In for former case, you must use "/file.xml" (note the leading slash) to find the file and it doesn't matter which class you use to try to locate it.

If the XML file is next to some class, SomeClass.class.getResourceAsStream() with just the filename is the way to go.

Possible reasons for timeout when trying to access EC2 instance

ping the DNS first . If fails then configure your inbound/outbound rules in the launch wizard . configure ALL traffic and ALL protocol and just save with default options . Ping again with your local system and then should work

android : Error converting byte to dex

For some reasons, @ChintanSoni's answer didn't worked. I tried deleting the build folder manually but couldn't delete some files since they were being used by some process. Cleaning and re-building the project didn't help so I opened task manager, selected JAVA(TM) Platform SE binary and pressed on 'End task`.

Then I tried to run the project once again and it started compiling fine.

Export table data from one SQL Server to another

Yet another option if you have it available: c# .net. In particular, the Microsoft.SqlServer.Management.Smo namespace.

I use code similar to the following in a Script Component of one of my SSIS packages.

var tableToTransfer = "someTable";
var transferringTableSchema = "dbo";

var srvSource = new Server("sourceServer");
var dbSource = srvSource.Databases["sourceDB"];

var srvDestination = new Server("destinationServer"); 
var dbDestination = srvDestination.Databases["destinationDB"];

var xfr = 
    new Transfer(dbSource) {
        DestinationServer = srvDestination.Name,
        DestinationDatabase = dbDestination.Name,
        CopyAllObjects = false,
        DestinationLoginSecure = true,
        DropDestinationObjectsFirst = true,
        CopyData = true
    };

xfr.Options.ContinueScriptingOnError = false; 
xfr.Options.WithDependencies = false; 

xfr.ObjectList.Add(dbSource.Tables[tableToTransfer,transferringTableSchema]);
xfr.TransferData();

I think I had to explicitly search for and add the Microsoft.SqlServer.Smo library to the references. But outside of that, this has been working out for me.

Update: The namespace and libraries were more complicated than I remembered.

For libraries, add references to:

  • Microsoft.SqlServer.Smo.dll
  • Microsoft.SqlServer.SmoExtended.dll
  • Microsoft.SqlServer.ConnectionInfo.dll
  • Microsoft.SqlServer.Management.Sdk.Sfc.dll

For the Namespaces, add:

  • Microsoft.SqlServer.Management.Common
  • Microsoft.SqlServer.Management.Smo

How do I revert a Git repository to a previous commit?

I believe some people may come to this question wanting to know how to rollback committed changes they've made in their master - ie throw everything away and go back to origin/master, in which case, do this:

git reset --hard origin/master

https://superuser.com/questions/273172/how-to-reset-master-to-origin-master

Get the value for a listbox item by index

I'm using a BindingSource with a SqlDataReader behind it and none of the above works for me.

Question for Microsoft: Why does this work:

  ? lst.SelectedValue

But this doesn't?

   ? lst.Items[80].Value

I find I have to go back to to the BindingSource object, cast it as a System.Data.Common.DbDataRecord, and then refer to its column name:

   ? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"]

Now that's just ridiculous.

What is the color code for transparency in CSS?

Simply put:

.democlass {
    background-color: rgba(246,245,245,0);
}

That should give you a transparent background.

How to hide element label by element id in CSS?

You probably have to add a class/id to and then make another CSS declaration that hides it as well.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

not finding android sdk (Unity)

Easier solution: set the environment variable USE_SDK_WRAPPER=1, or hack tools/android.bat to add the line "set USE_SDK_WRAPPER=1". This prevents android.bat from popping up a "y/n" prompt, which is what's confusing Unity.

How can I generate a unique ID in Python?

unique and random are mutually exclusive. perhaps you want this?

import random
def uniqueid():
    seed = random.getrandbits(32)
    while True:
       yield seed
       seed += 1

Usage:

unique_sequence = uniqueid()
id1 = next(unique_sequence)
id2 = next(unique_sequence)
id3 = next(unique_sequence)
ids = list(itertools.islice(unique_sequence, 1000))

no two returned id is the same (Unique) and this is based on a randomized seed value

How to get first character of string?

charAt do not work if it has a parent prop
ex parent.child.chartAt(0)
use parent.child.slice(0, 1)

jQuery: how to find first visible input/select/textarea excluding buttons?

This is my summary of the above and works perfectly for me. Thanks for the info!

<script language='javascript' type='text/javascript'>
    $(document).ready(function () {
        var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
        if (firstInput != null) {
            firstInput.focus();
        }
    });
</script>

Set Session variable using javascript in PHP

You can't directly manipulate a session value from Javascript - they only exist on the server.

You could let your Javascript get and set values in the session by using AJAX calls though.

See also

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}

Verify a certificate chain using openssl verify

I've had to do a verification of a letsencrypt certificate and I did it like this:

  1. Download the root-cert and the intermediate-cert from the letsencrypt chain of trust.
  2. Issue this command:

    $ openssl verify -CAfile letsencrypt-root-cert/isrgrootx1.pem.txt -untrusted letsencrypt-intermediate-cert/letsencryptauthorityx3.pem.txt /etc/letsencrypt/live/sitename.tld/cert.pem 
    /etc/letsencrypt/live/sitename.tld/cert.pem: OK
    

How do you get the contextPath from JavaScript, the right way?

A Spring Boot with Thymeleaf solution could look like:

Lets say my context-path is /app/

In Thymeleaf you can get it via:

<script th:inline="javascript">
    /*<![CDATA[*/
        let contextPath    = /*[[@{/}]]*/
    /*]]>*/
</script>

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to get image size (height & width) using JavaScript?

Try

_x000D_
_x000D_
function sizes() {
  console.log(`width: ${pic.width}, height:${pic.height}`);
}
_x000D_
<img id="pic" src="https://picsum.photos/300/150">
<button onclick="sizes()">show size</button>
_x000D_
_x000D_
_x000D_

How can I create an editable combo box in HTML/Javascript?

Was looking for an Answer as well, but all I could find was outdated.

This Issue is solved since HTML5: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>

If I had not found that, I would have gone with this approach:

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Set a form's action attribute when submitting?

You can do that on javascript side .

<input type="submit" value="Send It!" onClick="return ActionDeterminator();">

When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.

function ActionDeterminator() {
  if(document.myform.reason[0].checked == true) {
    document.myform.action = 'http://google.com';
  }
  if(document.myform.reason[1].checked == true) {
    document.myform.action = 'http://microsoft.com';
    document.myform.method = 'get';
  }
  if(document.myform.reason[2].checked == true) {
    document.myform.action = 'http://yahoo.com';
  }
  return true;
}

Does "\d" in regex mean a digit?

Info regarding .NET / C#:

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.

Info: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d

List of installed gems?

The Gem command is included with Ruby 1.9+ now, and is a standard addition to Ruby pre-1.9.

require 'rubygems'

name = /^/i
dep = Gem::Dependency.new(name, Gem::Requirement.default)
specs = Gem.source_index.search(dep)
puts specs[0..5].map{ |s| "#{s.name} #{s.version}" }
# >> Platform 0.4.0
# >> abstract 1.0.0
# >> actionmailer 3.0.5
# >> actionpack 3.0.5
# >> activemodel 3.0.5
# >> activerecord 3.0.5

Here's an updated way to get a list:

require 'rubygems'

def local_gems
   Gem::Specification.sort_by{ |g| [g.name.downcase, g.version] }.group_by{ |g| g.name }
end

Because local_gems relies on group_by, it returns a hash of the gems, where the key is the gem's name, and the value is an array of the gem specifications. The value is an array of the instances of that gem that is installed, sorted by the version number.

That makes it possible to do things like:

my_local_gems = local_gems()

my_local_gems['actionmailer']
# => [Gem::Specification.new do |s|
#       s.authors = ["David Heinemeier Hansson"]
#       s.date = Time.utc(2013, 12, 3)
#       s.dependencies = [Gem::Dependency.new("actionpack",
#         Gem::Requirement.new(["= 4.0.2"]),
#         :runtime),
#        Gem::Dependency.new("mail",
#         Gem::Requirement.new(["~> 2.5.4"]),
#         :runtime)]
#       s.description = "Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments."
#       s.email = "[email protected]"
#       s.homepage = "http://www.rubyonrails.org"
#       s.licenses = ["MIT"]
#       s.name = "actionmailer"
#       s.require_paths = ["lib"]
#       s.required_ruby_version = Gem::Requirement.new([">= 1.9.3"])
#       s.requirements = ["none"]
#       s.rubygems_version = "2.0.14"
#       s.specification_version = 4
#       s.summary = "Email composition, delivery, and receiving framework (part of Rails)."
#       s.version = Gem::Version.new("4.0.2")
#       end]

And:

puts my_local_gems.map{ |name, specs| 
  [ 
    name,
    specs.map{ |spec| spec.version.to_s }.join(',')
  ].join(' ') 
}
# >> actionmailer 4.0.2
...
# >> arel 4.0.1,5.0.0
...
# >> ZenTest 4.9.5
# >> zucker 13.1

The last example is similar to the gem query --local command-line, only you have access to all the information for a particular gem's specification.

why should I make a copy of a data frame in pandas

Because if you don't make a copy then the indices can still be manipulated elsewhere even if you assign the dataFrame to a different name.

For example:

df2 = df
func1(df2)
func2(df)

func1 can modify df by modifying df2, so to avoid that:

df2 = df.copy()
func1(df2)
func2(df)

What represents a double in sql server?

float is the closest equivalent.

SqlDbType Enumeration

For Lat/Long as OP mentioned.

A metre is 1/40,000,000 of the latitude, 1 second is around 30 metres. Float/double give you 15 significant figures. With some quick and dodgy mental arithmetic... the rounding/approximation errors would be the about the length of this fill stop -> "."

Cannot find the declaration of element 'beans'

This error of Cannot find the declaration of element 'beans' but for a whole different reason

It turs out my internet connection was not very reliable, so i decided to check first for this url

http://www.springframework.org/schema/context/spring-context-4.0.xsd

Once I saw that the xsd was open succesfully I clean the Eclipse(IDE) project and the error was gone

If you try this steps and still get the error then check the Spring version so that it matches as mentioned by another answer

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-**[MAYOR.MINOR]**.xsd">

Replace [MAYOR.MINOR] on the last line with whatever major.minor Spring version that you are using

For Spring 4.0 http://www.springframework.org/schema/context/spring-context-4.0.xsd

For Sprint 3.1 http://www.springframework.org/schema/beans spring-beans-3.1.xsd

All the contexts are available here http://www.springframework.org/schema/context/

Reversing a String with Recursion in Java

Another Solutions for reversing a String in Java.

Convert you string into a char array using .toCharArray() function.

public static char[] reverse(char in[], int inLength, char out[],
            int tractOut) {

        if (inLength >= 0) {
            out[tractOut] = in[inLength];
            reverse(in, inLength - 1, out, tractOut + 1);
        }

        return null;

    }

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Add this code in the Module :

Public Sub ClearTextBoxes(frm As Form) 

    For Each Control In frm.Controls
        If TypeOf Control Is TextBox Then
            Control.Text = ""     'Clear all text
        End If       
    Next Control

End Sub

Add this code in the Form window to Call the Sub routine:

Private Sub Command1_Click()
    Call ClearTextBoxes(Me)
End Sub

How to resize the jQuery DatePicker control

You don't have to change it in the jquery-ui css file (it can be confusing if you change the default files), it is enough if you add

div.ui-datepicker{
 font-size:10px;
}

in a stylesheet loaded after the ui-files

div.ui-datepicker is needed in case ui-widget is mentioned after ui-datepicker in the declaration

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

Actually, you can achieve this pretty easy. Simply specify the line height as a number:

<p style="line-height:1.5">
    <span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
    <span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>

The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.

For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.

Optimal way to Read an Excel file (.xls/.xlsx)

Using OLE Query, it's quite simple (e.g. sheetName is Sheet1):

DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
{           
    DataTable sheetData = new DataTable();
    using (OleDbConnection conn = this.returnConnection(fileName))
    {
       conn.Open();
       // retrieve the data using data adapter
       OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
       sheetAdapter.Fill(sheetData);
       conn.Close();
    }                        
    return sheetData;
}

private OleDbConnection returnConnection(string fileName)
{
    return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}

For newer Excel versions:

return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");

You can also use Excel Data Reader an open source project on CodePlex. Its works really well to export data from Excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

Reference: How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

How can I lookup a Java enum from its String value?

with Java 8 you can achieve with this way:

public static Verbosity findByAbbr(final String abbr){
    return Arrays.stream(values()).filter(value -> value.abbr().equals(abbr)).findFirst().orElse(null);
}

Difference between "or" and || in Ruby?

and/or are for control flow.

Ruby will not allow this as valid syntax:

false || raise "Error"

However this is valid:

false or raise "Error"

You can make the first work, with () but using or is the correct method.

false || (raise "Error")

Serialize and Deserialize Json and Json Array in Unity

To Read JSON File, refer this simple example

Your JSON File (StreamingAssets/Player.json)

{
    "Name": "MyName",
    "Level": 4
}

C# Script

public class Demo
{
    public void ReadJSON()
    {
        string path = Application.streamingAssetsPath + "/Player.json";
        string JSONString = File.ReadAllText(path);
        Player player = JsonUtility.FromJson<Player>(JSONString);
        Debug.Log(player.Name);
    }
}

[System.Serializable]
public class Player
{
    public string Name;
    public int Level;
}

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

This simple method solved the problem for me: Copy the content of your dataset, open an empty Excel sheet, choose "Paste Special" -> "Values", and save. Import the new file instead.

(I tried all the existing solutions, and none worked for me. My old dataset appeared to have no missing values, space, special characters, or embedded formulas.)

Display animated GIF in iOS

From iOS 11 Photos framework allows to add animated Gifs playback.

Sample app can be dowloaded here

More info about animated Gifs playback (starting from 13:35 min): https://developer.apple.com/videos/play/wwdc2017/505/

enter image description here

Circle drawing with SVG's arc path

i made a jsfiddle to do it in here:

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
}

function describeArc(x, y, radius, startAngle, endAngle){

var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);

var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

var d = [
    "M", start.x, start.y, 
    "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");

return d;       
}
console.log(describeArc(255,255,220,134,136))

link

all you need to do is to change the input of console.log and get the result in console

PHP "pretty print" json_encode

PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).

This should do the job:

$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);

See http://www.php.net/manual/en/function.json-encode.php

Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)