Easy way to see saved NSUserDefaults?

Question: Is there a way to see what's been saved to NSUserDefaults directly?  I'd like to see if my data saved correctly.
Comment: Use this to get the location of your apps directory: print(NSHomeDirectory()) from that location, go to Library>Preferences> this will be where NSUserDefaults is saving your data.
Comment: Using XCode 12.3 on Catalina UserDefaults.plist is visible in project resources but does not contain preferences values.
Comment: The file suggested by Bobby is in a hidden folder  not visible to Finder unless hidden items are shown by clicking cmd-shift-period
Answer: You can print all current NSUserDefaults to the log:
Just keys:
NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);

Keys and values:
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

Comment: Apple could make a simple viewer in XCode for this. Like the plist viewer. But no, they don't want to make it easy.
Comment: THX, this one is more efficient~
Answer: You can find the pList file for your app in the simulator if you go to:
/users/your user name/Library/Application Support/iPhone Simulator/<Sim Version>/Applications
This directory has a bunch of GUID named directories.  If you are working on a few apps there will be a few of them.  So you need to find your app binary:
find . -name foo.app
./1BAB4C83-8E7E-4671-AC36-6043F8A9BFA7/foo.app

Then go to the Library/Preferences directory in the GUID directory.  So:
cd 1BAB4C83-8E7E-4671-AC35-6043F8A9BFA7/Library/Preferences

You should find a file that looks like:
<Bundle Identifier>.foo.pList

Open this up in the pList editor and browse persisted values to your heart's content.
Comment: The path has changed to: ~/Library/Developer/CoreSimulator/Devices
Comment: I've found this has changed in later versions of XCode. You'll now find it in a directory under the current ios version number instead of User - eg /users/your user name/Library/Application Support/iPhone Simulator/4.3/Applications
Comment: Interesting... It seems that if you're doing OCMock / SenTestingKit unit testing with `NSUserDefaults`, then the `NSUserDefaults` aren't persisted to a .plist file but rather managed in memory: http://stackoverflow.com/questions/6193597/where-does-ocunit-store-nsuserdefaults
Comment: How can I view it for an already installed application? My client downloaded the application from the appstore, and something is wrong. I need to check the NSUserDefaults file
Comment: Your client - if you can talk to him and he somewhat savvy - could use a tool like PhoneView to get access to his phones filesystem and copy the file off the phone to send it to you.
Comment: For those people wanting to get access to the folder in the simulator, see Jeff's answer below about SimPholders - a great little app to find the folder easily for you: https://simpholders.com/
I have no connection to the author of the app at all, but it is very useful.
Comment: What if my simulator version in not there. I am using latest Xcode 7.2 iOS SDK 9.2
Comment: @Kyll sorry for the mistake.I understood :)
Comment: I have no `~/Library` (`/Users//Library`) folder
Comment: (on macOS Sierra)
Comment: In Xcode 10, the plist file seems to have non of the keys set in `UserDefault.standard`...
Answer: In Swift we can use the following:-
Swift 3.x & 4.x
For getting all keys & values:
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
    print("\(key) = \(value) \n")
}

For retrieving the complete dictionary representation of user defaults:
print(Array(UserDefaults.standard.dictionaryRepresentation()))

For retrieving the keys:
// Using dump since the keys are an array of strings.
dump(Array(UserDefaults.standard.dictionaryRepresentation().keys))

For retrieving the values:
We can use dump here as well, but that will return the complete inheritance hierarchy of each element in the values array. If more information about the objects is required, then use dump, else go ahead with the normal print statement.
// dump(Array(UserDefaults.standard.dictionaryRepresentation().values))
print(Array(UserDefaults.standard.dictionaryRepresentation().values))

Swift 2.x
For retrieving the complete dictionary representation of user defaults:
print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation())

For retrieving the keys:
print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array)

For retrieving the values:
print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().values.array)

Answer: You can check the values for each key in the array, returned by
[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]

Comment: This worked in the debugger too by using this command: (lldb) "po [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]"
Answer: I sometimes use the following snippet to print out the location of my NSUserDefaults file when running in the simulator

NSArray *path = NSSearchPathForDirectoriesInDomains(
   NSLibraryDirectory, NSUserDomainMask, YES);
NSString *folder = [path objectAtIndex:0];
NSLog(@"Your NSUserDefaults are stored in this folder: %@/Preferences", folder);

It yields the path to the preferences folder

Your NSUserDefaults are stored in this folder: /Users/castle/Library/Application Support/iPhone Simulator/User/Applications/BC5056A0-F46B-4AF1-A6DC-3A7DAB984960/Library/Preferences

Your NSUserDefaults file is located in the preferences folder and named according to your prefix and appliation name e.g.
dk.castleandersen.dreamteam.grid.plist

I expect the same to be true for the actual device.
Comment: i like this response. It's stable and will always work, hopefully!
Answer: Easy, since the plist file name is <app-bundle-identifier>.plist, you can use find command to find its path. But it will take very long if you search your whole computer, so you have to pick a good scope, like ~/Library/Developer/CoreSimulator for Xcode 6.
example:
find ~/Library/Developer/CoreSimulator -type f -name com.awesome.app.plist
the output will be something like this...
/Users/hlung/Library/Developer/CoreSimulator/Devices/B61913F6-7D7C-4E45-AE2F-F45220A71823/data/Containers/Data/Application/E4CC51CF-11E5-4168-8A74-6BAE3B89998F/Library/Preferences/com.awesome.app.plist

And from there you can use open command. Or if you use iTerm2, just command-click on the path to open it.
Answer: In Swift 4.0
//func dictionaryRepresentation() -> [String : AnyObject]

because dictionaryRepresentation of NSUserDefaults.standardUserDefaults() returns [String : AnyObject]
We cast it into an NSDictionary. Then by surrounding it in parenthesis '()' will allow us to to call .allKeys or .allValues just as you would on any NSDictionary
 print((UserDefaults.standard.dictionaryRepresentation() as NSDictionary).allKeys)

Answer: Use below code.
NSLog(@"NSUserDefault: %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);

Comment: Brilliant!  Interesting how the best answers are usually the shortest.  Rarely is navigating directories in terminal mode necessary.  Evidently, the geeks like the back door approach, maybe the secret hacker in them?
Comment: Thanks, But cant getting you. What you want to say?
Answer: For OS X applications, instead of finding the application's defaults plist file, it is simpler to use the defaults command line utility.

NAME
 defaults -- access the Mac OS X user defaults system

SYNOPSIS
 defaults [-currentHost | -host hostname] read [domain [key]]

 defaults [-currentHost | -host hostname] read-type domain key

 defaults [-currentHost | -host hostname] write domain { 'plist' | key 'value' }

 defaults [-currentHost | -host hostname] rename domain old_key new_key

 defaults [-currentHost | -host hostname] delete [domain [key]]

 defaults [-currentHost | -host hostname] { domains | find word | help }

DESCRIPTION
defaults allows users to read, write, and delete Mac OS X user defaults from a command-line shell. Mac
  OS X applications and other programs use the defaults system to record user preferences and other
  information that must be maintained when the applications aren't running (such as default font for new
  documents, or the position of an Info panel). Much of this information is accessible through an appli-
  cation's Preferences panel, but some of it isn't, such as the position of the Info panel. You can
  access this information with defaults

Example:
$ defaults read com.apple.Safari
{
    AutoplayPolicyWhitelistConfigurationUpdateDate = "2018-08-24 17:33:48 +0000";
    AutoplayQuirksWhitelistConfigurationUpdateDate = "2018-08-24 17:33:48 +0000";
    DefaultBrowserPromptingState2 = 4;
    ...

Answer: For Xcode 7
NSUserDefaults standardDefaults are stored here:
/Users/{USER}/Library/Developer/CoreSimulator/Devices/{UUID}/data/Containers/Data/Application/{UUID}
NSUserDefaults for a suite/app group are stored here:
/Users/{USER}/Library/Developer/CoreSimulator/Devices/{UUID}/data/Containers/Shared/AppGroup/{UUID}/Library/Preferences/{GROUP_NAME}.plist
I would recommend using https://github.com/scinfu/NCSimulatorPlugin because these days everything is behind UUIDs and are a pain to find. It allows easy access to your simulator app directories.
Answer: I built this method based on Morion's suggestion for better presentation. Use it by calling [self logAllUserDefaults]
- (void) logAllUserDefaults
{
    NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
    NSArray *values = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues];
    for (int i = 0; i < keys.count; i++) {
        NSLog(@"%@: %@", [keys objectAtIndex:i], [values objectAtIndex:i]);
    }
}

Comment: May I suggest that you call that function "logAllUserDefaults" since it doesn't actually "get" the defaults?
Comment: Or simply.. `NSLog(@"%@", [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] debugDescription]);` (Almost as in the top-voted answer above.)
Comment: Right, @markrickert. Maybe one could create a dictionary from it and return it, then.
Answer: Look for the Mac app called SimPholders2.  It lives in the menu bar, and lists all of the simulators you've used, and then shows each of your apps.  Select one and you get a new Finder window, already open to the app's directory.  This makes it super easy to find your app and all of it's directories.  It's a huge time saver (and I readily donated to the author).
Answer: Simulator App
This shell script search for the name of the app, obtain the bundle id, and open folders containing the Plist files.
#!/bin/bash

appname="$1"
[ -z $appname ] && read -p "Application name : " appname

apppath=$(find ~/Library/Developer/CoreSimulator/Devices/ -name "$appname.app" -print -quit)
if [[ ! -z $apppath ]]; then
    appbundle=$(osascript -e "id of app \"$apppath\"")
    find ~/Library/Developer/CoreSimulator/Devices/ -name "$appbundle.plist" -exec bash -c 'open "$(dirname "$1")"' -- {} \;
