Programs & Examples On #Domdocument

DOMDocument refers to a class encapsulating the DOM (Document Object Model). Various languages and technologies use the name DOMDocument for this PHP, COM, C++, ActiveX

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

PHP XML how to output nice format

<?php

$xml = $argv[1];

$dom = new DOMDocument();

// Initial block (must before load xml string)
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// End initial block

$dom->loadXML($xml);
$out = $dom->saveXML();

print_R($out);

How to change the default background color white to something else in twitter bootstrap

how to change background color in html & css with class

example:

on html you write

<div class="pad_menu">
</div>

on css

.pad_menu {
   padding: 100px;
   background-color: #A9FFCB;
}

so your background will be change to Magic Mint, if you want to know the code of the color, i suggest you visit https://coolors.co. Hope this useful :)

Export pictures from excel file into jpg using VBA

If i remember correctly, you need to use the "Shapes" property of your sheet.

Each Shape object has a TopLeftCell and BottomRightCell attributes that tell you the position of the image.

Here's a piece of code i used a while ago, roughly adapted to your needs. I don't remember the specifics about all those ChartObjects and whatnot, but here it is:

For Each oShape In ActiveSheet.Shapes
    strImageName = ActiveSheet.Cells(oShape.TopLeftCell.Row, 1).Value
    oShape.Select
    'Picture format initialization
    Selection.ShapeRange.PictureFormat.Contrast = 0.5: Selection.ShapeRange.PictureFormat.Brightness = 0.5: Selection.ShapeRange.PictureFormat.ColorType = msoPictureAutomatic: Selection.ShapeRange.PictureFormat.TransparentBackground = msoFalse: Selection.ShapeRange.Fill.Visible = msoFalse: Selection.ShapeRange.Line.Visible = msoFalse: Selection.ShapeRange.Rotation = 0#: Selection.ShapeRange.PictureFormat.CropLeft = 0#: Selection.ShapeRange.PictureFormat.CropRight = 0#: Selection.ShapeRange.PictureFormat.CropTop = 0#: Selection.ShapeRange.PictureFormat.CropBottom = 0#: Selection.ShapeRange.ScaleHeight 1#, msoTrue, msoScaleFromTopLeft: Selection.ShapeRange.ScaleWidth 1#, msoTrue, msoScaleFromTopLeft
    '/Picture format initialization
    Application.Selection.CopyPicture
    Set oDia = ActiveSheet.ChartObjects.Add(0, 0, oShape.Width, oShape.Height)
    Set oChartArea = oDia.Chart
    oDia.Activate
    With oChartArea
        .ChartArea.Select
        .Paste
        .Export ("H:\Webshop_Zpider\Strukturbildene\" & strImageName & ".jpg")
    End With
    oDia.Delete 'oChartArea.Delete
Next

What is the default text size on Android?

In general:

Three "default" textSize values:

 - 14sp
 - 18sp
 - 22sp

These values are defined within the following TextAppearances:

 - TextAppearance.Small
 - TextAppearance.Medium
 - TextAppearance.Large

More information about Typography can be found in the design guidelines

Related to your question:

If you don't set a custom textSize or textAppearance, TextAppearance.Small will be used.


Update: Material design:

New guidelines related to font and typefaces. The standard rule of 14sp remains (body).

Examples how to set textappearances

AppCompat version:

android:textAppearance="@style/TextAppearance.AppCompat.Body"

Lollipop and up version:

android:textAppearance="@android:style/TextAppearance.Material.Body"

Mean of a column in a data frame, given the column's name

if your column contain any value that you want to neglect. it will help you

## da is data frame & Ozone is column name 

##for single column
mean(da$Ozone, na.rm = TRUE)  

##for all columns
colMeans(x=da, na.rm = TRUE)

How to convert Nvarchar column to INT

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A;

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A;

Simple SQLfiddle here.

Fetch: POST json data

I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:

const request = await fetch ('/echo/json', {
  headers: {
    'Content-type': 'application/json'
  },
  method: 'POST',
  body: { a: 1, b: 2 }
});

Such as the curl request

curl -v -X POST -H 'Content-Type: application/json' -d '@data.json' '/echo/json'

In case to the remote serve not accept a json file as the body, just send a dataForm:

const data =  new FormData ();
data.append ('a', 1);
data.append ('b', 2);

const request = await fetch ('/echo/form', {
  headers: {
    'Content-type': 'application/x-www-form-urlencoded'
  },
  method: 'POST',
  body: data
});

Such as the curl request

curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '@data.txt' '/echo/form'

How to convert datatype:object to float64 in python?

You can try this:

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))

C split a char array into different variables

In addition, you can use sscanf for some very simple scenarios, for example when you know exactly how many parts the string has and what it consists of. You can also parse the arguments on the fly. Do not use it for user inputs because the function will not report conversion errors.

Example:

char text[] = "1:22:300:4444:-5";
int i1, i2, i3, i4, i5;
sscanf(text, "%d:%d:%d:%d:%d", &i1, &i2, &i3, &i4, &i5);
printf("%d, %d, %d, %d, %d", i1, i2, i3, i4, i5);

Output:

1, 22, 300, 4444, -5

For anything more advanced, strtok() and strtok_r() are your best options, as mentioned in other answers.

Cannot send a content-body with this verb-type

Please set the request Content Type before you read the response stream;

 request.ContentType = "text/xml";

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

What's the difference between %s and %d in Python string formatting?

These are placeholders:

For example: 'Hi %s I have %d donuts' %('Alice', 42)

This line of code will substitute %s with Alice (str) and %d with 42.

Output: 'Hi Alice I have 42 donuts'

This could be achieved with a "+" most of the time. To gain a deeper understanding to your question, you may want to check {} / .format() as well. Here is one example: Python string formatting: % vs. .format

also see here a google python tutorial video @ 40', it has some explanations https://www.youtube.com/watch?v=tKTZoB2Vjuk

Generate HTML table from 2D JavaScript array

Here's a version using template literals. It maps over the data creating new arrays of strings build from the template literals, and then adds them to the document with insertAdjacentHTML:

_x000D_
_x000D_
let data = [_x000D_
  ['Title', 'Artist', 'Duration', 'Created'],_x000D_
  ['hello', 'me', '2', '2019'],_x000D_
  ['ola', 'me', '3', '2018'],_x000D_
  ['Bob', 'them', '4.3', '2006']_x000D_
];_x000D_
_x000D_
function getCells(data, type) {_x000D_
  return data.map(cell => `<${type}>${cell}</${type}>`).join('');_x000D_
}_x000D_
_x000D_
function createBody(data) {_x000D_
  return data.map(row => `<tr>${getCells(row, 'td')}</tr>`).join('');_x000D_
}_x000D_
_x000D_
function createTable(data) {_x000D_
  const [headings, ...rows] = data;_x000D_
  return `_x000D_
    <table>_x000D_
      <thead>${getCells(headings, 'th')}</thead>_x000D_
      <tbody>${createBody(rows)}</tbody>_x000D_
    </table>_x000D_
  `;_x000D_
}_x000D_
_x000D_
document.body.insertAdjacentHTML('beforeend', createTable(data));
_x000D_
table { border-collapse: collapse; }_x000D_
tr { border: 1px solid #dfdfdf; }_x000D_
th, td { padding: 2px 5px 2px 5px;}
_x000D_
_x000D_
_x000D_

Hidden TextArea

use

textarea{
  visibility:hidden;
}

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

how to send multiple data with $.ajax() jquery

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

Difference between spring @Controller and @RestController annotation

As you can see in Spring documentation (Spring RestController Documentation) Rest Controller annotation is the same as Controller annotation, but assuming that @ResponseBody is active by default, so all the Java objects are serialized to JSON representation in the response body.

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

How can I do DNS lookups in Python, including referring to /etc/hosts?

This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''
    import socket

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='google.com')

How can I write to the console in PHP?

Use:

function console_log($data) {
    $bt = debug_backtrace();
    $caller = array_shift($bt);

    if (is_array($data))
        $dataPart = implode(',', $data);
    else
        $dataPart = $data;

    $toSplit = $caller['file'])) . ':' .
               $caller['line'] . ' => ' . $dataPart

    error_log(end(split('/', $toSplit));
}

Datatables - Search Box outside datatable

I want to add one more thing to the @netbrain's answer relevant in case you use server-side processing (see serverSide option).

Query throttling performed by default by datatables (see searchDelay option) does not apply to the .search() API call. You can get it back by using $.fn.dataTable.util.throttle() in the following way:

var table = $('#myTable').DataTable();
var search = $.fn.dataTable.util.throttle(
    function(val) {
        table.search(val).draw();
    },
    400  // Search delay in ms
);

$('#mySearchBox').keyup(function() {
    search(this.value);
});

Build Android Studio app via command line

You're likely here because you want to install it too!

Build

gradlew

(On Windows gradlew.bat)

Then Install

adb install -r exampleApp.apk

(The -r makes it replace the existing copy, add an -s if installing on an emulator)

Bonus

I set up an alias in my ~/.bash_profile, to make it a 2char command.

alias bi="gradlew && adb install -r exampleApp.apk"

(Short for Build and Install)

Does Python have a package/module management system?

There are at least two, easy_install and its successor pip.

How to change an input button image using CSS?

HTML

<div class="myButton"><INPUT type="submit" name="" value=""></div>

CSS

div.myButton input {
    background:url(/images/Btn.PNG) no-repeat;
    cursor:pointer;
    width: 200px;
    height: 100px;
    border: none;
}

This will work anywhere, even in Safari.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

If you are building a windows app try to build as x64 instead of Any CPU. It should work fine.

Can I have a video with transparent background using HTML5 video tag?

At this time, the only video codec that truly supports an alpha channel is VP8, which Flash uses. MP4 would probably support it if the video was exported as an image sequence, but I'm fairly certain Ogg video files have no support whatsoever for an alpha channel. This might be one of those rare instances where sticking with Flash would serve you better.

Running shell command and capturing the output

The output can be redirected to a text file and then read it back.

import subprocess
import os
import tempfile

def execute_to_file(command):
    """
    This function execute the command
    and pass its output to a tempfile then read it back
    It is usefull for process that deploy child process
    """
    temp_file = tempfile.NamedTemporaryFile(delete=False)
    temp_file.close()
    path = temp_file.name
    command = command + " > " + path
    proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    if proc.stderr:
        # if command failed return
        os.unlink(path)
        return
    with open(path, 'r') as f:
        data = f.read()
    os.unlink(path)
    return data

if __name__ == "__main__":
    path = "Somepath"
    command = 'ecls.exe /files ' + path
    print(execute(command))

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

To answer your question specifically, it seems to be working correctly. You said that it returns [object Object], which is what jQuery will return with the find("#result") method. It returns a jQuery element that matches the find query.

Try getting an attribute of that object, like result.attr("id") - it should return result.


In general, this answer depends on whether or not #result is the top level element.

If #result is the top level element,

<!-- #result as top level element -->
<div id="result">
  <span>Text</span>
</div>
<div id="other-top-level-element"></div>

find() will not work. Instead, use filter():

var $result = $(response).filter('#result');

If #result is not the top level element,

<!-- #result not as top level element -->
<div>
  <div id="result">
    <span>Text</span>
  </div>
</div>

find() will work:

var $result = $(response).find('#result');

Converting from IEnumerable to List

In case you're working with a regular old System.Collections.IEnumerable instead of IEnumerable<T> you can use enumerable.Cast<object>().ToList()

Pandas read_csv low_memory and dtype options

The deprecated low_memory option

The low_memory option is not properly deprecated, but it should be, since it does not actually do anything differently[source]

