Filter dict to contain only certain keys?

Question: I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?
Comment: @smci String keys. Don't think it even occurred to me that I could use anything else; I've been coding in JS and PHP for so long...
Comment: It's helpful to say what type of keys (integers? strings? dates? arbitrary objects?) and thus whether there's a simple (string, regex, list membership, or numerical inequality) test to check which keys are in or out. Or else do we need to call an arbitrary function(s) to determine that.
Answer: Constructing a new dict:
dict_you_want = {key: old_dict[key] for key in your_keys}

Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]

Comment: Throws a KeyError if one of the filer keys is not present in old_dict. I would suggest {k:d[k] for k in filter if k in d}
Comment: @PeterGibson Yes, if that's part of the requirements, you need to do *something* about it. Whether it's silently dropping the keys, adding a default value, or something else, depends on what you are doing; there are plenty of use cases where your approach is wrong. There are also many where a key missing in `old_dict` indicates a bug elsewhere, and in that case I very much prefer an error to silently wrong results.
Comment: @PeterGibson It doesn't, dictionary lookup is O(1).
Comment: nit: Dictionaries are hash maps, so the normal case is O(1). Worst (highly unlikely) case is O(n), but depends on hash collision likelihood. You'd need an astronomically large dictionary, or a really crude hashing algorithm to start seeing that be an issue. https://stackoverflow.com/a/1963514/1335793
Comment: @delnan, also the "if k in d" addition slows you down if d is large, I just thought it was worth mentioning
Comment: If you do want to not throw an error if the key is not present, this works: dict_youwant = dict((key, old_dict[key]) for key in [k for k in your_keys if k in old_dict])
Comment: I think that should be "unwanted = set(keys) & set(your_dict)", i.e. set intersection (&), not set difference (-).  Assuming keys is your list of unwanted keys.
Comment: @andrewpate Little bit neater: `dict_youwant = {k: old[k] for k in your_keys & old.keys()}`
Answer: Slightly more elegant dict comprehension:
foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}

Comment: Answered my own question. The {k:dict[k] for k in dict ...} is about 20-25% faster, at least in Python 2.7.6, with a dictionary of 26 items (timeit(..., setup="d = {chr(x+97):x+1 for x in range(26)}")), depending on how many items are being filtered out (filtering out consonant keys is faster than filtering out vowel keys because you're looking up fewer items). The difference in performance may very well become less significant as your dictionary size grows.
Comment: Would probably be the same perf if you used `mydict.iteritems()` instead. `.items()` creates another list.
Comment: Upvoted. I was thinking about adding an answer similar to this. Just out of curiosity though, why do {k:v for k,v in dict.items() ...} rather than {k:dict[k] for k in dict ...}

Is there a performance difference?
Answer: Here's an example in python 2.6:
>>> a = {1:1, 2:2, 3:3}
>>> dict((key,value) for key, value in a.iteritems() if key == 1)
{1: 1}

The filtering part is the if statement.
This method is slower than delnan's answer if you only want to select a few of very many keys.
Comment: except I'd probably use `if key in ('x','y','z')` I guess.
Comment: This solution has one more advantage. If the dictionary is returned from an expensive function call (i.e. a/old_dict is a function call) this solution calls the function only once. In an imperative environment storing the dictionary returned by the function in a variable is not a big deal but in a functional environment (e.g. in a lambda) this is key observation.
Comment: if you already know which keys you want, use delnan's answer. If you need to test each key with an if statement, use ransford's answer.
Comment: Who is using Python 2 still? Should this answer be removed as it's useless these days for the most of us?
Answer: You can do that with project function from my funcy library:
from funcy import project
small_dict = project(big_dict, keys)

Also take a look at select_keys.
Answer: This one liner lambda should work:
dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])

Here's an example:
my_dict = {"a":1,"b":2,"c":3,"d":4}
wanted_keys = ("c","d")

# run it
In [10]: dictfilt(my_dict, wanted_keys)
Out[10]: {'c': 3, 'd': 4}

It's a basic list comprehension iterating over your dict keys (i in x) and outputs a list of tuple (key,value) pairs if the key lives in your desired key list (y). A dict() wraps the whole thing to output as a dict object.
Comment: One thing, "dict" is a reserved word so you shouldn't use it to name a dict. What were the keys you were trying to pull out? If I run: `foo = {'0':[1,3], '1':[0,2,4], '2':[1,4]}; dictfilt(foo,('0','2'))`, I get: `{'0': [1, 3], '2': [1, 4]}` which is the intended outcome
Comment: Should use a `set` for `wanted_keys`, but otherwise looks good.
Comment: This gives me a blank dictionary if my original dictionary contains lists in place of values. Any workarounds?
Comment: @Francesco, can you provide an example? If I run:
`dictfilt({'x':['wefwef',52],'y':['iuefiuef','efefij'],'z':['oiejf','iejf']}, ('x','z'))`,
it returns
`{'x': ['wefwef', 52], 'z': ['oiejf', 'iejf']}` as intended.
Comment: I tried this with: `dict={'0':[1,3], '1':[0,2,4], '2':[1,4]}` and the result was `{}`, which I assumed to be a blank dict.
Answer: Code 1:
dict = { key: key * 10 for key in range(0, 100) }
d1 = {}
for key, value in dict.items():
    if key % 2 == 0:
        d1[key] = value

Code 2:
dict = { key: key * 10 for key in range(0, 100) }
d2 = {key: value for key, value in dict.items() if key % 2 == 0}

Code 3:
dict = { key: key * 10 for key in range(0, 100) }
d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}

All pieced of code performance are measured with timeit using number=1000, and collected 1000 times for each piece of code.

For python 3.6 the performance of three ways of filter dict keys almost the same. For python 2.7 code 3 is slightly faster.
Comment: better not use `dict` as it's builtin in python.
Comment: just curious, did you make that plot from Python?
Comment: ggplot2 in R - part of [tidyverse](https://ggplot2.tidyverse.org/reference/geom_bar.html)
Answer: Given your original dictionary orig and the set of entries that you're interested in keys:
filtered = dict(zip(keys, [orig[k] for k in keys]))

which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of keys existing in your original dictionary.
Comment: I don't disagree; 2.3 really shouldn't exist anymore. However, as an outdated survey of 2.3 usage: http://moinmo.in/PollAboutRequiringPython24
Short version: RHEL4, SLES9, shipped with OS X 10.4
Comment: Well, this is basically an eager version of the "tuple generator version" of my dict comprehension. Very compatible indeed, though generator expressions were introduced in 2.4, spring 2005 - seriously, is anyone still using this?
Answer: This seems to me the easiest way:
d1 = {'a':1, 'b':2, 'c':3}
d2 = {k:v for k,v in d1.items() if k in ['a','c']}

I like doing this to unpack the values too:
a, c = {k:v for k,v in d1.items() if k in ['a','c']}.values()

Comment: For efficiency, I'd recommend filtering keys using a set: `if k in {'a','c'}` rather than `if k in ['a','c']`.
Comment: This method is the easiest one to parse and understand for newbies like me.
Answer: Based on the accepted answer by delnan.
What if one of your wanted keys aren't in the old_dict? The delnan solution will throw a KeyError exception that you can catch. If that's not what you need maybe you want to:

only include keys that excists both in the old_dict and your set of wanted_keys.
old_dict = {'name':"Foobar", 'baz':42}
wanted_keys = ['name', 'age']
new_dict = {k: old_dict[k] for k in set(wanted_keys) & set(old_dict.keys())}

>>> new_dict
{'name': 'Foobar'}

have a default value for keys that's not set in old_dict.
default = None
new_dict = {k: old_dict[k] if k in old_dict else default for k in wanted_keys}

>>> new_dict
{'age': None, 'name': 'Foobar'}

Comment: You could also do `{k: old_dict.get(k, default) for k in ...}`
Answer: This function will do the trick:
def include_keys(dictionary, keys):
    """Filters a dict by only including certain keys."""
    key_set = set(keys) & set(dictionary.keys())
    return {key: dictionary[key] for key in key_set}

Just like delnan's version, this one uses dictionary comprehension and has stable performance for large dictionaries (dependent only on the number of keys you permit, and not the total number of keys in the dictionary).
And just like MyGGan's version, this one allows your list of keys to include keys that may not exist in the dictionary.
And as a bonus, here's the inverse, where you can create a dictionary by excluding certain keys in the original:
def exclude_keys(dictionary, keys):
    """Filters a dict by excluding certain keys."""
    key_set = set(dictionary.keys()) - set(keys)
    return {key: dictionary[key] for key in key_set}

Note that unlike delnan's version, the operation is not done in place, so the performance is related to the number of keys in the dictionary. However, the advantage of this is that the function will not modify the dictionary provided.
Edit: Added a separate function for excluding certain keys from a dict.
Comment: You should allow `keys` to by any kind of iterable, like what [set](http://docs.python.org/2/library/sets.html#sets.Set) accepts.
Comment: Ah, good call, thanks for pointing this out. I'll make that update.
Comment: I wonder if you are better off with two functions.  If you asked 10 people "does `invert` imply that the `keys` argument is kept, or that the `keys` argument is rejected?", how many of them would agree?
Comment: Updated. Let me know what you think.
Comment: This appears not to be working if the input dict has lists in place of values. In this case you get a void dict. Any workarounds?
Answer: Another option:
content = dict(k1='foo', k2='nope', k3='bar')
selection = ['k1', 'k3']
filtered = filter(lambda i: i[0] in selection, content.items())

But you get a list (Python 2) or an iterator (Python 3) returned by filter(), not a dict.
Comment: Wrap `filtered` in `dict` and you get back the dictionary!
Answer: If we want to make a new dictionary with selected keys removed, we can make use of dictionary comprehension
For example:
d = {
'a' : 1,
'b' : 2,
'c' : 3
}
x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
# x is {'a': 1, 'b': 2}
# y is {'a': 1, 'b': 2}

Comment: Neat. Only works in Python 3. Python 2 says "TypeError: unsupported operand type(s) for -: 'list' and 'set'"
Comment: Added set(d.keys()) for Python 2. This is working when I run.
Answer: We can also achieve this by slightly more elegant dict comprehension:
my_dict = {"a":1,"b":2,"c":3,"d":4}

filtdict = {k: v for k, v in my_dict.items() if k.startswith('a')}
print(filtdict)

Answer: According to the title of the question, one would expect to filter the dictionary in place - a couple of answers suggest methods for doing that - still it's not obvious what is the one obvious way - I added some timings:
import random
import timeit
import collections

repeat = 3
numbers = 10000

setup = ''
def timer(statement, msg='', _setup=None):
    print(msg, min(
        timeit.Timer(statement, setup=_setup or setup).repeat(
            repeat, numbers)))

timer('pass', 'Empty statement')

dsize = 1000
d = dict.fromkeys(range(dsize))
keep_keys = set(random.sample(range(dsize), 500))
drop_keys = set(random.sample(range(dsize), 500))

def _time_filter_dict():
    """filter a dict"""
    global setup
    setup = r"""from __main__ import dsize, collections, drop_keys, \
keep_keys, random"""
    timer('d = dict.fromkeys(range(dsize));'
          'collections.deque((d.pop(k) for k in drop_keys), maxlen=0)',
          "pop inplace - exhaust iterator")
    timer('d = dict.fromkeys(range(dsize));'
          'drop_keys = [k for k in d if k not in keep_keys];'
          'collections.deque('
              '(d.pop(k) for k in list(d) if k not in keep_keys), maxlen=0)',
          "pop inplace - exhaust iterator (drop_keys)")
    timer('d = dict.fromkeys(range(dsize));'
          'list(d.pop(k) for k in drop_keys)',
          "pop inplace - create list")
    timer('d = dict.fromkeys(range(dsize));'
          'drop_keys = [k for k in d if k not in keep_keys];'
          'list(d.pop(k) for k in drop_keys)',
          "pop inplace - create list (drop_keys)")
    timer('d = dict.fromkeys(range(dsize))\n'
          'for k in drop_keys: del d[k]', "del inplace")
    timer('d = dict.fromkeys(range(dsize));'
          'drop_keys = [k for k in d if k not in keep_keys]\n'
          'for k in drop_keys: del d[k]', "del inplace (drop_keys)")
    timer("""d = dict.fromkeys(range(dsize))
{k:v for k,v in d.items() if k in keep_keys}""", "copy dict comprehension")
    timer("""keep_keys=random.sample(range(dsize), 5)
d = dict.fromkeys(range(dsize))
{k:v for k,v in d.items() if k in keep_keys}""",
          "copy dict comprehension - small keep_keys")

if __name__ == '__main__':
    _time_filter_dict()

results:
Empty statement 8.375600000000427e-05
pop inplace - exhaust iterator 1.046749841
pop inplace - exhaust iterator (drop_keys) 1.830537424
pop inplace - create list 1.1531293939999987
pop inplace - create list (drop_keys) 1.4512304149999995
del inplace 0.8008298079999996
del inplace (drop_keys) 1.1573763689999979
copy dict comprehension 1.1982901489999982
copy dict comprehension - small keep_keys 1.4407784069999998

So seems del is the winner if we want to update in place - the dict comprehension solution depends on the size of the dict being created of course and deleting half the keys is already too slow - so avoid creating a new dict if you can filter in place.
Edited to address a comment by @mpen - I calculated drop keys from keep_keys (given we do not have drop keys) - I assumed keep_keys/drop_keys are sets for this iteration or would take ages. With these assumptions del is still faster - but to be sure the moral is: if you have a (set, list, tuple) of drop keys, go for del
Comment: There @mpen - seems del beats the dict comprehension even if I calculate `drop_keys` (I assumed keep keys are sets for O(1) `k in keep_keys`). Probably this means that creating a dict with 500 entries is a bit slower than creating a list with 500 elements :P
Comment: `drop_keys` isn't a fair comparison. Question is more akin to `keep_keys`. We know which keys we want, not which ones we don't want.
Comment: Thanks @mpen - indeed if we try to calculate `drop_keys` this slows down a lot pop/del methods. Will post some timings for that
Comment: That's just for the sake of in place edit. In many cases, the original data is to be cached for different filters be apply on to produced different results, instead of recreating the original dict and chop it down repeatedly.
Answer: If you know the negation set (aka not keys) in advance:
v = {'a': 'foo', 'b': 'bar', 'command': 'fizz', 'host': 'buzz'  }
args = {k: v[k] for k in v if k not in ["a", "b"]}
args # {'command': 'fizz', 'host': 'buzz'}

Answer: Short form:
[s.pop(k) for k in list(s.keys()) if k not in keep]

As most of the answers suggest in order to maintain the conciseness we have to create a duplicate object be it a list or dict. This one creates a throw-away list but deletes the keys in original dict.
Comment: Can you profile what is faster? Note you don't need to create the list: https://stackoverflow.com/a/36763172/281545
Answer: You could use python-benedict, it's a dict subclass.
Installation: pip install python-benedict
from benedict import benedict

dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])

