Programs & Examples On #Java metro framework

Metro is a mature web services framework for Java.

Converting cv::Mat to IplImage*

One problem might be: when using external ipl and defining HAVE_IPL in your project, the ctor

_IplImage::_IplImage(const cv::Mat& m)
{
    CV_Assert( m.dims <= 2 );
    cvInitImageHeader(this, m.size(), cvIplDepth(m.flags), m.channels());
    cvSetData(this, m.data, (int)m.step[0]);
}

found in ../OpenCV/modules/core/src/matrix.cpp is not used/instanciated and conversion fails.

You may reimplement it in a way similar to :

IplImage& FromMat(IplImage& img, const cv::Mat& m)
{
    CV_Assert(m.dims <= 2);
    cvInitImageHeader(&img, m.size(), cvIplDepth(m.flags), m.channels());
    cvSetData(&img, m.data, (int)m.step[0]);
    return img;
}

IplImage img;
FromMat(img,myMat);

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

How to populate HTML dropdown list with values from database

<select name="owner">
<?php 
$sql = mysql_query("SELECT username FROM users");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

How to combine two strings together in PHP?

1.Concatenate the string (space between each string)

Code Snippet :

<?php
 $txt1 = "Sachin";
 $txt2 = "Tendulkar";

 $result = $txt1.$txt2 ;
 echo  $result. "\n";
 ?>  

Output: SachinTendulkar

2.Concatenate the string where space exists

Code Snippet :

<?php
 $txt1 = "Sachin";
 $txt2 = "Tendulkar";

 $result = $txt1." ".$txt2; 
 echo  $result. "\n";
?>  

Output : Sachin Tendulkar

  1. Concatenate the string using printf function.

Code Snippet :

  <?php
 $data1 = "Sachin";
 $data2 = "Tendulkar";
 printf("%s%s\n",$data1, $data2);
 printf("%s %s\n",$data1, $data2); 
?>

Output:
SachinTendulkar
Sachin Tendulkar

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
}
<button type="button" onClick="changeHeight();"> Click Me!</button>

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

set dropdown value by text using jquery

$("#HowYouKnow option:eq(XXX)").attr('selected', 'selected');

where XXX is the index of the one you want.

Command line input in Python

It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:

For interactive user input (or piped commands or redirected input)

Use raw_input in Python 2.x, and input in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)

For example:

user_input = raw_input("Some input please: ")

More details can be found here.

So, for example, you might have a script that looks like this

# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)

# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3

# Now do something with the above
print(user_input)

If you saved this in foo.py, you could just call the script from the command line, it would print out tok tiktok, then ask you for input. You could enter bar baz (followed by the enter key) and it would print bar baz. Here's what that would look like:

$ python foo.py
tok tiktok
Some input please: bar baz
bar baz

Here, $ represents the command-line prompt (so you don't actually type that), and I hit Enter after typing bar baz when it asked for input.

For command-line arguments

Suppose you have a script named foo.py and want to call it with arguments bar and baz from the command line like

$ foo.py bar baz

(Again, $ represents the command-line prompt.) Then, you can do that with the following in your script:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

Here, the variable arg1 will contain the string 'bar', and arg2 will contain 'baz'. The object sys.argv is just a list containing everything from the command line. Note that sys.argv[0] is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:].

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

disable all form elements inside div

Use the CSS Class to prevent from Editing the Div Elements

CSS:

.divoverlay
{
position:absolute;
width:100%;
height:100%;
background-color:transparent;
z-index:1;
top:0;
}

JS:

$('#divName').append('<div class=divoverlay></div>');

Or add the class name in HTML Tag. It will prevent from editing the Div Elements.

string.Replace in AngularJs

In Javascript method names are camel case, so it's replace, not Replace:

$scope.newString = oldString.replace("stackover","NO");

Note that contrary to how the .NET Replace method works, the Javascript replace method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:

$scope.newString = oldString.replace(/stackover/g,"NO");

See this example.

jQuery - get all divs inside a div with class ".container"

To set the class when clicking on a div immediately within the .container element, you could use:

<script>
$('.container>div').click(function () {
        $(this).addClass('whatever')
    });
</script>

convert epoch time to date

EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(1318386508000L);
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        String formatted = format.format(date);
        System.out.println(formatted);
        format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
        formatted = format.format(date);
        System.out.println(formatted);
    }
}

Output:

12/10/2011 02:28:28
12/10/2011 13:28:28

I would also suggest you start using Joda Time which is simply a much nicer date/time API...

EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)

How to find out if an installed Eclipse is 32 or 64 bit version?

In Linux, run file on the Eclipse executable, like this:

$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Using request.setAttribute in a JSP page

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

Ascii/Hex convert in bash

For the first part, try

echo Aa | od -t x1

It prints byte-by-byte

$ echo Aa | od -t x1
0000000 41 61 0a
0000003

The 0a is the implicit newline that echo produces.

Use echo -n or printf instead.

$ printf Aa | od -t x1
0000000 41 61
0000002

Is JavaScript's "new" keyword considered harmful?

Another case for new is what I call Pooh Coding. Winnie the Pooh follows his tummy. I say go with the language you are using, not against it.

Chances are that the maintainers of the language will optimize the language for the idioms they try to encourage. If they put a new keyword into the language they probably think it makes sense to be clear when creating a new instance.

Code written following the language's intentions will increase in efficiency with each release. And code avoiding the key constructs of the language will suffer with time.

EDIT: And this goes well beyond performance. I can't count the times I've heard (or said) "why the hell did they do that?" when finding strange looking code. It often turns out that at the time when the code was written there was some "good" reason for it. Following the Tao of the language is your best insurance for not having your code ridiculed some years from now.

What is the proper way to format a multi-line dict in Python?

Since your keys are strings and since we are talking about readability, I prefer :

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)

How do I get the SharedPreferences from a PreferenceActivity in Android?

Declare these methods first..