The reason you get this low_memory warning is because guessing dtypes for each column is very memory demanding. Pandas tries to determine what dtype to set by analyzing the data in each column.

Dtype Guessing (very bad)

Pandas can only determine what dtype a column should have once the whole file is read. This means nothing can really be parsed before the whole file is read unless you risk having to change the dtype of that column when you read the last value.

Consider the example of one file which has a column called user_id. It contains 10 million rows where the user_id is always numbers. Since pandas cannot know it is only numbers, it will probably keep it as the original strings until it has read the whole file.

Specifying dtypes (should always be done)

adding

dtype={'user_id': int}

to the pd.read_csv() call will make pandas know when it starts reading the file, that this is only integers.

Also worth noting is that if the last line in the file would have "foobar" written in the user_id column, the loading would crash if the above dtype was specified.

Example of broken data that breaks when dtypes are defined

import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO


csvdata = """user_id,username
1,Alice
3,Bob
foobar,Caesar"""
sio = StringIO(csvdata)
pd.read_csv(sio, dtype={"user_id": int, "username": "string"})

ValueError: invalid literal for long() with base 10: 'foobar'

dtypes are typically a numpy thing, read more about them here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html

What dtypes exists?

We have access to numpy dtypes: float, int, bool, timedelta64[ns] and datetime64[ns]. Note that the numpy date/time dtypes are not time zone aware.

Pandas extends this set of dtypes with its own:

'datetime64[ns, ]' Which is a time zone aware timestamp.

'category' which is essentially an enum (strings represented by integer keys to save

'period[]' Not to be confused with a timedelta, these objects are actually anchored to specific time periods

'Sparse', 'Sparse[int]', 'Sparse[float]' is for sparse data or 'Data that has a lot of holes in it' Instead of saving the NaN or None in the dataframe it omits the objects, saving space.

'Interval' is a topic of its own but its main use is for indexing. See more here

'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64' are all pandas specific integers that are nullable, unlike the numpy variant.

'string' is a specific dtype for working with string data and gives access to the .str attribute on the series.

'boolean' is like the numpy 'bool' but it also supports missing data.

Read the complete reference here:

Pandas dtype reference

Gotchas, caveats, notes

Setting dtype=object will silence the above warning, but will not make it more memory efficient, only process efficient if anything.

Setting dtype=unicode will not do anything, since to numpy, a unicode is represented as object.

Usage of converters

@sparrow correctly points out the usage of converters to avoid pandas blowing up when encountering 'foobar' in a column specified as int. I would like to add that converters are really heavy and inefficient to use in pandas and should be used as a last resort. This is because the read_csv process is a single process.

CSV files can be processed line by line and thus can be processed by multiple converters in parallel more efficiently by simply cutting the file into segments and running multiple processes, something that pandas does not support. But this is a different story.

Rails params explained?

As others have pointed out, params values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.

As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params. For example, if you have a route like this:

match 'products/:id', ...

Then a request to a URL like http://example.com/products/42 will set params[:id] to 42.

What's the correct way to convert bytes to a hex string in Python 3?

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

I included an snippet that illustrates it.

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'

Modifying the "Path to executable" of a windows service

Slight modification to this @CodeMaker 's answer, for anyone like me who is trying to modify a MongoDB service to use authentication.

When I looked at the "Path to executable" in "Services" the executed line already contained speech marks. So I had to make minor modification to his example.

To be specific.

  1. Type Services in Windows
  2. Find MongoDB (or the service you want to change) and open the service, making sure to stop it.
  3. Make a note of the Service Name (not the display name)
  4. Look up and copy the "Path to executable" and copy it.

For me the path was (note the speech marks)

"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --config "C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg" --service

In a command line type

sc config MongoDB binPath= "<Modified string with \" to replace ">"

In my case this was

sc config MongoDB binPath= "\"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe\" --config \"C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg\" --service -- auth"

Error while sending QUERY packet

If inserting 'too much data' fails due to the max_allowed_packet setting of the database server, the following warning is raised:

SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 
'max_allowed_packet' bytes

If this warning is catched as exception (due to the set error handler), the database connection is (probably) lost but the application doesn't know about this (failing inserts can have several causes). The next query in line, which can be as simple as:

SELECT 1 FROM DUAL

Will then fail with the error this SO-question started:

Error while sending QUERY packet. PID=18486

Simple test script to reproduce my explanation, try it with and without the error handler to see the difference in impact:

set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try
{
    // $oDb is instance of PDO
    var_dump($oDb->query('SELECT 1 FROM DUAL'));

    $oStatement = $oDb->prepare('INSERT INTO `test` (`id`, `message`) VALUES (NULL, :message);');
    $oStatement->bindParam(':message', $largetext, PDO::PARAM_STR);
    var_dump($oStatement->execute());
}
catch(Exception $e)
{
    $e->getMessage();
}
var_dump($oDb->query('SELECT 2 FROM DUAL'));

Difference between MEAN.js and MEAN.io

The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.

Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%

generator- angular- fullstack offers 8% that MEANJS.org doesn't

  • 1.9% Client-side end-to-end tests
  • 0.6% factory
  • 0.5% provider
  • 0.4% SASS
  • 0.4% LESS
  • 0.4% Compass
  • 0.4% decorator
  • 0.4% Endpoint subgenerator
  • 0.4% Comments
  • 0.3% FontAwesome
  • 0.3% Run server in debug mode
  • 0.3% Save generator answers to a file
  • 0.2% constant
  • 0.2% Development build script: ...... replace 3rd party deps with CDN versions
  • 0.2% Authentication - Cookie
  • 0.2% Authentication - JSON Web Token (JWT)
  • 0.2% Server-side logging
  • 0.1% Development build script: run tasks in parallel to speed it up
  • 0.1% Development build script: Renames asset files to prevent browser caching
  • 0.1% Development build script: run end to end tests
  • 0.1% Production build script: safe pre-minification
  • 0.1% Production build script: add CSS vendor prefixes
  • 0.1% Heroku deployment automation
  • 0.1% value
  • 0.1% Jade
  • 0.1% Coffeescript
  • 0.1% Serverside authenticated route restriction
  • 0.1% SASS version of Twitter Bootstrap
  • 0.1% Production build script: compress images
  • 0.1% OpenShift deployment automation

MeanJS.org. offers 9% that generator-angular-fullstack doesn't

  • 3.7% Dedicated/searchable user group: response time mostly under a day
  • 0.4% Generate routes
  • 0.4% Authentication - Oauth
  • 0.4% config
  • 0.4% i18n, localization
  • 0.4% Input application profile
  • 0.3% FEATURE (a.k.a. module, entity, crud-mock)
  • 0.3% Menus system
  • 0.3% Options for making subcomponents
  • 0.3% test - client side
  • 0.3% Javascript performance thing
  • 0.3% Production build script: make static pages for SEO
  • 0.2% Quick install?
  • 0.2% Dedicated/searchable user group
  • 0.1% Development build script: reload build file upon change
  • 0.1% Development build script: coffee files compiled to JS
  • 0.1% controller - server side
  • 0.1% model - server side
  • 0.1% route - server side
  • 0.1% test - server side
  • 0.1% Swig
  • 0.1% Safe from IP Spoofing
  • 0.1% Production build script: uglification
  • 0.0% Approach to views: URLs start with "#!"
  • 0.0% Approach to frontend services and ajax calls: uses $resource

Here is the one between MEAN.io and MEAN.js in a more readable format

_x000D_
_x000D_
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using github issues<br>&nbsp;&nbsp;&nbsp;&nbsp;* There's a book about it<br><b>File Organization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Basic sourcecode organization, module(-&gt;submodule)-&gt;side<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold directives<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, Only one module definition per file<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Object-relational mapping<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side validation, server-side example<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client side validation, using Angular 1.3<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS views, Directives start with "data-"<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, Use ng-init<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, URLs start with '#!'<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, LESS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, SASS<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Mocha<br>&nbsp;&nbsp;&nbsp;&nbsp;* End-to-end tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* End-to-end tests, using Protractor<br>&nbsp;&nbsp;&nbsp;&nbsp;* Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI), using Yeoman<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build configurations file(s)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Azure<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Digital Ocean, screencast of it<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Input application profile<br>&nbsp;&nbsp;&nbsp;&nbsp;* Quick install?<br>&nbsp;&nbsp;&nbsp;&nbsp;* Options for making subcomponents<br>&nbsp;&nbsp;&nbsp;&nbsp;* config generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* controller (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* directive generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* filter generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* route (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* service (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* test - client side<br>&nbsp;&nbsp;&nbsp;&nbsp;* view or view partial generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* controller (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* model (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* route (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* test (server side) generator<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, Forgotten Password with Resetting<br>&nbsp;&nbsp;&nbsp;&nbsp;* Chat<br>&nbsp;&nbsp;&nbsp;&nbsp;* CSV processing<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system, using Nodemailer<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system, using its own e-mail implementation<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system, state-based<br>&nbsp;&nbsp;&nbsp;&nbsp;* Paypal integration<br>&nbsp;&nbsp;&nbsp;&nbsp;* Responsive design<br>&nbsp;&nbsp;&nbsp;&nbsp;* Social connections management page<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Creates a favicon<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Safe from IP Spoofing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authorization, Access Contol List (ACL)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Cookie<br>&nbsp;&nbsp;&nbsp;&nbsp;* Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Sponsoring company<br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Docs with flatdoc<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Share code between projects<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module manager<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, Use AMD with Require.js<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, using wiredep<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Centralized event handling<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* API introspection report and testing interface, using Swagger<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Heroku<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Scaffolding undo&nbsp;&nbsp;&nbsp;&nbsp;(mean package -d &lt;name&gt;)<br>&nbsp;&nbsp;&nbsp;&nbsp;* FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Admin page for users and roles<br>&nbsp;&nbsp;&nbsp;&nbsp;* Content Management System&nbsp;&nbsp;&nbsp;&nbsp;(Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br>&nbsp;&nbsp;&nbsp;&nbsp;* File Upload<br>&nbsp;&nbsp;&nbsp;&nbsp;* i18n, localization<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system, submenus<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search, actually works with backend API<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search, using Elastic Search<br>&nbsp;&nbsp;&nbsp;&nbsp;* Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br>&nbsp;&nbsp;&nbsp;&nbsp;* Text (WYSIWYG) Editor<br>&nbsp;&nbsp;&nbsp;&nbsp;* Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Instrumentation, server-side<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serverside authenticated route restriction<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, using Oauth, Link multiple Oauth strategies to one account<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Version Control, using git<br><b>Platforms</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client-side JS Framework, using AngularJS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Frontend Server/ Framework, using Node.JS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Frontend Server/ Framework, using Node.JS, using Express<br>&nbsp;&nbsp;&nbsp;&nbsp;* API Server/ Framework, using NodeJS<br>&nbsp;&nbsp;&nbsp;&nbsp;* API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using Google Groups<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using Facebook<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, response time mostly under a day<br>&nbsp;&nbsp;&nbsp;&nbsp;* Example application<br>&nbsp;&nbsp;&nbsp;&nbsp;* Tutorial screencast in English<br>&nbsp;&nbsp;&nbsp;&nbsp;* Tutorial screencast in English, using Youtube<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated chatroom<br><b>File Organization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Basic sourcecode organization, module(-&gt;submodule)-&gt;side, with type subfolders<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold controllers<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold services<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold templates<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Separate route configuration files for each module<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Modularized Functionality<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, No global 'app' module variable<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage, using NoSQL db<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* No XHR calls in controllers<br>&nbsp;&nbsp;&nbsp;&nbsp;* Templates, using Angular directives<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, example of it<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, State-based routing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, State-based routing, using ui-router<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, HTML5 Mode<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serve status codes only as responses<br>&nbsp;&nbsp;&nbsp;&nbsp;* Accept nested, JSON parameters<br>&nbsp;&nbsp;&nbsp;&nbsp;* Add timer header to requests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Support for signed and encrypted cookies<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serve URLs based on the route definitions<br>&nbsp;&nbsp;&nbsp;&nbsp;* Can serve headers only<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using JSON<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, JavaScript (server side)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, Swig<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Separate runtime configuration profiles<br><b>Testing</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Jasmine<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Karma<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client-side unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Continuous integration (CI)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Automated device testing, using Live Reload<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side integration &amp; unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side integration &amp; unit tests, using Mocha<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI)<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build-time Dependency Management, using npm<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build-time Dependency Management, using bower<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build tool / Task runner, using Grunt<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build tool / Task runner, using gulp<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, script<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, reload build script file upon change<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, copy assets to build or dist or target folder<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories, injects js references<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories, injects css references<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, LESS/SASS/etc files are linted, compiled<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, JavaScript style checking<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, JavaScript style checking, using jshint or jslint<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, run unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, script<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, concatenation (aggregation, globbing, bundling)&nbsp;&nbsp;&nbsp;&nbsp;(If you add debug:true to your config/env/development.js the will not be <br>uglified)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, minification<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, safe pre-minification, using ng-annotate<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, uglification<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, make static pages for SEO<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* FEATURE (a.k.a. module, entity) generator&nbsp;&nbsp;&nbsp;&nbsp;(README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* 404 Page<br>&nbsp;&nbsp;&nbsp;&nbsp;* 500 Page<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, register/login/logout<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, is password manager friendly<br>&nbsp;&nbsp;&nbsp;&nbsp;* Front-end CRUD<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD, with Read<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD, with Create, Update and Delete<br>&nbsp;&nbsp;&nbsp;&nbsp;* Google Analytics<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system<br>&nbsp;&nbsp;&nbsp;&nbsp;* Realtime data sync<br>&nbsp;&nbsp;&nbsp;&nbsp;* Realtime data sync, using socket.io<br>&nbsp;&nbsp;&nbsp;&nbsp;* Styles, using Bootstrap<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Javascript performance thing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Javascript performance thing, using lodash<br>&nbsp;&nbsp;&nbsp;&nbsp;* One event-loop thread handles all requests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Configurable response caching&nbsp;&nbsp;&nbsp;&nbsp;(Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Clustered HTTP sessions<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript obfuscation<br>&nbsp;&nbsp;&nbsp;&nbsp;* https<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, using Oauth<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Basic&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Digest&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Token&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br></td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

HTML5 canvas ctx.fillText won't do line breaks?

Using javascript I developed a solution. It isn't beautiful but it worked for me:


function drawMultilineText(){

    // set context and formatting   
    var context = document.getElementById("canvas").getContext('2d');
    context.font = fontStyleStr;
    context.textAlign = "center";
    context.textBaseline = "top";
    context.fillStyle = "#000000";

    // prepare textarea value to be drawn as multiline text.
    var textval = document.getElementByID("textarea").value;
    var textvalArr = toMultiLine(textval);
    var linespacing = 25;
    var startX = 0;
    var startY = 0;

    // draw each line on canvas. 
    for(var i = 0; i < textvalArr.length; i++){
        context.fillText(textvalArr[i], x, y);
        y += linespacing;
    }
}

// Creates an array where the <br/> tag splits the values.
function toMultiLine(text){
   var textArr = new Array();
   text = text.replace(/\n\r?/g, '<br/>');
   textArr = text.split("<br/>");
   return textArr;
}

Hope that helps!

Display two fields side by side in a Bootstrap Form

@KyleMit's answer on Bootstrap 4 has changed a little

<div class="input-group">
    <input type="text" class="form-control">
    <div class="input-group-prepend">
        <span class="input-group-text">-</span>
    </div>
    <input type="text" class="form-control">
</div>

How to move screen without moving cursor in Vim?

Here's my solution in vimrc:

"keep cursor in the middle all the time :)
nnoremap k kzz
nnoremap j jzz
nnoremap p pzz
nnoremap P Pzz
nnoremap G Gzz
nnoremap x xzz
inoremap <ESC> <ESC>zz
nnoremap <ENTER> <ENTER>zz
inoremap <ENTER> <ENTER><ESC>zzi
nnoremap o o<ESC>zza
nnoremap O O<ESC>zza
nnoremap a a<ESC>zza

So that the cursor will stay in the middle of the screen, and the screen will move up or down.

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

invalid target release: 1.7

This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.

Check Mike's answer to his own question here: stackoverflow question 24705877

This solved the issue for me both command line AND within eclipse.

Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.

how to implement a pop up dialog box in iOS

For Swift 3 & Swift 4 :

Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3

let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title:     NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
                //Do whatever you want here
        })
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)