It's open-source on GitHub: https://github.com/fabiocaccamo/python-benedict

Disclaimer: I'm the author of this library.
Answer: We can do simply with lambda function like this:
>>> dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
>>> large_dict = {"a":1,"b":2,"c":3,"d":4}
>>> new_dict_keys = ("c","d")
>>> small_dict=dict_filter(large_dict, new_dict_keys)
>>> print(small_dict)
{'c': 3, 'd': 4}
>>>

Answer: The accepted answer throws a KeyError if one of the filter keys is not present in the given dict.
To get a copy of the given dict, containing only some keys from the allowed keys, an approach is to check that the key was indeed present on the given dict in the dict comprehension:
filtered_dict = { k: old_dict[k] for k in allowed_keys if k in old_dict }

This does not impact performance, as the lookup against the dictionary has constant runtime complexity.
Alternatively, you could use old_dict.get(k, some_default) to populate missing items.
Answer: Here is another simple method using del in one liner:
for key in e_keys: del your_dict[key]

e_keys is the list of the keys to be excluded. It will update your dict rather than giving you a new one.
If you want a new output dict, then make a copy of the dict before deleting:
new_dict = your_dict.copy()           #Making copy of dict

for key in e_keys: del new_dict[key]

Comment: Turns out dict comprehension is indeed slower but greatly depends on size of filtered keys - see: https://stackoverflow.com/a/69973383/281545
Comment: Can you profile what is faster in case you don't need to create a copy (so creating the dict vs `for key in e_keys: del your_dict[key]`)?
Comment: @Mr_and_Mrs_D **Not** creating a copy would be definitely faster. About 15% faster
Answer: This is my approach, supports nested fields like mongo query.
How to use:
>>> obj = { "a":1, "b":{"c":2,"d":3}}
>>> only(obj,["a","b.c"])
{'a': 1, 'b': {'c': 2}}

only function:
def only(object,keys):
    obj = {}
    for path in keys:
        paths = path.split(".")
        rec=''
        origin = object
        target = obj
        for key in paths:
            rec += key
            if key in target:
                target = target[key]
                origin = origin[key]
                rec += '.'
                continue
            if key in origin:
                if rec == path:
                    target[key] = origin[key]
                else:
                    target[key] = {}
                target = target[key]
                origin = origin[key]
                rec += '.'
            else:
                target[key] = None
                break
    return obj

Answer: Just a simple one-line function with a filter to allow only for existing keys.
data = {'give': 'what', 'not': '___', 'me': 'I', 'no': '___', 'these': 'needed'}
keys = ['give', 'me', 'these', 'not_present']

n = { k: data[k] for k in filter(lambda k: k in data, keys) }

print(n)
print(list(n.keys()))
print(list(n.values()))

output:

{'give': 'what', 'me': 'I', 'these': 'needed'}
['give', 'me', 'these']
['what', 'I', 'needed']

Answer: You can use python's built in filter function and rebuild a dict from the items – though it's not as neat or performant as some of the other methods here:
my_dict = {i: str(i) for i in range(10)}

# I only want specific keys
want_keys = [6, 7, 8]
new_dict = dict(filter(lambda x: x[0] in want_keys, my_dict.items()))

# Or use logic – I want greater than 6
new_dict_2 = dict(filter(lambda x: x[0] >6, my_dict.items()))

You can get unnecessarily fancy with partial functions and operators if you wish too:
from functools import partial
from operator import is_, is_not, gt, contains

condition = partial(contains, want_keys)
condition = partial(gt, 6)

# use one of the conditions
dict(filter(lambda x: condition(x[0]), my_dict.items()))


How to estimate the inclination of a galaxy between edge on and face on?

Question: I have the images of a galaxy and the field of view and I would like to determinte the inclination of a galaxy between edge-on and face-on. Would that information be enough to do the calculation? Or what other details would be needed?
Comment: Possibly more than you've provided in this question... Details are required.
Comment: I have the images of a galaxy and the field of view. Would that be enough to do the calculation? Or what other details would be needed?
Comment: @andi Welcome to astronomy SE. I included your comment to your question, and as far I as I can tell, it looks like a valid question, so I voted to keep it open.
Answer: If you tilt a circular object, then along one axis the length will appear to be shortened, while along a perpendicular axis the apparent size will be unchanged.  So you can use that to determine the tilt angle (inclination).
If we define $0^\circ$ to be face-on, then when tilted at an angle $i$ away from face-on, the shorter axis will appear to be decreased in length by a factor of $\cos i$.  Thus, assuming that the galaxy is circular in cross-section, you can determine its inclination from $\cos i = \frac{\rm short\ axis}{\rm long\ axis}$.
This should work for spiral galaxies, but won't work for elliptical galaxies, which aren't necessarily circular in projection when viewed face-on.
Comment: Good enough.  There is a small correction for the intrinsic thickness though.  See Tully et al 1998 https://ui.adsabs.harvard.edu/abs/1998AJ....115.2264T/abstract Equation 2.
Answer:
You can visit IncliNET which is a Web application that uses the power of Convolutional Neural Networks to evaluate the inclination of spiral galaxies. This online GUI allows users to submit a galaxy image through various methods.
https://edd.ifa.hawaii.edu/inclinet/
1. Galaxy PGC ID
Entering the name of a galaxy by querying its PGC number (the ID of galaxy in the Principal Galaxy Catalog) - The PGC catalog is deployed with our model, and contains a table of galaxy coordinates and their sizes. Images are then queried from the SDSS quick-look image server.
2. Galaxy Name
Searching a galaxy by its common name. - The entered name is queried through the NASA/IPAC Extragalactic Database. Then, a python routine based on the package Beautiful Soup extracts the corresponding PGC number. Once the PGC ID is available, the galaxy image is imported from the SDSS quick-look.
3. Galaxy Coordinates
A specific location in the sky can be queried by entering the sky coordinates and the field size. In the first release we only provide access to the SDSS images, if they are available. The SDSS coverage is mainly limited to the Northern sky.
4. Galaxy Image
Uploading a galaxy image from the local computer of the user. User has the option of uploading a galaxy image for evaluation(s) by our model(s).
Please refer to the gitHub repository and the documentation of the GUI for further details on the entire process.
Each galaxy has its own unique morphology, luminosity, and surface brightness profiles. In addition, galaxy images are covered by foreground stars of the Milky Way galaxy. Therefore, it is challenging to design an algorithm that automatically determines the 3D inclination of spiral galaxies. The inclinations of spiral galaxies can be coarsely derived from the ellipticity of apertures used for photometry, assuming that the image of a spiral galaxy is the projection of a disk with the shape of an oblate spheroid. For ~1/3 of spirals, the approximation of axial ratios provides inclination estimates good to better than 5 degrees, with degradation to ~5 degrees for another 1/3. However in ~1/3 of cases, ellipticity-derived inclinations are problematic for a variety of reasons.