public static void putPref(String key, String value, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

Then call this when you want to put a pref:

putPref("myKey", "mystring", getApplicationContext());

call this when you want to get a pref:

getPref("myKey", getApplicationContext());

Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo which simplifies everything even further

Example:

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

multiple packages in context:component-scan, spring config

You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:

<context:component-scan base-package="x.y.z">
   <context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>

Largest and smallest number in an array

Here is the complete programme give Below`

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace oops3
{  
    public class Demo
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size of the array");
            int x = Convert.ToInt32(Console.ReadLine());
            int[] arr = new int[x];
            Console.WriteLine("Enter the elements of the array");
            for(int i=0;i<x;i++)
            {
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = arr[0];
            int Largest = arr[0];
            for(int i=0;i<x;i++)
            {
                if(smallest>arr[i])
                {
                    smallest = arr[i];
                }
            }
            for (int i = 0; i < x; i++)
            {
                if (Largest< arr[i])
                {
                    Largest = arr[i];
                }
            }
            Console.WriteLine("The greater No in the array:" + Largest);
            Console.WriteLine("The smallest No in the array:" + smallest);
            Console.ReadLine();
        }
    }        
}

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

How do I write data to csv file in columns and rows from a list in python?

>>> import csv
>>> with open('test.csv', 'wb') as f:
...     wtr = csv.writer(f, delimiter= ' ')
...     wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
...     for line in f:
...         print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>

To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.

How to do logging in React Native?

console.log() is the best and simple way to see your log on console when you use remote js debugger from your developer menu

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

How we can bold only the name in table td tag not the value

Try this

_x000D_
_x000D_
.Bold { font-weight: bold; }
_x000D_
<span> normal text</span> <br>_x000D_
<span class="Bold"> bold text</span> <br>_x000D_
<span> normal text</span> <spanspan>
_x000D_
_x000D_
_x000D_

What is the difference between json.dump() and json.dumps() in python?

There isn't much else to add other than what the docs say. If you want to dump the JSON into a file/socket or whatever, then you should go with dump(). If you only need it as a string (for printing, parsing or whatever) then use dumps() (dump string)

As mentioned by Antti Haapala in this answer, there are some minor differences on the ensure_ascii behaviour. This is mostly due to how the underlying write() function works, being that it operates on chunks rather than the whole string. Check his answer for more details on that.

json.dump()

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object

If ensure_ascii is False, some chunks written to fp may be unicode instances

json.dumps()

Serialize obj to a JSON formatted str

If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

A lot of things can configured in applicationproperties. Unfortunately this feature only in Version 1.3, but you can add in a Config-Class

@Autowired(required = true)
public void configureJackson(ObjectMapper jackson2ObjectMapper) {
    jackson2ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}

[UPDATE: You must work on the ObjectMapper because the build()-method is called before the config is runs.]

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

Can I use jQuery with Node.js?

A simple crawler using Cheerio

This is my formula to make a simple crawler in Node.js. It is the main reason for wanting to do DOM manipulation on the server side and probably it's the reason why you got here.

First, use request to download the page to be parsed. When the download is complete, handle it to cheerio and begin DOM manipulation just like using jQuery.

Working example:

var
    request = require('request'),
    cheerio = require('cheerio');

function parse(url) {
    request(url, function (error, response, body) {
        var
            $ = cheerio.load(body);

        $('.question-summary .question-hyperlink').each(function () {
            console.info($(this).text());
        });
    })
}

parse('http://stackoverflow.com/');

This example will print to the console all top questions showing on SO home page. This is why I love Node.js and its community. It couldn't get easier than that :-)

Install dependencies:

npm install request cheerio

And run (assuming the script above is in file crawler.js):

node crawler.js


Encoding

Some pages will have non-english content in a certain encoding and you will need to decode it to UTF-8. For instance, a page in brazilian portuguese (or any other language of latin origin) will likely be encoded in ISO-8859-1 (a.k.a. "latin1"). When decoding is needed, I tell request not to interpret the content in any way and instead use iconv-lite to do the job.

Working example:

var
    request = require('request'),
    iconv = require('iconv-lite'),
    cheerio = require('cheerio');

var
    PAGE_ENCODING = 'utf-8'; // change to match page encoding

function parse(url) {
    request({
        url: url,
        encoding: null  // do not interpret content yet
    }, function (error, response, body) {
        var
            $ = cheerio.load(iconv.decode(body, PAGE_ENCODING));

        $('.question-summary .question-hyperlink').each(function () {
            console.info($(this).text());
        });
    })
}

parse('http://stackoverflow.com/');

Before running, install dependencies:

npm install request iconv-lite cheerio

And then finally:

node crawler.js


Following links

The next step would be to follow links. Say you want to list all posters from each top question on SO. You have to first list all top questions (example above) and then enter each link, parsing each question's page to get the list of involved users.

When you start following links, a callback hell can begin. To avoid that, you should use some kind of promises, futures or whatever. I always keep async in my toolbelt. So, here is a full example of a crawler using async:

var
    url = require('url'),
    request = require('request'),
    async = require('async'),
    cheerio = require('cheerio');

var
    baseUrl = 'http://stackoverflow.com/';

// Gets a page and returns a callback with a $ object
function getPage(url, parseFn) {
    request({
        url: url
    }, function (error, response, body) {
        parseFn(cheerio.load(body))
    });
}

getPage(baseUrl, function ($) {
    var
        questions;

    // Get list of questions
    questions = $('.question-summary .question-hyperlink').map(function () {
        return {
            title: $(this).text(),
            url: url.resolve(baseUrl, $(this).attr('href'))
        };
    }).get().slice(0, 5); // limit to the top 5 questions

    // For each question
    async.map(questions, function (question, questionDone) {

        getPage(question.url, function ($$) {

            // Get list of users
            question.users = $$('.post-signature .user-details a').map(function () {
                return $$(this).text();
            }).get();

            questionDone(null, question);
        });

    }, function (err, questionsWithPosters) {

        // This function is called by async when all questions have been parsed

        questionsWithPosters.forEach(function (question) {

            // Prints each question along with its user list
            console.info(question.title);
            question.users.forEach(function (user) {
                console.info('\t%s', user);
            });
        });
    });
});

Before running:

npm install request async cheerio

Run a test:

node crawler.js

Sample output:

Is it possible to pause a Docker image build?
    conradk
    Thomasleveil
PHP Image Crop Issue
    Elyor
    Houston Molinar
Add two object in rails
    user1670773
    Makoto
    max
Asymmetric encryption discrepancy - Android vs Java
    Cookie Monster
    Wand Maker
Objective-C: Adding 10 seconds to timer in SpriteKit
    Christian K Rider

And that's the basic you should know to start making your own crawlers :-)


Libraries used

Check date with todays date

tl;dr

LocalDate
.parse( "2021-01-23" )
.isBefore(
    LocalDate.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
)

… or:

try 
{
    org.threeten.extra.LocalDateRange range =         
        LocalDateRange.of( 
            LocalDate.of( "2021-01-23" ) ,
            LocalDate.of( "2021-02-21" )
        )
    ;
    if( range.isAfter( 
        LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
    ) { … }
    else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
    // Handle error where end is before start.
}

Details

The other answers ignore the crucial issue of time zone.

The other answers use outmoded classes.

Avoid old date-time classes

The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.

java.time

LocalDate

For date-only values, without time-of-day and without time zone, use the LocalDate class.

LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );

Time Zone

Be aware that while LocalDate does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.

If all you have is an offset-from-UTC, use ZoneOffset. If you have a full time zone (continent/region), then use ZoneId. If you want UTC, use the handy constant ZoneOffset.UTC.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

Comparing is easy with isEqual, isBefore, and isAfter methods.

boolean invalidInterval = stop.isBefore( start );

We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.

// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;

LocalDateRange

If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.

ThreeTen-Extra includes an LocalDateRange class with handy methods such as abuts, contains, encloses, overlaps, and so on.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

SQL JOIN and different types of JOINs

What is SQL JOIN ?

SQL JOIN is a method to retrieve data from two or more database tables.

What are the different SQL JOINs ?

There are a total of five JOINs. They are :

  1. JOIN or INNER JOIN
  2. OUTER JOIN

     2.1 LEFT OUTER JOIN or LEFT JOIN
     2.2 RIGHT OUTER JOIN or RIGHT JOIN
     2.3 FULL OUTER JOIN or FULL JOIN

  3. NATURAL JOIN
  4. CROSS JOIN
  5. SELF JOIN

1. JOIN or INNER JOIN :

In this kind of a JOIN, we get all records that match the condition in both tables, and records in both tables that do not match are not reported.

In other words, INNER JOIN is based on the single fact that: ONLY the matching entries in BOTH the tables SHOULD be listed.

Note that a JOIN without any other JOIN keywords (like INNER, OUTER, LEFT, etc) is an INNER JOIN. In other words, JOIN is a Syntactic sugar for INNER JOIN (see: Difference between JOIN and INNER JOIN).

2. OUTER JOIN :

OUTER JOIN retrieves

Either, the matched rows from one table and all rows in the other table Or, all rows in all tables (it doesn't matter whether or not there is a match).

There are three kinds of Outer Join :

2.1 LEFT OUTER JOIN or LEFT JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

2.2 RIGHT OUTER JOIN or RIGHT JOIN

This JOIN returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

2.3 FULL OUTER JOIN or FULL JOIN

This JOIN combines LEFT OUTER JOIN and RIGHT OUTER JOIN. It returns rows from either table when the conditions are met and returns NULL value when there is no match.

In other words, OUTER JOIN is based on the fact that: ONLY the matching entries in ONE OF the tables (RIGHT or LEFT) or BOTH of the tables(FULL) SHOULD be listed.

Note that `OUTER JOIN` is a loosened form of `INNER JOIN`.

3. NATURAL JOIN :

It is based on the two conditions :

  1. the JOIN is made on all the columns with the same name for equality.
  2. Removes duplicate columns from the result.

This seems to be more of theoretical in nature and as a result (probably) most DBMS don't even bother supporting this.

4. CROSS JOIN :

It is the Cartesian product of the two tables involved. The result of a CROSS JOIN will not make sense in most of the situations. Moreover, we won't need this at all (or needs the least, to be precise).

5. SELF JOIN :

It is not a different form of JOIN, rather it is a JOIN (INNER, OUTER, etc) of a table to itself.

JOINs based on Operators

Depending on the operator used for a JOIN clause, there can be two types of JOINs. They are

  1. Equi JOIN
  2. Theta JOIN

1. Equi JOIN :

For whatever JOIN type (INNER, OUTER, etc), if we use ONLY the equality operator (=), then we say that the JOIN is an EQUI JOIN.

2. Theta JOIN :

This is same as EQUI JOIN but it allows all other operators like >, <, >= etc.

Many consider both EQUI JOIN and Theta JOIN similar to INNER, OUTER etc JOINs. But I strongly believe that its a mistake and makes the ideas vague. Because INNER JOIN, OUTER JOIN etc are all connected with the tables and their data whereas EQUI JOIN and THETA JOIN are only connected with the operators we use in the former.

Again, there are many who consider NATURAL JOIN as some sort of "peculiar" EQUI JOIN. In fact, it is true, because of the first condition I mentioned for NATURAL JOIN. However, we don't have to restrict that simply to NATURAL JOINs alone. INNER JOINs, OUTER JOINs etc could be an EQUI JOIN too.

How do I check whether a checkbox is checked in jQuery?

I believe you could do this:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

Getting date format m-d-Y H:i:s.u from milliseconds

// Procedural
$fineStamp = date('Y-m-d\TH:i:s') . substr(microtime(), 1, 9);
echo $fineStamp . PHP_EOL;

// Object-oriented (if you must). Still relies on $fineStamp though :-\
$d = new DateTime($fineStamp);
echo $d->format('Y-m-d\TH:i:s.u') . PHP_EOL;

ListView inside ScrollView is not scrolling on Android

I know this question is asked long ago, but who ever is stuck for now can solve this by adding this line into your ListView

android:nestedScrollingEnabled="true"

For Example -

                    <ListView
                    android:id="@+id/listView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:nestedScrollingEnabled="true" />

ngOnInit not being called when Injectable class is Instantiated

Note: this answer applies only to Angular components and directives, NOT services.

I had this same issue when ngOnInit (and other lifecycle hooks) were not firing for my components, and most searches led me here.

The issue is that I was using the arrow function syntax (=>) like this:

class MyComponent implements OnInit {
    // Bad: do not use arrow function
    public ngOnInit = () => {
        console.log("ngOnInit");
    }
}

Apparently that does not work in Angular 6. Using non-arrow function syntax fixes the issue:

class MyComponent implements OnInit {
    public ngOnInit() {
        console.log("ngOnInit");
    }
}

Lightweight Javascript DB for use in Node.js

Lokijs: A fast, in-memory document-oriented datastore for node.js, browser and cordova.

  • In-memory Javascript Datastore wih Persistence
  • In-Browser NoSQL db with syncing and persisting
  • a Redis-style store an npm install away
  • Persistable NoSQL db for Cordova
  • Embeddable NoSQL db with Persistence for node-webkit

LokiJS to be the ideal solution:

  • Mobile applications - especially HTML5 based (Cordova, Phonegap, etc.)
  • Node.js embedded datastore for small-to-medium apps
  • Embedded in desktop application with Node Webkit

https://github.com/techfort/LokiJS

Why shouldn't I use mysql_* functions in PHP?

Speaking of technical reasons, there are only a few, extremely specific and rarely used. Most likely you will never ever use them in your life.
Maybe I am too ignorant, but I never had an opportunity to use them things like

  • non-blocking, asynchronous queries
  • stored procedures returning multiple resultsets
  • Encryption (SSL)
  • Compression

If you need them - these are no doubt technical reasons to move away from mysql extension toward something more stylish and modern-looking.

Nevertheless, there are also some non-technical issues, which can make your experience a bit harder

  • further use of these functions with modern PHP versions will raise deprecated-level notices. They simply can be turned off.
  • in a distant future, they can be possibly removed from the default PHP build. Not a big deal too, as mydsql ext will be moved into PECL and every hoster will be happy to compile PHP with it, as they don't want to lose clients whose sites were working for decades.
  • strong resistance from Stackoverflow community. ?verytime you mention these honest functions, you being told that they are under strict taboo.
  • being an average PHP user, most likely your idea of using these functions is error-prone and wrong. Just because of all these numerous tutorials and manuals which teach you the wrong way. Not the functions themselves - I have to emphasize it - but the way they are used.

This latter issue is a problem.
But, in my opinion, the proposed solution is no better either.
It seems to me too idealistic a dream that all those PHP users will learn how to handle SQL queries properly at once. Most likely they would just change mysql_* to mysqli_* mechanically, leaving the approach the same. Especially because mysqli makes prepared statements usage incredible painful and troublesome.
Not to mention that native prepared statements aren't enough to protect from SQL injections, and neither mysqli nor PDO offers a solution.

So, instead of fighting this honest extension, I'd prefer to fight wrong practices and educate people in the right ways.

Also, there are some false or non-significant reasons, like

  • Doesn't support Stored Procedures (we were using mysql_query("CALL my_proc"); for ages)
  • Doesn't support Transactions (same as above)
  • Doesn't support Multiple Statements (who need them?)
  • Not under active development (so what? does it affect you in any practical way?)
  • Lacks an OO interface (to create one is a matter of several hours)
  • Doesn't support Prepared Statements or Parametrized Queries

The last one is an interesting point. Although mysql ext do not support native prepared statements, they aren't required for the safety. We can easily fake prepared statements using manually handled placeholders (just like PDO does):

function paraQuery()
{
    $args  = func_get_args();
    $query = array_shift($args);
    $query = str_replace("%s","'%s'",$query); 

    foreach ($args as $key => $val)
    {
        $args[$key] = mysql_real_escape_string($val);
    }

    $query  = vsprintf($query, $args);
    $result = mysql_query($query);
    if (!$result)
    {
        throw new Exception(mysql_error()." [$query]");
    }
    return $result;
}

$query  = "SELECT * FROM table where a=%s AND b LIKE %s LIMIT %d";
$result = paraQuery($query, $a, "%$b%", $limit);

voila, everything is parameterized and safe.

But okay, if you don't like the red box in the manual, a problem of choice arises: mysqli or PDO?

Well, the answer would be as follows:

  • If you understand the necessity of using a database abstraction layer and looking for an API to create one, mysqli is a very good choice, as it indeed supports many mysql-specific features.
  • If, like vast majority of PHP folks, you are using raw API calls right in the application code (which is essentially wrong practice) - PDO is the only choice, as this extension pretends to be not just API but rather a semi-DAL, still incomplete but offers many important features, with two of them makes PDO critically distinguished from mysqli:

    • unlike mysqli, PDO can bind placeholders by value, which makes dynamically built queries feasible without several screens of quite messy code.
    • unlike mysqli, PDO can always return query result in a simple usual array, while mysqli can do it only on mysqlnd installations.

So, if you are an average PHP user and want to save yourself a ton of headaches when using native prepared statements, PDO - again - is the only choice.
However, PDO is not a silver bullet too and has its hardships.
So, I wrote solutions for all the common pitfalls and complex cases in the PDO tag wiki

Nevertheless, everyone talking about extensions always missing the 2 important facts about Mysqli and PDO:

  1. Prepared statement isn't a silver bullet. There are dynamical identifiers which cannot be bound using prepared statements. There are dynamical queries with an unknown number of parameters which makes query building a difficult task.

  2. Neither mysqli_* nor PDO functions should have appeared in the application code.
    There ought to be an abstraction layer between them and application code, which will do all the dirty job of binding, looping, error handling, etc. inside, making application code DRY and clean. Especially for the complex cases like dynamical query building.

So, just switching to PDO or mysqli is not enough. One has to use an ORM, or a query builder, or whatever database abstraction class instead of calling raw API functions in their code.
And contrary - if you have an abstraction layer between your application code and mysql API - it doesn't actually matter which engine is used. You can use mysql ext until it goes deprecated and then easily rewrite your abstraction class to another engine, having all the application code intact.

Here are some examples based on my safemysql class to show how such an abstraction class ought to be:

$city_ids = array(1,2,3);
$cities   = $db->getCol("SELECT name FROM cities WHERE is IN(?a)", $city_ids);

Compare this one single line with amount of code you will need with PDO.
Then compare with crazy amount of code you will need with raw Mysqli prepared statements. Note that error handling, profiling, query logging already built in and running.

$insert = array('name' => 'John', 'surname' => "O'Hara");
$db->query("INSERT INTO users SET ?u", $insert);

Compare it with usual PDO inserts, when every single field name being repeated six to ten times - in all these numerous named placeholders, bindings, and query definitions.

Another example:

$data = $db->getAll("SELECT * FROM goods ORDER BY ?n", $_GET['order']);

You can hardly find an example for PDO to handle such practical case.
And it will be too wordy and most likely unsafe.

So, once more - it is not just raw driver should be your concern but abstraction class, useful not only for silly examples from beginner's manual but to solve whatever real-life problems.

How to ensure a <select> form field is submitted when it is disabled?

The easiest way i found was to create a tiny javascript function tied to your form :

function enablePath() {
    document.getElementById('select_name').disabled= "";
}

and you call it in your form here :

<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">

Or you can call it in the function you use to check your form :)

Find MongoDB records where array field is not empty

ME.find({pictures: {$exists: true}}) 

Simple as that, this worked for me.

Twitter Bootstrap scrollable table rows and fixed header

<table class="table table-striped table-condensed table-hover rsk-tbl vScrollTHead">
            <thead>
            <tr>
                <th>Risk Element</th>
                <th>Description</th>
                <th>Risk Value</th>
                <th>&nbsp;</th>
            </tr>
            </thead>
        </table>
<div class="vScrollTable">
            <table class="table table-striped table-condensed table-hover rsk-tbl vScrollTBody">
                <tbody>
                <tr class="">
                    <td>JEWELLERY</td>
                    <td>Jewellery business</td>

                </tr><tr class="">
                    <td>NGO</td>
                    <td>none-governmental organizations</td>
                    </tr>
                </tbody>
            </table>
        </div>





.vScrollTBody{
  height:15px;
}

.vScrollTHead {
  height:15px;
}

.vScrollTable{
  height:100px;
  overflow-y:scroll;
}

having two tables for head and body worked for me

Remove Fragment Page from ViewPager in Android

my working solution to remove fragment page from view pager

public class MyFragmentAdapter extends FragmentStatePagerAdapter {

    private ArrayList<ItemFragment> pages;

    public MyFragmentAdapter(FragmentManager fragmentManager, ArrayList<ItemFragment> pages) {
        super(fragmentManager);
        this.pages = pages;
    }

    @Override
    public Fragment getItem(int index) {
        return pages.get(index);
    }

    @Override
    public int getCount() {
        return pages.size();
    }

    @Override
    public int getItemPosition(Object object) {
        int index = pages.indexOf (object);

        if (index == -1)
            return POSITION_NONE;
        else
            return index;
    }
}

And when i need to remove some page by index i do this

pages.remove(position); // ArrayList<ItemFragment>
adapter.notifyDataSetChanged(); // MyFragmentAdapter

Here it is my adapter initialization

MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(), pages);
viewPager.setAdapter(adapter);

Multiplying across in a numpy array

You could also use matrix multiplication (aka dot product):

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)

numpy.dot(c,a)

Which is more elegant is probably a matter of taste.

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

How to right-align form input boxes?

To affect ONLY text type input boxes use the attribute selector

input[type="text"]

This way it will not affect other inputs and just text inputs.

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

example, use a div and give it an idea to refer to:

#divEntry input[type="text"] {
text-align: right;}

How to make Twitter bootstrap modal full screen

I've came up with a "responsive" solution for fullscreen modals:

Fullscreen Modals that can be enabled only on certain breakpoints. In this way the modal will display "normal" on wider (desktop) screens and fullscreen on smaller (tablet or mobile) screens, giving it the feeling of a native app.

Implemented for Bootstrap 3 and Bootstrap 4. Included by default in Bootstrap 5.


Bootstrap v5

Fullscreen modals are included by default in Bootstrap 5: https://getbootstrap.com/docs/5.0/components/modal/#fullscreen-modal


Bootstrap v4

The following generic code should work:

.modal {
  padding: 0 !important; // override inline padding-right added from js
}
.modal .modal-dialog {
  width: 100%;
  max-width: none;
  height: 100%;
  margin: 0;
}
.modal .modal-content {
  height: 100%;
  border: 0;
  border-radius: 0;
}
.modal .modal-body {
  overflow-y: auto;
}

By including the scss code below, it generates the following classes that need to be added to the .modal element:

+---------------+---------+---------+---------+---------+---------+
|               |   xs    |   sm    |   md    |   lg    |   xl    | 
|               | <576px  | =576px  | =768px  | =992px  | =1200px |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen    |  100%   | default | default | default | default | 
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-sm |  100%   |  100%   | default | default | default | 
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-md |  100%   |  100%   |  100%   | default | default |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-lg |  100%   |  100%   |  100%   |  100%   | default |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-xl |  100%   |  100%   |  100%   |  100%   |  100%   |
+---------------+---------+---------+---------+---------+---------+

The scss code is:

@mixin modal-fullscreen() {
  padding: 0 !important; // override inline padding-right added from js

  .modal-dialog {
    width: 100%;
    max-width: none;
    height: 100%;
    margin: 0;
  }

  .modal-content {
    height: 100%;
    border: 0;
    border-radius: 0;
  }

  .modal-body {
    overflow-y: auto;
  }

}

@each $breakpoint in map-keys($grid-breakpoints) {
  @include media-breakpoint-down($breakpoint) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    .modal-fullscreen#{$infix} {
      @include modal-fullscreen();
    }
  }
}

Demo on Codepen: https://codepen.io/andreivictor/full/MWYNPBV/


Bootstrap v3

Based on previous responses to this topic (@Chris J, @kkarli), the following generic code should work:

.modal {
  padding: 0 !important; // override inline padding-right added from js
}

.modal .modal-dialog {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.modal .modal-content {
  height: auto;
  min-height: 100%;
  border: 0 none;
  border-radius: 0;
  box-shadow: none;
}

If you want to use responsive fullscreen modals, use the following classes that need to be added to .modal element:

  • .modal-fullscreen-md-down - the modal is fullscreen for screens smaller than 1200px.
  • .modal-fullscreen-sm-down - the modal is fullscreen for screens smaller than 922px.
  • .modal-fullscreen-xs-down - the modal is fullscreen for screen smaller than 768px.

Take a look at the following code:

/* Extra small devices (less than 768px) */
@media (max-width: 767px) {
  .modal-fullscreen-xs-down {
    padding: 0 !important;
  }
  .modal-fullscreen-xs-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-xs-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  } 
}

/* Small devices (less than 992px) */
@media (max-width: 991px) {
  .modal-fullscreen-sm-down {
    padding: 0 !important;
  }
  .modal-fullscreen-sm-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-sm-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }
}

/* Medium devices (less than 1200px) */
@media (max-width: 1199px) {
  .modal-fullscreen-md-down {
    padding: 0 !important;
  }
  .modal-fullscreen-md-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-md-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }
}

Demo is available on Codepen: https://codepen.io/andreivictor/full/KXNdoO.

Those who use Sass as a preprocessor can take advantage of the following mixin:

@mixin modal-fullscreen() {
  padding: 0 !important; // override inline padding-right added from js

  .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }

  .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }

}

Installing Android Studio, does not point to a valid JVM installation error

Most probably the issue happens because of the incompatability of 32 bit and 64 bit excecutables. Suppose if you have installed 32 bit Android Studio by mistake and you will be downloading a 64 bit JDK. In this case 32 bit Android Studio will not be able to pick up the 64 bit JDK. This was the issue I faced. So I followed the below simple steps to make it working,

  1. Downloaded 32 bit JDK(you can also download 64 bit Android Studio if you do not want to change the 64 bit JDK)
  2. Right click MyComputer > Advanced System Settings > under 'Advanced tab' > Environment variables > Under System Variables > Add JAVA_HOME as key and your jdk(eg:C:\Program Files (x86)\Java\jdk1.7.0_79) location as value.
  3. Save it and launch Android Studio. You are good to go now.

Java 8 Lambda Stream forEach with multiple statements

Forgot to relate to the first code snippet. I wouldn't use forEach at all. Since you are collecting the elements of the Stream into a List, it would make more sense to end the Stream processing with collect. Then you would need peek in order to set the ID.

List<Entry> updatedEntries = 
    entryList.stream()
             .peek(e -> e.setTempId(tempId))
             .collect (Collectors.toList());

For the second snippet, forEach can execute multiple expressions, just like any lambda expression can :

entryList.forEach(entry -> {
  if(entry.getA() == null){
    printA();
  }
  if(entry.getB() == null){
    printB();
  }
  if(entry.getC() == null){
    printC();
  }
});

However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null) if you do.

How to set -source 1.7 in Android Studio and Gradle

You can change it in new Android studio version(0.8.X)

FIle-> Other Settings -> Default Settings -> Compiler (Expand it by clicking left arrow) -> Java Compiler -> You can change the Project bytecode version here

enter image description here

How to Call VBA Function from Excel Cells?

Here's the answer

Steps to follow:

  1. Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.

  2. Insert a new module. From the menu: Insert -> Module (Don't skip this!).

  3. Create a Public function. Example:

    Public Function findArea(ByVal width as Double, _
                             ByVal height as Double) As Double
        ' Return the area
        findArea = width * height
    End Function
    
  4. Then use it in any cell like you would any other function: =findArea(B12,C12).

Date format Mapping to JSON Jackson

I want to point out that setting a SimpleDateFormat like described in the other answer only works for a java.util.Date which I assume is meant in the question. But for java.sql.Date the formatter does not work. In my case it was not very obvious why the formatter did not work because in the model which should be serialized the field was in fact a java.utl.Date but the actual object ended up beeing a java.sql.Date. This is possible because

public class java.sql extends java.util.Date

So this is actually valid

java.util.Date date = new java.sql.Date(1542381115815L);

So if you are wondering why your Date field is not correctly formatted make sure that the object is really a java.util.Date.

Here is also mentioned why handling java.sql.Date will not be added.

This would then be breaking change, and I don't think that is warranted. If we were starting from scratch I would agree with the change, but as things are not so much.

How to put scroll bar only for modal-body?

Problem solved with combine solution @carlos calla and @jonathan marston.

    /* Important part */
.modal-dialog{
    overflow-y: initial !important
}
.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

How do I resolve "Cannot find module" error using Node.js?

This error can be encountered if you are requireing a module that has a missing or incorrect main field in its package.json. Though the module itself is installed, npm/node has to use a single .js file as an entrypoint to your module. If the main field is not there, it defaults to looking for index.js in your module's folder. If your module's main file is not called index.js, it won't be able to require it.

Discovered while turning a browserify-based module into a CommonJS require-able module; browserify didn't care about the missing main field, and so the error had gone unnoticed.

Unresolved reference issue in PyCharm

After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies and re-arrange them.

pycharm prefrence

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

I had to delete Tomcat's work directory as it had cached previously generated files. To do this:

  1. Stop Tomcat
  2. Delete the 'work' directory
  3. Start Tomcat

This will cause the work directory to be newly generated.

Run react-native on android emulator

I had a similar problem, and after spending so much time and lots of searching about this issue the only trick worked for me:

  1. Please Install the Required SDKs as shown in this figure

Configure Required SDKs Configure Required SDKs

  1. If You have already installed it, so you must have to update the following SDKs:
    • Android SDK Tool (update it to latest version)
    • Android SDK Platform-tools (update it to latest version)
    • Android SDK Build-tools (update it to latest version)
    • Android Support Repository under Extra folder (update it to latest version)
  2. You Must have at least Installed the Same version Android API as the installed Android SDK Build-tools & Android SDK Platform-tools version as shown in the Configure Required SDKs figure above.

Note: Local Maven repository for Support Libraries which is listed as the SDK requirement in the official docs of React-native is now named as Android Support Repository in the SDK Manager .

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

iPhone app could not be installed at this time

You can try to publish the application by changing the version of the build. I was also having the same problem and tried the same by just changing tIt may help you too.

How do I merge a specific commit from one branch into another in Git?

The git cherry-pick <commit> command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.

Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)

Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.

CSS: how do I create a gap between rows in a table?

Add following rule to tr and it should work

float: left

Sample (Open it in IE9 offcourse :) ): http://jsfiddle.net/zshmN/

EDIT: This isn't a legal or correct solution as pointed out by many, but if you are left with no option and need something this will work in IE9.

So all those who are giving down votes, please let us know correct solution as well

Unique constraint on multiple columns

USE [TSQL2012]
GO

/****** Object:  Table [dbo].[Table_1]    Script Date: 11/22/2015 12:45:47 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Table_1](
    [seq] [bigint] IDENTITY(1,1) NOT NULL,
    [ID] [int] NOT NULL,
    [name] [nvarchar](50) NULL,
    [cat] [nvarchar](50) NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [IX_Table_1] UNIQUE NONCLUSTERED 
(
    [name] ASC,
    [cat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

How to get the real and total length of char * (char array)?

Given just the pointer, you can't. You'll have to keep hold of the length you passed to new[] or, better, use std::vector to both keep track of the length, and release the memory when you've finished with it.

Note: this answer only addresses C++, not C.

Color different parts of a RichTextBox string

I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.

static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
{
    int pos = box.SelectionStart;
    string s = box.Text;
    for (int ix = 0; ; )
    {
        int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
        if (jx < 0) break;
        int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
        box.SelectionStart = jx;
        box.SelectionLength = ex - jx + 1;
        box.SelectionColor = color1;
        
        int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
        int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
        if (bx == bxtest)
        {
            box.SelectionStart = ex + 1;
            box.SelectionLength = bx - ex + 1;
            box.SelectionColor = color2;
        }
        
        ix = ex + 1;
    }
    box.SelectionStart = pos;
    box.SelectionLength = 0;
}

and this is how you call it

   HighlightPhrase(richTextBox1, "<", ">","</", Color.Red, Color.Black);

How to update a single library with Composer?

You can basically do following one to install new package as well.

php composer.phar require

then terminal will ask you to enter the name of the package for searching.

$ Search for a package []: //Your package name here

Then terminal will ask the version of the package (If you would like to have the latest version just leave it blank)

$ Enter the version constraint to require (or leave blank to use the latest version) []: //your version number here

Then you just press the return key. Terminal will ask for another package, if you dont want to install another one just press the return key and you will be done.

SQL query for a carriage return in a string and ultimately removing carriage return

The main question was to remove the CR/LF. Using the replace and char functions works for me:

Select replace(replace(Name,char(10),''),char(13),'')

For Postgres or Oracle SQL, use the CHR function instead:

       replace(replace(Name,CHR(10),''),CHR(13),'')

Text file with 0D 0D 0A line breaks

The CRCRLF is known as result of a Windows XP notepad word wrap bug.

For future reference, here's an extract of relevance from the linked blog:

When you press the Enter key on Windows computers, two characters are actually stored: a carriage return (CR) and a line feed (LF). The operating system always interprets the character sequence CR LF the same way as the Enter key: it moves to the next line. However when there are extra CR or LF characters on their own, this can sometimes cause problems.

There is a bug in the Windows XP version of Notepad that can cause extra CR characters to be stored in the display window. The bug happens in the following situation:

If you have the word wrap option turned on and the display window contains long lines that wrap around, then saving the file causes Notepad to insert the characters CR CR LF at each wrap point in the display window, but not in the saved file.

The CR CR LF characters can cause oddities if you copy and paste them into other programs. They also prevent Notepad from properly re-wrapping the lines if you resize the Notepad window.

You can remove the CR CR LF characters by turning off the word wrap feature, then turning it back on if desired. However, the cursor is repositioned at the beginning of the display window when you do this.

C linked list inserting node at the end

After you malloc a node make sure to set node->next = NULL.

int addNodeBottom(int val, node *head)
{    
    node *current = head;
    node *newNode = (node *) malloc(sizeof(node));
    if (newNode == NULL) {
        printf("malloc failed\n");
        exit(-1);
    }    

    newNode->value = val;
    newNode->next = NULL;

    while (current->next) {
        current = current->next;
    }    
    current->next = newNode;
    return 0;
}    

I should point out that with this version the head is still used as a dummy, not used for storing a value. This lets you represent an empty list by having just a head node.

AngularJS view not updating on model change

setTimout executes outside of angular. You need to use $timeout service for this to work:

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply() kicks off a $digest cycle. This will apply the binding. $timeout handles the $apply for you so it is the recommended service to use when using timeouts.

Essentially, binding happens during the $digest cycle (if the value is seen to be different).

Jquery - animate height toggle

You should be using a class to achieve what you want:

css:

#topbar { width: 100%; height: 40px; background-color: #000; }
#topbar.hide { height: 10px; }

javascript:

  $(document).ready(function(){
    $("#topbar").click(function(){
      if($(this).hasClass('hide')) {
        $(this).animate({height:40},200).removeClass('hide');
      } else { 
        $(this).animate({height:10},200).addClass('hide');
      }
    });
  });

javac: invalid target release: 1.8

I got the same issue in IntelliJ IDEA Community with Maven and I had to reimport the project by right-clicking the project in the Project tab -> Maven -> Reimport

How to programmatically set style attribute in a view

Depending on what style attributes you'd like to change you may be able to use the Paris library:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Paris.style(view).apply(R.style.YourStyle);

Many attributes like background, padding, textSize, textColor, etc. are supported.

Disclaimer: I authored the library.

How to show math equations in general github's markdown(not github's blog)

I used the following in the head of mark down file

<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js? 
config=TeX-MML-AM_CHTML"
</script>

Then typed the following mathjax statement
$$x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2b}.$$
It worked for me

Select a dummy column with a dummy value in SQL?

If you meant just ABC as simple value, answer above is the one that works fine.

If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.

Something like this may work:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;

Actual syntax maybe a bit off though

Difference between File.separator and slash in paths

You use File.separator because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the ":" character as a file separator, and so dutifully the JVM obeys their wishes.

WPF Button with Image

Another way to Stretch image to full button. Can try the below code.

<Grid.Resources>
  <ImageBrush x:Key="AddButtonImageBrush" ImageSource="/Demoapp;component/Resources/AddButton.png" Stretch="UniformToFill"/>
</Grid.Resources>

<Button Content="Load Inventory 1" Background="{StaticResource AddButtonImageBrush}"/> 

Referred from Here

Also it might helps other. I posted the same with MouseOver Option here.

How to use IntelliJ IDEA to find all unused code?

In latest IntelliJ versions, you should run it from Analyze->Run Inspection By Name:

enter image description here

Than, pick Unused declaration:

enter image description here

And finally, uncheck the Include test sources:

enter image description here

Javascript Date: next month

try this:

var a = screen.Data.getFullYear();
var m = screen.Data.getMonth();
var d = screen.Data.getDate();

m = m + 1;
screen.Data = new Date(a, m, d);

if (screen.Data.getDate() != d)
screen.Data = new Date(a, m + 1, 0);

Split string into list in jinja?

After coming back to my own question after 5 year and seeing so many people found this useful, a little update.

A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

or

{% set list1 = variable1.split(';') %}
{% for item in list1 %}
    <p>{{ item }}<p/>
{% endfor %} 

or

{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}

Append a single character to a string or char array in java?

public class lab {
public static void main(String args[]){
   Scanner input = new Scanner(System.in);
   System.out.println("Enter a string:");
   String s1;
   s1 = input.nextLine();
   int k = s1.length();
   char s2;
   s2=s1.charAt(k-1);
   s1=s2+s1+s2;
   System.out.println("The new string is\n" +s1);
   }
  }

Here's the output you'll get.

* Enter a string CAT The new string is TCATT *

It prints the the last character of the string to the first and last place. You can do it with any character of the String.

Align contents inside a div

Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:

I know what pixel values each div and their respective margins hold...so I do the following.

I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):

.wrapper {
    position: absolute;
    left: 50%;
    margin-left: -100px;
}

EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.

This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!

Key error when selecting columns in pandas dataframe after read_csv

The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':

You could also try:

import csv
import pandas as pd
import re
    with open (filename, "r") as file:
        df = pd.read_csv(file, delimiter = ",")
        df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
        print(df.columns)

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

View stored procedure/function definition in MySQL

An alternative quick and hacky solution if you want to get an overview of all the produres there are, or run into the issue of only getting the procedure header shown by SHOW CREATE PROCEDURE:

mysqldump --user=<user> -p --no-data --routines <database>

It will export the table descriptions as well, but no data. Works well for sniffing around unknown or forgotten schemas... ;)

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

Import a custom class in Java

If your classes are in the same package, you won't need to import. To call a method from class B in class A, you should use classB.methodName(arg)

How do I use Linq to obtain a unique list of properties from a list of objects?

        int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
        var nonRepeats = (from n in numbers select n).Distinct();


        foreach (var d in nonRepeats)
        {

            Response.Write(d);
        }

OUTPUT

1234567890

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.

In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.

build.gradle

android {

    // [...]

    defaultConfig {

        // [...]

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // add the schema location to the source sets
    // used by Room, to test migrations
    sourceSets {
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }

    // [...]
}

Is it necessary to write HEAD, BODY and HTML tags?

Firebug shows this correctly because your Browser automagically fixes the bad markup for you. This behaviour is not specified anywhere and can (will) vary from browser to browser. Those tags are required by the DOCTYPE you're using and should not be omitted.

The html element is the root element of every html page. If you look at all other elements' description it says where an element can be used (and almost all elements require either head or body).

Easiest way to read from and write to files

These are the best and most commonly used methods for writing to and reading from files:

using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.

Append text to an existing file:

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else 
        {
            sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

Get file name from the user via file explorer/open file dialog (you will need this to select existing files).

private string getFileNameFromUser()//returns file path\name
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

Get text from an existing file:

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}

Do C# Timers elapse on a separate thread?

It depends. The System.Timers.Timer has two modes of operation.

If SynchronizingObject is set to an ISynchronizeInvoke instance then the Elapsed event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke instances are none other than plain old Control and Form instances that we are all familiar with. So in that case the Elapsed event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer. Otherwise, it really depends on the specific ISynchronizeInvoke instance that was used.

If SynchronizingObject is null then the Elapsed event is invoked on a ThreadPool thread and it behaves similar to the System.Threading.Timer. In fact, it actually uses a System.Threading.Timer behind the scenes and does the marshaling operation after it receives the timer callback if needed.

In-place edits with sed on OS X

sed -i -- "s/https/http/g" file.txt

Subscript out of range error in this Excel VBA script

This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.

Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")

Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:

sh1.Range("A69").Paste
sh1.Range("A69").Select

The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.

How do I retrieve query parameters in Spring Boot?

In Spring boot: 2.1.6, you can use like below:

    @GetMapping("/orders")
    @ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
    public List<OrderResponse> getOrders(
            @RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
            @RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
            @RequestParam(value = "location_id", required = true) String location_id) {

        // TODO...

        return response;

@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.

How to overlay one div over another div

By using a div with style z-index:1; and position: absolute; you can overlay your div on any other div.

z-index determines the order in which divs 'stack'. A div with a higher z-index will appear in front of a div with a lower z-index. Note that this property only works with positioned elements.

Android : Check whether the phone is dual SIM

I was taking a look at the call logs and I noticed that apart from the usual fields in the contents of managedCursor, we have a column "simid" in Dual SIM phones (I checked on Xolo A500s Lite), so as to tag each call in the call log with a SIM. This value is either 1 or 2, most probably denoting SIM1/SIM2.

managedCursor = context.getContentResolver().query(contacts, null, null, null, null);
managedCursor.moveToNext();        
for(int i=0;i<managedCursor.getColumnCount();i++)
{//for dual sim phones
    if(managedCursor.getColumnName(i).toLowerCase().equals("simid"))
        indexSIMID=i;
}

I did not find this column in a single SIM phone (I checked on Xperia L).

So although I don't think this is a foolproof way to check for dual SIM nature, I am posting it here because it could be useful to someone.

SQL Server convert select a column and convert it to a string

This a stab at creating a reusable column to comma separated string. In this case, I only one strings that have values and I do not want empty strings or nulls.

First I create a user defined type that is a one column table.

-- ================================
-- Create User-defined Table Type
-- ================================
USE [RSINET.MVC]
GO

-- Create the data type
CREATE TYPE [dbo].[SingleVarcharColumn] AS TABLE 
(
    data NVARCHAR(max)
)
GO

The real purpose of the type is to simplify creating a scalar function to put the column into comma separated values.

-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  Rob Peterson        
-- Create date: 8-26-2015
-- Description: This will take a single varchar column and convert it to
-- comma separated values.
-- =============================================
CREATE FUNCTION fnGetCommaSeparatedString 
(
    -- Add the parameters for the function here
    @column AS [dbo].[SingleVarcharColumn] READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @result VARCHAR(MAX)
DECLARE @current VARCHAR(MAX)
DECLARE @counter INT
DECLARE @c CURSOR

SET @result = ''
SET @counter = 0
-- Add the T-SQL statements to compute the return value here
SET @c = CURSOR FAST_FORWARD
    FOR SELECT COALESCE(data,'') FROM @column
    OPEN @c
    FETCH NEXT FROM @c
    INTO @current
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF @result <> '' AND @current <> '' SET @result = @result + ',' + @current
        IF @result = '' AND @current <> '' SET @result = @current
    FETCH NEXT FROM @c
    INTO @current
    END
    CLOSE @c
    DEALLOCATE @c
-- Return the result of the function
RETURN @result

END
GO

Now, to use this. I select the column I want to convert to a comma separated string into the SingleVarcharColumn Type.

DECLARE @s as SingleVarcharColumn

INSERT INTO @s VALUES ('rob')
INSERT INTO @s VALUES ('paul')
INSERT INTO @s VALUES ('james')
INSERT INTO @s VALUES (null)


INSERT INTO @s
SELECT iClientID FROM [dbo].tClient

SELECT [dbo].fnGetCommaSeparatedString(@s)

To get results like this.

rob,paul,james,1,9,10,11,12,13,14,15,16,18,19,23,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,52,53,54,56,57,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,81,82,83,84,87,88,90,91,92,93,94,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159

I made my data column in my SingleVarcharColumn type an NVARCHAR(MAX) which may hurt performance, but I flexibility was what I was looking for and it runs fast enough for my purposes. It would probably be faster if it were a varchar and if it had a fixed and smaller width, but I have not tested it.

Compare string with all values in list

for word in d:
    if d in paid[j]:
         do_something()

will try all the words in the list d and check if they can be found in the string paid[j].

This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]

s1 = set(sentence.split())
s2 = set(d)

print (s1.intersection(s2))

Output:

{'come', 'easy'}

Java Wait for thread to finish

Thread has a method that does that for you join which will block until the thread has finished executing.

In C#, what's the difference between \n and \r\n?

The Difference

There are a few characters which can indicate a new line. The usual ones are these two:

* '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF).
* '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:

* DOS and Windows

They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

* Unix (and hence Linux as well)

Unix uses a single '\n' to indicate a new line.

* Mac

Macs use a single '\r'.

Taken from Here

How to include External CSS and JS file in Laravel 5

In laravel 5.1,

 <link rel="stylesheet" href="{{URL::asset('assets/css/bootstrap.min.css')}}">
 <script type="text/javascript" src="{{URL::asset('assets/js/jquery.min.js')}}"></script>

Where assets folder location is inside public folder

Accessing certain pixel RGB value in openCV

uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values 
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{

        if (r > 2) r = 0;

        if (r == 0) value[i] = 0;
        if (r == 1)value[i] =  0;
        if (r == 2)value[i] = 255;

        r++;
}

Angular expression if array contains

You can accomplish this with a slightly different syntax:

ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"

Plnkr

UICollectionView spacing margins

Set the insetForSectionAt property of the UICollectionViewFlowLayout object attached to your UICollectionView

Make sure to add this protocol

UICollectionViewDelegateFlowLayout

Swift

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
    }

Objective - C

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);
}

C# Double - ToString() formatting with two decimal places but no rounding

The following rounds the numbers, but only shows up to 2 decimal places (removing any trailing zeros), thanks to .##.

decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;

d0.ToString("0.##");   //24.15
d1.ToString("0.##");   //24.16 (rounded up)
d2.ToString("0.##");   //24.1  
d3.ToString("0.##");   //24

http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

Why is "npm install" really slow?

One of the simple solution to speed up your npm install is to spin up a high powered machine on AWS and use that to compile your project and ship the code back to you.

I was experimenting with it and I found that there was a very high decrease in the time to run npm install. I found a tool to execute the above command easily https://stormyapp.com

Add or change a value of JSON key with jquery or javascript

Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

data.busNum = 12345;
...

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Append a Lists Contents to another List C#

if you want to get "terse" :)

List<string>GlobalStrings = new List<string>(); 

for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});

How to overcome the CORS issue in ReactJS

Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.

A simpler way is to use express-http-proxy

  1. run npm run build to create the bundle.

    var proxy = require('express-http-proxy');
    
    var app = require('express')();
    
    //define the path of build
    
    var staticFilesPath = path.resolve(__dirname, '..', 'build');
    
    app.use(express.static(staticFilesPath));
    
    app.use('/api/api-server', proxy('www.api-server.com'));
    

Use "/api/api-server" from react code to call the API.

So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

How do I plot in real-time in a while loop using matplotlib?

I know I'm a bit late to answer this question. Nevertheless, I've made some code a while ago to plot live graphs, that I would like to share:

Code for PyQt4:

###################################################################
#                                                                 #
#                    PLOT A LIVE GRAPH (PyQt4)                    #
#                  -----------------------------                  #
#            EMBED A MATPLOTLIB ANIMATION INSIDE YOUR             #
#            OWN GUI!                                             #
#                                                                 #
###################################################################


import sys
import os
from PyQt4 import QtGui
from PyQt4 import QtCore
import functools
import numpy as np
import random as rd
import matplotlib
matplotlib.use("Qt4Agg")
from matplotlib.figure import Figure
from matplotlib.animation import TimedAnimation
from matplotlib.lines import Line2D
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import time
import threading


def setCustomSize(x, width, height):
    sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
    sizePolicy.setHorizontalStretch(0)
    sizePolicy.setVerticalStretch(0)
    sizePolicy.setHeightForWidth(x.sizePolicy().hasHeightForWidth())
    x.setSizePolicy(sizePolicy)
    x.setMinimumSize(QtCore.QSize(width, height))
    x.setMaximumSize(QtCore.QSize(width, height))

''''''

class CustomMainWindow(QtGui.QMainWindow):

    def __init__(self):

        super(CustomMainWindow, self).__init__()

        # Define the geometry of the main window
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("my first window")

        # Create FRAME_A
        self.FRAME_A = QtGui.QFrame(self)
        self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(210,210,235,255).name())
        self.LAYOUT_A = QtGui.QGridLayout()
        self.FRAME_A.setLayout(self.LAYOUT_A)
        self.setCentralWidget(self.FRAME_A)

        # Place the zoom button
        self.zoomBtn = QtGui.QPushButton(text = 'zoom')
        setCustomSize(self.zoomBtn, 100, 50)
        self.zoomBtn.clicked.connect(self.zoomBtnAction)
        self.LAYOUT_A.addWidget(self.zoomBtn, *(0,0))

        # Place the matplotlib figure
        self.myFig = CustomFigCanvas()
        self.LAYOUT_A.addWidget(self.myFig, *(0,1))

        # Add the callbackfunc to ..
        myDataLoop = threading.Thread(name = 'myDataLoop', target = dataSendLoop, daemon = True, args = (self.addData_callbackFunc,))
        myDataLoop.start()

        self.show()

    ''''''


    def zoomBtnAction(self):
        print("zoom in")
        self.myFig.zoomIn(5)

    ''''''

    def addData_callbackFunc(self, value):
        # print("Add data: " + str(value))
        self.myFig.addData(value)



''' End Class '''


class CustomFigCanvas(FigureCanvas, TimedAnimation):

    def __init__(self):

        self.addedData = []
        print(matplotlib.__version__)

        # The data
        self.xlim = 200
        self.n = np.linspace(0, self.xlim - 1, self.xlim)
        a = []
        b = []
        a.append(2.0)
        a.append(4.0)
        a.append(2.0)
        b.append(4.0)
        b.append(3.0)
        b.append(4.0)
        self.y = (self.n * 0.0) + 50

        # The window
        self.fig = Figure(figsize=(5,5), dpi=100)
        self.ax1 = self.fig.add_subplot(111)


        # self.ax1 settings
        self.ax1.set_xlabel('time')
        self.ax1.set_ylabel('raw data')
        self.line1 = Line2D([], [], color='blue')
        self.line1_tail = Line2D([], [], color='red', linewidth=2)
        self.line1_head = Line2D([], [], color='red', marker='o', markeredgecolor='r')
        self.ax1.add_line(self.line1)
        self.ax1.add_line(self.line1_tail)
        self.ax1.add_line(self.line1_head)
        self.ax1.set_xlim(0, self.xlim - 1)
        self.ax1.set_ylim(0, 100)


        FigureCanvas.__init__(self, self.fig)
        TimedAnimation.__init__(self, self.fig, interval = 50, blit = True)

    def new_frame_seq(self):
        return iter(range(self.n.size))

    def _init_draw(self):
        lines = [self.line1, self.line1_tail, self.line1_head]
        for l in lines:
            l.set_data([], [])

    def addData(self, value):
        self.addedData.append(value)

    def zoomIn(self, value):
        bottom = self.ax1.get_ylim()[0]
        top = self.ax1.get_ylim()[1]
        bottom += value
        top -= value
        self.ax1.set_ylim(bottom,top)
        self.draw()


    def _step(self, *args):
        # Extends the _step() method for the TimedAnimation class.
        try:
            TimedAnimation._step(self, *args)
        except Exception as e:
            self.abc += 1
            print(str(self.abc))
            TimedAnimation._stop(self)
            pass

    def _draw_frame(self, framedata):
        margin = 2
        while(len(self.addedData) > 0):
            self.y = np.roll(self.y, -1)
            self.y[-1] = self.addedData[0]
            del(self.addedData[0])


        self.line1.set_data(self.n[ 0 : self.n.size - margin ], self.y[ 0 : self.n.size - margin ])
        self.line1_tail.set_data(np.append(self.n[-10:-1 - margin], self.n[-1 - margin]), np.append(self.y[-10:-1 - margin], self.y[-1 - margin]))
        self.line1_head.set_data(self.n[-1 - margin], self.y[-1 - margin])
        self._drawn_artists = [self.line1, self.line1_tail, self.line1_head]

''' End Class '''

# You need to setup a signal slot mechanism, to 
# send data to your GUI in a thread-safe way.
# Believe me, if you don't do this right, things
# go very very wrong..
class Communicate(QtCore.QObject):
    data_signal = QtCore.pyqtSignal(float)

''' End Class '''


def dataSendLoop(addData_callbackFunc):
    # Setup the signal-slot mechanism.
    mySrc = Communicate()
    mySrc.data_signal.connect(addData_callbackFunc)

    # Simulate some data
    n = np.linspace(0, 499, 500)
    y = 50 + 25*(np.sin(n / 8.3)) + 10*(np.sin(n / 7.5)) - 5*(np.sin(n / 1.5))
    i = 0

    while(True):
        if(i > 499):
            i = 0
        time.sleep(0.1)
        mySrc.data_signal.emit(y[i]) # <- Here you emit a signal!
        i += 1
    ###
###


if __name__== '__main__':
    app = QtGui.QApplication(sys.argv)
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec_())

''''''

 
I recently rewrote the code for PyQt5.
Code for PyQt5:

###################################################################
#                                                                 #
#                    PLOT A LIVE GRAPH (PyQt5)                    #
#                  -----------------------------                  #
#            EMBED A MATPLOTLIB ANIMATION INSIDE YOUR             #
#            OWN GUI!                                             #
#                                                                 #
###################################################################

import sys
import os
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import functools
import numpy as np
import random as rd
import matplotlib
matplotlib.use("Qt5Agg")
from matplotlib.figure import Figure
from matplotlib.animation import TimedAnimation
from matplotlib.lines import Line2D
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import time
import threading

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super(CustomMainWindow, self).__init__()
        # Define the geometry of the main window
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("my first window")
        # Create FRAME_A
        self.FRAME_A = QFrame(self)
        self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QColor(210,210,235,255).name())
        self.LAYOUT_A = QGridLayout()
        self.FRAME_A.setLayout(self.LAYOUT_A)
        self.setCentralWidget(self.FRAME_A)
        # Place the zoom button
        self.zoomBtn = QPushButton(text = 'zoom')
        self.zoomBtn.setFixedSize(100, 50)
        self.zoomBtn.clicked.connect(self.zoomBtnAction)
        self.LAYOUT_A.addWidget(self.zoomBtn, *(0,0))
        # Place the matplotlib figure
        self.myFig = CustomFigCanvas()
        self.LAYOUT_A.addWidget(self.myFig, *(0,1))
        # Add the callbackfunc to ..
        myDataLoop = threading.Thread(name = 'myDataLoop', target = dataSendLoop, daemon = True, args = (self.addData_callbackFunc,))
        myDataLoop.start()
        self.show()
        return

    def zoomBtnAction(self):
        print("zoom in")
        self.myFig.zoomIn(5)
        return

    def addData_callbackFunc(self, value):
        # print("Add data: " + str(value))
        self.myFig.addData(value)
        return

''' End Class '''


class CustomFigCanvas(FigureCanvas, TimedAnimation):
    def __init__(self):
        self.addedData = []
        print(matplotlib.__version__)
        # The data
        self.xlim = 200
        self.n = np.linspace(0, self.xlim - 1, self.xlim)
        a = []
        b = []
        a.append(2.0)
        a.append(4.0)
        a.append(2.0)
        b.append(4.0)
        b.append(3.0)
        b.append(4.0)
        self.y = (self.n * 0.0) + 50
        # The window
        self.fig = Figure(figsize=(5,5), dpi=100)
        self.ax1 = self.fig.add_subplot(111)
        # self.ax1 settings
        self.ax1.set_xlabel('time')
        self.ax1.set_ylabel('raw data')
        self.line1 = Line2D([], [], color='blue')
        self.line1_tail = Line2D([], [], color='red', linewidth=2)
        self.line1_head = Line2D([], [], color='red', marker='o', markeredgecolor='r')
        self.ax1.add_line(self.line1)
        self.ax1.add_line(self.line1_tail)
        self.ax1.add_line(self.line1_head)
        self.ax1.set_xlim(0, self.xlim - 1)
        self.ax1.set_ylim(0, 100)
        FigureCanvas.__init__(self, self.fig)
        TimedAnimation.__init__(self, self.fig, interval = 50, blit = True)
        return

    def new_frame_seq(self):
        return iter(range(self.n.size))

    def _init_draw(self):
        lines = [self.line1, self.line1_tail, self.line1_head]
        for l in lines:
            l.set_data([], [])
        return

    def addData(self, value):
        self.addedData.append(value)
        return

    def zoomIn(self, value):
        bottom = self.ax1.get_ylim()[0]
        top = self.ax1.get_ylim()[1]
        bottom += value
        top -= value
        self.ax1.set_ylim(bottom,top)
        self.draw()
        return

    def _step(self, *args):
        # Extends the _step() method for the TimedAnimation class.
        try:
            TimedAnimation._step(self, *args)
        except Exception as e:
            self.abc += 1
            print(str(self.abc))
            TimedAnimation._stop(self)
            pass
        return

    def _draw_frame(self, framedata):
        margin = 2
        while(len(self.addedData) > 0):
            self.y = np.roll(self.y, -1)
            self.y[-1] = self.addedData[0]
            del(self.addedData[0])

        self.line1.set_data(self.n[ 0 : self.n.size - margin ], self.y[ 0 : self.n.size - margin ])
        self.line1_tail.set_data(np.append(self.n[-10:-1 - margin], self.n[-1 - margin]), np.append(self.y[-10:-1 - margin], self.y[-1 - margin]))
        self.line1_head.set_data(self.n[-1 - margin], self.y[-1 - margin])
        self._drawn_artists = [self.line1, self.line1_tail, self.line1_head]
        return

''' End Class '''


# You need to setup a signal slot mechanism, to
# send data to your GUI in a thread-safe way.
# Believe me, if you don't do this right, things
# go very very wrong..
class Communicate(QObject):
    data_signal = pyqtSignal(float)

''' End Class '''



def dataSendLoop(addData_callbackFunc):
    # Setup the signal-slot mechanism.
    mySrc = Communicate()
    mySrc.data_signal.connect(addData_callbackFunc)

    # Simulate some data
    n = np.linspace(0, 499, 500)
    y = 50 + 25*(np.sin(n / 8.3)) + 10*(np.sin(n / 7.5)) - 5*(np.sin(n / 1.5))
    i = 0

    while(True):
        if(i > 499):
            i = 0
        time.sleep(0.1)
        mySrc.data_signal.emit(y[i]) # <- Here you emit a signal!
        i += 1
    ###
###

if __name__== '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec_())

Just try it out. Copy-paste this code in a new python-file, and run it. You should get a beautiful, smoothly moving graph:

enter image description here

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

How to copy to clipboard using Access/VBA?

I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm

Which works nicely. :)

Binding ComboBox SelectedItem using MVVM

<!-- xaml code-->
    <Grid>
        <ComboBox Name="cmbData"    SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
        <Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
    </Grid>



        //student Class
        public class Student
        {
            public  int Id { set; get; }
            public string name { set; get; }
        }

        //set 2 properties in MainWindow.xaml.cs Class
        public ObservableCollection<Student> studentInfo { set; get; }
        public Student SelectedstudentInfo { set; get; }

        //MainWindow.xaml.cs Constructor
        public MainWindow()
        {
            InitializeComponent();
            bindCombo();
            this.DataContext = this;
            cmbData.ItemsSource = studentInfo;

        }

        //method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
        public void bindCombo()
        {
            ObservableCollection<Student> studentList = new ObservableCollection<Student>();
            studentList.Add(new Student { Id=0 ,name="==Select=="});
            studentList.Add(new Student { Id = 1, name = "zoyeb" });
            studentList.Add(new Student { Id = 2, name = "siddiq" });
            studentList.Add(new Student { Id = 3, name = "James" });

              studentInfo=studentList;

        }

        //button click to get selected student MainWindow.xaml.cs
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Student student = SelectedstudentInfo;
            if(student.Id ==0)
            {
                MessageBox.Show("select name from dropdown");
            }
            else
            {
                MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
            }
        }

Writing a dictionary to a csv file with one line for every 'key: value'

#code to insert and read dictionary element from csv file
import csv
n=input("Enter I to insert or S to read : ")
if n=="I":
    m=int(input("Enter the number of data you want to insert: "))
    mydict={}
    list=[]
    for i in range(m):
        keys=int(input("Enter id :"))
        list.append(keys)
        values=input("Enter Name :")
        mydict[keys]=values

    with open('File1.csv',"w") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=list)
        writer.writeheader()
        writer.writerow(mydict)
        print("Data Inserted")
else:
    keys=input("Enter Id to Search :")
    Id=str(keys)
    with open('File1.csv',"r") as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row[Id]) #print(row) to display all data

What is the meaning of Bus: error 10 in C

Whenever you are using pointer variables ( the asterix ) such as

char *str = "First string";

you need to asign memory to it

str = malloc(strlen(*str))

Find max and second max salary for a employee table MySQL

Not really a nice query but :

SELECT * from (
    SELECT max(Salary) from Employee
    ) as a
LEFT OUTER JOIN 
    (SELECT MAX(Salary) FROM Employee
        WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as b
ON 1=1

How to get main window handle from process id?

There's the possibility of a mis-understanding here. The WinForms framework in .Net automatically designates the first window created (e.g., Application.Run(new SomeForm())) as the MainWindow. The win32 API, however, doesn't recognize the idea of a "main window" per process. The message loop is entirely capable of handling as many "main" windows as system and process resources will let you create. So, your process doesn't have a "main window". The best you can do in the general case is use EnumWindows() to get all the non-child windows active on a given process and try to use some heuristics to figure out which one is the one you want. Luckily, most processes are only likely to have a single "main" window running most of the time, so you should get good results in most cases.

Is there a query language for JSON?

The built-in array.filter() method makes most of these so-called javascript query libraries obsolete

You can put as many conditions inside the delegate as you can imagine: simple comparison, startsWith, etc. I haven't tested but you could probably nest filters too for querying inner collections.

How to capture UIView to UIImage without loss of quality on retina display

Swift 3.0 implementation

extension UIView {
    func getSnapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return snapshotImage
    }
}

How do I turn a C# object into a JSON string in .NET?

Since we all love one-liners

... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})

Documentation: Serializing and Deserializing JSON

Select values from XML field in SQL Server 2008

Considering that XML data comes from a table 'table' and is stored in a column 'field': use the XML methods, extract values with xml.value(), project nodes with xml.nodes(), use CROSS APPLY to join:

SELECT 
    p.value('(./firstName)[1]', 'VARCHAR(8000)') AS firstName,
    p.value('(./lastName)[1]', 'VARCHAR(8000)') AS lastName
FROM table 
    CROSS APPLY field.nodes('/person') t(p)

You can ditch the nodes() and cross apply if each field contains exactly one element 'person'. If the XML is a variable you select FROM @variable.nodes(...) and you don't need the cross apply.

jQuery: count number of rows in a table

Here's my take on it:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

USAGE:

var rowCount = $('#productTypesTable').rowCount();

Having the output of a console application in Visual Studio instead of the console

In the Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window". Then go to your project settings and change the type from "Console Application" to "Windows Application". At that point Visual Studio does not open up a console window anymore, and the output is redirected to the Output window in Visual Studio. However, you cannot do anything "creative", like requesting key or text input, or clearing the console - you'll get runtime exceptions.

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

No problem if all the arrays you are about to use in this scenario are small like in your example.

If you will use this for large blobs (e.g. storing large binary files many Mbs or even Gbs in size into a VARBINARY) then you'd probably be much better off using specific support in SQL Server for reading/writing subsections of such large blobs. Things like READTEXT and UPDATETEXT, or in current versions of SQL Server SUBSTRING.

For more information and examples see either my 2006 article in .NET Magazine ("BLOB + Stream = BlobStream", in Dutch, with complete source code), or an English translation and generalization of this on CodeProject by Peter de Jonghe. Both of these are linked from my weblog.

How to drop column with constraint?

I have updated script a little bit to my SQL server version

DECLARE @sql nvarchar(max)

SELECT @sql = 'ALTER TABLE `table_name` DROP CONSTRAINT ' + df.NAME 
FROM sys.default_constraints df
  INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
  INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
where t.name = 'table_name' and c.name = 'column_name'

EXEC sp_executeSql @sql
GO

ALTER TABLE table_name
  DROP COLUMN column_name;

UIImageView aspect fit and center

[your_imageview setContentMode:UIViewContentModeCenter];

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

How do I add multiple conditions to "ng-disabled"?

Make sure you wrap the condition in the correct precedence

ng-disabled="((!product.img) || (!product.name))"

MongoDB query multiple collections at once

Trying to JOIN in MongoDB would defeat the purpose of using MongoDB. You could, however, use a DBref and write your application-level code (or library) so that it automatically fetches these references for you.

Or you could alter your schema and use embedded documents.

Your final choice is to leave things exactly the way they are now and do two queries.

Forbidden You don't have permission to access /wp-login.php on this server

This should work :

The instructions says that you add a separate .htaccess containing the lines above to the wp-admin folder - and leave the main .htaccess, in the root, alone.

if that don't help , you can try this:

copy the .htaccess file as is from the wp-admin and placed it in the root folder and bingo! It should work ! if you face new error after this let us know.

for reference you can look here as well:

http://wordpress.org/support/topic/you-dont-have-permission-to-access-blogwp-loginphp-on-this-server

Check using this:

<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

Declaring a boolean in JavaScript using just var

How about something like this:

var MyNamespace = {
    convertToBoolean: function (value) {
        //VALIDATE INPUT
        if (typeof value === 'undefined' || value === null) return false;

        //DETERMINE BOOLEAN VALUE FROM STRING
        if (typeof value === 'string') {
            switch (value.toLowerCase()) {
                case 'true':
                case 'yes':
                case '1':
                    return true;
                case 'false':
                case 'no':
                case '0':
                    return false;
            }
        }

        //RETURN DEFAULT HANDLER
        return Boolean(value);
    }
};

Then you can use it like this:

MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false

I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!

Java count occurrence of each item in an array

You can use HashMap, where Key is your string and value - count.

How to close an iframe within iframe itself

"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.

In IFrame:

parent.closeIFrame();

In parent:

function closeIFrame(){
     $('#youriframeid').remove();
}

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

How can I convert a .py to .exe for Python?

I've been using Nuitka and PyInstaller with my package, PySimpleGUI.

Nuitka There were issues getting tkinter to compile with Nuikta. One of the project contributors developed a script that fixed the problem.

If you're not using tkinter it may "just work" for you. If you are using tkinter say so and I'll try to get the script and instructions published.

PyInstaller I'm running 3.6 and PyInstaller is working great! The command I use to create my exe file is:

pyinstaller -wF myfile.py

The -wF will create a single EXE file. Because all of my programs have a GUI and I do not want to command window to show, the -w option will hide the command window.

This is as close to getting what looks like a Winforms program to run that was written in Python.

[Update 20-Jul-2019]

There is PySimpleGUI GUI based solution that uses PyInstaller. It uses PySimpleGUI. It's called pysimplegui-exemaker and can be pip installed.

pip install PySimpleGUI-exemaker

To run it after installing:

python -m pysimplegui-exemaker.pysimplegui-exemaker

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

If you need to skip the password prompt for some reason, you can input the password in the command (Dangerous)

mysql -u root --password=secret

How to rollback just one step using rake db:migrate

  try {
        $result=DB::table('users')->whereExists(function ($Query){
            $Query->where('id','<','14162756');
            $Query->whereBetween('password',[14162756,48384486]);
            $Query->whereIn('id',[3,8,12]);
        });
    }catch (\Exception $error){
        Log::error($error);
        DB::rollBack(1);
        return redirect()->route('bye');
    }

Difference between Select Unique and Select Distinct

select unique is not valid syntax for what you are trying to do

you want to use either select distinct or select distinctrow

And actually, you don't even need distinct/distinctrow in what you are trying to do. You can eliminate duplicates by choosing the appropriate union statement parameters.

the below query by itself will only provide distinct values

select col from table1 
union 
select col from table2

if you did want duplicates you would have to do

select col from table1 
union all
select col from table2

Where are static variables stored in C and C++?

Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA

insert echo into the specific html element like div which has an id or class

You can repeat it by fetching again the data

 while($row = mysql_fetch_assoc($result)){
 //another html element
 <div>$row['name']</div>
 <div>$row['title']</div>
 //and so on
 }

or you need to put it on the variable and call display it again on other html element

 $name = $row['name'];
 $title = $row['title']
 //and so on

then put it on the other element, but if you want to call all the data of each id, you need to do the first code

How to check if a column exists in a datatable

DataColumnCollection col = datatable.Columns;        
if (!columns.Contains("ColumnName1"))
{
   //Column1 Not Exists
}

if (columns.Contains("ColumnName2"))
{
   //Column2 Exists
}

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

"java.lang.SecurityException: class" org.hamcrest.Matchers "'s signer information does not match signer information of other classes in the same package"

Do it: Right-click on your package click on Build Path -> Configure Build Path Click on the Libraries tab Remove JUnit Apply and close Ready.

Prevent a webpage from navigating away using JavaScript

If you are catching a browser back/forward button and don't want to navigate away, you can use:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.

git reset --hard HEAD leaves untracked files behind

If you have files you still want to keep:

git clean -di will do an interactive clean which allows you to only delete the files/dirs you don't want anymore.

Testing Private method using mockito

Think about this in terms of behaviour, not in terms of what methods there are. The method called method has a particular behaviour if b is true. It has different behaviour if b is false. This means you should write two different tests for method; one for each case. So instead of having three method-oriented tests (one for method, one for method1, one for method2, you have two behaviour-oriented tests.

Related to this (I suggested this in another SO thread recently, and got called a four-letter word as a result, so feel free to take this with a grain of salt); I find it helpful to choose test names that reflect the behaviour that I'm testing, rather than the name of the method. So don't call your tests testMethod(), testMethod1(), testMethod2() and so forth. I like names like calculatedPriceIsBasePricePlusTax() or taxIsExcludedWhenExcludeIsTrue() that indicate what behaviour I'm testing; then within each test method, test only the indicated behaviour. Most such behaviours will involve just one call to a public method, but may involve many calls to private methods.

Hope this helps.

Windows 7, 64 bit, DLL problems

Installation of SQL Server Management Studio 2014 on a freshly installed Windows 7 resolved this problem at our client after a two-day ridiculous battle.

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

tl;dr

  • Use modern java.time classes.
  • Never use Date/Calendar/SimpleDateFormat classes.

Example:

ZonedDateTime                                // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now(                                        // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )              // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo(                                // Lop off finer part of this value.
    ChronoUnit.MILLIS                        // Specify level of truncation via `ChronoUnit` enum object.
)                                            // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format(                                     // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME    // This standard ISO 8601 format is close to your desired output.
)                                            // Returns a `String`.
.replace( "T" , " " )                        // Replace `T` in middle with a SPACE.

java.time

The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.

want current date and time

Capture the current moment in UTC using Instant.

Instant instant = Instant.now() ;

To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;

The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.

ZonedDateTime
.now( 
    ZoneId.of( "Pacific/Auckland" ) 
)
.truncatedTo(
    ChronoUnit.MILLIS
)

in “dd/MM/yyyy HH:mm:ss.SS” format

I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.

But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.

String output = 
    zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
    .replace( "T" , " " )  
;

sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");

Date date = sdf1.parse(strDate);

Never exchange date-time values using text intended for presentation to humans.

Instead, use the standard formats defined for this very purpose, found in ISO 8601.

The java.time use these ISO 8601 formats by default when parsing/generating strings.

Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.

Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;

2018-01-23T01:23:45.123456789Z

This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Encrypt & Decrypt using PyCrypto AES 256

Another take on this (heavily derived from solutions above) but

  • uses null for padding
  • does not use lambda (never been a fan)
  • tested with python 2.7 and 3.6.5

    #!/usr/bin/python2.7
    # you'll have to adjust for your setup, e.g., #!/usr/bin/python3
    
    
    import base64, re
    from Crypto.Cipher import AES
    from Crypto import Random
    from django.conf import settings
    
    class AESCipher:
        """
          Usage:
          aes = AESCipher( settings.SECRET_KEY[:16], 32)
          encryp_msg = aes.encrypt( 'ppppppppppppppppppppppppppppppppppppppppppppppppppppppp' )
          msg = aes.decrypt( encryp_msg )
          print("'{}'".format(msg))
        """
        def __init__(self, key, blk_sz):
            self.key = key
            self.blk_sz = blk_sz
    
        def encrypt( self, raw ):
            if raw is None or len(raw) == 0:
                raise NameError("No value given to encrypt")
            raw = raw + '\0' * (self.blk_sz - len(raw) % self.blk_sz)
            raw = raw.encode('utf-8')
            iv = Random.new().read( AES.block_size )
            cipher = AES.new( self.key.encode('utf-8'), AES.MODE_CBC, iv )
            return base64.b64encode( iv + cipher.encrypt( raw ) ).decode('utf-8')
    
        def decrypt( self, enc ):
            if enc is None or len(enc) == 0:
                raise NameError("No value given to decrypt")
            enc = base64.b64decode(enc)
            iv = enc[:16]
            cipher = AES.new(self.key.encode('utf-8'), AES.MODE_CBC, iv )
            return re.sub(b'\x00*$', b'', cipher.decrypt( enc[16:])).decode('utf-8')
    

Validating email addresses using jQuery and regex

Lolz this is much better

    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
        return pattern.test(emailAddress);
    };

UITableView load more when scrolling to bottom like Facebook application

For Xcode 10.1, Swift 4.2

This video seems like a great tutorial!

Starter/Complete project: https://github.com/RobCanton/Swift-Infinite-Scrolling-Example

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tableView:UITableView!

    var fetchingMore = false
    var items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        initTableView()
    }

    func initTableView() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
        tableView.delegate = self
        tableView.dataSource = self

        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false

        let layoutGuide = view.safeAreaLayoutGuide
        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.reloadData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
            cell.textLabel?.text = "Item \(items[indexPath.row])"
            return cell
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height

        if offsetY > contentHeight - scrollView.frame.height * 4 {
            if !fetchingMore {
                beginBatchFetch()
            }
        }
    }

    func beginBatchFetch() {
        fetchingMore = true
        print("Call API here..")
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.50, execute: {
            print("Consider this as API response.")
            let newItems = (self.items.count...self.items.count + 12).map { index in index }
            self.items.append(contentsOf: newItems)
            self.fetchingMore = false
            self.tableView.reloadData()
        })
    }
}

JDBC connection to MSSQL server in windows authentication mode

Try following these steps:

  1. Add the integratedSecurity=true to JDBC URL like this:

    Url: jdbc:sqlserver://<<Server>>:<<Port>>;databasename=<<DatabaseName>>;integratedsecurity=true 
    
  2. Make sure to add the sqljdbc driver 4 or above version (sqljdbc.jar) in your project build path:

    java.sql.DatabaseMetaData metaData = connection.getMetaData();
    System.out.println("Driver version:" + metaData.getDriverVersion());
    
  3. Add the VM argument for your project:

    • Find the sqljdbc_auth.dll file from DB installed server (C:\Program Files\sqljdbc_4.0\enu\auth\x86), or download from this link.

    • Place the dll file in your project folder and specify the VM argument like this: VM Argument: -Djava.library.path="<<DLL File path till folder>>"

      NOTE: Check your java version 32/64 bit then add 32/64 bit version dll file accordingly.

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

Like it's written up there, you forget to type #include <sstream>

#include <sstream>
using namespace std;

QString Stats_Manager::convertInt(int num)
{
   stringstream ss;
   ss << num;
   return ss.str();
}

You can also use some other ways to convert int to string, like

char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

check this!

How to resize an Image C#

I use ImageProcessorCore, mostly because it works .Net Core.

And it have more option such as converting types, cropping images and more

http://imageprocessor.org/imageprocessor/

Eclipse does not start when I run the exe?

re install your java. First check your OS version.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

Here's how you can mock your FileConnection

Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
                                                           MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
              .Throws(new IOException());

Then instantiate your Transfer class and use the mock in your method call

Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);

Update:

First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

Since you are setting those properties using another dependency, I would write it like this:

public class Transfer
{
    public Transfer(IInternalConfig internalConfig)
    {
        source = internalConfig.GetFileConnection("source");
        destination = internalConfig.GetFileConnection("destination");
    }

    //you should consider making these private or protected fields
    public virtual IFileConnection source { get; set; }
    public virtual IFileConnection destination { get; set; }

    public virtual void GetFile(IFileConnection connection, 
        string remoteFilename, string localFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void PutFile(IFileConnection connection, 
        string localFilename, string remoteFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void TransferFiles(string sourceName, string destName)
    {
        var tempName = Path.GetTempFileName();
        GetFile(source, sourceName, tempName);
        PutFile(destination, tempName, destName);
    }
}

This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Datatables Select All Checkbox

You can use Checkboxes extension for jQuery Datatables.

var table = $('#example').DataTable({
   'ajax': 'https://api.myjson.com/bins/1us28',
   'columnDefs': [
      {
         'targets': 0,
         'checkboxes': {
            'selectRow': true
         }
      }
   ],
   'select': {
      'style': 'multi'
   },
   'order': [[1, 'asc']]
});

See this example for code and demonstration.

See Checkboxes project page for more examples and documentation.

Check if an apt-get package is installed and then install it if it's not on Linux

For Ubuntu, apt provides a fairly decent way to do this. Below is an example for google chrome:

apt -qq list google-chrome-stable 2>/dev/null | grep -qE "(installed|upgradeable)" || apt-get install google-chrome-stable

I'm redirecting error output to null because apt warns against using its "unstable cli". I suspect list package is stable so I think it's ok to throw this warning away. The -qq makes apt super quiet.

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I faced this issue because of lower version of Jdk. Previously I installed Jdk 1.7 and Android Studio 1.5.1, I got this issue. If you install Android Studio 1.5.1 or above JDK 1.8 required

So Installing JDK 1.8 solved this issue.

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

SELECT CASE WHEN THEN (SELECT)

I ended up leaving the common properties from the SELECT queries and making a second SELECT query later on in the page. I used a php IF command to call for different scripts depending on the first SELECT query, the scripts contained the second SELECT query.

How do I encrypt and decrypt a string in python?

For Decryption:

     def decrypt(my_key=KEY, my_iv=IV, encryptText=encrypttext):

        key = binascii.unhexlify(my_key)
        iv = binascii.unhexlify(my_iv)
        encryptor = AES.new(key, AES.MODE_CBC, iv, segment_size=128)  # Initialize encryptor
        result = encryptor.decrypt(binascii.a2b_hex(encryptText))
        padder = PKCS7Padder()
        decryptText=padder.decode(result)  

           return {
          "plain": encryptText,
          "key": binascii.hexlify(key),
          "iv": binascii.hexlify(iv),
          "decryptedTest": decryptText
}

How to return a file using Web API?

Example with IHttpActionResult in ApiController.

[HttpGet]
[Route("file/{id}/")]
public IHttpActionResult GetFileForCustomer(int id)
{
    if (id == 0)
      return BadRequest();

    var file = GetFile(id);

    IHttpActionResult response;
    HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
    responseMsg.Content = new ByteArrayContent(file.SomeData);
    responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
    responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    response = ResponseMessage(responseMsg);
    return response;
}

If you don't want to download the PDF and use a browsers built in PDF viewer instead remove the following two lines:

responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;

Best way to remove the last character from a string built with stringbuilder

How About this..

string str = "The quick brown fox jumps over the lazy dog,";
StringBuilder sb = new StringBuilder(str);
sb.Remove(str.Length - 1, 1);

Java: splitting a comma-separated string but ignoring commas in quotes

I was impatient and chose not to wait for answers... for reference it doesn't look that hard to do something like this (which works for my application, I don't need to worry about escaped quotes, as the stuff in quotes is limited to a few constrained forms):

final static private Pattern splitSearchPattern = Pattern.compile("[\",]"); 
private List<String> splitByCommasNotInQuotes(String s) {
    if (s == null)
        return Collections.emptyList();

    List<String> list = new ArrayList<String>();
    Matcher m = splitSearchPattern.matcher(s);
    int pos = 0;
    boolean quoteMode = false;
    while (m.find())
    {
        String sep = m.group();
        if ("\"".equals(sep))
        {
            quoteMode = !quoteMode;
        }
        else if (!quoteMode && ",".equals(sep))
        {
            int toPos = m.start(); 
            list.add(s.substring(pos, toPos));
            pos = m.end();
        }
    }
    if (pos < s.length())
        list.add(s.substring(pos));
    return list;
}

(exercise for the reader: extend to handling escaped quotes by looking for backslashes also.)

PHP write file from input to txt

If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.

Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.

How does the communication between a browser and a web server take place?

There is a commercial product with an interesting logo which lets you see all kind of traffic between server and client named charles.

Another open source tools include: Live HttpHeaders, Wireshark or Firebug.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

If you are looking for high performance matrix/linear algebra/optimization on Intel processors, I'd look at Intel's MKL library.

MKL is carefully optimized for fast run-time performance - much of it based on the very mature BLAS/LAPACK fortran standards. And its performance scales with the number of cores available. Hands-free scalability with available cores is the future of computing and I wouldn't use any math library for a new project doesn't support multi-core processors.

Very briefly, it includes:

  1. Basic vector-vector, vector-matrix, and matrix-matrix operations
  2. Matrix factorization (LU decomp, hermitian,sparse)
  3. Least squares fitting and eigenvalue problems
  4. Sparse linear system solvers
  5. Non-linear least squares solver (trust regions)
  6. Plus signal processing routines such as FFT and convolution
  7. Very fast random number generators (mersenne twist)
  8. Much more.... see: link text

A downside is that the MKL API can be quite complex depending on the routines that you need. You could also take a look at their IPP (Integrated Performance Primitives) library which is geared toward high performance image processing operations, but is nevertheless quite broad.

Paul

CenterSpace Software ,.NET Math libraries, centerspace.net

merge one local branch into another local branch

To merge one branch into another, such as merging "feature_x" branch into "master" branch:

git checkout master

git merge feature_x

This page is the first result for several search engines when looking for "git merge one branch into another". However, the original question is more specific and special case than the title would suggest.
It is also more complex than both the subject and the search expression. As such, this is a minimal but explanatory answer for the benefit of most visitors.

Accessing an array out of bounds gives no error, why?

It's undefined behavior as far as I know. Run a larger program with that and it will crash somewhere along the way. Bounds checking is not a part of raw arrays (or even std::vector).

Use std::vector with std::vector::iterator's instead so you don't have to worry about it.

Edit:

Just for fun, run this and see how long until you crash:

int main()
{
   int array[1];

   for (int i = 0; i != 100000; i++)
   {
       array[i] = i;
   }

   return 0; //will be lucky to ever reach this
}

Edit2:

Don't run that.

Edit3:

OK, here is a quick lesson on arrays and their relationships with pointers:

When you use array indexing, you are really using a pointer in disguise (called a "reference"), that is automatically dereferenced. This is why instead of *(array[1]), array[1] automatically returns the value at that value.

When you have a pointer to an array, like this:

int array[5];
int *ptr = array;

Then the "array" in the second declaration is really decaying to a pointer to the first array. This is equivalent behavior to this:

int *ptr = &array[0];

When you try to access beyond what you allocated, you are really just using a pointer to other memory (which C++ won't complain about). Taking my example program above, that is equivalent to this:

int main()
{
   int array[1];
   int *ptr = array;

   for (int i = 0; i != 100000; i++, ptr++)
   {
       *ptr++ = i;
   }

   return 0; //will be lucky to ever reach this
}

The compiler won't complain because in programming, you often have to communicate with other programs, especially the operating system. This is done with pointers quite a bit.

How can I make git accept a self signed certificate?

I do it like this:

git init
git config --global http.sslVerify false
git clone https://myurl/myrepo.git

Align DIV's to bottom or baseline

An old post but thought i would share an answer for anyone looking. And because when you use absolute things can go wrong. What I would do is

HTML

<div id="parentDiv"></div>
<div class="childDiv"></div>

The Css

parentDiv{

}
childDiv{
    height:40px;
    margin-top:-20px;
}

And that would just sit that bottom div back up into the parent div. safe for most browsers too

PHPExcel - creating multiple sheets by iteration

When you first instantiate the $objPHPExcel, it already has a single sheet (sheet 0); you're then adding a new sheet (which will become sheet 1), but setting active sheet to sheet $i (when $i is 0)... so you're renaming and populating the original worksheet created when you instantiated $objPHPExcel rather than the one you've just added... this is your title "0".

You're also using the createSheet() method, which both creates a new worksheet and adds it to the workbook... but you're also adding it again yourself which is effectively adding the sheet in two position.

So first iteration, you already have sheet0, add a new sheet at both indexes 1 and 2, and edit/title sheet 0. Second iteration, you add a new sheet at both indexes 3 and 4, and edit/title sheet 1, but because you have the same sheet at indexes 1 and 2 this effectively writes to the sheet at index 2. Third iteration, you add a new sheet at indexes 5 and 6, and edit/title sheet 2, overwriting your earlier editing/titleing of sheet 1 which acted against sheet 2 instead.... and so on

Get list of databases from SQL Server

SELECT [name] 
FROM master.dbo.sysdatabases 
WHERE dbid > 4 and [name] <> 'ReportServer' and [name] <> 'ReportServerTempDB'

This will work for both condition, Whether reporting is enabled or not

Calculate the center point of multiple latitude/longitude coordinate pairs

I did this task in javascript like below

function GetCenterFromDegrees(data){
    // var data = [{lat:22.281610498720003,lng:70.77577162868579},{lat:22.28065743343672,lng:70.77624369747241},{lat:22.280860953131217,lng:70.77672113067706},{lat:22.281863655593973,lng:70.7762061465462}];
    var num_coords = data.length;
    var X = 0.0;
    var Y = 0.0;
    var Z = 0.0;

    for(i=0; i<num_coords; i++){
        var lat = data[i].lat * Math.PI / 180;
        var lon = data[i].lng * Math.PI / 180;
        var a = Math.cos(lat) * Math.cos(lon);
        var b = Math.cos(lat) * Math.sin(lon);
        var c = Math.sin(lat);

        X += a;
        Y += b;
        Z += c;
    }

    X /= num_coords;
    Y /= num_coords;
    Z /= num_coords;

    lon = Math.atan2(Y, X);
    var hyp = Math.sqrt(X * X + Y * Y);
    lat = Math.atan2(Z, hyp);

    var finalLat = lat * 180 / Math.PI;
    var finalLng =  lon * 180 / Math.PI; 

    var finalArray = Array();
    finalArray.push(finalLat);
    finalArray.push(finalLng);
    return finalArray;
}

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Read input stream twice

if your InputStream support using mark, then you can mark() your inputStream and then reset() it . if your InputStrem doesn't support mark then you can use the class java.io.BufferedInputStream,so you can embed your stream inside a BufferedInputStream like this

    InputStream bufferdInputStream = new BufferedInputStream(yourInputStream);
    bufferdInputStream.mark(some_value);
    //read your bufferdInputStream 
    bufferdInputStream.reset();
    //read it again

What is the apply function in Scala?

Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".

In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia

apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].

 // define a function in scala
 (x:Int) => x + 1

 // assign an object representing the function to a variable
 val f = (x:Int) => x + 1

Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:

  f.toString

Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:

 val f2 = f.compose((x:Int) => x - 1)

Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:

 f2.apply(2)

Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).

Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:

// we will be able to use this object as a function, as well as an object
object Foo {
  var y = 5
  def apply (x: Int) = x + y
}


Foo (1) // using Foo object in function notation 

There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:

List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation

// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3) 

So apply method is just a handy way of closing the gap between functions and objects in Scala.

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

The only thing which helps me on Windows 7 (x64): https://stackoverflow.com/a/29714359/2670121

Reinstall node and python with x32 versions.
I spent many time with this error (Failed to load c++ bson extension) and finally, when I installed module node-gyp (for build native addons) and even installed windows SDK with visual studio - nodejs didn't recognize assembled module bson.node as module. After reinstall the problem is gone.

Again, What means this error?

Actually, it's even not error. You still can use mongoose. But in this case, instead of fast native realization of bson module, you got js-realization, which slower. I saw many tips like: "edit path deep inside node_modules..." - which totaly useless because it's not solve the problem but just turned off the error messages.

How to set the color of "placeholder" text?

Try this

textarea::-webkit-input-placeholder {  color: #999;}

On select change, get data attribute value

Vanilla Javascript:

this.querySelector(':checked').getAttribute('data-id')

Python 3 print without parenthesis

No. That will always be a syntax error in Python 3. Consider using 2to3 to translate your code to Python 3

Saving and loading objects and using pickle

The following works for me:

class Fruits: pass

banana = Fruits()

banana.color = 'yellow'
banana.value = 30

import pickle

filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()

file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()

print(object_file.color, object_file.value, sep=', ')
# yellow, 30

How to embed a Google Drive folder in a website

Embedding a Google Drive directory in an IFRAME

Google Drive folders can be embedded and displayed in list and grid views (in which all you can do is click a file or folder to open it on a new tab). To do so, simply replace FOLDER-ID with your own in:

List view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>

or without specifying a mode, since list mode is the default:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID" style="width:100%; height:600px; border:0;"></iframe>

Grid view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Obtaining your folder id

The id is the hash (alphanumeric gibberish) after folders/ in the URL of the folder. You can see the URL in the address bar of your browser when you open the Drive folder. For example, in:

https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2 

The Folder ID is 0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2.

Folder with G Suite/Google Apps domain

If your folder is part of a Google Apps domain, you can add the domain to the URL to alleviate the permission problems (detailed further ahead):

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Just replace MY.DOMAIN.COM and FOLDER-ID with your own.

Caveat with folders requiring permission

This technique works best for folders with public access. Folders that are shared only with certain Google accounts can cause trouble when you embed them this way, depending on which Google accounts are active on the user's browser:

  1. If the user has not logged in to any Google account, then nothing appears in the frame.
  2. If the user is logged onto an account without authorisation to access the folder, the frame will contain the message You need permission, with some buttons to Request access or Switch accounts, but if you click on this last, the frame blanks out.
  3. If the user logs into an account without proper permissions, and later adds the authorised account, on loading the embedded Drive Google will resort to the first active account, and the user will see You need permission, unless...
  4. If the URL contains a Google Suite domain, and the user is logged into that domain's account, the embedded view will work, even if the user logged to another account first.

The blank frames are because Google forbids embedding its login page in an IFRAME (presumably to prevent account stealing), via the X-Frame-Options header, which if set to SAMEORIGIN will cause any well-behaved browser to refuse to load the page if it's not in the same domain (v.g. drive.google.com). You can see this in the developer console of your browser.

TL;DR

To get a list or grid view of a Drive folder (in which all you can do is click a file or folder to open it on a new tab), use:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

or alternatively, for a Google Suite/Apps Drive:

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Replace MY.DOMAIN.COM and FOLDER-ID with your own; remove #grid to get a detailed file list.

For private folders, have your users log to the correct account before loading the page with the embedded folder; if the folder is in a Google Apps domain, you can add the domain to the URL. Else, they must log into the authorised account before any other.

(this answer is an edit of Mori's, but it was rejected as it changed his intent, somehow)

How can I generate a tsconfig.json file?

If you don't want to install Typescript globally (which makes sense to me, so you don't need to update it constantly), you can use npx:

npx -p typescript tsc --init

The key point is using the -p flag to inform npx that the tsc binary belongs to the typescript package

Java: Best way to iterate through a Collection (here ArrayList)

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
            System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

Java JTextField with input hint

You could create your own:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;

public class Main {

  public static void main(String[] args) {

    final JFrame frame = new JFrame();

    frame.setLayout(new BorderLayout());

    final JTextField textFieldA = new HintTextField("A hint here");
    final JTextField textFieldB = new HintTextField("Another hint here");

    frame.add(textFieldA, BorderLayout.NORTH);
    frame.add(textFieldB, BorderLayout.CENTER);
    JButton btnGetText = new JButton("Get text");

    btnGetText.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        String message = String.format("textFieldA='%s', textFieldB='%s'",
            textFieldA.getText(), textFieldB.getText());
        JOptionPane.showMessageDialog(frame, message);
      }
    });

    frame.add(btnGetText, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.pack();
  }
}

class HintTextField extends JTextField implements FocusListener {

  private final String hint;
  private boolean showingHint;

  public HintTextField(final String hint) {
    super(hint);
    this.hint = hint;
    this.showingHint = true;
    super.addFocusListener(this);
  }

  @Override
  public void focusGained(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText("");
      showingHint = false;
    }
  }
  @Override
  public void focusLost(FocusEvent e) {
    if(this.getText().isEmpty()) {
      super.setText(hint);
      showingHint = true;
    }
  }

  @Override
  public String getText() {
    return showingHint ? "" : super.getText();
  }
}

If you're still on Java 1.5, replace the this.getText().isEmpty() with this.getText().length() == 0.

Waiting until two async blocks are executed before starting another block

Swift 4.2 example:

let group = DispatchGroup.group(count: 2)
group.notify(queue: DispatchQueue.main) {
     self.renderingLine = false
     // all groups are done
}
DispatchQueue.main.async {
    self.renderTargetNode(floorPosition: targetPosition, animated: closedContour) {
        group.leave()
        // first done
    }
    self.renderCenterLine(position: targetPosition, animated: closedContour) {
        group.leave()
        // second done
    }
 }

HTML5 <video> element on Android

After much research, in many different devices, up to now, I've reached the simple conclusion that MP4 is much less supported than MOV format. So, I'm using MOV format, which is supported by all Android and Apple devices, on all browsers. I've detected weather the device is a mobile device or a desktop browser, and set the SRC accordingly:

if (IsMobile()) {
    $('#vid').attr('src', '/uploads/' + name + '.mov');
}
else {
    $('#vid').attr('src', '/uploads/' + name + '.webm');        
}

function IsMobile() {
    var isMobile = false; //initiate as false

    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
                || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;
    return isMobile;
}

"NoClassDefFoundError: Could not initialize class" error

NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).

NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them. Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).

The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound. So look at earlier logs.

I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.

Log4j, configuring a Web App to use a relative path

I've finally done it in this way.

Added a ServletContextListener that does the following:

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    System.setProperty("rootPath", context.getRealPath("/"));
}

Then in the log4j.properties file:

log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log

By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.

It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.

What do you think?

Add custom headers to WebView resource requests - android

Maybe my response quite late, but it covers API below and above 21 level.

To add headers we should intercept every request and create new one with required headers.

So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+

    webView.setWebViewClient(new WebViewClient() {

        // Handle API until level 21
        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

            return getNewResponse(url);
        }

        // Handle API 21+
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

            String url = request.getUrl().toString();

            return getNewResponse(url);
        }

        private WebResourceResponse getNewResponse(String url) {

            try {
                OkHttpClient httpClient = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(url.trim())
                        .addHeader("Authorization", "YOU_AUTH_KEY") // Example header
                        .addHeader("api-key", "YOUR_API_KEY") // Example header
                        .build();

                Response response = httpClient.newCall(request).execute();

                return new WebResourceResponse(
                        null,
                        response.header("content-encoding", "utf-8"),
                        response.body().byteStream()
                );

            } catch (Exception e) {
                return null;
            }

        }
   });

If response type should be processed you could change

        return new WebResourceResponse(
                null, // <- Change here
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );

to

        return new WebResourceResponse(
                getMimeType(url), // <- Change here
                response.header("content-encoding", "utf-8"),
                response.body().byteStream()
        );

and add method

        private String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);

            if (extension != null) {

                switch (extension) {
                    case "js":
                        return "text/javascript";
                    case "woff":
                        return "application/font-woff";
                    case "woff2":
                        return "application/font-woff2";
                    case "ttf":
                        return "application/x-font-ttf";
                    case "eot":
                        return "application/vnd.ms-fontobject";
                    case "svg":
                        return "image/svg+xml";
                }

                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }

            return type;
        }

TypeScript: Interfaces vs Types

When it comes to compilation speed, composed interfaces perform better than type intersections:

[...] interfaces create a single flat object type that detects property conflicts. This is in contrast with intersection types, where every constituent is checked before checking against the effective type. Type relationships between interfaces are also cached, as opposed to intersection types.

Source: https://github.com/microsoft/TypeScript/wiki/Performance#preferring-interfaces-over-intersections