Deprecated :

This is the swift version inspired by the checked response :

Display AlertView :

   let alert = UIAlertView(title: "No network connection", 
                           message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
    alert.delegate = self
    alert.show()

Add the delegate to your view controller :

class AgendaViewController: UIViewController, UIAlertViewDelegate

When user click on button, this code will be executed :

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {


}

Add click event on div tag using javascript

Just add the onclick-attribute:

<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>

It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script> tags - maybe it does what you want.

While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener (as pointed out by other answers), if you expect the code to grow and stay maintainable.

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

How can I get the timezone name in JavaScript?

This gets the timezone code (e.g., GMT) in older javascript (I'm using google app script with old engine):

function getTimezoneName() {
  return new Date().toString().get(/\((.+)\)/);
}

I'm just putting this here in case someone needs it.

install cx_oracle for python

Alternatively you can install the cx_Oracle module without the PIP using the following steps

  1. Download the source from here https://pypi.python.org/pypi/cx_Oracle [cx_Oracle-6.1.tar.gz ]
  2. Extract the tar using the following commands (Linux)

    gunzip cx_Oracle-6.1.tar.gz

    tar -xf cx_Oracle-6.1.tar

  3. cd cx_Oracle-6.1

  4. Build the module

    python setup.py build

  5. Install the module

    python setup.py install

IN vs OR in the SQL WHERE Clause

I assume you want to know the performance difference between the following:

WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'

According to the manual for MySQL if the values are constant IN sorts the list and then uses a binary search. I would imagine that OR evaluates them one by one in no particular order. So IN is faster in some circumstances.

The best way to know is to profile both on your database with your specific data to see which is faster.

I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:

SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)

SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)

So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.

Python Library Path

import sys
sys.path

How abstraction and encapsulation differ?

Abstraction

In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.

Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.

Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.

Encapsulation:

Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.

  1. If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
  2. Within a package, if we declare each class filed (member field) as private and having a public method to access those fields, this way giving class level encapsulation to those fields

How to get the index of an item in a list in a single step?

Here's a copy/paste-able extension method for IEnumerable

public static class EnumerableExtensions
{
    /// <summary>
    /// Searches for an element that matches the conditions defined by the specified predicate,
    /// and returns the zero-based index of the first occurrence within the entire <see cref="IEnumerable{T}"/>.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list">The list.</param>
    /// <param name="predicate">The predicate.</param>
    /// <returns>
    /// The zero-based index of the first occurrence of an element that matches the conditions defined by <paramref name="predicate"/>, if found; otherwise it'll throw.
    /// </returns>
    public static int FindIndex<T>(this IEnumerable<T> list, Func<T, bool> predicate)
    {
        var idx = list.Select((value, index) => new {value, index}).Where(x => predicate(x.value)).Select(x => x.index).First();
        return idx;
    }
}

Enjoy.

round up to 2 decimal places in java?

This is long one but a full proof solution, never fails

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;

if 4.25, Output 4.25

if 4.20, Output 4.20

if 4.24, Output 4.20

if 4.26, Output 4.30

if you want to round upto 2 decimal places,then use

DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));

if up to 3 places, new DecimalFormat("#.###")

if up to n places, new DecimalFormat("#.nTimes #")

 public double roundToMultipleOfFive(double x)
            {

                x=input.nextDouble();
                String str=String.valueOf(x);
                int pos=0;
                for(int i=0;i<str.length();i++)
                {
                    if(str.charAt(i)=='.')
                    {
                        pos=i;
                        break;
                    }
                }

                int after=Integer.parseInt(str.substring(pos+1,str.length()));
                int Q=after/5;
                int R =after%5;

                if((Q%2)==0)
                {
                    after=after-R;
                }
                else
                {
                   if(5-R==5)
                   {
                     after=after;
                   }
                   else after=after+(5-R);
                }

                       return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));

            }

What are NDF Files?

From Files and Filegroups Architecture

Secondary data files

Secondary data files make up all the data files, other than the primary data file. Some databases may not have any secondary data files, while others have several secondary data files. The recommended file name extension for secondary data files is .ndf.

Also from file extension NDF - Microsoft SQL Server secondary data file

See Understanding Files and Filegroups

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

The recommended file name extension for secondary data files is .ndf.

/

For example, three files, Data1.ndf, Data2.ndf, and Data3.ndf, can be created on three disk drives, respectively, and assigned to the filegroup fgroup1. A table can then be created specifically on the filegroup fgroup1. Queries for data from the table will be spread across the three disks; this will improve performance. The same performance improvement can be accomplished by using a single file created on a RAID (redundant array of independent disks) stripe set. However, files and filegroups let you easily add new files to new disks.

converting a base 64 string to an image and saving it

In a similar scenario what worked for me was the following:

byte[] bytes = Convert.FromBase64String(Base64String);    
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);

ImageTagId is the ID of the ASP image tag.

How to increase heap size for jBoss server

What to change?

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

Where to change? (Normally)

bin/standalone.conf(Linux) standalone.conf.bat(Windows)

What if you are using custom script which overrides the existing settings? then?

setAppServerEnvironment.cmd/.sh (kind of file name will be there)

More information are already provided by one of our committee members! BalusC.

String isNullOrEmpty in Java?

com.google.common.base.Strings.isNullOrEmpty(String string) from Google Guava

Exit/save edit to sudoers file? Putty SSH

#UBUNTU20

if you are opening this file as root, then type

root# visudo

the file will be opened, go to the line where you want to add/modifiy anything simply without any insert or i button pressed.

press ctrl + O
press ctrl + x
press enter

How to open a new form from another form

For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.

your name example=form2.

form2 obj=new form2();

obj.show();

To close form1, write the following code:

form1.visible=false; or form1.Hide();

How does DHT in torrents work?

The general theory can be found in wikipedia's article on Kademlia. The specific protocol specification used in bittorrent is here: http://wiki.theory.org/BitTorrentDraftDHTProtocol

Automatically plot different colored lines

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);

figure;
plot(data);