Prominent bulges can dominate the axial ratio measurement.
Some galaxies may not be axially symmetric due to tidal effects.
High surface brightness bars within much lower surface brightness disks can lead to large errors. Simply the orientation of strong spiral features with respect to the tilt axis can be confusing.

The statistical derivation of inclinations for large samples has been unsatisfactory until recently. There is a report on how 20,000 spiral galaxies have been sorted manually in a collaborative project with the help of amateur astronomers using an online tool called Galaxy Inclination Zoo. Please refer to the section 2.3 of the following paper for more details.
Cosmicflows-4: The Catalog of ~10000 Tully-Fisher Distances (Journal ref: Kourkchi et al., 2020, ApJ, 902, 145, arXiv:2009.00733)


Why was this moderation flag declined?

Question: Just out of curiosity but I flagged this answer to the "Is there a metabolically superior diet?" as "very low quality." Even though the "This post does not cite any references or sources." banner has been applied to the answer I was dinged on the flag with "declined - flags should not be used to indicate technical inaccuracies, or an altogether wrong answer " being the response back. This is a bit confusing for me since as far as I know, not having any citations has already been grounds for a "very low quality" flag. Has this changed recently?
Answer: Looks like a minor mix-up - a moderator race-condition.
I think the order of events was:

You saw it and flagged it.
@Fabian independently saw it, and added the post notice.
I looked at the flag, saw there was already a post notice, didn't think it needed any further action, and declined the flag.

Sorry for any confusion.
Comment: Not a problem, I thought that might have been the case but wanted to make sure.

Why was this moderation flag declined?


Accessing arraylist in different class?

Question: Member class = super class  SeniorMember class = sub class  JuniorMember class = sub class
Is it possible to have the same arraylist in different class to store the members?
"Commiittee class" having an arraylist to add and remove only seniormember
"Society class" having an arraylist to store all member, with add and remove seniormember and juniormember.
Can they share the same arraylist? how is it done?
import java.util.*;

public class ManagementCommittee{

    private ArrayList<SeniorMember> smlist;

    public ManagementCommittee(){
        smlist = new ArrayList<SeniorMember>();
    }

    public void addCommitteeMember(SeniorMember sm){
        smlist.add(sm);
    }

    public SeniorMember search(String smName){
        for (SeniorMember sm : smlist){
            if ((sm.getName()).equals(smName)){
                return sm;
            }
        }
        return null;
    }

    public boolean removeCommitteeMember(String smName){
        SeniorMember tmp = search(smName);
        if (tmp != null)
            return smlist.remove(tmp);
        else
            return false;
    }

    public String toString(){
        for (SeniorMember sm : smlist){
            return "Name : " + sm.getName() + "\nAddress : " + sm.getAddress() + "\nFee : " + sm.getFee();
        }
    }
}

How should I write for the society class to use the same arraylist in this committeemember class?
Comment: What do you mean by "Overall class having an arraylist"? Is this a superclass of Committee?
Answer: static arraylist in the superclass
Answer: If I understood you correctly, you're implementing a class to wrap around a collection and you'd like to shadow one of the collection handling methods. In that case, it should be something like:
import java.util.ArrayList;

public class HelloWorld {
    static class Member {
    }

    static class SeniorMember extends Member {
    }

    static class Committee {
        private ArrayList<Member> _members = new ArrayList<Member>();

        public void add(Member member) {
            _members.add(member);
        }
    }

    static class ManagementCommittee extends Committee {
        public void add(Member member) {
            if (!(member instanceof SeniorMember)) {
                throw new Error("Only senior members here");
            }
            super.add(member);
        }
    }

    public static void main(String[] args) {
        Member member = new Member();
        SeniorMember senior = new SeniorMember();
        Committee committee = new Committee();
        ManagementCommittee management = new ManagementCommittee();

        committee.add(member);
        committee.add(senior);

        management.add(member);
        management.add(senior); // throws a run-time error
    }
}

Note that if you override the method add to accept a SpecialMember you'd still be exposing the superclass' add(Member) version.
Comment: hmmm, I guess so, The society class is wrapping up all the member in the senior and junior member, only the committeemember class are wrapping the senior members. SO i need to do in the way that committee extends society?
Comment: Your phrasing is a bit confusing to me. You have a `SocietyCommittee`  which holds all kinds of `Member`s, and a `ManagementCommittee` class which holds only `SeniorMember`s but shares all functionality with the `SocietyCommittee` class? It sounds like a good reason to use `ManagementCommittee extends SocietyCommittee`, or at least to have them both extend a common base-class, e.g. `Committee`.
Answer: I'd set up your Society class using ArrayList.  Then make a Committee class that uses Society the way Society uses ArrayList.  To get a list of Committee members, you'd get the full list from Society (which gets it from ArrayList) and keep only the committee members.  Adding a committee member means making sure its in the Society instance, adding it if necessary, then getting hold of it and marking it as a committee member.  There's a bit of busy work here, but it's straightforward.  Also, you might want the Society and Committee classes to implement the same interface so other parts of your code need not know whether they are dealing with committee members, ordinary memebers, or even some other group entirely (but that does implement the interface).
If this is a really large society, you might want to maintain a separate list of committee members, but it needs to be synchronized.  A Committee instance would need to have a Listener added to it's Society interface to catch all removals in case one is a committee member--for example.  I don't think you want to bother with that just now.

Accessing arraylist in different class?


Tautology and Redundancy difference

Question: My text says that :
Redundancy refers to information that is expressed more than once.
Ex:Forever and ever, past history
Tautology refers to phrases that repeats a meaning with different though semantically similar words.
Ex: Free gift
I really can't understand the difference. Is there even any? Are they both the same?
Comment: I don't believe that English usage bears out the distinction that your text makes. I think that your text (like some of the answers below) is trying to find a principled distinction where there isn't one. Some speakers may make the distinction, but many do not.
Answer: The word tautology has several different senses, depending upon its field of use.
A grammatical tautology is little different from redundancy. It just means that the same thing is repeated twice using different words.
Rhetorical and logical tautologies are more interesting.
A logical tautology is a proposition that is true given any possible variables.
A rhetorical tautology is a statement that is logically irrefutable. This can be by repetition, but in its more nuanced form it is done by stating things in such a way that it fails to make a point, while obscuring this fact in the language which is used.
So, for example:

"Either we will live or we will die."

There is no repetition in this statement, but it is nevertheless a rhetorical tautology.
Rhetorical tautologies are meant to sound profound, but they add nothing to a conversation because they literally make no point.
Comment: I disagree with your last point. Sure literally "we will live or we will die" is always true. However, you are introducing the possibility of death during forthcoming events. Under normal circumstances this is highly unlikely; it introduces a concept, specially as two potential outcomes of a situation.
Comment: Tautologies exist within a context. The tautology does not create the context. In this case the statement is made in the context where death is already a reasonable possibility. QED.
Comment: You're proving my point for me. The person is saying "Either we will live or we will die." *because* death is already a reasonable possibility (this is an unusual situation). Therefore, it draws attention to an unusual situation; the heightened likelihood of death. Thus, it adds something to the conversation. QED.

I can think of no likely situation where somebody might say "Either we will live or we will die.", in the context of it adding nothing to a conversation (ie no change in the likelihood of life or death).

Also in your answer "literally" is itself a tautology :D
Comment: You are being pedantic. Please stop.
Comment: My work here is done.
Comment: "You are being pedantic" seems a poor defense. Not a good argument.
Answer: Tautology is redundancies within phrases. Redundancy is any kind of repetition: phrases, sentences, paragraphs, entire books, it's all the same; the scale isn't important.
Answer: A tautology refers to phrasing that repeats a single meaning in identical words:

They followed each other one after the other in succession.

Succession means one after the other.
Redundancy refers to multiple phrasings that are no more meaningful together than one of the phrasings by itself.  My favorite is the legalism found in contracts and trusts that empowers someone to take action

at any time and from time to time

These are two different things:  "At any time" means without temporal restriction, and "from time to time" means sporadically.  But they're redundant because if you may do one, then you may do the other.
Note that redundancy is bad style when it appears in a definitional sense like the "succession" example.  Grammatical tautology falls into this category.  Other redundant language is acceptable for emphatic rhetorical effect:

I am completely, thoroughly, and totally angry with you.

or to make a subtle semantic point -- a free gift is one comes without obligation as opposed to those other things that people call gifts, but which come with strings attached.
Comment: I like to reserve *redundancy* to describe the over-use of a word or phrase within a short time period or piece of writing.
Answer: The OED gives several different senses for tautology. Some of them confirm the points that have already been made in answer to this post, where the same thing is stated more than once using synonymous words and expressions.
However the OED sense which has most resonance with my understanding of the term is meaning 4:

An argument, explanation, or definition that merely restates in different words the very thing which is to be explained, shown, or
  defined; a failure fully to separate cause from effect in explaining
  an event, phenomenon, etc.

1997   J. D. Moore Visions of Culture xiii. 178   'I am taller than
  other people because most people are shorter than I am' is a
  tautology.

I am not saying other uses of tautology are wrong, indeed the OED supports them. But for my own part tautology infers an attempted explanation which is no explanation at all, simply a synonymous expression. For other senses of tautology, I would personally tend to use redundancy, or synonymous.
Comment: +1 for bothering to supply a reference. Though I'm sure this has been addressed here before (but I'm making a point about references or rather the lack of them).
Comment: "I am taller than other people because most people are shorter than I am." There is hardly anything you could place after "because" that would not be tautologous, other than perhaps "both my parents were very tall."
Comment: @Cargill Or *...because I eat spinach*.  It doesn't have to have any basis in science or fact to be grammatically non-tautologous.
Comment: @WS2 Point taken - I expect I was limiting myself to the realm of reasonableness and likely answers, but concede I overlooked the nutritional benefits of spinach!
Answer: All of the above answers say most of what needs to be said. I'll just contribute a small etymological note:
tautology comes from the Greek word tautalogos, a contraction of to auton (the same thing) and  logos (word, speech, reason, argument).
redundancy comes from the Latin verb redundare, which means to overflow or to be abundant. This is a simpler word, I think; one that connotes mere repetition rather than logical fallacy (which is what a tautology is).
Answer: The law for some reason has more than its share of redundant terminology - law and order, cease and desist, null and void, without let or hindrance, and many more.
Apart from grammar and syntax, tautology is also concerned with logical (or illogical) formulations where things are said unnecessarily, because they could not be any other way, and they're far more common in both creative writing and journalism than one might think:

Before she died, my grandmother used to walk to the shops every day.
When the plane came to a stop, we disembarked.
It's raining outside.
The accident happened at 2:00 am this morning.
Annual Fees are to be paid in four quarterly instalments.

If you start looking, you see and hear them everywhere.
Answer: I consider redundancies to be the use of an extra word, whereas tautologies are the statements which equate that which is already equal: "I drew a round circle" as opposed to "My circle was round." In the first, "round" is redundant, but at least the sentence tells us one fact, that I drew it, so the sentence was not a compleat waste of time. In the second, no information is given at all.
Comment: Hi cflpeace, welcome to EL&U. This isn't a bad start, but you don't provide any supporting evidence to differentiate your answer from mere personal opinion. An answer on EL&U is expected to be *authoritative, detailed, and explain why it is correct*. You might like to [edit] your answer to provide the necessary detail. For further guidance, see [answer] and take the EL&U **[Tour]** :-)

Tautology and Redundancy difference


How to use the latest stable version of org-mode?

Question: Is there a ppa for org-mode?
I'm using ubuntu 12.04.
If not, can I install the latest stable version of org-mode for Emacs manually?
Answer: This does maybe not apply to 12.04 anymore (I think it does though). The easiest version by now (Using ubuntu 14.04.2) is:
sudo apt-get install emacs24

Then, inside of emacs, use the package manager:
M-x package-list-packages

Search (C-s) "org", there may be a few entries but the one with the date is the newest (as of now 20150413). Mark it for installation with I, install with x.
Restart emacs, done.
Comment: thnx a lot...  it worked
Answer: To install the latest, make sure that Emacs is installed on your machine.
If not, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:
sudo apt-get install emacs23

Once the installation is done. download the latest org-mode from Ubuntu Updates.  Once downloaded, from terminal navigate to where the file was downloaded (probably the Downloads folder), and run the command below:
sudo dpkg -i <file_name>.deb

And that will install the latest stable version of org-mode 7.8.02-1
Comment: Now Stable version is 8.2. How to install 8.2?
Comment: I havn't been able to find any PPA that has version 8.2 for 12.04.  8.2 is available form the PPA for 12.10, and 13.04.  What you can try is to download and build the file from [Orgmode](http://orgmode.org/).
Answer: Here is a solution that uses the latest source code, borrowed from two Emacs StackExchange threads (here and here).
Run this in a shell:
cd ~/src/  # or any other location
git clone https://code.orgmode.org/bzg/org-mode.git
cd org-mode/
make autoloads