else
    echo "No application found by that name: $appname.app"
fi

Extended script version
Usage: iphone-app-folder "My App"
#!/bin/bash
appname="$1"
[ -z "$appname" ] && read -p "Application name : " appname

apppath=$(find ~/Library/Developer/CoreSimulator/Devices -name "$appname.app" -print -quit)
if [[ ! -z $apppath ]]; then
    appbundle=$(osascript -e "id of app \"$apppath\"")
    echo "Found app $appname (${appbundle})"
    echo -e "\033[1;30m$apppath\033[0m"
    plists=$(find ~/Library/Developer/CoreSimulator/Devices -name "$appbundle.plist" -print -quit)
    count=$(echo plists | wc -l | sed "s/ //g")
    if [[ $count -eq 1 ]] && [[ -f "$plists" ]]; then
        echo -e "\033[1;32mUserDefaults found for $appname\033[0m"
        echo -e "\033[1;30m$plists\033[0m"
        plistutil -i "$plists"
        /usr/bin/open $(dirname "$plists")
    elif [[ ${#plists} -gt 0 ]]; then
        echo -e "\033[1;32mUserDefaults found for $appname\033[0m"
        i=1
        while read line; do
            echo "[${i}] ${line} "
            i=$((i+1))
        done < <(echo "$plists")
        echo
        read -p "Select defaults to read: [1-${count}] " choice
        plist=$(echo ${plists} | sed -n "${choice}p")
        plistutil -i "$plist"
        /usr/bin/open $(dirname "$plist")
    else
        echo -e "\033[31mNo UserDefaults plist found for $appname\033[0m"
    fi
else
    echo -e "\033[31mNo application found by that name: $appname.app\033[0m"
fi

Found app My App (com.organisation.MyApp)
  /Users/organisation/Library/Developer/CoreSimulator/Devices/3E4C8DC3-6FF4-428F-A624-B78DBE0B8C83/data/Containers/Bundle/Application/960A5232-219D-4C46-8CA3-01E259D8DDAD/My App.app
UserDefaults found for My App

Mac App
defaults read com.bundleid.app

Answer: In Swift 2.2
let path = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
let folder = path[0]
NSLog("Your NSUserDefaults are stored in this folder: \(folder)/Preferences")

will print out NSUserDefaults's plist file folder location in Xcode debug console. Copy  the path string. Open your Finder, select Go to Folder in Go menu item, Paste the path string. Double click the plist file. You will see the contents in your Xcode editor.
Only work in Simulator
Thanks @Niels Castle
Comment: This is the only solution that worked for finding the userdefaults plist on simulator for xcode 9.4
Answer:
Swift 5 Xcode 11.2 Solution

This is the whole path where your UserDefaults key values will be in a plist file. Follow and find your app bundle identifier .plist file.

/Users/'Your User Name'/Library/Developer/CoreSimulator/Devices/4176EED3-B9FC-4C77-A25E-ASD201B9FDFG2/data/Containers/Data/Application/56D7CE31-9A8B-4371-9B0F-9604E239423B0/Library/Preferences

Here "4176EED3-B9FC-4C77-A25E-ASD201B9FDFG2" is your Device ID
and "56D7CE31-9A8B-4371-9B0F-9604E239423B0" is your Application ID
I normally get them by sorting folders by last Date Modified in Finder. And most recent edited folder is my device ID and App ID.
Enjoy!
Answer: I keep a shortcut on my desktop to the simulator's folder where it keeps the apps, ie:
/Users/gary/Library/Application Support/iPhone Simulator/User/Applications

Sorted by most recent date, then just go into the most recent app folder Library/Preferences and view the file in the plist editor.
Answer: Swift 3
print(UserDefaults.standard.dictionaryRepresentation())

Answer: For MacOS apps
Go to: /Users/{User}/Library/Containers/com.{your company}.{your app}/Data/Library/Preferences and open your app's pList with Xcode.
Answer: You could NSLog each value you set, like:
NSLog(@"%@",[[NSUserDefaults standardDefaults] stringForKey:@"WhateverTheKeyYouSet"]);

Answer: After reading this question's accepted answer, I put together this simple script that opens the plist files used by the iOS simulator to store the NSUserDefaults preferences, and while it assumes a certain setup (fits mine perfectly), it may work as a starting point for others.
$ cat open-prefs-plist.sh
#!/bin/sh

# The project name based on the workspace path, e.g. "MyProject" from "./MyProject.xcworkspace"
WORKSPACE_NAME=$(echo `find . -name *.xcworkspace -type d -exec basename {} \;` | cut -d'.' -f1)
SIMULATOR_PATH="$HOME/Library/Application Support/iPhone Simulator"
# The App's bundle ID taken from its info plist, e.g "com.myproject" from "./MyProject/MyProject-Info.plist"
BUNDLE_ID=`/usr/libexec/PlistBuddy -c Print:CFBundleIdentifier $WORKSPACE_NAME/$WORKSPACE_NAME"-Info.plist"`
# Open all plist files in the simulator path that match the app's bundle ID
# normally one per iOS version
find "$SIMULATOR_PATH" -name $BUNDLE_ID".plist" -type f -print0 \
    | while IFS= read -r -d '' PLIST; do
    echo $PLIST
    open "$PLIST"
done

Example placement:
$ ls -1
MyProject
MyProject Tests
MyProject.xcodeproj
MyProject.xcworkspace
Podfile
open-prefs-plist.sh

Comment: @Josh You have to put it alongside your project files (in my example the script is named open-prefs-plist.sh). I've not tested this with the latest Xcode though. I recommend you Flex to inspect this info now. https://github.com/Flipboard/FLEX
Comment: How do I eat this script, with forks or with hands? where do I put it, I mean?
Answer: You can user this to get the full path on user preferences, cache and many other data
print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true))
Answer: You can print out the path for the preferences directory from application:didFinishLaunchingWithOptions: callback in your AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    print(FileManager.default.urls(for: .preferencePanesDirectory, in: .userDomainMask).first!)
    return true
}

Then you can look at the plist file directly to see what's saved in there.
Answer: It will work on upper version SWIFT 4
just put that code in AppDelegate's any method and set breakpoint there
**> let path =
> NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,
> FileManager.SearchPathDomainMask.userDomainMask, true).first**

when you run a project, print "path" and you will get path to reach info.plist with userdefaults
Then just go to finder and paste that path
you are reached on that file
Answer: for users looking to find the new location for preference stored in the simulator.
This is where I find the values stored.
/Users/vikas/Library/Developer/CoreSimulator/Devices/CE5A0444-BD98-4FEE-A839-92728D6E9895/data/Containers/Data/Application/F7430839-ED2C-408A-8A8E-FE7FFAABA8E2/Library/Preferences

since we can see there are big identifiers that are hard to guess from the terminal so I would suggest searching for them in your terminal or finder.
the file name should end with {bundle id}.plist for example com.sellerbuddy.online.plist so you can just head to terminal and hit enter something like below with your app bundle identifier.
find ~/Library/Developer/CoreSimulator/Devices -type f -name "com.sellerbuddy.online.plist"

Easy way to see saved NSUserDefaults?


Windows Kernel - Is there something like ExGetPoolsForTag(pool_tag)?

Question: this is about Windows kernel driver and memory management.
I am really curious about if there is a function (or even any inconvinent approach) to get (or iterate) all memory allocations for a specific pool-tag ?? These are allocated using ExAllocatePoolWithTag(type, size, tag) ...
There are kernel functions using a specific Pool-Tag, now i need to find all allocations made using that Tag?
I am relatively sure that this is not possible (for security reasons), but still need the confirmation about that.
Cheers,
Will

Update:
(about the WinDbg comment below)

kd> !poolfind ObFl

Scanning large pool allocation table for Tag: ObFl (fffffa8002290000 : fffffa8002350000)

Searching NonPaged pool (fffffa8001772000 : ffffffe000000000) for Tag: ObFl

... So this means we have to find a generic way to find the "pool allocation table" or the bounds of the non-paged pool (if required). Sounds promising.

Update2:
There are some ntoskrnl exports: nt!PoolBigPageTable nt!PoolBigPageTableSize nt!PoolBigPageTableHash that i need to check....
Comment: It can't really be due to security reasons, since kernel mode code already has full privileges. Probably more about encapsulation.
Comment: I believe those tags are solely for debug purpose. Almost sure there's no "effective" way to enumerate all the allocations for specific tag. Anyway, why do you need this (apart from debugging)?
Answer: There's no documented way that I am aware of that allows for this from code, however the Windows Kernel Debugger (WinDBG) will allow you to get at this.
See the docs for the !pool, !poolused, !poolfind commands.
Comment: no documented way means that an application shouldn't use it, since it might change in later versions of windows, breaking your application.
Comment: So you mean there has to be a programmatic way...  we will see. :>
Answer: Kernel allocations can be allocated and freed at any time.  If you are iterating over the internal data structures, they may suddenly disappear out from under you and you will bugcheck.
The debugger can walk these structures since it freezes the system first.


Sorting column in dataframe in each group in R

Question: I have a timeseries dataset with price variables and want to sort them. The time ist structured into quarter hours. So each group is marked by 4 rows. I want to sort the first two columns within each group. I used different codes, like order or arrange, but they weren't helpful. I hope someone of you, has a idea. Many thanks!
Answer: order() is a way to sort data frames, that should have worked. Consider sharing the code used--perhaps it is just a usage issue.
Another good way to sort if you're open to using to using data.table is with setkey(). For data.table you can use setkey() to sort, though it will always be ascending (unless descending setkey() ordering is ever added). For smaller datasets it doesn't much matter, but for larger datasets many operations will be faster with data.table than with data frames.
Comment: This is what I thought: df2 <- df1[order(df1$price1)]. And group_by(hour) before doesn't help to sort the values within each group. There must be a code, which says, that each group should be sort seperately.
Comment: Make the group column the first column sorted, then price1, etc., following.
Comment: Okay, thanks. But my group variable is already sorted, every group (hour) has 4 quarter hours, so the rows are numbered by 1 to 4. The main issue is to identify, how the dataset can be sorted within each group, so that the other columns and rows stay unchanged. Thanks for your help!