legend(cellstr(num2str((1:size(data,2))')))

Or, if you have a cell with kernels names, use

legend(names)

Connect Android Studio with SVN

In Android Studio we can get the repositories of svn using the VCS->Subversion and the extract the repository and work on the code

See full command of running/stopped container in Docker

docker ps --no-trunc will display the full command along with the other details of the running containers.

How to open a link in new tab using angular?

Try this:

 window.open(this.url+'/create-account')

No need to use '_blank'. window.open by default opens a link in a new tab.

Summernote image upload

This code worked well with new version (v0.8.12) (2019-05-21)

$('#summernote').summernote({
        callbacks: {
            onImageUpload: function(files) {
                for(let i=0; i < files.length; i++) {
                    $.upload(files[i]);
                }
            }
        },
        height: 500,
    });

    $.upload = function (file) {
        let out = new FormData();
        out.append('file', file, file.name);

        $.ajax({
            method: 'POST',
            url: 'upload.php',
            contentType: false,
            cache: false,
            processData: false,
            data: out,
            success: function (img) {
                $('#summernote').summernote('insertImage', img);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(textStatus + " " + errorThrown);
            }
        });
    };

PHP Code (upload.php)

if ($_FILES['file']['name']) {
 if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = explode('.', $_FILES['file']['name']);
    $filename = $name . '.' . $ext[1];
    $destination = 'images/' . $filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'images/' . $filename;//change this URL
 }
 else
 {
  echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
 }
}

How can I clear the content of a file?

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

Insert/Update Many to Many Entity Framework . How do I do it?

In entity framework, when object is added to context, its state changes to Added. EF also changes state of each object to added in object tree and hence you are either getting primary key violation error or duplicate records are added in table.

Chmod recursively

Give 0777 to all files and directories starting from the current path :

chmod -R 0777 ./

multiple prints on the same line in Python

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.

Recover from git reset --hard?

I did git reset --hard on the wrong project by mistake (I know...). I had just worked on one file and it was still open during and after I ran the command.

Even though I had not committed, I was able to retrieve the old file with the simple COMMAND + Z.

Official reasons for "Software caused connection abort: socket write error"

In the situation explained below, client side will throw such an exception:

The server is asked to authenticate client certificate, but the client provides a certificate which Extended Key Usage doesn't support client auth, so the server doesn't accept the client's certificate, and then it closes the connection.

JSON order mixed up

For those who're using maven, please try com.github.tsohr/json

<!-- https://mvnrepository.com/artifact/com.github.tsohr/json -->
<dependency>
    <groupId>com.github.tsohr</groupId>
    <artifactId>json</artifactId>
    <version>0.0.1</version>
</dependency>

It's forked from JSON-java but switch its map implementation with LinkedHashMap which @lemiorhan noted above.

Insert some string into given string at given index in Python

I know it's malapropos, but IMHO easy way is:

def insert (source_str, insert_str, pos):
    return source_str[:pos]+insert_str+source_str[pos:]

How can I get the sha1 hash of a string in node.js?

Tips to prevent issue (bad hash) :

I experienced that NodeJS is hashing the UTF-8 representation of the string. Other languages (like Python, PHP or PERL...) are hashing the byte string.

We can add binary argument to use the byte string.

const crypto = require("crypto");

function sha1(data) {
    return crypto.createHash("sha1").update(data, "binary").digest("hex");
}

sha1("Your text ;)");

You can try with : "\xac", "\xd1", "\xb9", "\xe2", "\xbb", "\x93", etc...

Other languages (Python, PHP, ...):

sha1("\xac") //39527c59247a39d18ad48b9947ea738396a3bc47

Nodejs:

sha1 = crypto.createHash("sha1").update("\xac", "binary").digest("hex") //39527c59247a39d18ad48b9947ea738396a3bc47
//without:
sha1 = crypto.createHash("sha1").update("\xac").digest("hex") //f50eb35d94f1d75480496e54f4b4a472a9148752

How do I add my bot to a channel?

This is how I've added a bot to my channel and set up notifications:

  1. Make sure the channel is public (you can set it private later)
  2. Add administrators > Type the bot username and make it administrator
  3. Your bot will join your channel
  4. set a channel id by setting the channel url like

telegram.me/whateverIWantAndAvailable

the channel id will be @whateverIWantAndAvailable

Now set up your bot to send notifications by pusshing the messages here:

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test

the message which bot will notify is: Test

I strongly suggest an urlencode of the message like

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works

in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");

I hope it helps

Change language for bootstrap DateTimePicker

This is for your reference only:

https://github.com/rajit/bootstrap3-datepicker/tree/master/locales/zh-CN

https://github.com/smalot/bootstrap-datetimepicker

https://bootstrap-datepicker.readthedocs.io/en/v1.4.1/i18n.html

The case is as follows:

 <div class="input" id="event_period">
   <input class="date" required="required" type="text">
 </div>

 $.fn.datepicker.dates['zh-CN'] = {
    days:["???","???","???","???","???","???","???"],
    daysShort:["??","??","??","??","??","??","??"],
    daysMin:["?","?","?","?","?","?","?"],
    months:["??","??","??","??","??","??","??","??","??","??","???","???"],
    monthsShort:["1?","2?","3?","4?","5?","6?","7?","8?","9?","10?","11?","12?"],
    today:"??",
    clear:"??"
  };

  $('#event_period').datepicker({
    inputs: $('input.date'),
    todayBtn: "linked",
    clearBtn: true,
    format: "yyyy?mm?",
    titleFormat: "yyyy?mm?",
    language: 'zh-CN',
    weekStart:1 // Available or not
  });

Java output formatting for Strings

To answer your updated question you can do

String[] lines = ("Name =              Bob\n" +
        "Age =               27\n" +
        "Occupation =        Student\n" +
        "Status =            Single").split("\n");

for (String line : lines) {
    String[] parts = line.split(" = +");
    System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}

prints

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single

When do you use the "this" keyword?

There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.

You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.

template <typename T>
struct base {
   void f() {}
};

template <typename T>
struct derived : public base<T>
{
   void test() {
      //f(); // [1] error
      base<T>::f(); // quite verbose if there is more than one argument, but valid
      this->f(); // f is now an argument dependent symbol
   }
}

Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.

At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.

The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.

The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.

How to prevent going back to the previous activity?

Since there are already many great solutions suggested, ill try to give a more dipictive explanation.

How to skip going back to the previous activity?

Remove the previous Activity from Backstack. Simple

How to remove the previous Activity from Backstack?

Call finish() method

The Normal Flow:

enter image description here
All the activities are stored in a Stack known as Backstack.
When you start a new Activity(startActivity(...)) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
One key point to note is that when the back button is pressed then finish(); method is called internally. This is the default behavior of onBackPressed() method.

So if you want to skip Activity B?

ie A<--- C

Just add finish(); method after your startActvity(...) in the Activity B

Intent i = new Intent(this, C.class);
startActivity(i);
finish();

enter image description here

Java: Static Class?

comment on the "private constructor" arguments: come on, developers are not that stupid; but they ARE lazy. creating an object then call static methods? not gonna happen.

don't spend too much time to make sure your class cannot be misused. have some faith for your colleagues. and there is always a way to misuse your class no matter how you protect it. the only thing that cannot be misused is a thing that is completely useless.

Iterate through string array in Java

As long as this question remains unsanswered the OP's problem and Java has evolved over the years, I have decided to put my own one.

Let's change for sake of clarity the input String array to have 5 unique items.

String[] elements = {"a", "b", "c", "d", "e"};

You want to access two siblings in the list with each iteration incremented by one index.

for (int i=0; i<elements.length-1; i++) {        // note the condition
    String left = elements[i];
    String right = elements[i+1];

    System.out.println(left + " " + right);      // prints 4 lines
}

Printing the pairs of left and right in four iterations result in the lines a b, b c, c d, d e in your console.

What can happen if the input string array has less than 2 elements? Nothing prints our as long as this for-loop extracts always two sibling nodes. With less than 2 elements the program doesn't enter to the loop itself.

As far as your snippet says you want to not discard the extracted values but add them an another variable, assuming outside the scope of the for-loop, you want to store them in either a list or an array. Let's say you want to concatenate the siblings with the + character.

List<String> list = new ArrayList<>();
String[] array = new String[elements.length-1];  // note the defined size

for (int i=0; i<elements.length-1; i++) {
    String left = elements[i];
    String right = elements[i+1];

    list.add(left + "+" + right);            // adds to the list
    array[i] = left + "+" + right;           // adds to the array
}

Printing the contents both of the list and the array (Arrays.toString(array)) results in:

[a+b, b+c, c+d, d+e]

Java 8

As of Java 8, you might be tempted to use the advantage of Stream API, however, it was made for procesing the individual elements from a source collection. There is no such method for processing 2 or more sibling nodes at once.

The only way is to use Stream API to process the indices instead and map them to the real value. As long as you start with a primitive Stream called IntStream you need to use IntStream::mapToObj method to get boxed Stream<T>:

String[] array = IntStream.range(0, elements.length-1)
    .mapToObj(i -> elements[i] + "+" + elements[i + 1])
    .toArray(String[]::new);                              // [a+b, b+c, c+d, d+e]

List<String> list = IntStream.range(0, elements.length-1)
    .mapToObj(i -> elements[i] + "+" + elements[i + 1])
    .collect(Collectors.toList());                        // [a+b, b+c, c+d, d+e]

Multiple actions were found that match the request in Web Api

Update as of Web API 2.

With this API config in your WebApiConfig.cs file:

public static void Register(HttpConfiguration config)
{
    //// Web API routes
    config.MapHttpAttributeRoutes(); //Don't miss this

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = System.Web.Http.RouteParameter.Optional }
    );
}

You can route our controller like this:

[Route("api/ControllerName/Summary")]
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
    return null;
}

[Route("api/ControllerName/FullDetails")]
[HttpGet]
public HttpResponseMessage FullDetails()
{
    return null;
}

Where ControllerName is the name of your controller (without "controller"). This will allow you to get each action with the route detailed above.

For further reading: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Clear text area

This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element.

$('textarea').empty()

Uploading Files in ASP.net without using the FileUpload server control

Here is a solution without relying on any server-side control, just like OP has described in the question.

Client side HTML code:

<form action="upload.aspx" method="post" enctype="multipart/form-data">
    <input type="file" name="UploadedFile" />
</form>

Page_Load method of upload.aspx :

if(Request.Files["UploadedFile"] != null)
{
    HttpPostedFile MyFile = Request.Files["UploadedFile"];
    //Setting location to upload files
    string TargetLocation = Server.MapPath("~/Files/");
    try
    {
        if (MyFile.ContentLength > 0)
        {
            //Determining file name. You can format it as you wish.
            string FileName = MyFile.FileName;
            //Determining file size.
            int FileSize = MyFile.ContentLength;
            //Creating a byte array corresponding to file size.
            byte[] FileByteArray = new byte[FileSize];
            //Posted file is being pushed into byte array.
            MyFile.InputStream.Read(FileByteArray, 0, FileSize);
            //Uploading properly formatted file to server.
            MyFile.SaveAs(TargetLocation + FileName);
        }
    }
    catch(Exception BlueScreen)
    {
        //Handle errors
    }
}

How to completely uninstall Visual Studio 2010?

If I may give an answer to an old thread; You can use PC Decrapifier to select programs you want to uninstall. PC Decrapifier will uninstall them one by one for you so you don't have to click them all seperately.

This is very useful for removing all the 'junk' - like the SQL Database tools - Visual Studio leaves behind even when uninstalled.

wget ssl alert handshake failure

You probably have an old version of wget. I suggest installing wget using Chocolatey, the package manager for Windows. This should give you a more recent version (if not the latest).

Run this command after having installed Chocolatey (as Administrator):

choco install wget

EditText, inputType values (xml)

Supplemental answer

Here is how the standard keyboard behaves for each of these input types.

enter image description here

See this answer for more details.

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

How to implement Rate It feature in Android App

All those libraries are not the solution for the problem in this post. This libraries just open a webpage to the app on google play. Instead this Play core library has more consistent interface.

So I think this is the problem, ProGuard: it obfscates some classes enough https://stackoverflow.com/a/63650212/10117882

Failure [INSTALL_FAILED_INVALID_APK]

I had this issue and none of the above solutions worked for me.

The reason is probably root version phone that has available quota or apk install permissions only at the sdcard.