Then run this Emacs-LISP code before any other org code in your initialization files:
(add-to-list 'load-path "~/src/org-mode/lisp")
(require 'org-loaddefs)

See this answer for details on why you need the second line and in that order to avoid a mixed installation of built-in and latest versions:

The main idea is that you need to make sure that Org mode is set up,
  using the new bits that you downloaded only. Emacs comes with a
  version of Org mode bundled up with it, but that is inevitably older
  than what is available from the Org mode git repo. It is important to
  avoid loading any piece from the bundled up version or else you might
  end up with a "mixed" installation (there are many hits for that on
  the Org mode mailing list).
As I mention in a comment, and @Tobias has verified in another
  comment, you do not need to byte-compile the new version - you only
  need to make autoloads. That creates an org-loaddefs.el file, so that
  all the common entry points into org will, when first invoked, load
  the appropriate file first. It is important (and contrary to what the
  OP states in his comment) to set the load-path before loading the
  org-loaddefs.el file: otherwise, you may end up with the dreaded
  "mixed" install I mentioned above.


Failed to export all rows in attribute table in ArcMap to .dbf

Question: I would like to export a large attribute table to .dbf format, which includes almost 5,000,000 rows. But the exported table only contains about half of the rows without showing any error message during export progress. I am wondering if there is a size limit for exporting attribute table in ArcGIS.
Comment: Please **edit** your question to include either the fields defined in the dBase file or the sum of the widths of those fields.  It would also help to describe the exact procedure you used to do the export.
Comment: something that has worked for me when I've had problems exporting to .dbf tables, is export the attribute table to a geodatabase table, and then export that to .dbf format. i have no idea why it worked, or if it will help you, but it's worth a try
Answer: .dbf files do have a size limit, but it isn't necessarily the number of rows.  It's  a disk size limit of 2GB.  If you have a lot of attributes, the 5,000,000 rows could make the .dbf quite large.
Perhaps you might want to remove some unnecessary attributes.  Or split the file into parts.
Alternatively, try looking at other file formats.


can a multithread program still be running after killing it in system monitor

Question: Is it possible that a program which does not kill its threads properly before exiting still be running some piece of code somewhere even though it has been killed in system monitor?  I am running ubuntu in a non virtual environment.  My application is made with QT, it contains QThreads, a main thread and concurent functions.
Answer: If you kill the process then you kill all its threads.  The only cause for concern would be if your application had spawned multiple processes - if that is the case then you may still have code executing on the machine.
This is all very speculative though as I don't know what operating system you code is running on, whether or not your application runs in a virtual environment, etc.  Environment-specific factors are very relevant to the discussion, can you share a bit more about your application?
Answer: It is not possible, all modern heaviliy used operating systems manage these resources quite tightly. Threads cannot run without a process... They are all brantches from the original thread.
Answer: I don't know of any OS that doesn't fully terminate all it's threads when you kill the processes, it's possible to spawn child processes that live on after the main process has exited but in the case of threads i'd say it's not possible.


Can't install elementary OS because my monitor doesn't support the default resolution

Question: When I boot into the flash drive and try to install it, the screen says "unsupported" and there's nothing I can do except turning off the PC.
Is there a way to fix that?
Answer: Put the usb stick to a working operating system, open it go to /boot directory find the configuration file and open it and uncomment disable_overscan=1 (if this parameter is 0 then set it to 1).


Derivation of mean life of a radioactive nucleus

Question: How can the mean life of a radioactive nucleus be derived?
Consider R.dt number of nuclei decaying in the time interval t and t+dt. Then, isn't the lifetime of those R.dt number of nuclei is t? But, I couldn't understand why in many derivations, lifetime is mentioned as tR.dt instead of t and we integrate tR.dt from 0 to infinity?
Answer: Average values are calculated by integrating over a probability distribution:
$$\langle x\rangle=\int_a^b xP(x)\;dx.$$
Thus to solve the problem one must find the probability that a given nuclei does not decay, so that the mean lifetime is given by:
$$\langle t\rangle=\int_0^\infty tP_{not decayed}(t)\; dt.$$
Since we know the probability that a given nucleus will decay is given by the distribution:
$$P_{decayed}(t)=\int_0^t \lambda e^{-\lambda t^\prime}\; dt^\prime=1-e^{-\lambda t},$$ where $\lambda$ is the decay constant of the given radioactive species, and is included for normalization so that:
$$P_{decayed} (t)=\int_0^\infty \lambda{N(t)\over N_0}\; dt=1.$$
So the probability that the given nucleus has not decayed is given by:
$$P_{not decayed}(t)=1-P_{decayed}(t)=e^{-\lambda t}.$$
So that we have the mean life-time as:
$$\langle t\rangle=\int_0^{\infty} te^{-\lambda t}\; dt.$$
Using integration by parts, we find that the mean life time is :
$$\langle t\rangle={1\over \lambda}$$.
Why must we integrate over infinity, because the sample life time is such that $N(t)\rightarrow 0$ asymptoticaly as $t\rightarrow \infty$.
Answer: The basic assumption is that the rate of decay is proportional to the number of unstable nuclei,
ie $\dfrac{dN}{dt}\propto N \Rightarrow \dfrac{dN}{dt}= -\lambda N\Rightarrow N = N_0e^{-\lambda t}$
where $\lambda$ is the decay constant and $N_0$ is the number of unstable nuclei at time $t=0$.
As an aside suppose that you started with $15$ and $8$ nuclei decayed in the first two second interval, $4$ nuclei decayed in the second two second interval, $2$ nuclei decayed in the third two second interval and the last nucleus decayed in the fourth two second interval.
How might you estimate the mean lifetime of the unstable nuclei?
How about $\langle t\rangle=\dfrac{(8\times 1) + (4 \times 3)+(2\times 5)+(1\times7)}{8+4+2+1} \approx 2.47$.
Where did the $(8\times 1) $ come from?
It comes from the fact that between time $= 0$ and time $= 2$, mid interval time $1$ seconds, eight nuclei decayed and so on for $(\underbrace{4}_{\rm number}\times \underbrace{3}_{\rm mid\,interval})$ etc, with $(8+4+2+1)$ being the total number.
Coming back to the radioactive decay.
The number of unstable nuclei which decay in infinitesimal intervals of time from $t$ to $t+dt$ is
$dN= -\lambda N(t) \,dt=-\lambda N_0e^{-\lambda t} \,dt$.
and the mean lifetime is $\langle t\rangle=\dfrac{\displaystyle\int_{t=0}^\infty \left(-\lambda N_0e^{-\lambda t} \,dt\right) \times t}{N_0}=\dfrac{1}{\lambda}$


How can I predict the post popularity of reddit.com with hidden markov model(HMM)?

Question: If I get some posts on reddict.com, how can I predict whether this post will (trending/hot/popular) in the future or not? I would like to use the hidden markov model to predict it, but I don`t know how to define the hidden states and observation sequence...can anyone give me any suggestion? Thanks~

Answer: An HMM doesn't really make sense (echoing what Dries said). If you want to use an HMM, you would have to justify it by asking "Can Reddit posts be represented by a Markov process?" I can't think of a way to make that sentence true and still take advantage of the features related to a popular post.
Consider the possible feature set: the time it was posted, the user posting it, the type of post (link / image / text), the subreddit, the number of subscribers to that subreddit, a score of positivity / negativity, number of words in the title etc. Don't count out these features.
Answer: I don't think it makes a lot of sense to use HMM's for this problem. What I would suggest is some kind of text-based classifier.
If you want to use a cool technique, you could use a neural network to learn based on the text of successful posts.
On the other hand, If you want to use an easy technique you could make a predictor for the popularity such as a regression model (try to predict upvotes).
Comment: HI, can I use the regression model to predict the upvotes only with the comments (such as the interarrival time of the time series data)? But I have no idea about the clearly steps to build the model? Woud you mind give me some suggesion, please? Thanks a lot.


What to expect from champagne yeast?

Question: I bought a pack of champagne yeast, but not sure why, just to try it :) What differences should I expect compared to a "normal" English ale yest?
Comment: I've never used champagne yeast for beer, but I would guess that it will produce a very dry taste.
Answer: My experience is that champagne yeast makes lousy beer.  It ferments different sugars than ale/lager yeast and does not produce the flavors you expect from beer.
Answer: A champagne yeast will most likely be different from an ale yeast in two ways:

While an ale yeast may fermement down to 1.008 or so, a champagne yeast will ferment to something much much dryer, closet to 1.000
Wine and champage yeasts do not typically produce the amount of krausen that an ale yeast will.
Comment: I guess I didnt address this as much as I should have. An ale yeast and a champagne yeast will produce different flavors, obviously. I wouldnt ferment wort with a champagne yeast and expect good results.
Comment: I imagine that champagne yeast would be good if you wanted a high alcohol beer as it can tolerate higher amounts of alcohol, but they produce a very dry flavour, so if you wanted a sweeter strong beer, would they work for that as well?
Comment: Use ale and lager yeasts for beer. For a sweeter, stronger beer, ensure that you simply pitch enough viable yeast to get the job done since your beer is high gravity. Try a champagne yeast on something like a cider for good results.
Answer: I have used champagne yeast to make an ale but never alone, I have added it to very strong high ABV brews to dry them out at the end of the fermentation. If you want an ale flavour then use a standard ale yeast for the first week or 2 then add in the champagne yeast.
Most of the yeast based flavours are made in the first 3-4 days of your brew, so the main flavour profile you want choose that yeast for the first days. But, be warned that some yeasts may clear up the flavour compounds created by others.
Also, where an ale yeast may slow down at 8-9% and die off at 10-11% the champagne will keep fermenting to 14-17% so if you want a potent and dry barley wine than it may be for you.

What to expect from champagne yeast?


Needing some tips on toning up

Question: I have lost a good amount of weight, but now it is time to tone up and get ready for swim suit season.Not only toning up but i need to build some strength as well. What kind of exercises can help me with toning up but also help me build up some strength?
Answer: I'll get to the answer quickly - lift weights!  Find a good gym, a good strength coach/personal trainer or do a lot of research on a weight lifting program that will not only get you strong, but keep you lean and get you in the shape you want.  Here's a great resource: www.bodybuilding.com - take a look around.  If you can't afford a gym or personal trainer get ready to do a lot of research - read anything from Dan John or Jim Wendler.  Want more advice? let me know - good luck!!!
Comment: Thank you very much! this is very helpful, i had some health issues long story short it made me lose a lot of weight in a short amount of time about 30 to 40 pounds within 3 1/2 months so i am not trying to lose anymore weight. My main goal now is too tone up and to build strength
Comment: @Jessica - You took the biggest step, know it's more tough work to get your plan together and follow it.  I would start by learning all the basic lifts (deadlift, squat, bench, press) and practicing them for 2-3 weeks (you'll never stop learning how to improve on them).  During that time look into the various weight lifting plans (5x5 starting strenght, madcow, 5/3/1) - pick one- and stick with it for 2-3 month min....never give up, never look back and never put yourself in position where you'll get hurt and not be able to train the next day.  let us know how it goes - GOOD LUCK
Comment: Thank you very much! this information is very helpful and this time around i have decided to get a personal trainer not only support but for tips and advice

Needing some tips on toning up


Count activities on contact object

Question: Is it possible to create a rollup summary field on Contact to count the activities. For example, count the total number of times 'Log a call', total number of times 'log a meeting', and total number of times 'Log an email'?
Comment: I highly doubt that if it's possible you can't create a master-detail relationship with a standard object on the detail side and without being a relationship you can't create a Roll-Up summary
Answer: Rollup summary fields can only be used on Master-Detail relationships where you wish to rollup child information to the parent i.e detail to master.
In this case, you need to use Apex. A declarative tool like Flow is possible but to ensure you are working from the correct Related To Sobject, you will need to invoked Apex.
Sample Apex:
List<Id> conIds = new List<Id>();
for (Task t : Trigger.New) {
    if ((t.WhoId.getSObjectType() == Contact.sObjectType) && t.Subject == 'Log a Call') {
        conIds.add(t.WhoId);
    }
}

if (conIds.size() > 0) {
    List<Contact> cons = [select id, CallLogs__c from Contact where id in :conIds];
    for (Contact con : cons) {
        if (con.CallLogs__c == null) con.CallLogs__c = 1;
        else con.CallLogs__c += 1;
    }
    update cons;
}

A custom Number field has been added to the Contact object to count the specific number of "Log a Call" Tasks. You may wish to aggregate all Task Subjects in a single field, thats a design choice on your side. Another design decision for you is to build a known of set of Task subjects to check against. Note the check on WhoId.getSObjectType() as Task is a shared object and you want to safe guard your code for later operations.
You should extend this Apex to accommodate delete operations if you wish to decrement the count on the Contact record.

Count activities on contact object


Difference between 'holdings' and 'estates'

Question: I am reading a table related to production of rubber; the title of the table is Productions By Holdings And Estates. In this context, what is the difference between holdings and estates?
Comment: This is not a definitive answer, but 'Estates' may refer to wholly owned properties, whereas 'Holdings' may be intended as a broader term for rubber-producing properties in which one holds a controlling interest.  Is there anything in the text to which the table is appended that might support this interpretation?
Answer: Where is the table you are reading? Where does the document originate? If it's rubber, it may be about India?
In South Africa, a "Holding", or more properly, and "Agricultural Holding", is something between a farm and a town property, and can be used for agriculture, such as growing rubber.
An "Estate" has no legal meaning as far as property goes, but may be taken to mean an large contiguous piece of land made up of more than one registered property, but probably all owned by the same person/s or legal entity/ies, for a common purpose (such as, for example, growing rubber).
Comment: From India , the table belongs to a book based on rubber production in India
Comment: My guess is that it is about Malaysia. Both these terms are used there.


Does Catholic morality (i.e. Natural Law) reject the idea that different cultures fundamentally think differently?

Question: In the aftermath of the attack on Israel by Hamas, I've been listening to Ben Shapiro saying some things that I would like to know if are in-line with Catholic morality.  It doesn't much matter what my opinion on the Israeli response to the attack is, but is the moral tone that Ben Shapiro is setting where he has repeatedly said that people who appear indoctrinated to value what they consider martyrdom over any other good are fundamentally on a different plane and not possible to reason with or treat in any other way than as if they were inhuman in accord with Catholic morality.  Or does the Natural Law say that objective morality (i.e. not murdering - which is always wrong according to the Catechism) is accessible to even people who are brought up in a disordered value system?
Answer: I am sorry this answer is a bit ignorant. I am not a theologian but let me explore the idea.

Some words about martyrium in catholicism
In Catholicism, it is not "to value what they consider martyrdom over any other good" because the ultimate good is God.
We could argue that some apostles at some point avoided it, by being for example released from prison, (but ultimately died by it), but according to tradition, the Apostle John was spared from being boiled alive. So, no. It is not the ultimate goal.
But it is sometimes not only not avoided but embraced, because is part of The Beatitudes. Mathew 5:10

Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.

The testimony is especially credible in the moment of death, so it is traditionally explicit in death by persecution. But death is not a requirement for this. For example, Mary suffered with his son at the cross, but she did not die a violent death.
In the catechism, the number 2473 It says "Martyrdom is the supreme witness given to the truth of the faith: it means bearing witness even unto death."
But the context is persecution, it is not suicidal, and not harming others.

In catholicism, Can you reason with someone who embraces being a martyr? I suppose depends on the meaning of reasoning. Christianity for the world has no sense. The creator of the universe, died on the cross? We can see the "unreasoning" according to the world.
Logic is determined by the stated premises. Under Christian logic, death is only a transit, because the premise is the resurrection of Jesus and his promises. But in an atheist worldview that premise does not exist. So we need a frame of reference, a frame of thought.
There is a Mexican martyr during the Guerra Cristera persecution. He was a 14-year-old kid who said to her mom "nunca fue tan fácil ganarse el cielo" "Never was so easy to earn heaven" because in the persecution was very likely to get killed by saying "Live Christ the King".
But the context is persecution, it is not suicidal, and not harming others.
We would need to explore how it differs from martyrium in Islam.

Some specific parts of your question

as if they were inhuman in accord with Catholic morality

According to Catholic doctrine (The same as Christian doctrine in general), there is no way someone (human) would be considered not human. Even the most evil people have the potential to be saved by the grace of Jesus if they accept it.

Is (Moral law) accessible to even people who are brought up in a disordered value system?

What the Catechism says about Moral law No. 1954 (natural law) "The natural law is written and engraved in the soul of each and every man" So, in principle yes, it is accessible to every person.
The point would be not only how disordered is the surrounding value system, but how we adopt it knowing even if it is bad.
This has its roots in sin. For example, pride would have the consequence of not accepting self errors, or accepting the possibility of correcting them, therefore being incapable of reasoning with. But it is a fruit of self-decision, not only on the environment.

Catholicism also accepts the fact that "the devil" can objectively affect the behavior of man. But again it is not against the will of the person. A heavy influence of evil implies previous willing acceptance of it. An entry door can be the acceptance of an evil ideology, whatever this one is.


"зарплата" vs. "жалование"

Question: When to use "зарплата" and when "жалование"?
Answer: The word жалованье is really outdated although you can use it in humorous way. The word зарплата is contemporary but not official one, it should not be used in legal or official documents - use the word оклад instead.
There is another word, получка, which means the fact of getting the pay in hands. Back in a day when получка was happening at fairly large enterprises (state steel factory, for example) that usually meant sharp increase in alcohol sales in vicinity.
Comment: To be precise: «жалованье» and «зарплата» are the same, but the former one is outdated while the latter one is colloquial. «Оклад», accroding to the [dictionary](http://gramota.ru/slovari/dic/?bts=x&word=%EE%EA%EB%E0%E4) is the _amount_ of salary. «Заработная плата» is fine in official documents.
Answer: I believe "жалованье" (not "жалование") is obsolete these days, so use "зарплата" unless you're writing an historical novel.
The words have different connotations too. Жалованье comes from an act of charity or benevolence; зарплата (заработная плата) is pay for work performed.
Answer: As others have already noted the word жалованье is outdated. Historically this word was officially used in pre-Soviet Russia (in nineteenth cent as a name of a salary of people that worked for government (officials, soldiers, police, etc.), so even today most people couldn't call their wages as 'жалованье' anyway. During early Soviet times this word was also used by people that used to it (you may encounter it when reading Bulgakov novels, for instance), but it was no longer officially used.
Talking about Bulgakov we can also recall the "Иван Васильевич меняет профессию" movie when one of the characters says "Жалую тебе шубу с царского плеча". This shows that жалованье could be not only in monetary form, but also in form of different gifts and preferences. Also this is the phrase that most people associate with word жалованье nowadays.
As for зарплата - this is informal short form of official term заработная плата. This is a general term that describes monetary reward for an employee for the job performed, but the 'legal' name for such reward may vary depending on type of a contract. For example оклад usually means that an employee receives fixed payment every month, почасовая оплата if an employee's reward is based on how many hours they worked etc.

"зарплата" vs. "жалование"


MySQL Database Archive

Question: We have 300 databases in our environment mixed of MyISAM and Innodb(innodb_file_per_table has been enabled) tables.Using MySQL 5.5.19 version. I
we are planning archive inactive database.Is there any way we can check what databasese are inactive?
I have checked at the OS level file modification timestamp,but as we have so many database its taking time.Please let me know is there anyway we can check.
Note: Timestamp column is not present in any of tables
Answer: (A non-answer)
There is essentially no way.
atime should be turned off, else performance will be quite bad.
Just because you have not used a database in the last week does not mean that you won't use it next week.
Comment: yes james i agree..but there are few database are not using from last 2 yrs ..so i would like to listout such databases.(forgot to mention in my requirement)
Answer: You can check binary logs for databases and tables...
Comment: its standalone server..didn't enable binlogs...even if we enable how can it helpful

MySQL Database Archive


Are my peppers underripe or just a different variety?

Question: I'm growing what I was told was banana peppers; however, it's now fall and starting to cool off, but the peppers are not yet yellow. Rather than ripen yellow, they appear to be turning red. Is this an intermediate stage between green and yellow, or do I have a non-yellow variety?
Comment: They look like anahiem or new mexico chilies to me
Comment: @WebChemist I'll have my husband taste-test them, Anaheim is solidly hotter than banana
Comment: I've got a pack of Sweet Banana pepper seeds that shows red peppers on the label (Purchased from the Dollar Tree). We had banana peppers from another pack in 2014 (I think from the same company, and there were no red peppers on the label), but none of the 2014 ones turned red (in fact, they got black streaks on them after turning yellow, but that's as far as they got; I didn't try letting them ripen longer to see what happened, as they were already on for a good while).
Answer: Red is generally a final ripening stage for most peppers, indicating they are fully mature. There are many different kinds of mild chilis, however, referred to as "banana peppers" and some of them eventually become red instead of golden yellow.  It is also definitely possible you have something other than a true banana pepper growing - through mislabeling or cross-pollination of the seed used to produce the plant.
I'd go by taste rather than by appearance in deciding which is the most likely case - unless these are "Hungarian" Banana Peppers, they should be mild, slightly sweet, and slightly tangy in taste.  If they are hot, then you definitely have something that's not your regular banana pepper.
Comment: My husband tasted one and declared it a mild pepper for sure :) I think it might actually be "italian sweet pepper"? Which I've seen for sale at the farmer's market, and looks like some peppers I've also seen marked "banana" at the farmer's market.


Are reversible adiabatic processes always isentropic?

Question: If my understanding is correct, neither reversible nor adiabatic processes are necessarily isentropic.
But are reversible adiabatic processes always isentropic?
Comment: Related: http://physics.stackexchange.com/q/52231/2451 and links therein.
Comment: Just to alert you, the term "adiabatic" is now somewhat in a state of change. In thermal physics it was first widely used to mean "without heat transfer" but it has become very common to use it to mean "reversible and without heat transfer" and that is how it is usually used in areas outside thermal physics (e.g. basic quantum mechanics).
Answer: Yes. For a reversible process, we have the relation
\begin{align}
  dS = \frac{\delta Q}{T}
\end{align}
and for an adiabatic process, we have (by definition)
\begin{align}
  \delta Q = 0,
\end{align}
which implies that
\begin{align}
  dS=0.
\end{align}
Answer: Yes.
From Clausius theorem the following inequality can be deduced:
$$\delta Q \le TdS$$
where the equality holds in the reversible case.
So, a reversible adiabatic process is necessarily isentropic, but irreversible adiabatic processes are not so.
To put it in another way, in an irreversible process, according to the above inequality, either entropy  changes, or heat must be somehow removed from the system to make it possible to have zero change in entropy.  So an irreversible isentropic process can not be adiabatic.
Answer: I want to explain from fundamentals, rather than invoking the Clausius theorem. Here goes:
STEP 1: REVERSIBLE --> No entropy creation or destruction during the process
Entropy cannot be created or destroyed in any part of any reversible process whatsoever. The reason is, first, entropy can never be destroyed under any circumstance (second law of thermodynamics), and second, if entropy was created in (part of) the process, it would be destroyed in the corresponding part of the reversed-version-of-the-process. But again, entropy cannot be destroyed.
STEP 2: ADIABATIC --> No entropy flow during the process (into or out of the region in question)
If no heat is flowing into or out of the region (definition of "adiabatic"), and no matter is flowing into or out of the region (also part of the definition of "adiabatic" I think), then there's no way that entropy could be flowing into or out of the region.
CONCLUSION: The entropy of the region is fixed if the process is both reversible and adiabatic.
Comment: +1 This is a nice conceptual explanation. Nothing at all wrong with using formulae, but this is more satisfying in my view.
Answer: To answer this question, lets start with combined first and second law of thermodynamics,
\begin{equation}
dU = TdS-PdV
\end{equation}
For ideal gas, $dU=c_{v}dT$. Thus
$$TdS = c_{v}dT+PdV \qquad$$
Change in entropy in terms of exact differentials (by using the equation of state for an ideal gas $PV=RT$),
$$\tag{1} dS = c_{v}\frac{dT}{T}+ R\frac{dV}{V}$$
By taking log on both sides of the ideal gas equation $PV=RT$ and taking differentials on both sides yields
\begin{equation}
\frac{dP}{P}+\frac{dV}{V} = \frac{dT}{T}
\end{equation}
Using the above equation in Equation (1), and making use of the relations $c_{p}-c_{v}=R; \gamma=c_{p}/c_{v}$, we find
$$dS= c_{v}\left[\frac{dP}{P}+\frac{dV}{V}\right]+R\frac{dV}{V}$$
or
\begin{equation}
\frac{dS}{c_{v}} = \frac{dP}{P} + \gamma\frac{dV}{V}
\end{equation}
Integrating between two states 1 and 2, gives
\begin{equation}
\frac{\Delta S}{c_{v}} = \ln\left(\frac{P_{2}}{P_{1}}\right)+\gamma\ln\left(\frac{V_{2}}{V_{1}}\right) = \ln\left[\frac{P_{2}}{P_{1}}\left(\frac{V_{2}}{V_{1}}\right)^{\gamma}\right]
\end{equation}
Using both sides of the last expression as exponents we obtain
$$\tag{2} \boxed{\frac{P_{2}V_{2}^{\gamma}}{P_{1}V_{1}^{\gamma}} = e^{\Delta S/c_{v}}}$$

Equation (2) describes a general process. For the specific
situation in which entropy is constant, i.e. $\Delta S = 0$, we
recover the expression $PV^{\gamma}=\text{constant}$. Which is applied
for reversible adiabatic process.
We now see, through the use of the second law of thermodynamics, a
deeper meaning to the expression, and to the concept of a reversible
adiabatic process, in that both are characteristics of a constant
entropy, or isentropic process.

So in general an adiabatic process is not necessarily
isentropic-only if the process is reversible ($\Delta S =0$) and adiabatic ($dQ =0$), we
call it isentropic.
Answer: Every reversible adabatic process is isentropic. But the converse is not true.Every isentropic process may be reversible adabatic or may not be reversible adabatic.


Greenish Deposit on Outside of Copper Pipe in Bathroom

Question: I'm renovating my bathroom. I ripped out the floor and I noticed that there is a green deposit on the outside of the copper tubing. Is this a problem? Do I need to have a plumber check it out? The pipes are 50 yrs. old.
Answer: That normally means there was a water leak at some point.  If you look at the pipe on the left in your picture, you can see a small trail coming down from up above.  Is there any sign of water above the floor/cabinet?  A small amount of green on copper usually isn't anything to worry about.  You just want to make sure that whatever is leaking has stopped.
If there is still a leak, clearly you'll need to fix that.
Comment: That's an interesting observation. I hadn't noticed the trail. There was a small amount of deteriorated drywall near the sink. It looks like the previous owner had a leak at some point. I don't see any leaks now.
Comment: I have seen the green copper many times with no problems. I have seen a few where there was moisture, possibly a over flow made the Sheetrock wet and some corrosion has started. If no leaks clean the pipes and spray with a lacquer clear spray paint. If it stays clean , no problem,,, more green says there is a leak or small pinhole , cannot jump to what it is with just 1 check
Comment: Ed, I hadn't heard of the lacquer trick before, but that's neat.  I'll have to remember that.
Answer: The green deposit forms as the copper of the tubing chemically combines with other elements on the nearby environment. The presence of wetness or water can accelerate the formation of the greenish copper compound.
I have seen multiple instances where the acidity of the water sitting and flowing inside the pipe can eat the pipe walls thin from the inside over many years. This can lead to pin hole leaks in the pipe that lets small droplets of water come out and produce corrosion of the pipe like seen here. It would be well worth checking out this area of the copper pipe to see if there is a pending disaster waiting to happen.
Comment: I'm definitely concerned about pinhole leaks. I have acidic water. It would be really sucky to re-do the bathroom and then have a pinhole leak.
Comment: I had a set of pinhole leaks like this in piping above my water heater.
Comment: I decided not to risk it and will replace the pipes.


DDR3 U-DIMM Signal Reference Plain

Question: I am doing the PCB layout of a DDR3 U-DIMM and I have run into a perceived gap in the JEDEC DDR3 DIMM standards and am hoping to get some input from a DDR3 SME who could clarify the Address/Control reference plane.
Long story short, I am designing a U-DIMM card to accommodate parts testing of a fully packaged DDR3 memory module. There is a 199 pin BGA memory which I am going to be testing using a Zynq 7000 SoC on a custom Dev board with a 240 pin DDR3 U-DIMM slot. Another engineer previously did a test with the same memory using a COTS Zynq 7000 dev board using a SO-DIMM form factor for the test board. So I am referencing his design, which has lead me to reference both the U-DIMM and SO-DIMM JEDEC standards.
The gap I have run across surrounds the reference plane for the address/command group's transmission lines. The SO-DIMM JEDEC standards specifically mention these being run adjacent to VDD in two places.

JEDEC Standard No. 21C: 4.20.21 - 204-Pin EP3-6400/EP3-8500/EP3-10600/EP3-12800 DDR3 SDRAM
72b-S0-DIMM Design Specification: Section 5.3 Signal referencing guideline

Specifies Vdd as reference for Clock nets, pre/post-register address and command nets in a table

JEDEC Standard No. 21C: 4.20.18 - 204-Pin DDR3 SDRAM Unbuffered SO-DIMM Design
Specification: Section 6. SO-DIMM Wiring Details -> Cross Section Recommendations

Notes, in an introduction, that "All data is referenced to Vss and all address/command and clocks are referenced to Vdd."

The U-DIMM standard doesn't include any details about reference plains at all.
JEDEC Standard No. 21C: 4.20.19 - 240-Pin PC3-6400/PC3-8500/PC3-10600/PC3-12800/PC3-14900/PC3-17000 DDR3 SDRAM Unbuffered DIMM Design Specification
Skips/leaves out the Signal referencing guideline section, and leaves out mention of referencing in the Cross section recommendations section.
At this point I would speculate that the stricter SO-DIMM specification (thinner stackup -> fewer layers, smaller board) lead to the need to specify how to run something adjacent to something other than VSS, and if you have to do that it should be Address/Control <-> VDD. Where the less strict full size DIMM physical size (thicker stackup -> more layers, larger board) should not need this accommodation, so it isn't mentioned. However, the pinout of the 240-pin places all the Vdd supply pins adjacent to the address/control group, rather than Vss.
The ultimate guidance is whether my DIMM card should have address/command nets routed adjacent to a Vdd plane or a Vss plane, and whether the Zynq 7000 SoC dev board should have address/command routed adjacent to Vdd or Vss. I couldn't find details about how PC motherboard manufacturers do this.
Answer: Someone over on Redit was able to provide some insight.
https://www.reddit.com/r/PCB/comments/1b47hjm/ddr3_udimm_signal_reference_plain/

DDR3 U-DIMM Signal Reference Plain


What is the relationship of sound volume to atmospheric pressure?

Question: what is the relationship of sound volume to atmospheric pressure? if I was in a plane with a cabin pressure equal to 8000 feet would the volume drop be noticable?
Comment: also see here: https://physics.stackexchange.com/q/672/
Comment: Related:  http://physics.stackexchange.com/q/192996/59023
Answer: While sound intensity is usually measured in decibels (dB), the physical effect of sound can be measured as the amplitude of pressure in the medium in which it is propagating (in this case, Earth's atmosphere).  Remember that decibels are a logarithmic scale, but pressure is measured in SI units as pascals (Pa).
The accepted scientific standard for the threshold of human hearing is defined as $\text{0 dB}$ sound pressure level (SPL) on the logarithmic decibel scale, and the equivalent pressure is $\textrm{20 }\mu \text{Pa}$.
Standard atmospheric pressure at sea level is $\text{101325 Pa}$, and this converts to $\text{194.1 dB}$ SPL.
\begin{equation*}
\text{20} \cdot \log_{10}\dfrac{101325\text{ Pa}}{0.00002\text{ Pa}} = 194.1 \text{ dB}.
\end{equation*}
WARNING:  Do NOT attempt to reproduce, much less listen to sounds of this intensity.  Sounds above $\text{120 dB}$ SPL can permanently damage your hearing and also cause bodily injury.  Interestingly, $\text{120 dB}$ SPL is "only" $\text{20 Pa}$.
As you climb higher in the atmosphere, the pressure does indeed decrease, and at $\text{8000 ft}$ the standard pressure is $\text{75263 Pa}$.  Converting this to dB yields $\text{191.5 dB}$.  An interesting correlation is that the difference in theoretical max SPL between two altitudes also indicates the SPL attenuation of ordinary sounds between the two heights (some examples listed below).
Being just $\text{2.6 dB}$ "softer" than at sea level, I don't think anyone would notice a difference.
Here are some maximum SPLs (and attenuation relative to sea level) calculated based on the pressure at various altitudes of the ISA:

At $\text{8848 m} / \text{29029 ft}$ (Mount Everest):  $183.9 \text{ dB}$ max SPL, $10.2\text{ dB}$ attenuation.  Just noticeably quieter than at low altitudes.
At $\text{30000 m} / \text{98400 ft}:  155.4 \text{ dB}$ max SPL, $38.7\text{ dB}$ attenuation.  About the same as most industrial-grade hearing protection.
At $\text{50000 m} / \text{164000 ft}:  131.6 \text{ dB}$ max SPL, $62.5\text{ dB}$ attenuation.  A human voice a few feet away would not be audible.
At $\text{100000 m} / \text{62.1 mi}$ (The Kármán Line):  $62.2 \text{ dB}$ max SPL, $131.9\text{ dB}$ attenuation.  Sounds loud enough to permanently damage hearing and cause injury at sea level are inaudible at this height.
At $\text{400000 ft}$ (NASA "entry interface" for manned spacecraft re-entry):  $33.7 \text{ dB}$ max SPL, $160.4 \text{ dB}$ attenuation.  Imagine the volume of sound standing right next to the Space Shuttle at launch--even this would be inaudible at that height.
At $\text{200 km}: 3.69 \text{ dB}$ max SPL.  The loudest noise theoretically possible at this height would barely be audible.  The pressure calculated at this height is merely theoretical; actual pressure would be highly variable.

NOTE: I haven't factored in the maximum frequency heard at altitude--the maximum frequency decreases as height increases, due to the mean free path getting larger.
EDIT Corrected minor math errors in attenuation values. Added Mount Everest bullet.
ADDENDUM As a practical example of how sound attenuation "happens" as you increase altitude, check out this video of the STS-115 launch from the external tank (ET) camera.  Notice that the "rumble" of the SRBs and SSMEs tends to diminish to nearly inaudible (the ET camera records audio, too) as the vehicle climbs higher.
Comment: >At 50000 m/164000 ft:131.6 dB max SPL, 62.5 dB attenuation. A human voice a few feet away would not be audible. One reason it would be inaudible is that in less than half a minute at that altitude the experimenters would be unconscious.
Comment: @girarde:  Yes, but the question was about sound volume with relation to altitude and not about the physiological effects of hypoxia.  *NOT* that I disagree with you, though. :-)
Answer: There is not going to be any generic answer to your question.
Suppose I drop a book on the floor, and the book hits the floor with 1 joule of kinetic energy. Let's assume that there is very little internal friction in the book or the floor, so that none of the energy can be dissipated into heat, and that the floor is very stiff, so that no energy can be transmitted as vibrations in the floor. Then by conservation of energy, the amount of sound energy is going to be exactly 1 joule. This argument is independent of whether this is the floor of my house, near sea level, or the deck of an airplane. It only depends on the assumption that the mechanisms for dissipating energy into heat and vibration are much less efficient than the mechanism for dissipating it into sound waves in the air.
On the other hand, let's say for the sake of argument that in a hand clap at sea level, 1/3 of the energy goes into sound, 1/3 into vibrations transmitted down through the arms, and 1/3 into heating in the palms. In an airplane, these 1:1:1 proportions will be altered, because the conversion of energy into sound waves in air will be less efficient. Because the competition among the three dissipative processes is fairly equal, there will be a big reduction in loudness when the pressure is low.
So the answer is that it depends completely on the details of the process of production of the sound waves.
In the extreme case, suppose you do these experiments in outer space. Outer space is not a perfect vacuum, so it can support sound waves. However, the efficiency of the coupling to sound waves is extremely low, so almost any other mechanism for dissipating the energy will be many orders of magnitude more efficient.
Answer: I have no way of knowing if what you just said is true or not. I approached this question regarding passages in books about the civil war, referring to the fact that occasionally an atmospheric inversion/anomaly appears to completely muffle the sound of cannon fire, when you can actually see the gun fire. At some distance, say 650 yards, you see the puff of smoke, but NEVER hear the report. I'm sure there is an equation to explain it, but a simple definition would suffice.


Pointer Arithmetic

Question: Does anyone have any good articles or explanations (blogs, examples) for pointer arithmetic?  Figure the audience is a bunch of Java programmers learning C and C++.
Comment: http://www.c-faq.com section 4
Answer: Here is where I learned pointers: https://cplusplus.com/doc/tutorial/pointers/
Once you understand pointers, pointer arithmetic is easy. The only difference between it and regular arithmetic is that the number you are adding to the pointer will be multiplied by the size of the type that the pointer is pointing to. For example, if you have a pointer to an int and an int's size is 4 bytes, (pointer_to_int + 4) will evaluate to a memory address 16 bytes (4 ints) ahead.
So when you write
(a_pointer + a_number)

in pointer arithmetic, what's really happening is
(a_pointer + (a_number * sizeof(*a_pointer)))

in regular arithmetic.
Comment: But a Pointer address can't be added yo another one. Why
Comment: The article linked to is great, makes sooo much more sense now!
Comment: @MartinErhardt, you can like this p = (T*)(((long)p) + ((long)p2))
Answer: First, the binky video may help. It's a nice video about pointers. For arithmetic, here is an example:
int * pa = NULL;
int * pb = NULL;
pa += 1; // pa++. behind the scenes, add sizeof(int) bytes
assert((pa - pb) == 1);

print_out(pa); // possibly outputs 0x4
print_out(pb); // possibly outputs 0x0 (if NULL is actually bit-wise 0x0)

(Note that incrementing a pointer that contains a null pointer value strictly is undefined behavior. We used NULL because we were only interested in the value of the pointer. Normally, only use increment/decrement when pointing to elements of an array).
The following shows two important concepts

addition/subtraction of a integer to a pointer means move the pointer forward / backward by N elements. So if an int is 4 bytes big, pa could contain 0x4 on our platform after having incremented by 1.
subtraction of a pointer by another pointer means getting their distance, measured by elements. So subtracting pb from pa will yield 1, since they have one element distance.

On a practical example. Suppose you write a function and people provide you with an start and end pointer (very common thing in C++):
void mutate_them(int *begin, int *end) {
    // get the amount of elements
    ptrdiff_t n = end - begin;
    // allocate space for n elements to do something...
    // then iterate. increment begin until it hits end
    while(begin != end) {
        // do something
        begin++;
    }
}

ptrdiff_t is what is the type of (end - begin). It may be a synonym for "int" for some compiler, but may be another type for another one. One cannot know, so one chooses the generic typedef ptrdiff_t.
Comment: Hate to point it out, but your first example is undefined behavior. ;)
You're not allowed to increment a null pointer. :)
Comment: I generally find it difficult to follow video tutorials but this binky one was super simple, awesome and funny :). Nails the basics in just 3 minutes.
Comment: It should be noted that  or  defines ptrdiff_t (per the standard).  It is not a special type, I would say, just a name (typedef) for the type the compiler spits out.
Comment: yeah indeed, must be some signed integer type. didn't want to go too much into details.
Comment: jalf, thanks for pointing that out. i added a note about it :) well now my saying "if NULL is actually bitwise 0" is broken, since 0 is a zero integer. but i think u know what i mean hehe
Comment: The link no longer has any videos.
Answer: applying NLP, call it address arithmetic.  'pointers' are feared and misunderstood mostly because they are taught by the wrong people and/or at the wrong stage with wrong examples in the wrong way.  It is no wonder that nobody 'gets' it.
when teaching pointers, the faculty goes on about "p is a pointer to a, the value of p is the address of a" and so on.  it just wont work.  here is the raw material for you to build with.  practice with it and your students will get it.
'int a', a is an integer, it stores integer type values.
'int* p', p is an 'int star', it stores 'int star' type values.
'a' is how you get the 'what' integer stored in a (try not to use 'value of a')
'&a' is how you get the 'where' a itself is stored (try to say 'address')
'b = a' for this to work, both sides must be of the same type.  if a is int, b must be capable of storing an int. (so ______ b, the blank is filled with 'int')
'p = &a' for this to work, both sides must be of the same type.  if a is an integer,  &a is an address, p must be capable of storing addresses of integers.  (so ______ p, the blank is filled with 'int *')
now write int *p differently to bring out the type information:
int*   |    p
what is 'p'? ans: it is 'int *'.  so 'p' is an address of an integer.
int    |    *p
what is '*p'? ans: it is an 'int'.  so '*p' is an integer.
now on to the address arithmetic:
int a;
a=1;
a=a+1;
what are we doing in 'a=a+1'?  think of it as 'next'. Because a is a number, this is like saying 'next number'.  Since a holds 1, saying 'next' will make it 2.
// fallacious example. you have been warned!!!
int *p
int a;
p = &a
p=p+1;
what are we doing in 'p=p+1'?  it is still saying 'next'.  This time, p is not a number but an address.  So what we are saying is 'next address'.  Next address depends on the data type, more specifically on the size of the data type.
printf("%d %d %d", sizeof(char), sizeof(int), sizeof(float));
so 'next' for an address will move forward sizeof(data type).
this has worked for me and all of the people I used to teach.
Comment: Disagree with the 'next'. It is unclear if the next pointer is 4b away or if it refers to the next 4b that can be pointed to (reusing the lower 3b from before). This is rarely used, sure, but the analogy given here does not work for me.
Comment: This is actually a really clear answer. I really like the part explaining visually that _"*p"_ is an integer.
Answer: I consider a good example of pointer arithmetic the following string length function:
int length(char *s)
{
   char *str = s;
   while(*str++);
   return str - s;
}

Comment: The example does not show that a pointer is not always incremented by 1 byte, which is often missed.
Answer: So, the key thing to remember is that a pointer is just a word-sized variable that's typed for dereferencing. That means that whether it's a void *, int *, long long **, it's still just a word sized variable. The difference between these types is what the compiler considers the dereferenced type. Just to clarify, word sized means width of a virtual address. If you don't know what this means, just remember on a 64-bit machine, pointers are 8 bytes, and on a 32-bit machine, pointers are 4 bytes. The concept of an address is SUPER important in understanding pointers. An address is a number capable of uniquely identifying a certain location in memory. Everything in memory has an address. For our purposes, we can say that every variable has an address. This isn't necessarily always true, but the compiler lets us assume this. The address itself is byte granular, meaning 0x0000000 specifies the beginning of memory, and 0x00000001 is one byte into memory. This means that by adding one to a pointer, we're moving one byte forward into memory. Now, lets take arrays. If you create an array of type quux that's 32 elements big, it will span from the beginning of it's allocation, to the beginning of it's allocation plus 32*sizeof(quux), since each cell of the array is sizeof(quux) big. So, really when we specify an element of an array with array[n], that's just syntactic sugar (shorthand) for *(array+sizeof(quux)*n). Pointer arithmetic is really just changing the address that you're referring to, which is why we can implement strlen with
while(*n++ != '\0'){
  len++;
}

since we're just scanning along, byte by byte until we hit a zero. Hope that helps!
Answer: There are several ways to tackle it.
The intuitive approach, which is what most C/C++ programmers think of, is that pointers are memory addresses. litb's example takes this approach. If you have a null pointer (which on most machines corresponds to the address 0), and you add the size of an int, you get the address 4. This implies that pointers are basically just fancy integers.
Unfortunately, there are a few problems with this. To begin with, it may not work.
A null pointer is not guaranteed to actually use the address 0. (Although assigning the constant 0 to a pointer yields the null pointer).
Further, you're not allowed to increment the null pointer, or more generally, a pointer must always point to allocated memory (or one element past), or the special null pointer constant 0.
So a more correct way of thinking of it is that pointers are simply iterators allowing you to iterate over allocated memory.
This is really one of the key ideas behind the STL iterators. They're modelled to behave very much as pointers, and to provide specializations that patch up raw pointers to work as proper iterators.
A more elaborate explanation of this is given here, for example.
But this latter view means that you should really explain STL iterators, and then simply say that pointers are a special case of these. You can increment a pointer to point to the next element in the buffer, just like you can a std::vector<int>::iterator. It can point one element past the end of an array, just like the end iterator in any other container. You can subtract two pointers that point into the same buffer to get the number of elements between them, just like you can with iterators, and just like with iterators, if the pointers point into separate buffers, you can not meaningfully compare them. (For a practical example of why not, consider what happens in a segmented memory space. What's the distance between two pointers pointing to separate segments?)
Of course in practice, there's a very close correlation between CPU addresses and C/C++ pointers. But they're not exactly the same thing. Pointers have a few limitations that may not be strictly necessary on your CPU.
Of course, most C++ programmers muddle by on the first understanding, even though it's technically incorrect. It's typically close enough to how your code ends up behaving that people think they get it, and move on.
But for someone coming from Java, and just learning about pointers from scratch, the latter explanation may be just as easily understood, and it's going to spring fewer surprises on them later.
Comment: It is important to be aware that a pointer is not always 4 bytes long. On some systems (64bit) it may be 8 bytes long. For example never assume a pointer is the same size as a integer. Too many errors have been made because programmers hide pointers in integers!
Comment: True, that's an important point. I intended the 4 byte thing to just be an example, but I should probably have made that clearer, because pointers are certainly no *guaranteed* to be 4 bytes, and they often aren't.
Answer: This is one pretty good at link here about Pointer Arithmetic
For example:
Pointer and array
Formula for computing the address of ptr + i where ptr has type T *. then the formula for the address is:
addr( ptr + i ) = addr( ptr ) + [ sizeof( T ) * i ]
For for type of int on 32bit platform, addr(ptr+i) = addr(ptr)+4*i;
Subtraction
We can also compute ptr - i. For example, suppose we have an int array called arr.
    int arr[ 10 ] ;
    int * p1, * p2 ;
p1 = arr + 3 ; // p1 == & arr[ 3 ]
p2 = p1 - 2 ; // p1 == & arr[ 1 ]

Comment: This may be true -- there is no guarantee that an int is 32 bits wide on a 32 bit platform -- the rule is that it must be able to represent [−32767,+32767], which just means it must be at least 16 bits wide. You might have a 32 bit platform where the compiler sees ints as 16 or 64 bit wide.
Comment: Circular definitions @Clearer - usually when we talk of the "bit-width" of a platform, we're referring to the size of an `int` (which is supposed to be the 'natural' integer type).
Comment: @TobySpeight "Usual" is irrelevant.

Pointer Arithmetic


Looking for plain language resources

Question: I'm familiar with Letting go of the Words and www.plainlanguage.gov, and I have seen Sandra Fisher-Martins' Ted Talk, but I was wondering if there were any other sources, particularly academic sources, that talk about plain language, especially ones with a social justice bend.
Comment: This question appears to be off-topic because it seems to be more about English Language & Usage than UX.
Comment: The choice of tone of voice and complexity of language can have a big impact on how people interact and respond to a website. This is about using language to effect a particular user experience, and not so much about how language is used generally.
Comment: @Erics While I agree with you on that front, the question as asked is not related to UX at all. Plain language is about writing federal agency legal without legal jargon, which is more on the realm of English Language and Usage than UX.  There is nothing here about the experience of users as applied to design. Social justice also has nothing to do with UX.
Comment: What exactly are plain languages?
Comment: I could have included more detail in the question, but I totally disagree with the idea that plain language and social justice have nothing to do with UX. I have dyslexia and how web content or language in a UI is written and structured has a huge impact on how accessible that design is. And when an app or website is about access to resources (financial, educational, etc.) you better believe an accessible, easy to use UX is a social justice issue. Finally, you don't have to be dyslexic to get a better user experience from better language (e.g. better labels, instructions etc).
Answer: I've found the following peer-reviewed academic journals on the Plain Language topic that you can check out:
The Case for Plain Language
By: Douglas, Kristin Vickers; Smith, Becky; Parker, Beverly; Mehr, Holly; Ruud, Kari; Hathaway, Julie; Behrenbeck, Julia; O'Brien, Michael; Smith, Steven; Patient Education Management, 2011 Jul: Supplement: 1-4. (journal article) ISSN: 1087-0296
Introducing Plain Language Principles to Business Communication Students
By: Greer, Rachelle R. Business Communication Quarterly. Jun2012, Vol. 75 Issue 2, p136-152.
Can the Law Speak Directly to its Subjects? The Limitation of Plain Language
By: Assy, Rabeea. Journal of Law & Society. Sep2011, Vol. 38 Issue 3, p376-404. 29p.
AND THE WINNER IS: HOW PRINCIPLES OF COGNITIVE SCIENCE RESOLVE THE PLAIN LANGUAGE DEBATE
By: Baker, Julie A.. UMKC Law Review , Winter2011, Vol. 80 Issue 2, p287-305, 19p
PLAIN LANGUAGE LEGISLATION: A COMPARISON OF APPROACHES
By: Leete, Burt A. American Business Law Journal. Winter81, Vol. 18 Issue 4, p511. 14p.
Plain English Laws: Symbolic or Real?
By: Timm, Paul R.; Oswald, Daniel. Journal of Business Communication. Spring85, Vol. 22 Issue 2, p31-38. 8p.
And this UX oriented article by Janelle Estes:
User-centric vs. Maker-centric Language: 3 Essential Guidelines
Comment: Thank you this is exactly the kind of thing I was looking for!

Looking for plain language resources