How can I use smtp to connect email to mail client

Question: Right so we have set up a mail server for our company that does not use imap nor pop at the moment, it is based on smtp port 25 and I can't figure out how to link it with my mail client as it always asks for imap or pop :/
Comment: So you're email server only facilitates sending mail?
Answer: As forcer obliquely mentioned SMTP is for sending mail. And one of the most popular programs to do that is called "Sendmail." Not that you need to know that, but hey...
Anyway to be able to send and receive email you need both an SMTP server and an incoming mail server that speaks either POP or IMAP. I won't go into Exchange here as it is Microsoft's own take on IMAP.
Often times the sending and receiving servers are the same. At work mine is mail.domain.local. It sounds like you may have plugged in the same server (or IP address) for sending email into the receiving (POP/IMAP) mail location in your mail.app. If it didn't work, you will have to bug your IT folks for the POP/IMAP address too.
Comment: Well, mail server is based on this software https://github.com/MLstate/PEPS at the moment, as far as I understood it is all through smtp
Comment: @IlyaKnaup No, SMTP is only for sending email. From glancing through the documentation, I get the impression that PEPS offers webmail only. It's curious that they offer an SMTP server though, and no instructions on how to set up an example client, as you'd need to set up the client-side encryption (otherwise it wouldn't be end-to-end). The documentation seems very poor to me.


How to make default application in android?

Question: I need to add one of my app to my android such that even if it is fully formatted it remains within the android as the default installed app. Can i get help regarding it. I have my android rooted.
Answer: The term you mentioned 'Default app' means i assume you want to make your app as 'System app'. If your phone is rooted successfully you can do this with numerous methods.

File Explorer method
If you have a file explorer with root permission granted (ex. ES File explorer etc), it is very easy.

Just obtain an 'APK' file of your app.
Copy the APK file. Navigate to '/system/app'.  paste it under '/system/app' folder.
Long press 'APK' to change its properties. Under permissions property, click on change and set it to rw- r-- r--. ( Thats user: read and write, group: read only and other: read only. Thats it! Reboot your device.

ADB method
Same can be done with the help of ADB. You just have to copy and paste your Apps APK file under '/system/app' folder.

To do this, connect your device to your pc and make sure you have ADB drivers are installed correctly. Also enable the usb debugging.
Open command prompt and type:
adb shell
su
cd /data/app
mv 'your_app name' /system/app/'your_app_name'. Replace 'your_app_name' with obviously name of your application without quotes.
Again exit shell and reboot.

Apps method
This is most simple method. There are many apps available to do this task. One popular app is 'Titanium Backup'. But as per my knowledge 'convert to system app' feature is paid version only. So i prefer one of above method only.

Tip: do the tricks only if you know what you are doing and you are familiar with android file system at your own risk.
Comment: In adb method, to get the name of your application type command 'ls' it will list all the apps installed.
Comment: Also note that there might be `/system/app-priv` which according so some sources then might be the preferred place (instead of `/system/app`) if it exists.


What is the best way to handle domain-centric validation while providing a rich UI experience?

Question: My company is developing a GUI application that allows users to query a legacy database system and have the results displayed back to them on the screen (the results just come back in a blob of plain-text). I'm struggling with the best way to structure the interaction between the user interface and the domain layer, especially validation of user input.
Basic Use Case

User selects a query to run from a menu in the application.
The application code displays the data entry form for the selected query.
The user enters the parameters for the query. If a field contains invalid data, it is immediately highlighted in red, and its tooltip text is changed to display an error message (i.e. if you are entering a Person query, and you enter a date of birth in the future, for example, the date of birth field will immediately turn red).
When the user clicks Run Query, the application runs a second validation pass; this second validation pass is required in order to run validation checks that involve multiple fields. If the this validation check passes, and all the fields are valid, the query is sent; otherwise, the user is prompted to fix any remaining errors.

My Current Validation/Error Reporting Strategy
Currently, I'm using domain-centric validation, but the overall design seems messy to me and maybe a little too over-engineered. A brief overview of the current design:
Domain layer: I have one class per query. Every query class contains a collection of IQueryField objects that hold the values entered by the user. Each query class implements a common IQueryMessage interface, which defines (among other things) a Validate method. This method is called to enforce message-level validation rules (i.e. rules that must examine the state of multiple fields at once). The IQueryField interface also defines a 'Valdate' method (among other things). This is to support per-field validation rules.
Per-field validation: To handle the per-field validation and error reporting, the data entry code binds each input control to an IQueryField; whenever the user changes the value of a control, it calls the the corresponding IQueryField's Validate method, which in turn fills a Notification object (just a collection of strings at the moment) with any errors detected in the value entered by the user. The user interface code then checks the Notification object and changes the appearance of the user control to indicate an error condition, if necessary.
Message-level validation: When the user tries to send a query, the application calls the Validate method on the IQueryMessage instance associated with the data entry form (at this point, the data binding code has also ensured all the message's fields have been populated from the input controls on the form, and the per-field validation code has been run). If there are any validation errors, the user interface displays them at the top of the form. If there are no errors, the data entry form is closed and the query is serialized and sent over the network.
Is Something Wrong Here?
I feel like something isn't "right" here. I have a few issues with the current design:

I would like the domain-level validation code to indicate the name of any fields that are in error, bur I don't want to hard-code the UI label captions into the domain classes. One possibility I thought of was to have the domain-level Validate methods generate messages with a field placeholder, such as "%s cannot be in the future", and have the UI code fill in the placeholder with the correct label.
The IQueryMessage and IQueryField interfaces both have a method called Validate. I'm thinking this should be extracted into a separate interface, (IValidatable perhaps), but I wonder if I am making things needlessly complex.
I'm using VB6, so I can't use inheritance in my classes (VB6 supports classes but not inheritance). I can only define and implement interfaces. Because of this, and because of the way my current interfaces are designed, I'm duplicating a lot of boiler-plate code in my implementation classes. I am thinking of solving this with an inversion-of-control approach. For example, I was thinking of defining a single concrete QueryField class, which could be initialized with a collection of IValidationRule instances that define what validation rules to use, then the QueryField.Validate() method would just collect the results of executing each rule. This way, the validation rules can be tailored to each field, but the QueryField class can handle all the common field-related stuff (field name, field length, required/not required checks, etc.).

How Can I Improve This?
I'm interested in any refactoring suggestions and hints on improving the current design. Also, I'm not necessary tied down to domain-centric validation; other suggestions are welcome. The main motivation behind using domain-centric validation was to keep increase encapsulation, and allow query message and field objects to be used in a non-GUI environment, without having to rewrite all the validation logic.
Answer:
When you initialize a QueryField object, pass a label to it from the GUI. Then it's the UI that is responsible for setting the label name which seems reasonable to me.
I don't think this is necessary.
What you are describing doesn't really sound like IoC but rather just plain old composition. Since you can't even use inheritance this improvement seems to make sense. Generally you want to prefer composition to inheritance anyways. However if you are almost done with the work then I wouldn't bother refactoring this late in the game.


Can't get javascript to load

Question: I am trying to load a javascript file in my .info file, but I can't tell if it is loading or not. What is the best way to find out if it is loaded and if it is the right path?
Answer: Some things you can try:
The easiest way, in my opinion, is to look at the source of your page. Right click the page of your website and click "View source" (or something similar). Try searching for the reference to the javascript file in there.
This could be somewhat more difficult if you're using Javascript aggregation, which means that your file might be concatenated with other Javascript files into one big file. In that case: open the files you see in your source and search for something that's in your Javascript file.
You could also try to display an alert by appending alert('It works!') to your file.
Edit:
As said by Clive in the comments: you might need to clear your cache for the Javascript file to be included. You can clear the cache at /admin/config/development/performance.
Comment: Beat me to it :) You also need to clear caches after altering the .info file, might be worth mentioning that

Can't get javascript to load


OS with file manager and web browser only

Question: I'm looking for an OS that has only a file manager, and a web browser; i.e. as least bloatware as possible.
What is the best OS like that?
Comment: For what kind of computer/architecture? May it cost something? Does it need to have a GUI?
Comment: Wyse Terminal...
Answer: For simplicity, nothing beats https://en.wikipedia.org/wiki/Chrome_OS
Chrome OS is an operating system designed by Google that is based on the Linux kernel and uses the Google Chrome web browser as its principal user interface. As a result, Chrome OS primarily supports web applications.
Comment: Nevermind. I'll make a new post.
Answer: I agree with Booby, that ChromeOs is a good bet, for simplicity.
Other alternatives would be one of the smaller Linux Distros, such as :

 Puppy Linux(a little over 100***m***B (not gB), loads quickly & runs happily form a USB stick)
 Damn small Linux is even smaller at 50mB, and offers the same functionality
any other lightweight Linux Distro

These have the advantage of running very well on older, lower spec'd machines, an advantage over ChromeOs.
For complete control, Google for "build your own Linux distro", for instance  Linux From Scratch. There are quite a few systems which let you choose components simply by ticking a few check boxes (I like  Suse Studio, where you specify what you want, in the browser, and it generates a distro for you).
And, for the ultimate control, it can be a lot of fun to try Gentoo Linux, which lets you select components and compile each one to truly build your Linux from scratch.
You pays your zer0 eurodollars and you takes your choice.
(sorry about the logos, I got carried away :-)


When do we're say " a few" instead of few?

Question: When do we use 'a few'instead of 'few'? For example, why is it incorrect to say "I have few dollars left" instead of "I have a few dollars left"? Most people reason it should be few dollars because "dollars" is a plural noun.
Comment: It's not incorrect to say, "I have few dollars left." It depends on the circumstance. This question would be better asked on our sister site, [ELL](http://ell.stackexchange.com/)? It's a great site for more fundamental English questions.
Comment: Please [search the site before asking](http://english.stackexchange.com/search?tab=relevance&q=few). It saves both us and yourself a lot of work. It's much easier to type a single word and get your answer immediately than to compose an entire question and sit waiting.
Answer: Few in I have few dollars left is being used as an adjective to qualify dollars. It is a way of stressing that one's dollar supplies are low.
In a few, few is being used as a noun, hence the presence of the article. Idiomatically I have a few dollars left does not stress the limitations of one's dollars, but indicates more positively that one has some dollars left.
The different circumstances in which each might be used could be as follows:
few dollars left - I cannot possibly stay in America any longer, I have few dollars left.
a few dollars left - Hey, I've got a few dollars left, let's go out to dinner this evening.


RSpec Mock Object Example

Question: I am new to mock objects, and I am trying to learn how to use them in RSpec. Can someone please post an example (a hello RSpec Mock object world type example), or a link (or any other reference) on how to use the RSpec mock object API?
Answer: Here's an example of a simple mock I did for a controller test in a rails application:
before(:each) do
  @page = mock_model(Page)
  @page.stub!(:path)
  @page.stub!(:find_by_id)
  @page_type = mock_model(PageType)
  @page_type.stub!(:name)
  @page.stub!(:page_type).and_return(@page_type)
end

In this case, I'm mocking the Page & PageType models (Objects) as well as stubbing out a few of the methods I call.
This gives me the ability to run a tests like this:
it "should be successful" do
  Page.should_receive(:find_by_id).and_return(@page)
  get 'show', :id => 1
  response.should be_success
end

I know this answer is more rails specific, but I hope it helps you out a little.

Edit
Ok, so here is a hello world example...
Given the following script (hello.rb):
class Hello
  def say
    "hello world"
  end
end

We can create the following spec (hello_spec.rb):
require 'rubygems'
require 'spec'

require File.dirname(__FILE__) + '/hello.rb'

describe Hello do
  context "saying hello" do
    before(:each) do
      @hello = mock(Hello)
      @hello.stub!(:say).and_return("hello world")
    end

    it "#say should return hello world" do
      @hello.should_receive(:say).and_return("hello world")
      answer = @hello.say
      answer.should match("hello world")
    end
  end
end

Comment: You are setting up a mock object of the class you are supposed to be speccing/testing which means you are not exercising the class being devlopped at all. Pointless. Mocking is meant to help you surround the class/system under test with objects credibly posing as a real world environment albeit simpler/controlled/self-contained. It is an anti-pattern to use Mocking to check internal workings of the class being developped.
Comment: Also, this answer is out of date. See [tokhi's answer below](https://stackoverflow.com/a/39573538/634576) for how to write a pure mock object and [mine](https://stackoverflow.com/a/39186152/634576) for how to do partial mocking in current RSpec.
Answer: mock is deprecated based on this github pull.
Now instead we can use double - more here...
 before(:each) do
   @page = double("Page")
   end

  it "page should return hello world" do
    allow(@page).to receive(:say).and_return("hello world")
    answer = @page.say
    expect(answer).to eq("hello world")
  end

Answer: I don't have enough points to post a comment to an answer but I wanted to say that the accepted answer also helped me with trying to figure out how to stub in a random value.
I needed to be able to stub an object's instance value that is randomly assigned for example:
class ClumsyPlayer < Player do

  def initialize(name, health = 100)
    super(name, health)
    @health_boost = rand(1..10)
  end
end

Then in my spec I had a problem on figuring out how to stub the clumsy player's random health to test that when they get a heal, they get the proper boost to their health.
The trick was:
@player.stub!(health_boost: 5)

So that stub! was the key, I had been just using stub and was still getting random rspec passes and failures.
So thank you Brian
Answer: Current (3.x) RSpec provides both pure mock objects (as in tokhi's answer) and partial mocking (mocking calls to an existing object). Here's an example of partial mocking. It uses expect and receive to mock an Order's call to a CreditCardService, so that the test passes only if the call is made without having to actually make it.
class Order
  def cancel
     CreditCardService.instance.refund transaction_id
  end
end

describe Order do
  describe '#cancel' do
    it "refunds the money" do
      order = Order.new
      order.transaction_id = "transaction_id"
      expect(CreditCardService.instance).to receive(:refund).with("transaction_id")
      order.cancel
    end
  end
end

In this example the mock is on the return value of CreditCardService.instance, which is presumably a singleton.
with is optional; without it, any call to refund would satisfy the expectation. A return value could be given with and_return; in this example it is not used, so the call returns nil.

This example uses RSpec's current (expect .to receive) mocking syntax, which works with any object. The accepted answer uses the old rspec-rails mock_model method, which was specific to ActiveModel models and was moved out of rspec-rails to another gem.
Answer: Normally you want to use a Mock Object when you want to delegate some functionality to other object but you don't want to test the real functionality on your current test, so you replace that object with other that is easier to control. Let's call this object "dependency"...
The thing that you are testing (object/method/function...) can interact with this dependency by calling methods to...

Query for something.
Change something or produce some side effect.

When calling a method to query for something
When you are using the dependency to "query" for something, you don't need to use the "mock API" because you can just use a regular object, and test for the expected output in the object that you are testing... for example:
describe "Books catalog" do
  class FakeDB
    def initialize(books:)
      @books = books
    end

    def fetch_books
      @books
    end
  end

  it "has the stored books" do
    db = FakeDB.new(books: ["Principito"])
    catalog = BooksCatalog.new(db)
    expect(catalog.books).to eq ["Principito"]
  end
end

When calling a method to change something or produce some side effect...
When you want to make a change in your dependency or do something with side effects like inserting a new record on a database, sending an email, make a payment, etc... now instead of testing that the change or side effect was produced, you just check that you are calling the right function/method with the right attributes... for example:
describe "Books catalog" do
  class FakeDB
    def self.insert(book)
    end
  end

  def db
    FakeDB
  end

  it "stores new added books" do
    catalog = BooksCatalog.new(db)

    # This is how you can use the Mock API of rspec
    expect(db).to receive(:insert).with("Harry Potter")

    catalog.add_book("Harry Potter")
  end
end

This is a basic example, but you can do a lot just with this knowledge =)
I wrote a post with this content and a little more that maybe can be useful http://bhserna.com/2018/how-and-when-to-use-mock-objects-with-ruby-and-rspec.html

RSpec Mock Object Example


Linear regression changes in form when including other predictors

Question: let $y_{i}$ be the response variable, and let $x_{i}$ be a predictor in a  linear regression model. Suppose that we have the general model $y_{i}=B_{0}-B_{1}x_{1}$ now suppose that we include another predictor $x_{2}$ in the model and get the model to be $y_{i}=C_{0}+C_{1}x_{1}+C_{2}x_{2}$. In this particular instance the sign of the coefficient for the predictor $x_{1}$ has changed in signs from negative to positive. Under what circumstance would this occur? wouldn't the marginal relationships remain the same for the predictors irrespective of how many predictors are included?
Comment: This is a FAQ: see https://stats.stackexchange.com/search?q=regression+change+sign.
Answer: An overspecified model will still give unbiased coefficients, so with enough data, you should not see the sign change. In practice, where data is finite, this can happen for a few reasons, and the most common I can think of is if $x_1,x_2$ are very similar (you can think of approaching the multicollinearity issue), in which case you can observe, in finite samples, cases where one of the coefficients is positive and the other is negative in an attempt to, intuitively, 'cancel out'. Eventually, if you observe enough data, you won't run into any issues unless there is actual multicollinearity, but for for finite sums, you can always make $x_2$ similar-enough to $x_1$ to create a problem like you asked about.
Below is an illustration in R
<code>set.seed(582)

n = 1000
x1 = rnorm(n)
x2 = x1 + rnorm(n)*.0001

y = x1 + rnorm(n)

> lm(y ~ x1)

Call:
lm(formula = y ~ x1)

Coefficients:
(Intercept)           x1
   -0.01879      1.00850

> lm(y~ x1+x2)

Call:
lm(formula = y ~ x1 + x2)

Coefficients:
(Intercept)           x1           x2
   -0.01894    -32.84030     33.84874
</code>
Answer: This happens very often when your "weaker" variable is correlated with your "stronger" variable and also correlated with the residual of the dependent when regressed with your "stronger" variable and the two relationships are opposite. Hence, if you regress the dependent with the "weaker" variable alone, you may even get a significant coefficient, due to omitted variable bias (i.e. due to the weaker variable's correlation with the stronger one which is not included). However, when you then include the "strong" variable, the omitted variable bias disappears and the variables get the right signs.
Thus, I do not agree that $x_1,x_2$ need to be anywhere near fully co-linear for this to happen. They have to be correlated though. Here is an example in python:

As you can see the correlation between $x_1,x_2$ is not dramatically high and still we see that if we only include $x_2$ in the regression, it gets a significantly positive coefficient, due to omitted variable bias. However, once we add $x_1$ in the model, both variables' coefficients converge to their true values.
I believe that if you combine my example with the one posted below, you see a healthy and an unhealthy situation where this can happen. If you notice on the example posted by the user below, the coefficients go crazy when both variables are included and even though it is not printed, it is certain that the $R^2$ will be unaffected by the inclusion of the 2nd variable, which is in contrast with my example. Hence, I think that you can check which of the two examples your problem resembles and decide accordingly on whether your $x_1$ is useful in informatively adjusting the the influence $x_2$, like $x_2$ does for $x_1$ in my case or whether you have an artifact caused by high levels of multicolinearity, as the example of the user below.


Looking to blink entire led strip

Question: I am fairly new to FASTLED programming and am looking to make my entire LED strip blink at the same time. Similar to the Example Sketch "Blink" however all 30 of my LEDS. I might just be having a temporary mind derp right now but I cant figure it out.
Comment: please post the sketch that you are using .... include a clear description of observed behavior
Comment: look at the Cylon example code .... it shows you how to address the LEDs .... extrapolate to multiple LEDs  ......... the Blink example blinks the first LED .... think about what you would have to change in the code to blink the second LED ..... how would you blink the first and second LED at the same time?
Answer: FastLED has a function called fill_solid() which will change the color of an indicated range of LEDs in a strip.
From https://github.com/FastLED/FastLED/wiki/Controlling-leds#set-rgb-color

use new 'fill_solid', telling it to fill just one led. (v2) Note that
  this is a pretty silly way to set one pixel, but it lets us illustrate
  the existence of fill_solid, a new convenience function the library
  provides.
fill_solid( &(leds[i]), 1 /*number of leds*/, CRGB( 255, 68, 221) )

For your case, you want to change the color of all LEDS, so you would call:
fill_solid(leds, NUM_OF_LEDS, CRGB::Red);

To turn them back off, you would change the color to CRGB::Black

Looking to blink entire led strip


New Spot Light behavior in 4.0 no longer renders in a volume

Question: I have a model of the Abyss Cab 3 Mini sub. The model has a number of spotlights that cast a beams in a volume. It all works in 3.6 but in 4.0 all my spotlights are broken and don't work like the old spots. How do I get the 4.0 spots cast a beam rather than a circular glow that encompasses the whole fixture. this is not the way spot lights work. They cast a beam in a single direction and virtually no light in the opposite direction. 4.0 breaks every undersea model I have because of this lighting change.
Comment: Welcome. Please use a title that matches the content of the question. It should be descriptive but succinct, unique and identifying, summarizing the issue in such way that anyone searching for a similar problem may easily find it. Use the [edit] link above, remove anything superfluous, avoid words like "*this*","*issue with*" or "*question about*". Remember, your title is the first thing potential visitors will see, answers you get depend heavily on how inviting it is. See ["*What is the problem of asking "How do I do this?"*"](https://blender.meta.stackexchange.com/questions/2449)
Comment: Well, they seem to have changed the spotlight in version 4.0 as this question came up here before recently > [Spot Light size in principled volume Bug in 4.0](https://blender.stackexchange.com/questions/304906/) and this might be unfortunate but not an issue for this site, because if this is not supposed to be like that it's a bug which should be reported via _Help_ > _Report a Bug_ or - if this behavior is intended by the developers - then users should inform them that this is not desired. But since we are only Blender users ourselves and not developers, we cannot do anything about it.
Answer: I originally voted to close this question as rather being a bug or even intended behavior which makes this question off-topic for this site.
In the meantime I found out the spotlight is actually intended to work like that now and at least in the 4.0 Blender versions there will be no change to it. The googd thing about the new spotlight is, it respects the given radius better than the old one.
However, for everyone who wants to replicate/substitute the previous spotlight behavior, here is a workaround:
Instead of using the Spot, change the light to Area instead. Change the Shape to Disk and the size (since this represents the diameter now, not the radius) to twice the size as it was before. Under Beam Shape, the previous angle for Spot Size now needs to be set as Spread for the area light (the default of the Area light is 180°).
Unfortunately the area light seems to be much much brighter than the spot light. In the volumetrics, a Power of 30 - 50 W seems to have a similar effect like a Power of 1000 W on the area light.
So this is not a perfect equivalent of the old spot light, but at least a usable workaround.
Here are some comparison images, first of all the previous spot light in older versions:

And this is what you are experiencing now in 4.0:

This is what you can get with an Area light, as you can see it is much brighter:

This is the same with a reduced Power value of 40 W:
Comment: There's also a YT video about lighting in 4.0 [here](https://youtu.be/92__vH2LWB0).
Comment: @JohnEason Yes, I know the video, but this just deals with how the new light linking works, it's not about how they changed the light objects themselves.


When are reputation points awarded?

Question: There has been no update in my reputation points for today. Is the system down, as I believe that the system is automated in awarding the points. Anyone experiencing the same problem today?
Comment: Edit (when you have the "Edit anywhere" privilege) and review don't give reputation. Suggesting edit (for user without "Edit anywhere privilege") gives +2 reputation if approved.
Comment: Isn't it just that no one is upvoting your questions/answers?
Comment: I did some reviews earlier this mornings, Doesn't that contributes to some points. By the way, @nhahtdh I saw you have been actively editing ac couple of questions and answers, but your reputation for today haven't change tough.
Comment: @nhahtdh so all your recent edit does not contribute to any reputation. So you have been doing a charity work, Salute ya for doing so.
Answer: Reviewing doesn't give you any reputation point, but please continue to do so, since it keeps the quality of the site in control.
There are 4 levels of unsupervised edit privilege:

Edit your own questions and answers
Edit community wiki
Edit [any] questions and answers
Edit tag wiki

If you haven't earned the privilege, you can still suggest edit, which will be peer reviewed. You get +2 reputation for every approved suggested edit.
If you have earned the privilege, no reputation is given. However, please do continue to edit to keep the site quality high. We don't want to attract craps.

When are reputation points awarded?


Setting up DNS on reverse proxy

Question: I have a backend that used to be my front end. Now my front end is an nginx proxy server. It just serves as an http and an IMAP/SMTP proxy. The backend services apache,mysql,dovecot/postfix. Since I defined the nameservers to this box on the registrar, do I now define the nameservers to the proxy box? It is located in a different geographical location? If so, what hostname should the backend have? The proxy needs to resolve the MX. Thanks.
Answer: By defining nameservers at registrar to this box I assume that you are referring to glue records pointing to the IP(s) of that server. It means that you also have a DNS server running on that box, such as BIND or DNSMASQ. You would need to move that service to the new box.
Comment: Yes the glue records defined in the registrar and bind is set up on that box. Now I am moving my front end to a proxy. Should the glue records be defined for the new proxy? Also if I do that, what hostname should the backend NOT be? I assume since there aren't any authoritative dns servers on the backend anymore (after moving them to the proxy), that it would not matter since they wont resolve anyway. However my postfix needs to have my official mail exchanger record set up right. My MX record. I see that in nginx.conf, I can set the name server regardless of that physical hostname
Comment: Nameservers have nothing to do with nginx, there is no such thing as a physical hostname and, if you want your proxy to get the emails for the postfix server then the MX records have to be pointed to the proxy. I think that you either need to start reading and learn what you are doing and have to do, either hire a professional.
Comment: Let me clarify for you since I don't think you understand what I am asking. On the proxy box, I defined my dns zone to be my authoritative server and have the glue records pointed there. I already know that part. However, what kind of zone is supposed to be configured for the BACKEND? I run bind on the backend, yes or no and just point server_name in nginx.conf to the physical IP of the backend? When i said physical hostname, I am reffering to /etc/hostname. I also am aware I define the MX hostname inside nginx.conf no matter what is listed in /etc/hostname. This serves as reference for MX.
Comment: You don't run DNS on backend.
Comment: Thanks. I assumed that's what I needed. However, I should still define /etc/hostname as my MX like mail.example.com on the backend correct? postfix would need this. Finally, for /etc/hostname on the proxy, should that just be something like ns1.example.com? Defining mail.example.com here does not make sense since that is defined INSIDE nginx.conf for our single point of reference for our mail users correct? Really appreciate the clarification
Comment: Postfix may need that but you can setup the localdomains and hostname in the Postfix configuration file rather than letting it to determine it by the hostname. The hostnames for the servers can be whatever you want, TOM and JERRY or whatever.
Comment: Thanks. Thats true. I forgot about being able to define $myhostname as something else.

Setting up DNS on reverse proxy


How does TAB auto-complete find options to complete?

Question: And how does it also autocomplete aliases?
Answer: Depending on the command:

Someone may have written a function to generate possible completions of arguments, including options. You'll find functions for some commands in /etc/bash_completion.d/* (or a different location on some systems). These functions are registered with the complete built-in (e.g. complete -F _find find tells bash to call the _find function when you press Tab on a find command). They use the compgen built-in to tell bash "here are the possible completions".
For some commands, bash will call the command with the argument --help and parse the output. Such commands can be registered with the complete built-in, e.g. complete -F _longopt ls. _longopt is in fact a completion generation function, that happens to parse a command's output rather than use a fixed list. (There are other more specialized completion functions that parse a command's output to generate possible completions; look in /etc/bash_completion.d/* for examples.)
For things like aliases, the completion function looks them up in bash's internal tables. The complete built-in has options for that, e.g. -A for aliases.
Answer: Have a look at the file

/etc/bash_completion

and observe the files from the directory:

/etc/bash_completion.d

You will find the answer.
Answer: Support for bash completion is provided in Debian and Ubuntu by the bash completion package. You also usually need to uncomment the following in /etc/bash.bashrc and/or .bashrc to source the bash completion files. The following is from /etc/bash.bashrc:
# enable bash completion in interactive shells
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    . /etc/bash_completion
fi

for this to work. I usually uncomment it in both. The handling of interactive/login shells in Debian is a bit of a mess.
Similar comments presumably apply to other distributions, though maybe they enable the sourcing by default.


Is the universe eternal or temporary?

Question: Is the universe eternal or temporary? It is most importantly observed to differentiate illusion and truth.
Comment: It is eternal & unreal! that's why it is called "Maya" in Advaita
Comment: Universe is Eternal, for it is Brahman Himself. Its separateness from you (i.e. its individual existence as something different from you) is the illusion! Good question
Comment: Is a 'day' eternal or temporary ? It is temporary in the sense that after day, night comes. But it is eternal in the sense that after every night, day comes. so it is cyclically eternal.
Comment: Eternally Temporary.
Answer: This illusory world is both eternal and temporary.

ध्रुवं कश्चित् सर्वं सकलमपरस्त्वध्रुवमिदं
परो ध्रौव्याऽध्रौव्ये जगति गदति व्यस्तविषये।
समस्तेऽप्येतस्मिन् पुरमथन तैर्विस्मित इव
स्तुवन् जिह्रेमि त्वां न खलु ननु धृष्टा मुखरता॥ ९॥
O, Destroyer Of  ( Three ) Cities Shiva, some persons call this Universe eternal ( ever lasting), others call it temporary, and yet others call it both eternal and temporary . Hence, being surprised ( perplexed ) by  these contradictory opinions on this subject, I am really becoming immodest in loquaciously praising You .

From Mahimna Strotra
The Absolute GOD is universal, omnipresent and all knowing. Nobody is able to destroy it. And Illusory world that we see which is relative is temporary upto our death or judgement day or end of our time on earth.
Also in Shrimad Bhagwat Geeta Lord said

avyaktanadini bhutani vyaktamadhyani bharat avyaktanidhannyanaiva tatra ka paridevana
This universe is always disappeared in start, appearing in middle and again disappeared in end.
Comment: You could add your own viewpoints also in these posts. Some of them are showing up in low quality posts.
Comment: But if I add viewpoints then it will become opinion based answer. So better it is from sources.
Comment: I mean you could add your own thoughts on what the scripture says. In my opinion, Viewpoint+References makes a rich answer. Only viewpoint is not allowed here. Anyways, just wanted to let you know. :)
Answer:
Ashtavakra geetha verse 10.2 :- Look upon friends, lands, wealth,
  houses, wives, gifts-- and all apparent good fortune-- as a passing
  show, as a dream lasting three to five days.
verse 18.1 Praise That, which is Bliss itself, which is by nature
  stillness and light, and which by Its knowing reveals the world as a
  dream.

Also the story of Narada asking Krishna to show him the power of Maya confirms and reiterates the fact of life being just a dream.

Does a dream have a start? Does it have an end? All we can say is that
  it is not real. We can dream for ever and hence it is not temporary.
  We can wake up and end it once and for all hence it is not permanent.
Comment: can you pls provide more specific details about sources you quoted like chapter/verse numbers etc.?

Is the universe eternal or temporary?


Multiple user-selected front page layouts

Question: I would like my site builders to be able to select from three unique front page layouts.  The selection can be made either through config or through theme settings, but not require any coding.  The three pages have different pieces of content consisting mostly of fields.  I've looked at panels but I would prefer to use something a little lighter as panels seems like a lot for this one piece of functionality.  Has anyone here solved a similar problem?
Comment: You could use the Omega theme's layout extension.
Comment: Yes, it sounds like omega theme with the delta module would work, but I already have a custom theme so that's not going to work for me.  I think my best bet might be using context with bean, but they're both pretty new to me.
Answer: You could add a checkbox in the theme settings and adjust the page template accordingly in a page preprocess.
Something similar to this would go in the theme-settings.php file in your theme...
function THEMENAME_system_theme_settings_alter(&$form, $form_state) {
    $form['front_layout'] = array(
      '#type'          => 'radios',
      '#title'         => t('Front Page Layout'),
      '#options'       => array(
        'layout_1' => t('Layout 1'),
        'layout_2' => t('Layout 2'),
        'layout_3' => t('Layout 3'),
      ),
      '#default_value' => theme_get_setting('front_layout'),
    );
}

Add new page template suggestions in a page preprocess ...
function THEMENAME_preprocess_page(&$variables) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['theme_hook_suggestions'][] =  'page__' . $layout_setting;
  }
}

This would allow you to have separate page templates for each layout. An example being page--layout-3.tpl.php.
If it's merely css changes you need, you could add a body class in an html preprocess ...
function THEMENAME_preprocess_html(&$variables, $hook) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['classes_array'][] = drupal_html_class($layout_setting);
  }
}

In this example you would have a "layout-1", "layout-2" or "layout-3" class on the body element.
Comment: Awesome, this is exactly what I was looking for - thanks!  I tried to upvote your answer but I don't have enough reputation points yet.


which are the possible ways to detect impurity in drugs?

Question: I want some information regarding the protocol for determining any type of impurity in pharmaceutical substances or drug product.
Which type of impurities can be identified by HPLC and MS?
what is the difference between related substances and impurity?
Comment: I imagine you are talking about HPLC-MS (or LC-MS), and not the single technique (HPLC and MS). If so maybe [this article](http://onlinelibrary.wiley.com/doi/10.1002/(SICI)1098-2787(1999)18:3/4%3C187::AID-MAS2%3E3.0.CO;2-K/abstract;jsessionid=4F4B5C57EC958A52DFCA5A38BEE503DE.f01t04) could be helpful
Comment: Have you also looked into elemental analysis? This is a technique that 'counts' the number of Carbon, Hydrogen etc. atoms in the sample. If the molecular formula differs from this, there is bound to be an impurity. Look at the [wikipedia-page](http://en.wikipedia.org/wiki/Elemental_analysis) maybe?
Comment: Do you want something else than described fully in Pharmacopeia? http://en.wikipedia.org/wiki/European_Pharmacopoeia
That means, for each drug the full analytic procedure?
Answer: There are a lot of types of impurity. Basically, much as any plant that's growing where you don't want it is a weed, any material in your sample that isn't what you want to have in it is an impurity.
Since you asked a question in simple terms I will attempt to answer it in equally simple terms:

Byproduct contamination - The theoretical reaction is usually not the only possible one, especially in organic chemistry such as pharmaceutical work. Areas of the reaction which didn't have just the right mixture of reactants, or wasn't quite at the right temperature, could have produced different products. Additionally, devations from the ideal when adding reactants can result in unreacted quantities of those reactants.
Various forms of chromatography, such as HPLC, CC, GC, MS, etc can detect and even separate these various byproducts from the ideal product. How effective any one of these techniques is depends on the type and combination of the products and byproducts. One of the most basic aspects of any drug research chemist's job is to isolate their product from all of the byproducts of their reaction.

Structural isomer contamination - Two compounds are structural isomers if they have the same molecular formula (number and type of atoms), but have different molecular structures. Tetramethylbutane, for instance, is based on a 4-carbon alkane, to which two additional methyl groups each are added to the carbons in the "2" and "3" positions of the alkane. The resulting molecule has all the same carbons and hydrogens as the totally linear octane molecule, but its structure causes very different behaviors (for instance, it has a much narrower range of temperatures at which it is a liquid).
Your average petrochemist doesn't care too much about the difference between any of the structural isomers of these hydrocarbon alkanes; their primary reaction of interest, combustion, only cares about the required stoichiometric ratio of fuel to air, and the resulting rate and heat of combustion. However, such isomers pose problems in pharmacology for the above reasons; a reaction that was theorized to produce a molecule with one arrangement may in fact produce an entirely different isomer, with similar physical properties as the desired molecule, but much different reaction chemistry including biochemical effects. Chromatography methods based on molecular weight or physical properties like boiling point or solubility may or may not be able to tell you whether you have the right isomer, but other methods might show a difference in the physical properties of the chemical allowing separation.

Chirality and Racemization - Even if two isomers have all the same atoms, and each atom is bonded to the "correct" adjoining atoms, the molecules can have different shapes because the atoms are bonded to different relative positions of their adjoining atoms. These "spatial isomers" or "stereoisomers" have many forms, from structures that exhibit the same "mirror-image" symmetry that your left and right hand do (enantiomers), or that have certain functional groups transposed by rotation around a "chiral center" (diasteromers, including cis-trans and most detro-levo isomers). Again, like structural isomers, these stereoisomers can cause problems for pharmacologists because the different isomers can have different reactive properties in the complex biochemical soup that is the human body.
Sometimes these chiral isomers can be separated from each other; enantiomers and other spatial isomers are often "optically active", meaning they rotate polarized light in opposing directions depending on their chiral arrangement. Certain "chiral resolving agents" can also separate these isomers based on a differing affinity for one isomer over another, and these agents are often used as "stationary phases" of column chromatography including HPLC that can separate and thus "purify" the desired isomer from its chiral mirror. However, a few troublesome spatial isomers will "racemize"; that is, they will readily rearrange between the two stereoisomers when given the right environment, and so any attempt to produce a pure sample of one enantiomer is ultimately pointless.


What size asteroid would cause a nuclear explosion?

Question: What would be the size or composition of a asteroid to cause a nuclear explosion? Why doesn't the meteor we see not have a boom?
Comment: no jen, you are wrong on that,  search wikipedia, they come from different populations
Comment: Hold on for a minute. An asteroid is an asteroid, it has nothing to do with nuclear explosions. Meteors are tiny, they are only peanut sized, so don't compare them to planes. You wouldn't hear a thing from a peanut burning up.
Comment: @count_to_10 All meteorites are first meteors and before that asteroids.
Answer: An asteroid impact won't cause a nuclear explosion, but the impact can be very powerful causing effects that are also seen in case of a nuclear explosion like a large fireball, a huge blast wave and an electromagnetic pulse.
The fireball and the blast wave are caused by the meteorite's kinetic energy being converted to heat. This converts the meteorite and some of the surrounding rocks in the Earth to a gas, but its initial density is the same as what it was before the impact. From the gas law you can see that this means that the pressure must be extremely high. This causes the gas to expand very fast, giving rise to the blast wave and the fireball.
The electromagnetic pulse is caused by the extremely high temperatures of the fireball. There is a significant amount of electromagnetic radiation in the ultraviolet range which causes ionization of molecules in the air. The photons from the fireball will push the electrons away from the molecules,this means that at some point away from the fireball the negatively charged electrons are pushed away in the opposition direction to the fireball. So, you get a charge separation due to the radiation, when the radiation dies down after a few seconds, the electrons will move back, due to the attraction of the positively charged air molecules. Some electrons will be captured by the charged molecules, but the bulk of the charge will overshoot and you get an oscillation of the dipole moment. This causes electromagnetic radiation to be emitted.
You can crudely estimate how an asteroid impact compares to a nuclear explosion simply by calculating the kinetic energy of the asteroid when it hits Earth and comparing that energy to the yield of a nuclear device. This website offers a far greater detail into the effects, you can enter the relevant parameters such as asteroid diameter, density, impact velocity, etc. and it will output the physical effects of the impact.
Comment: If it was an asteroid made up of Uranium and Plutonium, it just might go fission upon impact.   But such an asteroid would need to be artificially constructed.    :-)
Comment: What about Australia. It hold 98% of the worlds uranium. could it have been an asteroid or the result of one?
Comment: @Jen - No. Actually, Hell no. Such an impact would leave telltale terrain structures, and none are visible. See the Sudbury Basin https://en.wikipedia.org/wiki/Sudbury_Basin for example. And an impact with a body containing a continent's worth of radioactives would disperse them over the entire planet, leaving a telltale layer in the geological record, rather like the Cretaceous iridium layer, but much older and more pronounced.
Answer: To answer this we need to do some physics and math. Assume a body of mass $m$ strikes the Earth, or the atmosphere and ground, at velocity $v$. The kinetic energy of the object is $K~=~\frac{1}{2}mv^2$ we now assume that the object completely dissipates its energy into thermal energy. One ton of explosives is equal to $4.2\times 10^9$ joules of energy. The velocity of meteoroids that impact Earth is between $14km/s$, escape velocity to twice the orbital velocity of the Earth around the sun plus escape velocity, $72km/s$. This would happen for a meteoroid in a near escape from the solar system velocity in the opposite direction the Earth orbits the sun. Let me assume $20km/sec$, which is about average.
Now let us consider nuclear bombs. The START treaty limits on tests is at $350$ kilotons, which is about the largest nuclear bomb yield in arsenals today. This has about $1.5\times 10^{15}$ joules of energy. Now we equate this with the kinetic energy and compute the mass of a meteoroid that would do this and we find this is $7.5\times 10^6kg$. or about $7500$ tons. As a nominal density I use $5g/cm^3$. If I assume a spherical shape for the meteoroid then the radius of this would be $70$ meters. This is pretty large, and in the same order of magnitude of the object that exploded over Chelabinsk in 2013 ($17$ meters).


Progress bar in updatedb

Question: Is it possible to get a reliable progress bar (or just a reliable information how long it will take) when doing updatedb?
Answer: This is not an efficient solution, but is not as bad as looping through everything twice.
Number of files processed by updatedb is equal to:
updatedb -v | wc -l

or roughly equal to:
find / -mount | wc -l

We cannot use these commands to get the number, because it would be looping twice.
But we can use the number of used inodes, which is approximately the same:
df -i | grep '/$' | awk '{print $3}'

Having this value, we can calculate how far we got while updatedb -v command is running:
count=$(df -i | grep '/$' | awk '{print $3}')

sudo updatedb -v | while read
do
    printf "%3d\r" $((100 * (++i) / count))
done

This is very inefficient, because printf is called for every line in the output of updatedb -v. Better if we printf for only some of the lines.
count=$(df -i | grep '/$' | awk '{print $3}')

sudo updatedb -v | while read
do
    if (( ++i % (count/20) == 0 )); then
        printf "%3d\r" $((100 * i / count))
    fi
done

Comment: Interesting idea. But my `df -i` reports 0 in all columns for /. Maybe extracting the current database's file count from `locate -S` (or `--statistics` or other similar switch your `locate` implementation has) could also be used as an approximative file count.
Comment: This solution worked for me, the percentage value seemed quite precise.
Comment: `updatedb` does not have `-v` option anymore [since `19.10`](https://askubuntu.com/questions/1183518/updatedb-command-line-options-changed-during-upgrade-from-19-04-to-19-10), dunno if there are alternatives...
Answer: No, there's no such option, as well it shouldn't have any.
If you need to measure that, you must first know how many files are present on your system, that means loop through everything twice, it can be slow
One evicent example is that if you extract kernel source code with file-roller, it's slower than doing the same thing with tar directly, because file-roller need to file out all files first(otherwise the progress bar might be incorrectly displayed), and you wait for a while before extraction process actually began.
Comment: You are totally right. However, it would be possible to predict the time for the next run using a "smart guess". For instance one could compute an exponentially weighted moving average from the past values, which basically assumes that the next run will take as long as the average of the last runs. This is of course not exact, but very cheap to compute since it doesn't loop over the file system. Given that neither the amount of files nor the load changes dramatically it will yield to very practical estimated values.

Progress bar in updatedb


Can an svmlight model be converted to work with libsvm?

Question: I have a model file that was created using svmlight in classification mode with a linear kernel. Is it possible to convert this file so that libsvm can use it for classifying?
Answer: You will have to retrain it. For the training file, in the svmlight / libsvm format, each line takes the form (source) :
<code><label> <feature-id>:<feature-value> <feature-id>:<feature-value> ....
</code>


Is it safe to look at an annular eclipse during sunrise using a medium?

Question: Will looking at an annular eclipse reflection through a bowl of water damage your sight?
I already tried viewing its reflection through a bowl of water.
Comment: There are two experiments you can do with your eyes. Left and right. Don't mess with it; there are a number of safe ways to observe an eclipse.
Comment: Is there a chance that the atmosphere will reduce the brightness enough?  Yes.  Would I count on it? No.  Why not just get eclipse glasses and be done with it?  That is the only scientifically studied method.
Answer: You are better off with eclipse glasses as noted in the comments. Beware that a partially eclipsed Sun is more dangerous to look at than either the full Sun (which is itself not such a good idea) or a totally eclipsed Sun, and "partially eclipsed" also includes an annular eclipse.
What happens is your eyes try to adjust to the changing brightness of the background; as the Sun becomes more covered by the Moon and the ambient darkens, your pupils open up to admit more light. Technically you don't even need an eclipse to see this; the same adjustment causes shadows to appear less dark on days when the Sun is shining hazily through high clouds than when the sky is perfectly clear. With the clouds there is no problem because they dim the entire solar disk, but with a partial solar eclipse the un-eclipsed part of the Sun is still delivering full intensity to your opened pupils. Having the pupils opened then magnifies the harmful effects of looking at the bright and UV-containing light.
Play it safe. They are called "eclipse glasses", not merely "total eclipse glasses". Get and use them.
Answer: It's unclear what is the reflection surface in your case.
Water does not absorb ultraviolet light but only scatters this light. Glass absorbs only a portion of the ultraviolet light spectrum. After a glass bowl of water, you still get energetic, invisible UV (most likely UV-A) into your eyes. Whether it's enough to damage the eyesight is outside of my expertise, but frankly, I wouldn't look through the bowl with water. As for the reflection off the surface of water, it's even worse, as the surface reflects the falling light of wavelengths down to about 100 nm; so don't do it.


The difference between exact solution and analytic solution

Question: My mother tongue is not English so I am confused with the difference between exact solution and analytic solution. Are these the same?
Answer: Yes, they are (for the most part) the same, typically being used interchangeably.
And really, both are kind of a misnomer, because things typically not considered "analytic" or "exact" forms are, in fact, very often "exact" in the literal sense. There is nothing "inexact" about, say, the expression
$$e = \lim_{n \rightarrow \infty} \left(1 + \frac{1}{n}\right)^n$$
for $e$, it's just that because it involves a limit, it is not consider as an "analytic" or "exact form" in the kind that is referred to by these terms. What these terms really mean is what would perhaps better be described as a "solution by special functions": we fix a finite number of "allowable" (or "special") functions and constants which (ideally) we understand well, and try to describe the solution of some given problem in terms of a finite composition of these. And when it is said that "no exact/analytic solution exists", it means that for some set set of such functions, we cannot write down a formula of this type for the given problem.
Of course, as you can tell, this depends very much on what special functions we allow. Most restrictively and commonly, these are just the so-called "elementary functions" consisting of addition, multiplication, exponentiation, and their inverses (trig. functions are also typically included but these are a special case of exponentiation when you use complex numbers). More "liberally", we may add some "non-elementary" special functions like the gamma function or Lambert's W-function to the mix, and depending on whether you do this, the range of problems for which you can give an "exact/analytic" solution will change.
That said, they are generally contrasted against numerical solutions which, by definition, are truly inexact or approximate. These solutions are basically amounting to generating a big list of approximate numbers through the use of a computer to specify the desired function over a range of points. They are used because they are extremely general: very little is not amenable to a numerical solution, though the computation may be extremely expensive. The downside besides not being exact (though we should remember that scientific models, in general, cannot be faithfully relied with certainty as being truly "exact" to the "real world" anyways), is that unlike a formula which can have parameters, they only ever describe one instance of a problem, they do not describe general instances. Hence, a new numerical solution needs to be calculated in each new instance we want to study, and as said, the computational expense can make this prohibitive.
Comment: Thank you very much!!
Answer: No, they are not the same.  Take an example of an ideal 3-body problem, the differential equation model of the system is not difficult to write, yet it is intractable analytically.  That is, no mathematical expression, or even infinite series, can be found that gives the positions of the objects as time progresses, that is, there is no analytic solution to the problem.  However, there is an exact solution, that is the path that the objects follow, and it can be approximated by numerical methods.


Can Compressed air be used as a thrust component in a spacecraft to propel the craft through space or to orient the craft?

Question: Hello I was watching a video recently about aircraft carriers and how they use compressed air to propel aircraft off the ship. It go me thinking if I had, maybe a 50cm x 50 cm x 50 cm spacecraft that was put into orbit. Would I be able to use compressed air as thrust to orientate the space craft? or even better would I be able to use it to give the space craft a greater distance from the Earth?
Comment: This question would be better suited to SE.SpaceExploration. However, from what I seen there the most likely answer would be be compressed would not be able to give space craft enough delta-v to be useful for deep space travel. For positioning a satellite into orbit it may technically be possible.
Comment: I'm voting to close this question as off-topic because: this question would be better suited to SE.Space Exploration.
Answer: In the case of aircraft carriers the compressed air is generally a working fluid for a mechanical catapult rather than providing direct thrust like a rocket (steam is also used for the same job on carriers using steam plant).
Having said that compressed gas can be useful in providing small amounts of thrust, although air may not be the best choice because of its oxygen content and an inert gas may be preferred.
In terms of overall power to weight ratio you generally get more out of a solid/liquid fuel system as you are going from a high density phase to a gas so you don't have the additional weight of a pressure vessel. Note that for standard industrial pressurized gas containers the container may have as much mass as the gas it contains. So even if you don't have actual combustion some sort of chemical gas generation may be preferable.
Overall compressed gas is convenient, portable and simple but has fairly mediocre power density.
It's also worth considering that simple 'bottle rockets' get much more thrust when they use water to provide reaction mass while the compressed air gives the energy storage.
The problem with pure gas thrust is that the rate of conversion of potential to kinetic energy is limited by the local speed of sound and tends to be quite lossy. For jet engines this is mitigated by the fact that there is an unlimited supply of air to push through the engine from the immediate environment, rockets using fuel/oxidiser use sheer brute force of energy density of the propellant at the expense of overall efficiency and the fact that a rocket is essentially very simple so the dead weight of the engine itself is very low.
Similarly where hydrogen of oxygen are used as fuel or oxidiser they are generally liquefied rather than pressurised.
So overall there isn't a general answer, compressed gas is viable for thrust on a small scale, as for small orbital adjustments but it is less attractive for larger thrust requirements.
Answer: The SAFER, used by NASA for EVAs ("Space Walks"), uses compressed nitrogen for thrust.  Air is mostly nitrogen, and the properties are fairly similar.  So, essentially it not only could be done, but even has been done.
Comment: To clarify the original claim, aircraft carriers do not use "compressed air" in their launching catapults.  The working fluid used here is steam, taken from the propulsion system and injected into a long cylinder on command.  The expansion of the steam in the cylinder is what drives the attached aircraft off the ship and into the air.  https://en.wikipedia.org/wiki/Aircraft_catapult


Can an electron jump to a higher orbit with an energy that is only a little less than the theoretical requirment?

Question: I understand that electrons can possess only discrete amounts of energy so if an electron in an atom has to jump from a lower orbit to a higher orbit it will require a discrete amount of energy to the same. Say for example it requires 2 units of energy to jump to the higher level.
So instead supplying that exact 2 units what if I supply a little less say 1.9999999999999... units, will it make the jump? If not does it need to be the exact 2 units?
Answer: Generally speaking you must provide the exact amount of energy needed for the transition from one energy state to another.  That is, this is a physical phenomenon that requires a specific amount of energy.  However, your question has some subtleties with regard to any practical situation.

Depending on your measuring devices, you may not have enough precision to detect a difference between 2 and 1.9999999999999, so it might appear that you could achieve the jump with less energy than required.

If you measuring devices are not calibrated correctly, they may not have the proper accuracy so again your measurement might suggest that you could make the jump with less energy.

If you are implying a value of 1.9999 with the 9's extending to infinity, than this - mathematically - is indeed equal to the value of 2.


Exchange Time Capsule hard drive with PS4 Hard Drive

Question: is it from the data and values possible, to exchange the PS4 and Time Capsule's Hard Drive?
So built in the PS4 the Time Capsule hard drive and in the Time Capsule the PS4 Hard Drive.
Could anyone say me if it so possible and works fine?
Comment: To you expand your question to tell us why you want to do this? Are you just wanting a larger drive in your PS4?
Comment: @Alistair McMillan Yes, I thought before I buy I new hard drive, I could only exchange them, because my time capsule has 2 TB storage.
Answer: It may be possible to put the PS4 drive in the Time Capsule but not vice versa, and not really recommended.
According to this support document from Sony, the PS4 uses a 2.5" hard drive.
According to iFixit guides such as this one for the pizza box model and this one for the newer vertical model the Apple Time Capsule uses 3.5" drives.
So, with an adapter, the Time Capsule drive could work in the PS4, but the PS4 drive won't fit in the Time Capsule.


Should pedal assist ebike battery discharge constantly?

Question: I have a Specialized Como 2.0 (pedal assist) which I absolutely LOVE.  I want to get as much exercise as possible, so I always ride it as a regular 9 speed and only hit the power button on grades or hills.  (Being 71 years of age, I don't feel that I should have to struggle riding a bike anymore.)   I ride mostly on Rails to Trails, so even though my power is turned on, I don't  hit the "assist" button very often.
My question is this:  Should my battery be discharging even when I am not using it? It seems to me that if I have the power on, but never use it on a 25 mile ride, the charge should remain full.  Or is it like a car where if the car is not turned on, but you leave the lights on, it'll drain the battery?
I'm just confused on this point.   Thanks for your help.
Answer: This obviously depends on the motor you have, and whether you have headlights.
Headlights connected to the battery always consume some power even if your assist level is off.
However, there is also something else that could consume a bit of power. All motors have drag when not in operation. Power on but zero assist level can depending on the motor mean either "use no battery power at all" (in which case the motor drag could slow you down considerably), or "use little battery power to barely offset the drag" (in which case you have the same experience pedaling that you would if you had a non-ebike).
The specifics depends on the motor. For example, I believe my Bosch Gen3 Active Line Plus mid-drive (50 Nm) motor has a clutch so when not assisting, the motor can be entirely disengaged from the drivetrain, and thus no power usage is necessary to offset drag.
Also every electronic device will consume some minimal amount of power even if not converting that power to light or motion. So there will be at least some minimal power loss even if your motor is a clutch-type motor and if you don't have headlights. This power loss is probably so minimal compared to the energy in the big battery that it shouldn't matter.
Comment: Specialized says that their mid drive motors have a freewheel mechanism.
Answer: No, assuming you are in a true "no assist" mode with lights off. The controller still shows velocity and the like but the energy for this is same as zero in comparison to the engine. I can make many kilometers with assist off that sometimes I need to do when returning down after ambitious mountain biking uphill. This has no effect on remaining range under battery power.
Maybe some models silently provide little help "to make it feel as normal bicycle" but none of my two bicycles does. Unlike in a car, brakes and steering are not energy dependent and work fine with even battery removed.
Answer: I may misinterpret the way the question is written: what attracts my attention is that you mention "hitting the assist button", which one normally doesn't do when riding an e-bike.
It may comes from a misunderstanding on how e-bikes work. E-bikes are generally set up with assistance level that you can change with the +/- button (Bosch calls the levels Eco/Tour/Sport/Turbo, Shimano Eco/Trail/Boost, and there's an "Off" mode, where the bike is "on", but no assistance is provided), and some have a temporary assist mode, to provide additional power on request (for example, if you have to push the bike, or want to overtake/start faster).
In that case, an explanation that may be consistent with the points written in the question is that the bike is in fact not "off", but in a mode that provide assistance, which would use the power. And when you "hit the assist button", either it provides an additional boost, or the assistance you have is actually coming from the current mode.
Comment: Other systems do have an assist on/off button as well as power up and down
Answer: Maybe there's just some confusion about the proprietary controls on Specialized e-bikes?
Pressing and holding the (+) button on the controls for "assist" is walk-assist mode.   It is not meant as an on-demand throttle for use when riding, if that's how you're trying to use it.
How much riding assistance the bike is providing is shown in the bottom right of the display as 'OFF', 'ECO', 'TURBO' etc. and it is adjusted by clicking the (+) or (-) buttons once, not pressing and holding (+).  If the 20kg+ e-bike 'feels like' a normal 9 speed it is likely on ECO ;)
Answer: I wouldn't be surprised if just having the electronics turned on would consume several Watts. Your eBike battery has 460Wh of energy capacity. If the electronics consume 5W (just a number which I think could be realistic) the battery would be empty after 92 hours.
For comparison, running the motor continuously at its full 250W power would empty the battery in less than two hours.
It's possible to design an eBike in a way which allows you to turn off the motor controller etc. completely and only have the LCD display running, consuming minimal power (note how simple bike computers can run on a single coin cell battery for months or even years). But I doubt they'd go through all the hassle for a bike which is supposed to be used with the motor. I think it's more likely they have a single voltage converter which powers all the electronics, leading to a few watts of "idle" power consumption which has very little impact on the four hours or so of runtime you'd get with using the motor moderately.
Comment: It is then possible to shut down the controller completely. The lack of the speed indicator is not a big loss. But 5 W is the power of Raspberry PI while running desktop complete with web browser and word processor. For the tasks the controller does I would expect more something like 0.3 W that Arduino board uses.