I fixed the issue using ADB (you'll need a rooted device):

  1. Connect your phone via USB
  2. Launch ADB using adb shell
  3. Switch to root mode using su
  4. create tmp folder in the sdcard: mkdir /sdcard/tmp
  5. cd /data/local
  6. create link the the folder in the sdcard: ln -s /sdcard/tmp tmp

deny directory listing with htaccess

Options -Indexes

I have to try create .htaccess file that current directory that i want to disallow directory index listing. But, sorry i don't know about recursive in .htaccess code.

Try it.

How to generate a random alpha-numeric string

Using UUIDs is insecure, because parts of the UUID aren't random at all. The procedure of erickson is very neat, but it does not create strings of the same length. The following snippet should be sufficient:

/*
 * The random generator used by this class to create random keys.
 * In a holder class to defer initialization until needed.
 */
private static class RandomHolder {
    static final Random random = new SecureRandom();
    public static String randomKey(int length) {
        return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)
            .toString(32)).replace('\u0020', '0');
    }
}

Why choose length*5? Let's assume the simple case of a random string of length 1, so one random character. To get a random character containing all digits 0-9 and characters a-z, we would need a random number between 0 and 35 to get one of each character.

BigInteger provides a constructor to generate a random number, uniformly distributed over the range 0 to (2^numBits - 1). Unfortunately 35 is not a number which can be received by 2^numBits - 1.

So we have two options: Either go with 2^5-1=31 or 2^6-1=63. If we would choose 2^6 we would get a lot of "unnecessary" / "longer" numbers. Therefore 2^5 is the better option, even if we lose four characters (w-z). To now generate a string of a certain length, we can simply use a 2^(length*numBits)-1 number. The last problem, if we want a string with a certain length, random could generate a small number, so the length is not met, so we have to pad the string to its required length prepending zeros.

Count words in a string method?

A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.

import java.util.HashMap;

import java.util.Map;

public class WordCountMethod {

    public static void main (String [] args){

        Map<String, Integer>m = new HashMap<String, Integer>();
        String phrase = "hello my name is John I repeat John";
        String [] array = phrase.split(" ");

        for(int i =0; i < array.length; i++){
            String word_i = array[i];
            Integer ci = m.get(word_i);
            if(ci == null){
                m.put(word_i, 1);
            }
            else m.put(word_i, ci+1);
        }

        for(String s : m.keySet()){
            System.out.println(s+" repeats "+m.get(s));
        }
    }

} 

Bulk Insert to Oracle using .NET

To follow up on Theo's suggestion with my findings (apologies - I don't currently have enough reputation to post this as a comment)

First, this is how to use several named parameters:

String commandString = "INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)";
using (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))
{
    command.Parameters.Add("Name", OracleType.VarChar, 50).Value = strategy;
    command.Parameters.Add("Desk", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;
    command.Parameters.Add("UpdateTime", OracleType.DateTime).Value = updated;
    command.ExecuteNonQuery();
}

However, I saw no variation in speed between:

  • constructing a new commandString for each row (String.Format)
  • constructing a now parameterized commandString for each row
  • using a single commandString and changing the parameters

I'm using System.Data.OracleClient, deleting and inserting 2500 rows inside a transaction

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}

and do the forward only once at last line...

you can also fix this problem using return statement after each forward() or put each forward() in if...else block

Nginx: Job for nginx.service failed because the control process exited

In my case, it's because of apache server is running somehow. So I stop apache then restart nginx. Work like a charm!

sudo /etc/init.d/apache2 stop
sudo systemctl restart nginx

undefined reference to boost::system::system_category() when compiling

Another workaround for those who don't need the entire shebang: use the switch

-DBOOST_ERROR_CODE_HEADER_ONLY.

If you use CMake, it's add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY).

How do I get an apk file from an Android device?

The procedures outlined here do not work for Android 7 (Nougat) [and possibly Android 6, but I'm unable to verify]. You can't pull the .apk files directly under Nougat (unless in root mode, but that requires a rooted phone). But, you can copy the .apk to an alternate path (say /sdcard/Download) on the phone using adb shell, then you can do an adb pull from the alternate path.

Passing in class names to react components

For anyone interested, I ran into this same issue when using css modules and react css modules.

Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component. But I want to pass some additional styles to Button from Promo

So the styleable Button looks like this:

Button.js

import React, { Component } from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'

class Button extends Component {

  render() {

    let button = null,
        className = ''

    if(this.props.className !== undefined){
        className = this.props.className
    }

    button = (
      <button className={className} styleName='button'>
        {this.props.children}
      </button>
    )

    return (
        button
    );
  }
};

export default CSSModules(Button, styles, {allowMultiple: true} )

In the above Button component the Button.css styles handle the common button styles. In this example just a .button class

Then in my component where I want to use the Button, and I also want to modify things like the position of the button, I can set extra styles in Promo.css and pass through as the className prop. In this example again called .button class. I could have called it anything e.g. promoButton.

Of course with css modules this class will be .Promo__button___2MVMD whereas the button one will be something like .Button__button___3972N

Promo.js

import React, { Component } from 'react';
import CSSModules from 'react-css-modules';
import styles from './Promo.css';

import Button from './Button/Button'

class Promo extends Component {

  render() {

    return (
        <div styleName='promo' >
          <h1>Testing the button</h1>
          <Button className={styles.button} >
            <span>Hello button</span>
          </Button>
        </div>
      </Block>
    );
  }
};

export default CSSModules(Promo, styles, {allowMultiple: true} );

Convert string to date in bash

date only work with GNU date (usually comes with Linux)

for OS X, two choices:

  1. change command (verified)

    #!/bin/sh
    #DATE=20090801204150
    #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\""
    date "Saturday, 1 August 2009 20:41:50"
    

    http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html

  2. Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html

How do I check if a file exists in Java?

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

Edit Crystal report file without Crystal Report software

My dad moved his office after 30 year and they need to update the address in the header of their Crystal Reports 7 (1997!) based billing system.

After buying old copies of Access 97 and Visual Studio 2003 Pro, I found out that both programs were too new - they could open the RPT files, but they saved them with an updated version that would not open in the billing system.

I ended up being able to make the changes using this life-saver program...

http://www.softwareforces.com/Products/rpt-inspector-professional-suite-for-crystal-reports

It was available with a 10 day free trial, and I only needed about 10 minutes to make my changes. That said, I would have happily paid whatever they asked for it. :)

Some hints:

  1. When I opened my RPT files, I got an error saving the database could not be found. I ignored this error and everything worked fine.
  2. Because my RPT files were Crystal Reports version 7, I had to go into Options->Misc and tell the program to save in the old format...

enter image description here

Get PHP class property by string

Something like this? Haven't tested it but should work fine.

function magic($obj, $var, $value = NULL)
{
    if($value == NULL)
    {
        return $obj->$var;
    }
    else
    {
        $obj->$var = $value;
    }
}

UITableview: How to Disable Selection for Some Rows but Not Others

Starting in iOS 6, you can use

-tableView:shouldHighlightRowAtIndexPath:

If you return NO, it disables both the selection highlighting and the storyboard triggered segues connected to that cell.

The method is called when a touch comes down on a row. Returning NO to that message halts the selection process and does not cause the currently selected row to lose its selected look while the touch is down.

UITableViewDelegate Protocol Reference

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 print a quotation mark in C?

You have to use escaping of characters. It's a solution of this chicken-and-egg problem: how do I write a ", if I need it to terminate a string literal? So, the C creators decided to use a special character that changes treatment of the next char:

printf("this is a \"quoted string\"");

Also you can use '\' to input special symbols like "\n", "\t", "\a", to input '\' itself: "\\" and so on.

How do I write JSON data to a file?

You forgot the actual JSON part - data is a dictionary and not yet JSON-encoded. Write it like this for maximum compatibility (Python 2 and 3):

import json
with open('data.json', 'w') as f:
    json.dump(data, f)

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file with

import json
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

Reset input value in angular 2

Use @ViewChild to reset your control.

Template:

<input mdInput placeholder="Name" #filterName name="filterName" >

In Code:

@ViewChild('filterName') redel:ElementRef;

then you can access your control as

this.redel= "";

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

If you are on Windows 7, simply run Eclipse with Admin privilege will solve this issue.

Just tried this on my Windows 7 64bits OS.

Is it possible to disable the network in iOS Simulator?

Yes. In Xcode, you can go to Xcode menu item -> Open Developer Tools -> More Developer Tools and download "Additional Tools for Xcode", which will have the Network Link Conditioner.

Using this tool, you can simulate different network scenarios (such as 100% loss, 3G, High latency DNS, and more) and you can create your own custom ones as well.

How to set default values in Go structs

From https://golang.org/doc/effective_go.html#composite_literals:

Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.

    func NewFile(fd int, name string) *File {
      if fd < 0 {
        return nil
      }
      f := new(File)
      f.fd = fd
      f.name = name
      f.dirinfo = nil
      f.nepipe = 0
      return f
}

Why do I get a warning icon when I add a reference to an MEF plugin project?

In a multi-project solution, If every other thing failed... On the startUp project, check. Dependencies->Assemblies and see if the erring referenced project is there. Remove it and re-build.

How do I dynamically assign properties to an object in TypeScript?

If you are using Typescript, presumably you want to use the type safety; in which case naked Object and 'any' are counterindicated.

Better to not use Object or {}, but some named type; or you might be using an API with specific types, which you need extend with your own fields. I've found this to work:

class Given { ... }  // API specified fields; or maybe it's just Object {}

interface PropAble extends Given {
    props?: string;  // you can cast any Given to this and set .props
    // '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";

// to avoid constantly casting: 
let k:PropAble = getTheGivenObject();
k.props = "value for props";

Flutter does not find android sdk

I solved this problem by below step,

1) go to -> system environment -> Environment Variables -> system Variable

2) create New Variable Name ANDROID_HOME and Value D:\Androidsdk\tools (custom android sdk path).

3) concat this path D:\Androidsdk\platform-tools in Path variable value using ";". (also in system Variable)

4) that's all, Restart the PC to apply changes and try again -- flutter Doctor.

How do I vertically center text with CSS?

.text{
   background: #ccc;
   position: relative;
   float: left;
   text-align: center;
   width: 400px;
   line-height: 80px;
   font-size: 24px;
   color: #000;
   float: left;
 }

How to skip the first n rows in sql query

This works with all DBRM/SQL, it is standard ANSI:

SELECT *
  FROM owner.tablename A
 WHERE condition
  AND  n+1 <= (
         SELECT COUNT(DISTINCT b.column_order)
           FROM owner.tablename B
          WHERE condition
            AND b.column_order>a.column_order
          )
ORDER BY a.column_order DESC

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Full Screen DialogFragment in Android

the following solution worked for me other solution gave me some space in the sides i.e not full screen

You need to make changes in onStart and onCreate method

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null)
    {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}


 public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = new Dialog(requireContext());
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
 }


   

Callback functions in Java

public class HelloWorldAnonymousClasses {

    //this is an interface with only one method
    interface HelloWorld {
        public void printSomething(String something);
    }

    //this is a simple function called from main()
    public void sayHello() {

    //this is an object with interface reference followed by the definition of the interface itself

        new HelloWorld() {
            public void printSomething(String something) {
                System.out.println("Hello " + something);
            }
        }.printSomething("Abhi");

     //imagine this as an object which is calling the function'printSomething()"
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
                new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }
}
//Output is "Hello Abhi"

Basically if you want to make the object of an interface it is not possible, because interface cannot have objects.

The option is to let some class implement the interface and then call that function using the object of that class. But this approach is really verbose.

Alternatively, write new HelloWorld() (*oberserve this is an interface not a class) and then follow it up with the defination of the interface methods itself. (*This defination is in reality the anonymous class). Then you get the object reference through which you can call the method itself.

How do I load a PHP file into a variable?

If you are using http://, as eyze suggested, you will only be able to read the ouput of the PHP script. You can only read the PHP script itself if it is on the same server as your running script. You could then use something like

$Vdata = file_get_contents('/path/to/your/file.php");

Android Pop-up message

You can use Dialog to create this easily

create a Dialog instance using the context

Dialog dialog = new Dialog(contex);

You can design your layout as you like.

You can add this layout to your dialog by dialog.setContentView(R.layout.popupview);//popup view is the layout you created

then you can access its content (textviews, etc.) by using findViewById method

TextView txt = (TextView)dialog.findViewById(R.id.textbox);

you can add any text here. the text can be stored in the String.xml file in res\values.

txt.setText(getString(R.string.message));

then finally show the pop up menu

dialog.show();

more information http://developer.android.com/guide/topics/ui/dialogs.html

http://developer.android.com/reference/android/app/Dialog.html

Set background image in CSS using jquery

Use :

 $(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");

instead of

 $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");

More examples you cand see here

Inline functions in C#?

Lambda expressions are inline functions! I think, that C# doesn`t have a extra attribute like inline or something like that!

Vim autocomplete for Python

Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.

It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).

Changing iframe src with Javascript

Here is my updated code. It works fine and it can help you.

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Untitled 1</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script type="text/javascript">
  function go(loc) {
    document.getElementById('calendar').src = loc;
  }
  </script>
</head>

<body>
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>

  <form method="post">
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
  </form>

</body>

</html>

Is it possible to set async:false to $.getJSON call

You need to make the call using $.ajax() to it synchronously, like this:

$.ajax({
  url: myUrl,
  dataType: 'json',
  async: false,
  data: myData,
  success: function(data) {
    //stuff
    //...
  }
});

This would match currently using $.getJSON() like this:

$.getJSON(myUrl, myData, function(data) { 
  //stuff
  //...
});

How to write a confusion matrix in Python?

I wrote a simple class to build a confusion matrix without the need to depend on a machine learning library.

The class can be used such as:

labels = ["cat", "dog", "velociraptor", "kraken", "pony"]
confusionMatrix = ConfusionMatrix(labels)

confusionMatrix.update("cat", "cat")
confusionMatrix.update("cat", "dog")
...
confusionMatrix.update("kraken", "velociraptor")
confusionMatrix.update("velociraptor", "velociraptor")

confusionMatrix.plot()

The class ConfusionMatrix:

import pylab
import collections
import numpy as np


class ConfusionMatrix:
    def __init__(self, labels):
        self.labels = labels
        self.confusion_dictionary = self.build_confusion_dictionary(labels)

    def update(self, predicted_label, expected_label):
        self.confusion_dictionary[expected_label][predicted_label] += 1

    def build_confusion_dictionary(self, label_set):
        expected_labels = collections.OrderedDict()

        for expected_label in label_set:
            expected_labels[expected_label] = collections.OrderedDict()

            for predicted_label in label_set:
                expected_labels[expected_label][predicted_label] = 0.0

        return expected_labels

    def convert_to_matrix(self, dictionary):
        length = len(dictionary)
        confusion_dictionary = np.zeros((length, length))

        i = 0
        for row in dictionary:
            j = 0
            for column in dictionary:
                confusion_dictionary[i][j] = dictionary[row][column]
                j += 1
            i += 1

        return confusion_dictionary

    def get_confusion_matrix(self):
        matrix = self.convert_to_matrix(self.confusion_dictionary)
        return self.normalize(matrix)

    def normalize(self, matrix):
        amin = np.amin(matrix)
        amax = np.amax(matrix)

        return [[(((y - amin) * (1 - 0)) / (amax - amin)) for y in x] for x in matrix]

    def plot(self):
        matrix = self.get_confusion_matrix()

        pylab.figure()
        pylab.imshow(matrix, interpolation='nearest', cmap=pylab.cm.jet)
        pylab.title("Confusion Matrix")

        for i, vi in enumerate(matrix):
            for j, vj in enumerate(vi):
                pylab.text(j, i+.1, "%.1f" % vj, fontsize=12)

        pylab.colorbar()

        classes = np.arange(len(self.labels))
        pylab.xticks(classes, self.labels)
        pylab.yticks(classes, self.labels)

        pylab.ylabel('Expected label')
        pylab.xlabel('Predicted label')
        pylab.show()

Java JTextField with input hint

Here is a fully working example based on Adam Gawne-Cain's earlier Posting. His solution is simple and actually works exceptionally well.

I've used the following text in a Grid of multiple Fields:

H__|__WWW__+__XXXX__+__WWW__|__H

this makes it possible to easily verify the x/y alignment of the hinted text.

A couple of observations:
- there are any number of solutions out there, but many only work superficially and/or are buggy
- sun.tools.jconsole.ThreadTab.PromptingTextField is a simple solution, but it only shows the prompting text when the Field doesn't have the focus & it's private, but nothing a little cut-and-paste won't fix.

The following works on JDK 8 and upwards:

import java.awt.*;
import java.util.stream.*;
import javax.swing.*;
/**
 * @author DaveTheDane, based on a suggestion from Adam Gawne-Cain
 */
public final class JTextFieldPromptExample extends JFrame {

    private static JTextField newPromptedJTextField (final String text, final String prompt) {

        final String promptPossiblyNullButNeverWhitespace = prompt == null || prompt.trim().isEmpty()  ?  null  :  prompt;

        return new JTextField(text) {
            @Override
            public void paintComponent(final Graphics    USE_g2d_INSTEAD) {
                final Graphics2D     g2d =  (Graphics2D) USE_g2d_INSTEAD;

                super.paintComponent(g2d);

//              System.out.println("Paint.: " + g2d);

                if (getText().isEmpty()
                &&  promptPossiblyNullButNeverWhitespace != null) {
                    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                    final Insets      ins = getInsets();
                    final FontMetrics fm  = g2d.getFontMetrics();

                    final int cB = getBackground().getRGB();
                    final int cF = getForeground().getRGB();
                    final int m  = 0xfefefefe;
                    final int c2 = ((cB & m) >>> 1) + ((cF & m) >>> 1); // "for X in (A, R, G, B) {Xnew = (Xb + Xf) / 2}"
                    /*
                     * The hint text color should be halfway between the foreground and background colors so it is always gently visible.
                     * The variables c0,c1,m,c2 calculate the halfway color's ARGB fields simultaneously without overflowing 8 bits.
                     * Swing sets the Graphics' font to match the JTextField's font property before calling the "paint" method,
                     * so the hint font will match the JTextField's font.
                     * Don't think there are any side effects because Swing discards the Graphics after painting.
                     * Adam Gawne-Cain, Aug 6 2019 at 15:55
                     */
                    g2d.setColor(new Color(c2, true));
                    g2d.drawString(promptPossiblyNullButNeverWhitespace, ins.left, getHeight() - fm.getDescent() - ins.bottom);
                    /*
                     * y Coordinate based on Descent & Bottom-inset seems to align Text spot-on.
                     * DaveTheDane, Apr 10 2020
                     */
                }
            }
        };
    }

    private static final GridBagConstraints GBC_LEFT  = new GridBagConstraints();
    private static final GridBagConstraints GBC_RIGHT = new GridBagConstraints();
    /**/    static {
        GBC_LEFT .anchor    = GridBagConstraints.LINE_START;
        GBC_LEFT .fill      = GridBagConstraints.HORIZONTAL;
        GBC_LEFT .insets    = new Insets(8, 8, 0, 0);

        GBC_RIGHT.gridwidth = GridBagConstraints.REMAINDER;
        GBC_RIGHT.fill      = GridBagConstraints.HORIZONTAL;
        GBC_RIGHT.insets    = new Insets(8, 8, 0, 8);
    }

    private <C extends Component> C addLeft (final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_LEFT);
        return                  component;
    }
    private <C extends Component> C addRight(final C component) {
        this    .add           (component);
        this.gbl.setConstraints(component, GBC_RIGHT);
        return                  component;
    }

    private static final String ALIGN = "H__|__WWW__+__XXXX__+__WWW__|__H";

    private final GridBagLayout gbl = new GridBagLayout();

    public JTextFieldPromptExample(final String title) {
        super(title);
        this.setLayout(gbl);

        final java.util.List<JTextField> texts = Stream.of(
                addLeft (newPromptedJTextField(ALIGN + ' ' + "Top-Left"    , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Top-Right"   , ALIGN)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Middle-Left" , ALIGN)),
                addRight(newPromptedJTextField(                       null , ALIGN)),

                addLeft (new        JTextField("x"        )),
                addRight(newPromptedJTextField("x",   ""  )),

                addLeft (new        JTextField(null       )),
                addRight(newPromptedJTextField(null,  null)),

                addLeft (newPromptedJTextField(ALIGN + ' ' + "Bottom-Left" , ALIGN)),
                addRight(newPromptedJTextField(ALIGN + ' ' + "Bottom-Right", ALIGN)) ).collect(Collectors.toList());

        final JButton button = addRight(new JButton("Get texts"));
        /**/                   addRight(Box.createVerticalStrut(0)); // 1 last time forces bottom inset

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setPreferredSize(new Dimension(740, 260));
        this.pack();
        this.setResizable(false);
        this.setVisible(true);

        button.addActionListener(e -> {
            texts.forEach(text -> System.out.println("Text..: " + text.getText()));
        });
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> new JTextFieldPromptExample("JTextField with Prompt"));
    }
}

Can I add and remove elements of enumeration at runtime in Java

You can load a Java class from source at runtime. (Using JCI, BeanShell or JavaCompiler)

This would allow you to change the Enum values as you wish.

Note: this wouldn't change any classes which referred to these enums so this might not be very useful in reality.

Getting the thread ID from a thread

According to MSDN:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

So basically, the Thread object does not necessarily correspond to an OS thread - which is why it doesn't have the native ID exposed.

How can I add a Google search box to my website?

Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".

Anyone know why?

How to set a JavaScript breakpoint from code in Chrome?

You can also use debug(function), to break when function is called.

Command Line API Reference: debug

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Printing pointers in C

If you pass the name of an array as an argument to a function, it is treated as if you had passed the address of the array. So &s and s are identical arguments. See K&R 5.3. &s[0] is the same as &s, since it takes the address of the first element of the array, which is the same as taking the address of the array itself.

For all the others, although all pointers are essentially memory locations they are still typed, and the compiler will warn about assigning one type of pointer to another.

  • void* p; says p is a memory address, but I don't know what's in the memory
  • char* s; says s is a memory address, and the first byte contains a character
  • char** ps; says ps is a memory address, and the four bytes there (for a 32-bit system) contain a pointer of type char*.

cf http://www.oberon2005.ru/paper/kr_c.pdf (e-book version of K&R)

How to append a char to a std::string?

To add a char to a std::string var using the append method, you need to use this overload:

std::string::append(size_type _Count, char _Ch)

Edit : Your're right I misunderstood the size_type parameter, displayed in the context help. This is the number of chars to add. So the correct call is

s.append(1, d);

not

s.append(sizeof(char), d);

Or the simpliest way :

s += d;

MVC 4 client side validation not working

Im my case I added and id equals to the name automatically generated for VS on the html and in the code I´ve added a line to that case.

$(function () {
            $.validator.addMethod('latinos', function (value, element) {
                return this.optional(element) || /^[a-záéóóúàèìòùäëïöüñ\s]+$/i.test(value);
            });

            $("#btn").on("click", function () {
                //alert("aa");
                $("#formulario").validate({                    
                    rules:
                    {
                        email: { required: true, email: true, minlength: 8, maxlength: 80 },
                        digitos: { required: true, digits: true, minlength: 2, maxlength: 100 },
                        nombres: { required: true, latinos: true, minlength: 3, maxlength: 50 },
                        NombresUsuario: { required: true, latinos: true, minlength: 3, maxlength: 50 }
                    },
                    messages:
                    {
                        email: {
                            required: 'El campo es requerido', email: 'El formato de email es incorrecto',
                            minlength: 'El mínimo permitido es 8 caracteres', maxlength: 'El máximo permitido son 80 caracteres'
                        },
                        digitos: {
                            required: 'El campo es requerido', digits: 'Sólo se aceptan dígitos',
                            minlength: 'El mínimo permitido es 2 caracteres', maxlength: 'El máximo permitido son 10 caracteres'
                        },
                        nombres: {
                            required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                            minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                        },
                        NombresUsuario: {
                            required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                            minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                        }
                    }
                });
            });

<tr>@*<div class="form-group">     htmlAttributes: new { @class = "control-label col-md-2" }      , @class = "form-control" }*@
                <td>@Html.LabelFor(model => model.NombresUsuario )</td>

                        @*<div class="col-md-10">*@
                <td>
                    @Html.EditorFor(model => model.NombresUsuario, new { htmlAttributes = new { id = "NombresUsuario" } })
                    @Html.ValidationMessageFor(model => model.NombresUsuario, "", new { @class = "text-danger" })
                </td>

After MySQL install via Brew, I get the error - The server quit without updating PID file

EDIT 2012/09/18: As pointed out by Kane, make sure the mysql database is properly set up before doing anything else. See “PID error on mysql.server start?” for more info.

Original answer kept for history's sake: It most likely is a permissions issue. Check /usr/local/var/mysql/*.err. Mine said:

120314 16:30:14  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'open'.
InnoDB: Cannot continue operation.
120314 16:30:14 mysqld_safe mysqld from pid file /usr/local/var/mysql/janmoesen.local.pid ended

I also had to do this:

sudo chown _mysql /usr/local/var/mysql/*

How to check if command line tools is installed

% xcode-select -h Usage: xcode-select [options]

Print or change the path to the active developer directory. This directory controls which tools are used for the Xcode command line tools (for example, xcodebuild) as well as the BSD development commands (such as cc and make).

Options: -h, --help print this help message and exit -p, --print-path print the path of the active developer directory -s , --switch set the path for the active developer directory --install open a dialog for installation of the command line developer tools -v, --version print the xcode-select version -r, --reset reset to the default command line tools path

SSIS Text was truncated with status value 4

I've had this problem before, you can go to "advanced" tab of "choose a data source" page and click on "suggested types" button, and set the "number of rows" as much as you want. after that, the type and text qualified are set to the true values.

i applied the above solution and can convert my data to SQL.

Import JSON file in React

With json-loader installed, you can use

import customData from '../customData.json';

or also, even more simply

import customData from '../customData';

To install json-loader

npm install --save-dev json-loader

Difference between os.getenv and os.environ.get

See this related thread. Basically, os.environ is found on import, and os.getenv is a wrapper to os.environ.get, at least in CPython.

EDIT: To respond to a comment, in CPython, os.getenv is basically a shortcut to os.environ.get ; since os.environ is loaded at import of os, and only then, the same holds for os.getenv.

Add a summary row with totals

You could use the ROLLUP operator

SELECT  CASE 
            WHEN (GROUPING([Type]) = 1) THEN 'Total'
            ELSE [Type] END AS [TYPE]
        ,SUM([Total Sales]) as Total_Sales
From    Before
GROUP BY
        [Type] WITH ROLLUP

Setting Windows PowerShell environment variables

Open PowerShell and run:

[Environment]::SetEnvironmentVariable("PATH", "$ENV:PATH;<path to exe>", "USER")

Postgresql: password authentication failed for user "postgres"

I had faced similar issue. While accessing any database I was getting below prompt after updating password "password authentication failed for user “postgres”" in PGAdmin


Solution:

  1. Shut down postgres server
  2. Re-run pgadmin
  3. pgadmin will ask for password.
  4. Please enter current password of mentioned user

Hope it will resolve your issue

enter image description here

Two dimensional array in python

What you're using here are not arrays, but lists (of lists).

If you want multidimensional arrays in Python, you can use Numpy arrays. You'd need to know the shape in advance.

For example:

 import numpy as np
 arr = np.empty((3, 2), dtype=object)
 arr[0, 1] = 'abc'

Mysql service is missing

I have done it by the following way

  1. Start cmd
  2. Go to the "C:\Program Files\MySQL\MySQL Server 5.6\bin"
  3. type mysqld --install

Like the following image. See for more information.

enter image description here

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

In my case increasing mem by setting MAVEN_OPTS helped:

set MAVEN_OPTS=-Xmx1024m

include external .js file in node.js app

Short answer:

// lib.js
module.exports.your_function = function () {
  // Something...
};

// app.js
require('./lib.js').your_function();

How to commit to remote git repository

git push

or

git push server_name master

should do the trick, after you have made a commit to your local repository.

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()

iOS / Android cross platform development

Cappuccino or PhoneGap.

Sometimes though trying to find a shortcut does not save you time or give you a comparable end product.

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

Best ways to teach a beginner to program?

I would actually argue to pick a simpler language with fewer instructions. I personally learned on BASIC at home, as did Jeff. This way, you don't have to delve into more complicated issues like object oriented programming, or even procedures if you don't want to. Once he can handle simple control flow, then move on to something a little more complicated, but only simple features.

Maybe start with very simple programs that just add 2 numbers, and then grow to something that might require a branch, then maybe reading input and responding to it, then some kind of loop, and start combining them all together. Just start little and work your way up. Don't do any big projects until he can grasp the fundamentals (otherwise it may very well be too daunting and he could give up midway). Once he's mastered BASIC or whatever you choose, move on to something more complicated.

Just my $0.02

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

How to download all files (but not HTML) from a website using wget?

This downloaded the entire website for me:

wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/

How do I pass data between Activities in Android application?

If you want to tranfer bitmap between Activites/Fragments


Activity

To pass a bitmap between Activites

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

And in the Activity class

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

Fragment

To pass a bitmap between Fragments

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

To receive inside the SecondFragment

Bitmap bitmap = getArguments().getParcelable("bitmap");

Transfering Large Bitmaps

If you are getting failed binder transaction, this means you are exceeding the binder transaction buffer by transferring large element from one activity to another activity.

So in that case you have to compress the bitmap as an byte's array and then uncompress it in another activity, like this

In the FirstActivity

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

And in the SecondActivity

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

Override hosts variable of Ansible playbook from the command line

I don't think Ansible provides this feature, which it should. Here's something that you can do:

hosts: "{{ variable_host | default('web') }}"

and you can pass variable_host from either command-line or from a vars file, e.g.:

ansible-playbook server.yml --extra-vars "variable_host=newtarget(s)"

Difference between two DateTimes C#?

Try the following

double hours = (b-a).TotalHours;

If you just want the hour difference excluding the difference in days you can use the following

int hours = (b-a).Hours;

The difference between these two properties is mainly seen when the time difference is more than 1 day. The Hours property will only report the actual hour difference between the two dates. So if two dates differed by 100 years but occurred at the same time in the day, hours would return 0. But TotalHours will return the difference between in the total amount of hours that occurred between the two dates (876,000 hours in this case).

The other difference is that TotalHours will return fractional hours. This may or may not be what you want. If not, Math.Round can adjust it to your liking.

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.

Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE

so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.

also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.

How to add elements of a string array to a string array list?

I prefer this,

List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);

The reason is Arrays.asList() method will create a fixed sized List. So if you directly store it into species then you will not be able to add any more element, still its not read-only. You can surely edit your items. So take it into temporary list.

Alternative for this is,

Collections.addAll(species, speciesArr);

In this case, you can add, edit, remove your items.

%i or %d to print integer in C using printf()?

d and i conversion specifiers behave the same with fprintf but behave differently for fscanf.

As some other wrote in their answer, the idiomatic way to print an int is using d conversion specifier.

Regarding i specifier and fprintf, C99 Rationale says that:

The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.

Problems with jQuery getJSON using local files in Chrome

On Windows, Chrome might be installed in your AppData folder:

"C:\Users\\AppData\Local\Google\Chrome\Application"

Before you execute the command, make sure all of your Chrome windows are closed and not otherwise running. Or, the command line param would not be effective.

chrome.exe --allow-file-access-from-files

String replace method is not replacing characters

You aren't doing anything with the return value of replace. You'll need to assign the result of the method, which is the new String:

sentence = sentence.replace("and", " ");

A String is immutable in java. Methods like replace return a new String.

Your contains test is unnecessary: replace will just no-op if there aren't instances of the text to replace.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

When I ran into this problem, it was a result of trying to use an inner class to serve as the DO. Construction of the inner class (silently) required an instance of the enclosing class -- which wasn't available to Jackson.

In this case, moving the inner class to its own .java file fixed the problem.

Initializing ArrayList with some predefined values

I would suggest to use Arrays.asList() for single line initialization. For different ways of declaring and initializing a List you can also refer Initialization of ArrayList in Java

Reverse of JSON.stringify?

JSON.parse is the opposite of JSON.stringify.

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

SQLite also supports a pragma statement called "table_info" which returns one row per column in a table with the name of the column (and other information about the column). You could use this in a query to check for the missing column, and if not present alter the table.

PRAGMA table_info(foo_table_name)

http://www.sqlite.org/pragma.html#pragma_table_info

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

How to center-justify the last line of text in CSS?

For people looking for getting text that is both centered and justified, the following should work:

<div class="center-justified">...lots and lots of text...</div>

With the following CSS rule (adjust the width property as needed):

.center-justified {
  text-align: justify;
  margin: 0 auto;
  width: 30em;
}

Here's the live demo.

What's going on?

  1. text-align: justify; makes sure the text fills the full width of the div it is enclosed in.
  2. margin: 0 auto; is actually a shorthand for four rules:
    • The first value is used for the margin-top and margin-bottom rules. The whole thing therefore means margin-top: 0; margin-bottom: 0, i.e. no margins above or below the div.
    • The second value is used for the margin-left and margin-right rules. So this rule results in margin-left: auto; margin-right: auto. This is the clever bit: it tells the browser to take whatever space is available on the sides and distribute it evenly on left and right. The result is centered text.
      However, this would not work without
  3. width: 30em;, which limits the width of the div. Only when the width is restricted is there some whitespace left over for margin: auto to distribute. Without this rule the div would take up all available horizontal space, and you'd lose the centering effect.

Reverse the ordering of words in a string

One way to do this is to parse each word of our input string and push it into a LIFO stack.

After whole string is processed, we pop out each word off the stack one by one and append it to a StringBuffer class object, which finally contains the reversed input string.

This is one possible solution in Java using StringTokenizer and Stack class. We need to import java.util.Stack.

public String revString(String input)
{
   StringTokenizer words=new StringTokenizer(input); //Split the string into words
   Stack<String> stack= new Stack<String>();
   while(words.hasMoreTokens())
   {
      stack.push(words.nextElement().toString()); // Push each word of the string onto stack. 
   }
   StringBuilder revString=new StringBuilder();
   while(!stack.empty())
   {
       revString.append(stack.pop()+" ");// pop the top item and append it to revString 
   }
   return revString.toString();
}

Remove a modified file from pull request

You would want to amend the commit and then do a force push which will update the branch with the PR.

Here's how I recommend you do this:

  1. Close the PR so that whomever is reviewing it doesn't pull it in until you've made your changes.
  2. Do a Soft reset to the commit before your unwanted change (if this is the last commit you can use git reset --soft HEAD^ or if it's a different commit, you would want to replace 'HEAD^' with the commit id)
  3. Discard (or undo) any changes to the file that you didn't intend to update
  4. Make a new commit git commit -a -c ORIG_HEAD
  5. Force Push to your branch
  6. Re-Open Pull Request

The now that your branch has been updated, the Pull Request will include your changes.

Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.

Reading/writing an INI file

Usually, when you create applications using C# and the .NET framework, you will not use INI files. It is more common to store settings in an XML-based configuration file or in the registry. However, if your software shares settings with a legacy application it may be easier to use its configuration file, rather than duplicating the information elsewhere.

The .NET framework does not support the use of INI files directly. However, you can use Windows API functions with Platform Invocation Services (P/Invoke) to write to and read from the files. In this link we create a class that represents INI files and uses Windows API functions to manipulate them. Please go through the following link.

Reading and Writing INI Files

JavaScript hard refresh of current page

window.location.href = window.location.href

Java generics: multiple generic parameters?

a and b must both be sets of the same type. But nothing prevents you from writing

myfunction(Set<X> a, Set<Y> b)

destination path already exists and is not an empty directory

Make a new-directory and then use the git clone url

How can I truncate a datetime in SQL Server?

In SQl 2005 your trunc_date function could be written like this.

(1)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
    CAST(FLOOR( CAST( @date AS FLOAT ) )AS DATETIME)
END

The first method is much much cleaner. It uses only 3 method calls including the final CAST() and performs no string concatenation, which is an automatic plus. Furthermore, there are no huge type casts here. If you can imagine that Date/Time stamps can be represented, then converting from dates to numbers and back to dates is a fairly easy process.

(2)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
      SELECT CONVERT(varchar, @date,112)
END

If you are concerned about microsoft's implementation of datetimes (2) or (3) might be ok.

(3)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
SELECT CAST((STR( YEAR( @date ) ) + '/' +STR( MONTH( @date ) ) + '/' +STR( DAY(@date ) )
) AS DATETIME
END

Third, the more verbose method. This requires breaking the date into its year, month, and day parts, putting them together in "yyyy/mm/dd" format, then casting that back to a date. This method involves 7 method calls including the final CAST(), not to mention string concatenation.

What is an uber jar?

ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:

  1. Unshaded: Unpack all JAR files, then repack them into a single JAR. Works with Java's default class loader. Tools maven-assembly-plugin
  2. Shaded: Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Works with Java's default class loader. Avoids some (not all) dependency version clashes. Tools maven-shade-plugin
  3. JAR of JARs: The final JAR file contains the other JAR files embedded within. Avoids dependency version clashes. All resource files are preserved. Tools: Eclipse JAR File Exporter

for more

Sound alarm when code finishes

Why use python at all? You might forget to remove it and check it into a repository. Just run your python command with && and another command to run to do the alerting.

python myscript.py && 
    notify-send 'Alert' 'Your task is complete' && 
    paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga

or drop a function into your .bashrc. I use apython here but you could override 'python'

function apython() {
    /usr/bin/python $*
    notify-send 'Alert' "python $* is complete"
    paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
}

Accessing dict keys like an attribute?

This doesn't address the original question, but should be useful for people that, like me, end up here when looking for a lib that provides this functionality.

Addict it's a great lib for this: https://github.com/mewwts/addict it takes care of many concerns mentioned in previous answers.

An example from the docs:

body = {
    'query': {
        'filtered': {
            'query': {
                'match': {'description': 'addictive'}
            },
            'filter': {
                'term': {'created_by': 'Mats'}
            }
        }
    }
}

With addict:

from addict import Dict
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'

How can I convert ticks to a date format?

It's much simpler to do this:

DateTime dt = new DateTime(633896886277130000);

Which gives

dt.ToString() ==> "9/27/2009 10:50:27 PM"

You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

Not sure where you get October 1.

Sqlite in chrome

Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.

How to upload a file using Java HttpClient library working with PHP

I ran into the same problem and found out that the file name is required for httpclient 4.x to be working with PHP backend. It was not the case for httpclient 3.x.

So my solution is to add a name parameter in the FileBody constructor. ContentBody cbFile = new FileBody(file, "image/jpeg", "FILE_NAME");

Hope it helps.

docker-compose up for only certain containers

I actually had a very similar challenge on my current project. That broght me to the idea of writing a small script which I called docker-compose-profile (or short: dcp). I published this today on GitLab as docker-compose-profile. So in short: I now can start several predefined docker-compose profiles using a command like dcp -p some-services "up -d". Feel free to try it out and give some feedback or suggestions for further improvements.

AngularJS access parent scope from child controller

You can also circumvent scope inheritance and store things in the "global" scope.

If you have a main controller in your application which wraps all other controllers, you can install a "hook" to the global scope:

function RootCtrl($scope) {
    $scope.root = $scope;
}

Then in any child controller, you can access the "global" scope with $scope.root. Anything you set here will be globally visible.

Example:

_x000D_
_x000D_
function RootCtrl($scope) {_x000D_
  $scope.root = $scope;_x000D_
}_x000D_
_x000D_
function ChildCtrl($scope) {_x000D_
  $scope.setValue = function() {_x000D_
    $scope.root.someGlobalVar = 'someVal';_x000D_
  }_x000D_
}_x000D_
_x000D_
function OtherChildCtrl($scope) {_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app ng-controller="RootCtrl">_x000D_
  _x000D_
  <p ng-controller="ChildCtrl">_x000D_
    <button ng-click="setValue()">Set someGlobalVar</button>_x000D_
  </p>_x000D_
  _x000D_
  <p ng-controller="OtherChildCtrl">_x000D_
    someGlobalVar value: {{someGlobalVar}}_x000D_
  </p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Examples of GoF Design Patterns in Java's core libraries

  1. Observer pattern throughout whole swing (Observable, Observer)
  2. MVC also in swing
  3. Adapter pattern: InputStreamReader and OutputStreamWriter NOTE: ContainerAdapter, ComponentAdapter, FocusAdapter, KeyAdapter, MouseAdapter are not adapters; they are actually Null Objects. Poor naming choice by Sun.
  4. Decorator pattern (BufferedInputStream can decorate other streams such as FilterInputStream)
  5. AbstractFactory Pattern for the AWT Toolkit and the Swing pluggable look-and-feel classes
  6. java.lang.Runtime#getRuntime() is Singleton
  7. ButtonGroup for Mediator pattern
  8. Action, AbstractAction may be used for different visual representations to execute same code -> Command pattern
  9. Interned Strings or CellRender in JTable for Flyweight Pattern (Also think about various pools - Thread pools, connection pools, EJB object pools - Flyweight is really about management of shared resources)
  10. The Java 1.0 event model is an example of Chain of Responsibility, as are Servlet Filters.
  11. Iterator pattern in Collections Framework
  12. Nested containers in AWT/Swing use the Composite pattern
  13. Layout Managers in AWT/Swing are an example of Strategy

and many more I guess

How to extract IP Address in Spring MVC Controller get call?

See below. This code works with spring-boot and spring-boot + apache CXF/SOAP.

    // in your class RequestUtil
    private static final String[] IP_HEADER_NAMES = { 
                                                        "X-Forwarded-For",
                                                        "Proxy-Client-IP",
                                                        "WL-Proxy-Client-IP",
                                                        "HTTP_X_FORWARDED_FOR",
                                                        "HTTP_X_FORWARDED",
                                                        "HTTP_X_CLUSTER_CLIENT_IP",
                                                        "HTTP_CLIENT_IP",
                                                        "HTTP_FORWARDED_FOR",
                                                        "HTTP_FORWARDED",
                                                        "HTTP_VIA",
                                                        "REMOTE_ADDR"
                                                    };

    public static String getRemoteIP(RequestAttributes requestAttributes)
    {
        if (requestAttributes == null)
        {
            return "0.0.0.0";
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String ip = Arrays.asList(IP_HEADER_NAMES)
            .stream()
            .map(request::getHeader)
            .filter(h -> h != null && h.length() != 0 && !"unknown".equalsIgnoreCase(h))
            .map(h -> h.split(",")[0])
            .reduce("", (h1, h2) -> h1 + ":" + h2);
        return ip + request.getRemoteAddr();
    }

    //... in service class:
    String remoteAddress = RequestUtil.getRemoteIP(RequestContextHolder.currentRequestAttributes());

:)

Could not commit JPA transaction: Transaction marked as rollbackOnly

For those who can't (or don't want to) setup a debugger to track down the original exception which was causing the rollback-flag to get set, you can just add a bunch of debug statements throughout your code to find the lines of code which trigger the rollback-only flag:

logger.debug("Is rollbackOnly: " + TransactionAspectSupport.currentTransactionStatus().isRollbackOnly());

Adding this throughout the code allowed me to narrow down the root cause, by numbering the debug statements and looking to see where the above method goes from returning "false" to "true".

Get MAC address using shell script

None of the above worked for me because my devices are in a balance-rr bond. Querying either would say the same MAC address with ip l l, ifconfig, or /sys/class/net/${device}/address, so one of them is correct, and one is unknown.

But this works if you haven't renamed the device (any tips on what I missed?):

udevadm info -q all --path "/sys/class/net/${device}"

And this works even if you rename it (eg. ip l set name x0 dev p4p1):

cat /proc/net/bonding/bond0

or my ugly script that makes it more parsable (untested driver/os/whatever compatibility):

awk -F ': ' '
         $0 == "" && interface != "" {
            printf "%s %s %s\n", interface, mac, status;
            interface="";
            mac=""
         }; 
         $1 == "Slave Interface" {
            interface=$2
         }; 
         $1 == "Permanent HW addr" {
            mac=$2
         };
         $1 == "MII Status" {
            status=$2
         };
         END {
            printf "%s %s %s\n", interface, mac, status
         }' /proc/net/bonding/bond0

Asynchronous Requests with Python requests

I have a lot of issues with most of the answers posted - they either use deprecated libraries that have been ported over with limited features, or provide a solution with too much magic on the execution of the request, making it difficult to error handle. If they do not fall into one of the above categories, they're 3rd party libraries or deprecated.

Some of the solutions works alright purely in http requests, but the solutions fall short for any other kind of request, which is ludicrous. A highly customized solution is not necessary here.

Simply using the python built-in library asyncio is sufficient enough to perform asynchronous requests of any type, as well as providing enough fluidity for complex and usecase specific error handling.

import asyncio

loop = asyncio.get_event_loop()

def do_thing(params):
    async def get_rpc_info_and_do_chores(id):
        # do things
        response = perform_grpc_call(id)
        do_chores(response)

    async def get_httpapi_info_and_do_chores(id):
        # do things
        response = requests.get(URL)
        do_chores(response)

    async_tasks = []
    for element in list(params.list_of_things):
       async_tasks.append(loop.create_task(get_chan_info_and_do_chores(id)))
       async_tasks.append(loop.create_task(get_httpapi_info_and_do_chores(ch_id)))

    loop.run_until_complete(asyncio.gather(*async_tasks))

How it works is simple. You're creating a series of tasks you'd like to occur asynchronously, and then asking a loop to execute those tasks and exit upon completion. No extra libraries subject to lack of maintenance, no lack of functionality required.

How to install toolbox for MATLAB

first, you need to find the toolbox that you need. There are many people developing 3rd party toolboxes for Matlab, so there isn't just one single place where you can find "the image processing toolbox". That said, a good place to start looking is the Matlab Central which is a Mathworks-run site for exchanging all kinds of Matlab-related material.

Once you find a toolbox you want, it will be in some compressed format, and its developers might have a "readme" file that details on how to install it. If it isn't the case, a generic way to attempt installation is to place the toolbox in any directory on your drive, and then add it to Matlab path, e.g., going to File -> Set Path... -> Add Folder or Add with Subfolders (I'm writing for memory but this is definitely close).

Otherwise, you can extract all .m files in your working directory, if you don't want to use downloaded toolbox in more than one project.