Can we label prophet mohammed a Sunni because he was the messenger through Sunnah?

Question: I am new to Islam. So please be forgiving and understanding, I am curious to learn. Thx.
Answer: The term "sunni" has been invented after the death of the prophet PBUH, because many sect were created after his death, those who are the mainstream (90% of Muslim population) had to be labeled so that they can be distinguished from other sects. and I think your question is somehow doesn't make sense, why ? because sunnah means, the actions and the sayings of the prophet. and muslims who follow these are called sunni. So how would you label the prophet sunni? he is not following anyone?
Hope that helps
Answer: No we can not, we can not be of any sect. See verse below:
Surah 6:159
Sahih International: Indeed, those who have divided their religion and become sects - you, [O Muhammad], are not [associated] with them in anything. Their affair is only [left] to Allah ; then He will inform them about what they used to do.
Pickthall: Lo! As for those who sunder their religion and become schismatics, no concern at all hast thou with them. Their case will go to Allah, Who then will tell them what they used to do.
Yusuf Ali: As for those who divide their religion and break up into sects, thou hast no part in them in the least: their affair is with Allah: He will in the end tell them the truth of all that they did.
Shakir: Surely they who divided their religion into parts and became sects, you have no concern with them; their affair is only with Allah, then He will inform them of what they did.
Muhammad Sarwar: Some of those who have divided their religion into different sects are not your concern. Their affairs are in the hands of God Who will show them all that they have done.
Mohsin Khan: Verily, those who divide their religion and break up into sects (all kinds of religious sects), you (O Muhammad SAW) have no concern in them in the least. Their affair is only with Allah, Who then will tell them what they used to do.
Arberry: Those who have made divisions in their religion and become sects, thou art not of them in anything; their affair is unto God, then He will tell them what they have been doing.
To me the above verse is as clear as daylight, corrupt and ignorant people will tell you different, Allah says that we should not be divided into sects, yet today majority of muslims are divided in sectarian groups even though Allah forbids it. The one group believing that they are on the right path and the other rejoicing in what they believe. You don't have to believe what I say, you are free to believe whatever you want but Allah's verse is clear.
Surah 4:82
Sahih International: Then do they not reflect upon the Qur'an? If it had been from [any] other than Allah , they would have found within it much contradiction.
See above the question that Allah poses for us, don't we reflect upon his book, had it been from anyone else they would find a lot of contradictions in it.
Just think for yourselves, how can each one of them be correct when they are all have different views??? Did Allah authorized the following of these humans and their views??? Nowhere in the Quran can I find this and if Allah left nothing out from the book then why is this not in his book?
Surah 6:38
Mohsin Khan: There is not a moving (living) creature on earth, nor a bird that flies with its two wings, but are communities like you. We have neglected nothing in the Book, then unto their Lord they (all) shall be gathered.
… because it is not for you to follow. We can now understand the reason as to why the Nabi of Allah will complain to Allah on the Day of Judgement that Muslims have deserted the Quran.
Surah25:30.
Sahih International: And the Messenger has said, "O my Lord, indeed my people have taken this Qur'an as [a thing] abandoned."
Pickthall: And the messenger saith: O my Lord! Lo! mine own folk make this Qur'an of no account.
Yusuf Ali: Then the Messenger will say: "O my Lord! Truly my people took this Qur'an for just foolish nonsense."
Shakir: And the Messenger cried out: O my Lord! surely my people have treated this Quran as a forsaken thing.
Muhammad Sarwar: The Messengers will say, "Lord, my people had abandoned this Quran."
Mohsin Khan: And the Messenger (Muhammad SAW) will say: "O my Lord! Verily, my people deserted this Quran (neither listened to it, nor acted on its laws and orders).
Arberry: The Messenger says, 'O my Lord, behold, my people have taken this Koran as a thing to be shunned.'
As you can see from the above verse the words "my people" (not the disbelievers they are already going to hell) have abandoned the Quran. I want you to look today how many religious practices today that we so sincerely practice upon is from Allah's Quran?


High Bush Blueberries with shriveled berries

Question: I have a some wild high bush blueberries in US/NH and there is one bush that needs a major pruning. In past years its produced fairly well but I've definitely noticed its bloomed out a lot this year but not many of the berries are making it all the way. Many of the berries are shriveling up as you can see in the picture. Is this simply because the bush is too old and needs a major prune (as it does and will happen this fall) or could this be another issue for the tree? Water? Diseases?
Answer: The photo indicates the bush has lost most of the leaves, which is typical if the soil has been too dry for longer periods.
Some diseases like Monilinia vaccinii-corymbosi (Mummy berries) can cause shriveled berries too. Cut berries a half and look for traces inside the berries.
The photo shows healthy green berries. I suggest to water when needed until they are fully ripe. If they ripe as healthy berries, then the issue most likely was caused by dry conditions.
Answer: Check the ph of your soil. Blueberries need very acidic soil. Try adding some ammonium sulphate ammonium nitrate, or sphagnum moss.


Preparing a hyper-v VM image

Question: We have a Hyper-V Windows Server 2k3, and we're hosting multiple VMs on it. However, right now, we always start the VM creation right on the server, i.e. when preparing a new Ubuntu image, I just install it into a new VM and set it up and when I'm happy we store the disk image. I wonder if there is a way to prepare a hyper-v image locally on my desktop machine instead? I'm running Windows 7, and I would love to be able to set up a VM so that we can copy the image over to the server and be done with it. This is for linux images only, and we definitely need the hyperv network integration. Is there a recommended way how to prepare hyperv images without running a hyperv instance somewhere?
Comment: Use a config management system. Then you can easily bootstrap and configure nodes in whatever virtualization environment you want. Or on bare metal if you will.
Comment: What config management system do you have in mind? And how would you migrate an image between for instance VirtualBox and hyper-v and KVM?
Comment: Isn't what you're trying to accomplish really just moving the work from the server to a workstation, which leads me to ask: What's the difference?
Answer: If you actually need to run the Ubuntu guest VM to configure it, you'd have to install Windows Server on your workstation.  (Or wait for Windows 8, which includes Hyper-V in client installations.)
If you have a Windows guest, you could use imageex.exe and dism.exe to prep the image off-line without running it.  Perhaps there are similar tools for manipulating Ubuntu.
Or you could use some other client virtualization package and then attempt to migrate it to Hyper-V after running it in some other environment.  Virtual PC is probably the closest environment to Hyper-V that's intended to run on top of Windows 7, though it only supports a single 32-bit virtual processor.  You might have success with Virtual Box or VMware, too.

Preparing a hyper-v VM image


How can I support Sitecorians in Ukraine?

Question: Please let me know how can I support the community in Ukraine?
Together we can make a huge difference. #WeAreSitecore #WeStandWithUkraine
Answer: Sitecore Ukraine Fund
Sitecore has set up a Ukraine Fund to provide immediate and direct assistance for the Sitecore employees and their extended families in Ukraine. Please note that Sitecore intends to match all donations to this fund so your support will go twice as far.
You can donate here to the Sitecore Ukraine Fund: https://www.sitecore.com/ukrainefund
Even if you cannot donate yourself please re-share the message from our CEO to help reach others in the community.
LinkedIn: https://lnkd.in/daXyRCa6
Twitter: https://twitter.com/Tzikakis/status/1498640809167495169
One EPAM
"We stand united with our friends, colleagues, their families and all communities that have been affected by the war in Ukraine and the impact in the surrounding areas.
We are, and we will always be, ONE EPAM. So many of you have already jumped into action with efforts on the ground and volunteering your support, and have asked what more you can do. Thank you for what you have already done to meet our #1 priority – relentlessly doing all we can to keep all of our people safe.
These five giving opportunities below are five more concrete and global ways we can help the urgent humanitarian crisis in the region."
https://epam.benevity.org/community
Other ways to help
Please add here the option you know about. This is a Community Wiki.


What are the possible options for UserType?

Question: The Salesforce docs describe the UserInfo.getUserType() call, which returns the same options as user.UserType.  But I can't figure out where to find a list of the possible return values.  Please provide a complete list, including what each value means.
Answer: Your best bet is to refer to the Salesforce api docs. They do a good job of explaining the fields and their possible values. The link to the doc in question is:
https://developer.salesforce.com/docs/atlas.en-us.212.0.api.meta/api/sforce_api_objects_user.htm
I've included the snippet from the UserType field below.

Description The category of user license. Each UserType is associated
  with one or more UserLicense records. Each UserLicense is associated
  with one or more profiles. In API version 10.0 and later, valid values
  include:

Standard: user license. This user type also includes Salesforce Platform and Salesforce Platform One user licenses. Label is Standard.
PowerPartner: PRM user whose access is limited because he or she is a partner and typically accesses the application through a partner
  portal. Label is Partner.
CSPLitePortal: user whose access is limited because he or she is an organization's customer and accesses the application through
  aCustomer Portal. Label is High Volume Portal.
CustomerSuccess: user whose access is limited because he or she is an organization's customer and accesses the application through a
  Customer Portal. Label is Customer Portal User.
PowerCustomerSuccess: user whose access is limited because he or she is an organization's customer and accesses the application through
  a Customer Portal. Label is Customer Portal Manager. Users with this
  license type can view and edit data they directly own or data owned by
  or shared with users below them in the Customer Portal role hierarchy.
CsnOnly: user whose access to the application is limited to Chatter. This user type includes Chatter Free and Chatter moderator
  users. Label is Chatter Free.
Comment: There are some undocumented usertypes, such as Guest, which is used for force.com and site.com sites users.
Comment: [Here's a bit more info about UserType guest.](http://help.salesforce.com/apex/HTViewSolution?id=000006778&language=en_US)  Ryan is correct in that they appear in a EE/UE SF orgs' Force.com site.
Comment: Additionally, if the Automated Process user is running (most commonly seen as the user creating DuplicateRecordSet and DuplicateRecordItem objects as part of Salesforce Duplicate Management), the UserType returned by this "ghost" user is "AutomatedProcess". Similarly, the License Management App "ghost" user has a UserType of "LicenseManager". I call these "ghost" users because they don't exist as User records and are not returned in SOQL queries.
Answer: Tim Smith's excellent answer already covers the User Types that are currently documented by Salesforce, so I'll focus on the "undocumented" ones.
This screenshot was taken from a picklist lookup, triggered from the List View customization screen for the User object.  It should be a complete list of all User Types as of Spring '14.

Comparing this list to the one that Tim found with the UserType field on the User Object API Documentation page, it would appear that there are two "undocumented" User Types.

Guest
Self Service

As Ryan Guest pointed out, the "Guest" User Type is used exclusively for unauthenticated Force.com and Site.com sites users.  This link, provided by Scott, has more information about how this license type is used: Force.com Sites Guest User Licenses.
That leaves the "Self Service" user type.
The "Self Service" User Type appears to have been deprecated, along with the Self-Service Portal, when Spring '12 was released.  Only orgs that existed prior to Spring '12 continue to have access to the Self-Service Portal.  More information about the Self Service Portal can be found in the Self-Service Portal Implementation Guide.
Answer: Adding one more...
If the running user is the Salesforce to Salesforce (S2S) Connection User, then (as of V32)
UserInfo.getUserType = 'PartnerNetwork'
UserInfo.getFirstName = 'Connection'
UserInfo.getLastName = 'User'
UserInfo.getName() = 'Connection User'
UserInfo.getUserRoleId() = null
UserInfo.getProfileId() = some profileId that can't be inspected (insufficent privileges)
UserInfo.getUserId() = some userId that can't be inspected (insufficient privileges)

The S2S Connection User can not be queried for in SObject User
Answer: It is worth to add that the method returns also:

AutomatedProcess: for Automated Process user only
Answer: Here's what I've figured out so far:

Standard: Indicates a full, normal Salesforce.com license
PowerCustomerSuccess: Customer Portal - Enterprise Admin (Customer Portal Manager Custom)

If you know others, comment and I'll add them in.
Answer: One more value I have encountered on top of the values documented on https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_user.htm

SfdcAdmin
UserInfo.getUserType() == 'SfdcAdmin'

In my use case CampaignInfluence records created by standard Salesforce campaign influence model are created in the context of system user with this usertype.
I have a flow after insert on CampaignInfluence which makes update on Opportunity under certain conditions.
Opportunity has a custom trigger uses fflib which throws exception System.NoAccessException during operations in the custom logic when being executed in this user context.
I use this check (UserInfo.getUserType() == 'SfdcAdmin') to bypass the whole Opportunity trigger as workaround until I identify a more reliable solution.
Interestingly enough when I use SOQL to query User for the CreatedById of CampaignInfluence records I receive zero records.
LastModifiedBy on Opportunity as a result shows either empty value (only timestamp is displayed) for some users and 'salesforce.com, inc.' for other users.
Field history shows that the change was executed by 'Salesforce Administrator'


Windows Phone | Dialog Window Cross Icon and Hardware Back Button

Question: I am developing a windows Phone Application. I have a pop up displayed when an icon is tapped on the screen. That pop has a cross icon on the top right corner so that user can tap on the cross icon and pop up gets closed?
Pop also gets closed when user presses the hardware back button.
I want to ask if it is OK to place a cross icon on pop up windows because there is two way to close the same pop(from hardware back button and from cross icon)????
Is it OK from Windows Phone Certification certification point of View.
Answer: From certification point of view its not a problem as long as the back button also does the same.
Just remember that many users have had WP for a while and you as a developer are expect to support native mechanisms while doing every thing you want to do on top of it.


Returning to a surfaceview after onResume kills performance

Question: My entire game slows down when returning from another app in the emulator (ie pressing the phone button, then back). frame rate drops by half - which turns it into sludge.
Everything is still there, apart from the thread which I kill when the (only) view is surfaceDestroyed (after calling join repeatedly, as with the lander sample.). I make a new thread and attach it - and the game runs, after a fashion.
<code>     if (_thread.getState() == Thread.State.TERMINATED)
     {
      _thread = null;
   _thread = new TutorialThread(getHolder(), this);
   _thread.setRunning(true);
   _thread.start();
  }
  else
  {
   _thread.setRunning(true);
   _thread.start();
  }
</code>
This was after some headbanging and searching on this forum and the game crashing when returning. All the big objects in the game (bitmaps, sound etc) are in the main activity so they don't need to be destroyed or recreated I hope. Music is paused onPause and restarted onResume. It all works much more smoothly on a real phone (htc desire) but I'm worried this behaviour is something to do with 1.6 (which the emulator runs for broad compatibility) or something has been left dangling.
LOGCAT - Lots of SurfaceFlinger messages do turn up (write blocked for n ms) SurfaceFlinger ("executeScheduledBroadcasts skipped, contention on the client") and SurfaceComposerClient whinges about "lock_layer" timing out.
Also, running and jumping back to the home page then running the app (several times) on both the htc and the emulator will eventually cause the app to crash, but with no red issues turning up in Logcat. I'm baffled - any help much appreciated.
Cheers,
Robin.
Answer: I came to the same solution and it works well for me, though I don't think you need the if stament nor _thread=null;
There is anoter solution which I could not make it work which you can see here together with my/your way: Android crash when app is closed and reopened


Call transfer from one device to another through Bluetooth

Question: I am working on an application where I need to transfer call from one device to another through Bluetooth protocol (i.e. I want the way like device transfer the call to hands-free). Any ideas?
Comment: There's no such thing as "transferring the call" in this context. Transferring a call means moving it from one phone to another phone (whereby the original phone is no longer a part of the call). You're trying to just activate an external speaker/microphone. Android already does this automatically if the previously paired device is discovered to be in range during a call.
Comment: @mah so when both devices are paired, lets say device "a" is a pc, and device "b" is a phone, if they're already paired and i get call on my phone, the pc can act like a car-speaker?
Comment: @Elior if your PC plays the role of a bluetooth speaker the way some cars do then yes, but it depends on what functions the pc exposes to remote devices (and though it's possible, it's not something I've heard of being done before... usually it works in the opposite direction -- pc putting out the audio to a remote bluetooth speaker/headset).
Comment: @raxpro: Have you been successful at this? because I need exactly that. To use one phone as freehands of another phone.
Comment: @m4l490n: I need exactly what you need. Please share your experiences.
Comment: @MajidYaghouti as you can see sadly I haven't received any answer to this
Answer: Generally you can't. Android Bluetooth stack implements several Bluetooth profiles including HFP and A2DP. Android is an audio source for both profiles and it streams audio to the connected headset.
The headset should implement Hands-Free Unit (HF) functionality and Android  - Audio Gateway (AG) - as described on Bluetooth.org.
Now you want HF functionality on Android devices, which by design supports AG. You would need to implement HFP profile (HF side) for the device, which you want in fact to act as a headset. Take a look at the profile model. HFP is based on RFCOMM (supported by Android API) and SDP (which is not present in API). You won't be able to access some parts from BlueDroid (modifying SDP etc.) which are on the stack layer. Therefore your mobile phone can't pretend to be headset with HF functionality.
Of course you can send everything over RFCOMM (which is asynchronous as far as I know) but there is no direct support from Android Bluetooth API for this. Implementation with RFCOMM would require SCO link (SCO socket) and it may also be hidden in Android OS stack layer (couldn't find the way to create such socket via API).


SharePoint list, restrict view of particular item within the list

Question: I want to create a list to track complaints progress and results but limit who can see what items. In particular I want to hide 1 item from a particular group
but leave it visible for other groups who have access to the list. All these people have permission to change items so any solutions that are related to amending views won't work because they can change the views themselves if they want to.
Answer: Use Audience Targeting.
That's the Out of Box feature available to meet your requirement. Create two separate views. In one view you give access to all groups while for other view you edit the page and in Audience targeting for that particular view, you list down the groups name you want to give access to.
Comment: is there a way to do the same thing without using two seperate views or lists. Basically have a single list view and one group only sees some of the items while others can see everything?
Comment: the issue here is the group I want to restrict the item from have permissions to write / change the list so could change their view and access the data, which I don't want them to see
Comment: Then give unique permission to the list or the folder or the item..
Comment: Yes those some of the items needs unique permission. Or if you have some kind of filter/policy for items which should be visible to a set of user, you can write custom scripts on the aspx page.


Best way to make a remote database driven iphone application

Question: I have a school project that i think i can do with the concept of secure database driven application , can anybody help me how to do that because i am confused with method will be best and secure. Tutorial link  will be good
Answer: It is relatively simple. You need to send an HTTP request to your server. I like using a JSON object. Or you can just stick everything into a POST. If you are just pulling data from a server and not sending any form the iPhone, you can use this tutorial. Your server then can update or select data in a database using your chosen web dev language.
Answer: hi friend i think you are talking about to use webservices . in this the data is kept in server and you have to retrive it from server for this you hav to first establish connection using asihttpconnection delegate and parse that data using nsxmlparserdalegate
thanks


Why is the equation for a single-neuron perceptron decision boundary Wp + b = 0 set to ZERO?

Question: I am learning about artificial neural networks. I understand how the weights determine the slope of the (orthogonal) decision boundary and how the bias shifts that decision boundary, much like a line. What I do not understamd is why the equation is always set to zero?
Answer: That's linear algebra, not specific to perceptrons or machine learning. Let's start with a simple, two-dimensional case, with axes $x_1$ and $x_2$. Your class boundary can be defined by a straight line:
$$x_2 = a x_1 + b$$
This is a so-called explicit line equation. It has one problem: What if the boundary is a vertical line? In that case $a$ would need to be infinte. You can circumvent this problem by swapping the coordinates and writing:
$$x_1 = c x_2 + d$$
A vertical line is then described by $x_1 = d$, i.e. taking $c=0$. However, here you have the same problem with the horizontal line, because $c$ would have to be infinite. In the first equation, the horizontal line would be written down as $x_2 = b$, i.e. setting $a$ to zero.
The implicit equation, which is easy to derive from the above two, unifies the notation into a general form and is not susceptible to that problem:
$$w_1 x_1 + w_2 x_2 + b = 0$$
You can get the first explicit equation from it by setting $w_1 = a$ and $w_2 = -1$, and the second equation by setting $w_1 = -1$, $w_2 = c$, and $b=d$. A horizontal line can be written down by setting $w_1 = 0$, and a vertical one by setting $w_2 = 0$.
Using vector notation, with $w = [w_1, w_2]$ and $x = [x_1, x_2]$, the implicit equation can be written more compactly as:
$$w \cdot x + b = 0$$
This can be generalized to any number of dimensions.
Comment: @AndréYuhai $a$ is the slope of the line. It gives you the change in $x_2$ for a unit change in $x_1$. For $a=1$, if you change $x_1$ by 1, $x_2$ will also change by 1. That's a 45° line. As $a$ grows, the line becomes steeper. For $a=1000$, increasing $x_1$ by 1 causes an increase of $x_2$ by 1000. That's already much steeper, but still not exactly vertical. Only when $a = \infty$, the line becomes vertical. It's easy to understand if you draw it up.
Comment: The simplified case helps me understand a bit more, but can you clarify how the implicit equation is not susceptible to the infinite _**a**_ problem? Is it not possible to have a verticle line as a decision boundary? or is it becuase the if the wieght is infinite then the decision boundary is horizontal?
Comment: I edited the answer and hope it to be clearer now.
Comment: Could you please elaborate more on the *explicit line* equations? I couldn't get why **a** would need to be infinite. Is it because **a** would need to compensate for all the different values of $x_2$ regardless of $b$ being any arbitrary value?
Comment: Oh, now I got it! Thank you!
Answer: The equation is parametrizing a hyperplane.
You could set your decision boundary to be any parametrized by say Wp + b' = 1 if you wanted to. However, the results would be the same. Since this would be equal to saying the decision boundary is Wp + b'-1 = 0, and then we can define b=b'-1 and estimate b instead of b'


Unable to find the contacts backed up to Google account after the loss of the phone

Question: I backed up my contacts to my Google account. I recently got my phone stolen. I have the same number. I have found some pictures from my previous phone but I can't find my contacts! Some of these cannot be replaced. The only thing I can find is how to restore contacts from my current phone. How to get my friends back?
Comment: Was sync enabled on your old phone? If not than there is a huge chance that the backup has never been created.
Comment: You **got** your phone stolen? You want to get your **friends** back? Firstly, this is all extremely fishy (:()) and secondly, this is also horribly unclear. Please clarify your question to be in simple terms with as little extraneous detail as possible.
Answer: Google offers an option to restore your contacts to any state within the past 30 days. This may help you recover deleted contacts. Just go to https://contacts.google.com/, click on More -> Restore contacts.
Answer: I think that when you log in with your Google account into your phone it should automatically sync those contacts into your device if sync is on.


Can Finder show dates including seconds?

Question: Can you make Finder show timestamps with hour:minutes:seconds?.  It seemed to be possible in old versions of OS X, judging by this post:
https://forums.macrumors.com/threads/show-date-created-down-to-seconds.569085/
Answer: Nothing has changed, except that the location within System Preference has had a name change.
You can do this as follows:

Got to Apple > System Preferences...
Select the Language & Region preference pane
Click the Advanced... button at bottom left
Select the Times tab
You'll see the Short format fields at top
Edit this field by dragging the 'Second' time element from the Time Elements area to the Short field (Note: You'll need to manually enter the colon (:) in between the mins and secs if you was it to be displayed as well)
Click on OK
Exit System Preferences

Now you'll have the seconds displayed in your Finder time stamps.
Comment: you're the absolute Master and Commander, thanks a lot
Comment: @Antonio23249 If this answered your question, should you not accept it?


How to help a child not copy her older sibling's behavior

Question: This question has the same background as Getting stuck on the wrong answer, but I thought it merited a separate question.  Our four year-old daughter quite frequently knows the answer, or could know if she paid better attention, but because of the way her siblings respond, she either thinks their response is normal or more fun, which causes her to not get as much out of the exercise as she could.  How can we help her be her own person and work to her potential instead of copying her siblings' abnormal behavior?
Comment: Ask her first - every time.
Comment: Well, except she remembers his behavior from yesterday.
Comment: Maybe over-time she'd try a different tact?  Especially if, on the days she does answer correctly you made a really big deal out of it!  "Wow, you must have really been paying attention!  What a smart and good decision!  Learning feels so good to me.  Does it to you?  I'm so proud of your choices. . . "
Answer: Why do you ask all of them the same question at the same time? That seems to naturally lead to a copying situation. If quizzing them is an important part of your teaching technique, I would suggest asking 3 different questions on the same video so that each child answers independently. Alternatively, ask a simple factual did-you-see-what-happened question to one child, and a more elaborate question to the next: why? what might come next? what else could it be? Encourage them to cue or tip each other, too, so if someone can't remember what colour something was, the others can give clues or otherwise be helpful. If it's a co-operative effort, there's less pressure to be "better than" or "as good at it" compared to the siblings.
Comment: I repeat the question to see if they were at *least* paying good enough attention to copy each other, which I consider to be a minimum standard of attention.  On the days they can handle that, I move on to independent questions.


Why should I switch to ext4 when upgrading to Ubuntu 9.10?

Question: I'm going to upgrade from Ubuntu 9.04 to Ubuntu 9.10 in a near future and wanted to know if I should migrate my existing ext3 partitions to ext4 during the process and, if yes, why?
Comment: Because every FS is bug proof at first "stable" release?  Wait, no.

As someone who has been bitten by being an early adopter of file systems a bunch of times, I would suggest waiting until someone else looses a bunch of data to some corner case.  In fact, I would suggest waiting for a few of those.
Comment: @Bill Well, I guess Ext4 was considered stable in Jaunty. So it's not really a first stable release. However, I'm not sure many people used it and totally agree with your advice (waiting for some people to loose data). BTW, XFS could be indeed a good idea. Thanks.
Comment: However, why wait?  You can upgrade to XFS right now, and get most of the features of ext4, along with some bonus ones :)
Answer: Ext4 Howto has some information about the features of ext4. Looks over benchmarks find ext4 faster than ext3, though it's not required to turn on all of the new features.
Honestly, you could mount your ext3 partitions with ext4 and take a taste of ext4 without needing to use all the new features. You'll have the ability to go back to ext3.
Comment: Thanks for the answer. However, I've read somewhere: "Ext4 is backward compatible with the ext3 disk format so all you need to do is to mount your ext3 filesystem as ext4 (edit /etc/fstab and reboot). You can later use tune2fs to turn on new ext4 features, but then you need to do a full fsck and wont be able to mount the filesystem as ext3 any more. Only new files created will use the extents feature though.". I'm not sure I'll do this move for now.
Answer: Ok, according to this blog post introducing new features of Karmic Koala:

Ext4 filesystem was introduced in
  Jaunty. In Karmic, it has graduated to
  become the default filesystem. Like
  the GRUB 2 bootloader, the ext4
  filsystem will only be applied for new
  installation. Existing users who are
  still on Ext3 will remain as Ext3
  unless you choose to upgrade to Ext 4
  manually.

So, I won't have to choose during the upgrade from Jaunty to Karmic itself. That's actually a good thing.
Then, I followed the given link describing how to upgrade to ext4 manually and, having read the whole post including comments:

I'm a bit scared
I'm not sure all applications are ready for ext4,
I don't think the benefits are worth the upgrade in my case.

I will thus patiently wait before to upgrade to ext4.


Why can certain variables in a multiple regression not be included in logarithmic form?

Question:
I have a multiple regression equation where log(salary) = b0 + b1(ceotenure). What is the purpose of putting the dependent variable in logarithmic form? How would you interpret the change in y for a 1 unit increase in ceotenure?
For this multiple regression equation, what are the unit measurements for RMSE?
I have a second multiple regression equation where salary = b0 + ln(sales) + ln(marketvalue). How does the fact that the independent variables are now in natural logarithmic form change the interpretation of a 1 unit increase in x leads to a ____ change in y?
I am asked to add profits to this second equation. It asks why this variable cannot be included in logarithmic form? I have no idea.
Comment: Because this is a homework/self-study question, you should add the `self-study` tag to your question. Please take a look at http://stats.stackexchange.com/tags/self-study/info
Answer:
You would use this model under the assumption that "salary" increases exponentially with "ceotenure". The log-linear form captures this relationship. For a 1 unit increase in "ceotenure", the salary changes by a multiplicative factor of $e^{b1}$.
I think it should be the same unit as the dependent variable, so probably "log-dollars".
b1*ln(sales) changes to b1*ln(sales+1), and this isn't free from the current level of sales, so an interpretation of the regression coefficient is not easy here.
Profits may be negative. (Loss!)
Comment: A unit increase in $\ln(\text{sales})$ is the same as multiplying $\text{sales}$ by $e$. More typically we'd examine the effect of say a $1\%$ or $10\%$ increase in sales ($\ln(sales) + \ln(1.01)$ for the log variable, for example) as being more interpretable.


Derivative of a function at a constant point

Question: Let $f(x)=\left\{\begin{array}{c}x^2\sin(1/x), x\ne 0\\0, x=0\end{array}\right.$
Why is it possible to calculate the derivative of the function when $x\neq 0$ "regularly" using the chain rule, and Lebiniz rule, but for the case when $x=0$ you have to calculate it by the definition of the derivative instead, and not just say that the derivative of a constant function is $0$?
Comment: The function would have to be constant on an open interval containing $0$ in order for that argument to be valid.
Comment: When you are given the definition of a function using cases (ie different formulas for different range of values of $x$) then it does not necessarily mean that derivative can be obtained by differentiating those formulas for each case. One actually needs to clearly see what cases are given. Let's not be too mechanical and instead apply definitions and theorems related to derivatives.
Comment: Perhaps I am missing something here; I am confused by your query.  Using the standard definition of the derivative, the chain rule is routinely proven.  Thus, (in effect), in all cases, the derivative is *based* on the standard definition $\lim_{h\to 0}\frac{f(x + h) - f(x)}{h}.$
Comment: I see by the other responses that I have (somewhat) interpreted your query backwards.  That is, instead of answering why you can't regard the function as constant at $x=0$, I have answered that the chain rule is nothing more than the standard definition in disguise.  Therefore, in all cases, the derivative is based on the standard definition.
Answer: Because this is NOT a "constant function"!  The fact that $f(0)= 0$ does not make it a "constant function".  Every function has some specific value at $x= 0$  (or at any $x$).  The fact that the value happens to be $0$ does not matter.
Answer: Note that the limit of your function is defined as
\begin{equation}
f^{\prime}\left(0\right) = \lim_{x\to 0}\frac{f\left(x\right)-f\left(0\right)}{x} = \lim_{x\to 0}\frac{x^{2}\sin{1/x}}{x} = \lim_{x\to 0}\frac{f\left(x\right)-f\left(0\right)}{x} = \lim_{x\to 0}{x\sin{1/x}}.
\end{equation}
Besides, a constant typically means a constant over a neighborhood. It is meaningless to say "constant over a single point". Your function only says that it is $0$ at $0$. It is not a "constant" in any neighborhood around $0$.
Comment: +1 there. I want to add that value of a function at a point is always a fixed number and if we go by the logic (in question) then derivative should be zero everywhere. The notion of derivative (and all things in calculus in general) always needs values at the point under consideration as well as values near that point.
Answer: "...and not just say that the derivative of a constant function is $0$".
There is no interval $(-\delta,\delta)$ in which the function is equal to the constant $0$ for all $x$ in this interval.
Answer: Let $g(x)=\left\{\begin{array}{c}99x+x^2\sin(1/x), x\ne 0\\0, x=0\end{array}\right.$
By your logic, the derivative of $g$ at $0$ is $0$. But I hope you can see that the derivative is actually $99$.


power drain and sometimes will not jump

Question: Mercury Grand Marqui 2000. Had issue last winter with needing to be jumped on very cold days.
Was fine in summer. This winter the problem returned so I bought a new battery. Still, when car sits for more than a few hours I have a portable jumper I have to use. Except last week one time I shut the car off right after a jump (accident) and it would not re-start, even with jump cables left on 8 hours until the flashing light indicated battery was full. Would not start. Next morning hooked up the jump kit and it started.
It's been starting up with a jump every few days but today I jumped it, drove for 20 min and let it sit for 2 hours and it would not take a jump from a truck.
Put gas in it, that isn't the problem. Lights work, car cranks it just doesn't ignite.
Usually with the 4amp charger it will start in 2 minutes even after sitting for 2 days. But tonight it would not start same as last week. Like it will only allow 1 jump per day?
So it does jump most of the time, crank sounds normal, no clicking, no issues with lights while driving or misfires, no other symptoms. I thought 100% it was some drain but the fact that it isn't taking a jump tonight must mean something else is going on?
Comment: What difference do you hear when you put jump leads on and it starts?  Does the starter run faster?  Is it the fact that you can run the starter for longer?  Is it simply the fact that you put the big connectors on the battery terminals that make a difference?  Maybe you just need to clean all the connectors on the battery terminal.
Comment: So the starter turns the engine over at a good (normal) speed, but it just doesn't fire up?
Comment: Yes. It sounds so normal I thought I might be out of gas but my gauge reads 1/2 full and I added a few gallons to be sure. It just won't spark. Usually the jumping works. But it now looks like it isn't going to be a solution every time.
Comment: I will clean battery connections and try newer jump cables tomorrow. But maybe a battery cable in the car is corroted?
Comment: No with the leads on the battery it cranks exactly the same except it (usually) completes the ignition and starts the car. The crank is ok but I'm not getting the spark or something. It just keeps cranking but won't turn the engine on? Today anyways. Earlier in the day I hooked up a 4amp jumper and it started right up. Ran it 30 min. 2 hours later it refused to take a jump. The starter sounds the same with or without the jump. I thought I had a parasitic bleed for sure but this "no 2 jumps in 1 day" thing is odd? Assuming it starts up later today.
Answer: From our discussion in the comments, it would appear to me that you possibly have a bad connection of one of the wires on the battery positive post.  The starter is getting power, but maybe one of the other wires that gives power to the ignition or fuel pump is not connecting every time.  I think adding the jump connectors you are making the connection work.
I would remove each of the wires on the battery terminals and check and clean them before refitting them.
Comment: Along with what HandyHowie is saying, also check the wiring (thick wires to ground and starter) to ensure there's no bulging in them. This would indicate corrosion within the wire which impedes the flow of electricity. If you find bulging, you'd need to replace the wire. Corrosion can cause issues as you've described.
Comment: makes sense. But if that doesn't work the next step is to check fuel delivery. You could have a drain back issue with your fuel pump. This is done with a fuel pressure gauge. Then to confirm Handy Howie's suggestion you can use a spark tester while it's not starting.
Comment: Thanks! It did start again with a jump today and re-started fine after 1 and 2 hours no problem.  Most often after a jump and a long drive it will always start for the next several hours. Also this only happens with cold weather. I did clean the battery hookups and the battery posts are new.

power drain and sometimes will not jump


How can I power a circuit while charging its Li-ion battery pack?

Question: I'm creating a portable device that can be powered by a battery pack, or plugged in and used while charging the battery. At 4:18 in this video (shown below), it shows that the circuit can be powered by the battery charger while it is charging the battery pack through the BMS. I feel like the current draw from the device would interfere with the charger's CC/CV modes and battery state monitoring, causing incorrect battery charging, or insufficient power for the device. Am I missing something, or is the video wrong?
Answer: For applications like this better choice is charger chip with power path, something like BQ2403x, BQ2407x etc.
You are correct that this setup will change charging profile, potentially causing charger overheating, undercharged battery or reduced battery lifetime. Or as simple as device not working if charger cannot supply enough power.
If you want to use these components somewhat better solution would be to create additional path from voltage regulator to the load using diodes or mosfets. Check this application note form Microchip for many good ideas.
Comment: I never looked for more than one cell chargers, so I can't say off-hand if those variants exist. But if you look through that app note you can see that power path can be built using discrete components external to the charger. These devices do not control discharge, usually. Low battery is only of interest to them as a special case where charging profile should be adjusted.
Comment: Looking at the charger on your photo I'd say bq24133 with all the external parts is about the same, complexity-wise. I guess your problem is not in chip complexity but in lack of cheap off-shelf module based on it. Although, if not going for cheap, the TI does sell [evaluation module](http://www.ti.com/tool/BQ24133EVM-715-15V) and [charger module](http://www.ti.com/tool/PMP4397)
Comment: Ooh, I wasn't aware those types of chips existed, the datasheet makes them sound amazing! Do you know if they make 2s or 3s variants? Also, do you know if the chip has low battery voltage protection, or does that need to be designed separately?
Comment: Alright, well apparently the bq24133 chip does the same thing but for 3 cells. Only problem is that it's freaking complicated, so I will be looking for a different solution... Good to know those things exist though!
Comment: Thanks man, you're the best! I'm kinda surprised there aren't more modules that implement that or similar chips. Surely this is a very common thing to need for mini-projects
Answer: It will just take longer during CC mode but may never finish in CV mode as the load current may exceed 5 or 10% of CC current used for cutoff. If this is the case, there should be a timer with CV time limit and cutoff minimum time in order to reduce aging effects at 4.2V.  I would just leave it float at 3.8V if you do not have a separate battery current sensor.
Normally the device senses battery current but here it is the charger.
Answer: You are correct, but the question is how big a deal it's going to be.
With the device powered, the charge will take longer. The charger switches modes based on the battery voltage at the charging current, but in this case, the charging current will be off.
I suppose if the charging circuit were super optimized for a particular battery, you might feel bad that your design was no longer optimum.  Then again, what if the battery life were reduced by 10%? Would it be worth the extra design trouble to get this life back? As the designer, you can decide.
(By the way, the 10% number is just a gut feel guess.  If you are designing something really important or critical, I guess you would have to experiment to find the actual number)


Looking for suitable word for doing errand jobs / petty jobs

Question: I am looking for a suitable word for doing errand / petty jobs. Clerk is not the right word.
Answer: Gofer

A person who runs errands, especially on a film set or in an office; a dogsbody:

Oxford Dictionaries Online
Comment: +1 I added a textual cite. This is our preferred form (text and link) so that readers have a quick indication of the quality of the cite.
Comment: Thank you .. i never heard of the word : dogsbody ... which is perfect
Answer: Errand boy:

(Professions) (in Britain, esp formerly) a boy employed by a shopkeeper to deliver goods and run other errands

(Collins Dictionary)
also
guy Friday:

a man who acts as a general assistant in a business office or to an executive and has a wide variety of especially secretarial and clerical duties.
Comment: and girl Friday
Answer: minion

a person who is not important and who has to do what another person
  of higher rank orders them to do:

http://dictionary.cambridge.org/dictionary/english/minion
Answer: A go-fer is an assistant who's job title derives from the responsibilty of getting coffee for the boss and doing other menial tasks.
"Errand boy" is the derisive title that Kurtz gives Willard in Apocalypse Now: "You're an errand boy, sent by grocery clerks, to collect a bill."
Also: peon, grunt (as in grunt work)
Answer: I would use the term factotum or general factotum.
Oxford Dictionaries Online says:

...an employee who does all kind of work. ORIGIN - mid 16th century
  (originally in the phrases dominum (or magister factotum),
  translating roughly as "master of everything", and Johannes factotum
  "John do-it-all" or "Jack of all trades": from medieval Latin, from
  Latin fac! "do!" (imperative of facere) + totum "the whole
  thing" (neuter of totus).
Answer: Depending on context, you might consider
office boy

: a person, traditionally a boy, employed in an office to run errands, do odd jobs, etc. [1840–50]
Random House Kernerman Webster's College Dictionary
An Office Boy job responsibilities fall into administrative assistants or secretaries. Their duties vary depending on the business office environment. An office boy position is an entry-level one, often filled by interns or recent graduates. Office boys perform various basic administrative duties, such as serving beverages to the guests or staff, handling electronic files and papers, greeting visitors and so on.
Sample Job Descriptions

bellhop

:  a hotel or club employee who escorts guests to rooms, assists them with luggage, and runs errands
M-W

lackey

: someone who does menial tasks or runs errands for another
M-W
Answer: I think "personal assistant" is the preferred term in Corporate America.
http://www.dictionary.com/browse/personal-assistant?s=t
Flunky is another good one, if you're trying to be humorous.


Activate SharePoint Central Admin from console

Question: I have accidentally stopped the central administration service on a share point server and can't find a way to re-activate it?  Is there any way to do this from one of the SP command line utilities?
Answer: That would depend on how it was stopped.  If it is simply the web site itself that has stopped, then you can open Administrative Tools -> IIS Manager, browse to the Sites -> Central Admin Web site, right click and pick Start.  If it doesn't start this way, look in your event logs and see if there is anything there, like a permissions or security error.
If it is stopped some other way or if you accidentally deleted the site then that will take additional steps to recover.
Comment: This link might help.  Step 2 explains the reprovisioning of the Central Admin web site: http://bytelab.blogspot.com/2008/02/move-central-administration-to-another.html.  As always, make sure your farm backups are good before doing this, just in case...
Comment: Yeah - Unfortunetly I believe the site got deleted somehow (kinda confused on how though) - I stoped the service via the Central Admin (clicked the wrong link on the 'Manage Services on this Server' page) but when I tried to start the website via IIS Manager it gave an error and then disappeared from the list of sites.


std::map default value

Question: Is there a way to specify the default value std::map's operator[] returns when an key does not exist?
Answer: While this does not exactly answer the question, I have circumvented the problem with code like this:
struct IntDefaultedToMinusOne
{
    int i = -1;
};

std::map<std::string, IntDefaultedToMinusOne > mymap;

Comment: note you can add `operator int() const {return i;}`, which allows you to treat it as an `int` in most cases.
Comment: This is the best solution for me. Easy to implement, very flexible, and generic.
Comment: @acegs You could make it actually generic: `template  struct default { T t; };` Then you can think about adding conversion operator and converting constructor
Answer: No, there isn't. The simplest solution is to write your own free template function to do this. Something like:
#include <string>
#include <map>
using namespace std;

template <typename K, typename V>
V GetWithDef(const  std::map <K,V> & m, const K & key, const V & defval ) {
   typename std::map<K,V>::const_iterator it = m.find( key );
   if ( it == m.end() ) {
      return defval;
   }
   else {
      return it->second;
   }
}

int main() {
   map <string,int> x;
   ...
   int i = GetWithDef( x, string("foo"), 42 );
}

C++11 Update
Purpose: Account for generic associative containers, as well as optional comparator and allocator parameters.
template <template<class,class,class...> class C, typename K, typename V, typename... Args>
V GetWithDef(const C<K,V,Args...>& m, K const& key, const V & defval)
{
    typename C<K,V,Args...>::const_iterator it = m.find( key );
    if (it == m.end())
        return defval;
    return it->second;
}

Comment: @David I'm assuming the OP doesn't actually want that behaviour. I use a similar scheme for reading configurations, but I don't want the configuration updated if a key is missing.
Comment: +1, but to provide the exact same behavior as the `operator[]` with default value, the default value should be inserted into the map inside the `if ( it == m.end() )` block
Comment: @GMan bool parameters are thought by some to be bad style because you can't tell by looking at the call (as opposed to the declaration) what they do - in this case does "true" mean "use default" or "don't use default" (or something else entirely)? An enum is always clearer but of course is more code.  I'm in two minds on the subject, myself.
Comment: This answer doesn't work if the default value is nullptr, but http://stackoverflow.com/a/26958878/297451 does.
Comment: Nice solution. You might want to add a few template arguments so that the function template works with maps that don't use the default template parameters for comparator and allocator.
Comment: why no auto in your C++11 update.  The definition of "it" is a prime candidate isn't it?
Comment: @David: I agree with Neil, but perhaps the best solution is having a parameter `doInsert` that defaults to false. When true it'll do the insert.
Comment: @GMan Boolean parameters? If the Brotherhood of API Purity get to hear about this, there'll be trouble!
Comment: @Neil: Oh I see, makes sense. I think I'm torn on it too, then.
Answer: C++17 provides try_emplace which does exactly this. It takes a key and an argument list for the value constructor and returns a pair: an iterator and a bool.: http://en.cppreference.com/w/cpp/container/map/try_emplace
Comment: @Ben : IMHO the OP did not intend actually to modify the map but rather to have an equivalent of python Dict get(key,defaultValue).
Definitly there is a missing API in the std to provides an overload at function for such case
Comment: Isn't it? The question was "Is there a way to specify the default value `std::map`'s `operator[]` returns when an key does not exist?" That implies they are calling the non-`const` version of `operator[]` which does (potentially) modify the map.
Comment: That's not exactly the same thing, since it modifies the map.
Answer: The C++ standard (188.8.131.52) specifies that the newly inserted value is default constructed, so map itself doesn't provide a way of doing it. Your choices are:

Give the value type a default constructor that initialises it to the value you want, or
Wrap the map in your own class that provides a default value and implements operator[] to insert that default.
Comment: Well, to be precise the newly inserted value is value initialized (8.5.5) so:
- if T is a class type with a user-declared constructor (12.1), then the default constructor for T is called
(and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static data member and baseclass
component of T is value-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized
Answer: The value is initialized using the default constructor, as the other answers say. However, it is useful to add that in case of simple types (integral types such as int, float, pointer or POD (plan old data) types), the values are zero-initialized (or zeroed by value-initialization (which is effectively the same thing), depending on which version of C++ is used).
Anyway, the bottomline is, that maps with simple types will zero-initialize the new items automatically. So in some cases, there is no need to worry about explicitly specifying the default initial value.
std::map<int, char*> map;
typedef char *P;
char *p = map[123],
    *p1 = P(); // map uses the same construct inside, causes zero-initialization
assert(!p && !p1); // both will be 0

See Do the parentheses after the type name make a difference with new? for more details on the matter.
Answer: There is no way to specify the default value - it is always value constructed by the default (zero parameter constructor).
In fact operator[] probably does more than you expect as if a value does not exist for the given key in the map it will insert a new one with the value from the default constructor.
Comment: Right, to avoid adding new entries you could use `find` which does return the end iterator if no element exists for a given key.
Comment: @ThomasSchaub How much is the time complexity of `find` in that case?
Answer: template<typename T, T X>
struct Default {
    Default () : val(T(X)) {}
    Default (T const & val) : val(val) {}
    operator T & () { return val; }
    operator T const & () const { return val; }
    T val;
};

<...>

std::map<KeyType, Default<ValueType, DefaultValue> > mapping;

Comment: Then modify it so it does work. I'm not going to bother to fix a case this code was not designed to accomplish.
Answer: More General Version, Support C++98/03 and More Containers
Works with generic associative containers, the only template parameter is the container type itself.
Supported containers: std::map, std::multimap, std::unordered_map, std::unordered_multimap, wxHashMap, QMap, QMultiMap, QHash, QMultiHash, etc.
template<typename MAP>
const typename MAP::mapped_type& get_with_default(const MAP& m,
                                             const typename MAP::key_type& key,
                                             const typename MAP::mapped_type& defval)
{
    typename MAP::const_iterator it = m.find(key);
    if (it == m.end())
        return defval;

    return it->second;
}

Usage:
std::map<int, std::string> t;
t[1] = "one";
string s = get_with_default(t, 2, "unknown");

Here is a similar implementation by using a wrapper class, which is more similar to the method get() of dict type in Python: https://github.com/hltj/wxMEdit/blob/master/src/xm/xm_utils.hpp
template<typename MAP>
struct map_wrapper
{
    typedef typename MAP::key_type K;
    typedef typename MAP::mapped_type V;
    typedef typename MAP::const_iterator CIT;

    map_wrapper(const MAP& m) :m_map(m) {}

    const V& get(const K& key, const V& default_val) const
    {
        CIT it = m_map.find(key);
        if (it == m_map.end())
            return default_val;

        return it->second;
    }
private:
    const MAP& m_map;
};

template<typename MAP>
map_wrapper<MAP> wrap_map(const MAP& m)
{
    return map_wrapper<MAP>(m);
}

Usage:
std::map<int, std::string> t;
t[1] = "one";
string s = wrap_map(t).get(2, "unknown");

Comment: MAP::mapped_type& is not safe to return since typename MAP::mapped_type& defval can be out of scope.
Answer: Pre-C++17, use std::map::insert(), for newer versions use try_emplace(). It may be counter-intuitive, but these functions effectively have the behaviour of operator[] with custom default values.
Realizing that I'm quite late to this party, but if you're interested in the behaviour of operator[] with custom defaults (that is: find the element with the given key, if it isn't present insert a chosen default value and return a reference to either the newly inserted value or the existing value), there is already a function available to you pre C++17: std::map::insert(). insert will not actually insert if the key already exists, but instead return an iterator to the existing value.
Say, you wanted a map of string-to-int and insert a default value of 42 if the key wasn't present yet:
std::map<std::string, int> answers;

int count_answers( const std::string &question)
{
    auto  &value = answers.insert( {question, 42}).first->second;
    return value++;
}

int main() {

    std::cout << count_answers( "Life, the universe and everything") << '\n';
    std::cout << count_answers( "Life, the universe and everything") << '\n';
    std::cout << count_answers( "Life, the universe and everything") << '\n';
    return 0;
}

which should output 42, 43 and 44.
If the cost of constructing the map value is high (if either copying/moving the key or the value type is expensive), this comes at a significant performance penalty, which would be circumvented with C++17's try_emplace().
Answer: One workaround is to use map::at() instead of [].
If a key does not exist, at throws an exception.
Even nicer, this also works for vectors, and is thus suited for generic programming where you may swap the map with a vector.
Using a custom value for unregistered key may be dangerous since that custom value (like -1) may be processed further down in the code. With exceptions, it's easier to spot bugs.
Answer: Expanding on the answer https://stackoverflow.com/a/2333816/272642, this template function uses std::map's key_type and mapped_type typedefs to deduce the type of key and def.
This doesn't work with containers without these typedefs.
template <typename C>
typename C::mapped_type getWithDefault(const C& m, const typename C::key_type& key, const typename C::mapped_type& def) {
    typename C::const_iterator it = m.find(key);
    if (it == m.end())
        return def;
    return it->second;
}

This allows you to use
std::map<std::string, int*> m;
int* v = getWithDefault(m, "a", NULL);

without needing to cast the arguments like std::string("a"), (int*) NULL.
Answer: If you have access to C++17, my solution is as follows:
std::map<std::string, std::optional<int>> myNullables;
std::cout << myNullables["empty-key"].value_or(-1) << std::endl;

This allows you to specify a 'default value' at each use of the map. This may not necessarily be what you want or need, but I'll post it here for the sake of completeness. This solution lends itself well to a functional paradigm, as maps (and dictionaries) are often used with such a style anyway:
Map<String, int> myNullables;
print(myNullables["empty-key"] ?? -1);

Comment: This assumes the map itself contains raw optionals, which isn't always the case.
Comment: @Zoe I'm not sure what you're suggesting. My solution is to create a map using an optional of T as the value. If you are writing the code from scratch (or modifying existing code), you can create a map of raw optionals any time you like (with some restrictions, e.g. no optional references)
Comment: But it doesn't work if the map is out of your control - that was my point. It's not a general solution that works for any arbitrary map
Comment: @Zoe Ah, now I understand. Thank you for the input and clarification.
Answer: With C++20 it is simple to write such getter:
constexpr auto &getOrDefault(const auto &map, const auto &key, const auto &defaultValue)
{
    const auto itr = map.find(key);
    return itr == map.cend() ? defaultValue : itr->second;
}

As @425nesp and КоеКто noticed, the compiler won't compile code with undefined behavior only if getOrDefault called as constant expression.
If getOrDefault called as regular function, it possible to end up with a reference to the destroyed temporary.
Example
constexpr auto &v = getOrDefault(m, key, "foo"); // Compile error!
auto &v = getOrDefault(map, key, "foo"); // Undefined behavior!

const auto value = "foo";
auto &v = getOrDefault(map, key, value); // Ok

Comment: If someone says `auto& v = getOrDefault(m, badKey, "foo");`, is it possible to end up with a reference to the destroyed temporary `"foo"`? Since we're returning a reference to `defaultValue`?
Comment: @Childcity the question isn't only about constant expressions. constexpr can be invoked as regular functions - in that case undefined expression isn't excluded,
Comment: @425nesp No, this is not possible, because a compiler must not compile such case
Comment: The standard says: `The requirements for constant expressions do not currently, but should, exclude expressions that have undefined behavior...`[link](https://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1313)
Comment: @КоеКто Yea, you are right! The compiler won't compile code with undefined behavior only if `getOrDefault` called as constant expression. The question is very old, but the c++ standard goes ahead, so my answer is for thouse, who search `getOrDefault` implementation in "constexpr world". Thank's for you're clarification, I will edit answer.
Answer: Maybe you can give a custom allocator who allocate with a default value you want.
template < class Key, class T, class Compare = less<Key>,
       class Allocator = allocator<pair<const Key,T> > > class map;

Comment: `operator[]` returns an object created by invoking `T()`, no matter what the allocator does.
Comment: @sbi: No, I agree this answer is wrong, but for a different reason. The compiler indeed does `insert` with a `T()`, but inside insert is when it will use the allocator get memory for a new `T` then call `construct` on that memory with the parameter it was given, which is `T()`. So it is indeed possible to change the behavior of `operator[]` to have it return something else, but the allocator cannot differentiate why it's being called. So even if we made `construct` ignore it's parameter and use our special value, that would mean *every* constructed element had that value, which is bad.
Comment: @sbi: Doesn't the map call the allocators `construct` method? It would be possible to change that, I think. I suspect a `construct` function that doesn something other than `new(p) T(t);` isn't well-formed, though. EDIT: In hindsight that was foolish, otherwise all the values would be the same :P Where's my coffee...
Comment: @GMan: my copy of C++03 says (in 220.127.116.11) that `operator[]` returns `(*((insert(make_pair(x, T()))).first)).second`. So unless I'm missing something, this answer is wrong.
Comment: You are right. But that seems wrong to me. Why dont they use the allocator function for inserting?
Comment: If you use an allocator to alter []'s behavior, you should keep in mind that T() will be called after allocation. So it's quite useless when used with classes that have their T() constructors. IMHO this approach is the only legal way to give default values for the primitive types like int or double.
Answer: Here is a correct approach that will conditionally return a reference if the caller passes in an lvalue reference to the mapped type.
template <typename Map, typename DefVal>
using get_default_return_t = std::conditional_t<std::is_same_v<std::decay_t<DefVal>,
    typename Map::mapped_type> && std::is_lvalue_reference_v<DefVal>,
    const typename Map::mapped_type&, typename Map::mapped_type>;

template <typename Map, typename Key, typename DefVal>
get_default_return_t<Map, DefVal> get_default(const Map& map, const Key& key, DefVal&& defval)
{
    auto i = map.find(key);
    return i != map.end() ? i->second : defval;
}

int main()
{
    std::map<std::string, std::string> map;
    const char cstr[] = "world";
    std::string str = "world";
    auto& ref = get_default(map, "hello", str);
    auto& ref2 = get_default(map, "hello", std::string{"world"}); // fails to compile
    auto& ref3 = get_default(map, "hello", cstr); // fails to compile
    return 0;
}

Answer: If you would like to keep using operator[] just like when you don't have to specify a default value other than what comes out from T() (where T is the value type), you can inherit T and specify a different default value in the constructor:
#include <iostream>
#include <map>
#include <string>

int main() {
  class string_with_my_default : public std::string {
  public:
    string_with_my_default() : std::string("my default") {}
  };

  std::map<std::string, string_with_my_default> m;

  std::cout << m["first-key"] << std::endl;
}

However, if T is a primitive type, try this:
#include <iostream>
#include <map>
#include <string>

template <int default_val>
class int_with_my_default {
private:
  int val = default_val;
public:
  operator int &() { return val; }
  int* operator &() { return &val; }
};

int main() {
  std::map<std::string, int_with_my_default<1> > m;

  std::cout << m["first-key"] << std::endl;
  ++ m["second-key"];
  std::cout << m["second-key"] << std::endl;
}

See also C++ Class wrapper around fundamental types

std::map default value


Google still indexes pages months after redirecting

Question: We have an event search engine on our site. When an event is over, we keep it viewable for 3 months along with a message telling people that this event is over. After these 3 month, we simply redirect with a 301 to the homepage for the search engine.
The problem is that we have yearly events, and google won't "forget" about those events, even after 5/6 months of redirecting with a 301 to another page. So each year, if you google our site about one of these events, you have two links:

last year's event that will redirect you on our events search engine
one that will take you to the thing you probably searched for

I thought of doing things differently, always showing events, even after 3 months, and instead of redirecting, simply add a noindex meta, would it be better ? should I do anything else ?
Answer: If the event is an annual event and you only keep event webpages online for three months after the event, I would suggest reusing the same URL for the event each year.


Metaphor for creativity

Question: What is a good metaphor for a person that is creative, or for creativity in general? I find nothing when searching and nothing really comes to my mind? Help appreciated!
Answer: Analogy
Analogy is the broader term for metaphors and similes. Pick an aspect of 'creativeness' that you want to emphasize and find a suitable analogy. If it's originality, or ingenuity, or free-association, or the ability to constantly produce, any of these might be analogous to some other well-known thing (a garden, a factory, a waterfall, a flock of sparrows) and by making the analogy you emphasize that aspect even though these things aren't normally associated.
Metonym
Metonym is an associative concept, like "Wall Street" (an actual street in New York's financial district) standing for the stock market and the industry that surrounds it. Similarly, "Hollywood" stands for the movie industry and movies in general, as well as being an actual place where film studios were located.
Synecdoche
synecdoche is when a part represents the whole (or vice-versa) so an artist has "an eye", a musician has "an ear", a dancer has "legs". These are specific things they use in their craft but they stand for broader concepts than what the word actually means. A hitman might be "a hired gun", and an attractive woman might be "a skirt".
Literary philosopher Kenneth Burke grouped 1 more language "trope" with these: Irony. It would probably be used to represent the idea in a negative way, but possibly revealing some underlying 'truth'. The irony of creativity might be some of the negative aspects of art and artists such as an unreliable work ethic, crippling self-doubt, disregarding of morals or society's norms, or inconsistent results.
Answer: Really depends on context but "A five year old when it comes to creativity" might work. The only problem is if the person you are trying to describe is 5 years old.
Comment: For me that example doesn't work _at all_. I'm sort of guessing you mean that five-year-olds are very creative (mostly because that's what the OP asked for), but the sentence could just as well mean the opposite (comparing someone to a young child usually implies a lack of growth/skills/etc). Like I said, I'm aware that you probably mean the former, but the very fact that it's ambiguous makes it a bad metaphor.
Comment: @Llewellyn young kids are much more creative than adults. As far as I know, the stereotype is that they never run out of ideas. The lack of growth/skills that you mention is the lack of practicality, or the lack of ability to make their imagination into reality, but tht in itself is not a lack of creativity.
Answer: "[persons name] is Leonardo da Vinci in terms of creativeness", came up with this.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/21974)
Answer: How about font of ideas? From M-W:
font: a point or place at which something is invented or provided // a domestic diva who is a seemingly endless font of new ideas
A commonly-used metaphor for a creative person.

Metaphor for creativity


Weighted Cox regression: test for goodness of fit?

Question: I want to do a weighted Cox regression analysis (coxphw command in R) since there is violation of proportional hazards assumption in standard Cox model shown by Schoenfeld residuals. What would be the test/metric for goodness of fit in a weighted Cox regression?
Comment: The `coxph` has an argument for `weights=` that you can supply. You don't have to augment the usual method for testing hazard proportionality just because there are non-identical weights. If you actually consult the documentation for `coxphw` you'll find it's a specialized procedure that specifically handles non-constant hazard ratios.
Comment: @AdamO It is the case with my data, I get non-constant hazard but I don't want to do time splitting as I don't have really large numbers. It looks to me that `coxph` with `weights=` argument does not work for my purpose. What would be the appropriate test for fitness in this case?
Answer: As AdamO commented, the coxphw() function is essentially the coxph() function with a particular set of weights. The weights, however, are a function of event times rather than fixed for each case. For the default AHR (average hazard ratio) setting, the weight for all cases at risk at an event time t is set to the product of the estimated survival probability and the inverse of the estimated probability of censoring at that time. That gives a particular type of "average hazard ratio" that has a reasonable interpretation even if proportional hazards (PH) doesn't hold.
The first implication is that there is no need to test for PH if you use coxphw() with the AHR setting. The PH assumption is irrelevant to interpretation of the coefficients.
Second, the "average hazard ratio" for coxphw() is closely related to the concordance metric for model performance; from page 8 of Dunkler et al:

in a two-group comparison, average hazard ratios approximate the odds of concordance $OC = c/(1 − c) = P(T_A < T_B)/P(T_B < T<A)$ very well, $T_A$ and $T_B$ being the survival times of two randomly chosen subjects of groups $A$ and $B$. Intuitively, this can be explained as each pairwise comparison of a subject that fails with all subjects still at risk being given equal importance.

It is not, however, suitable for predictions as functions of time (Table 4 of Dunkler et al). That would suggest a measure of concordance as most appropriate for testing goodness of fit. The coxphw package does provide a concord() function to provide a generalized measure of concordance for each predictor in the model, based on the cases that went into the model.
What would be more satisfying would be a way to validate the model in a way similar to what's done in the rms package: for example, fitting a model to multiple bootstrapped samples of the data, and testing performance of each of those models on the whole data set. That gives a reasonable idea of how well the results would apply to a new sample from the underlying population.
The coxphw package doesn't make that easy, as it seems to have only limited ability to predict outcomes on cases not included in the model. A work-around would be to use the regression coefficients returned by coxphw() to calculate the linear predictor from the covariate values of cases not in the model, and see how frequently the order of linear predictor values agrees with the order of event times between comparable pairs of cases (all pairs of cases with event times; pairs of censored/event cases with censored time greater than event time).
If times to events are important, you could consider spending more time working around the PH problem. For example, if your model has the wrong functional form for a continuous covariate, that could show up as non-PH. Depending on your goals and those of your audience, understanding the nature of any non-PH behavior might end up being more important than just reporting an average hazard ratio.


What is the advantage / disadvantage of joining stations?

Question: I am getting familiar joining stations. I usually have a railway station and 'not joined' bus stations around it. I transfer passengers from bus to railway station. Is it worth to join stations with ctrl-click? Is it any point after that to use busses?
Answer: Joining stations between station types (such as a bus with an airport) allows a common pool of cargo types to be serviced by different transportation methods.
For example, you could have an airport that is next to a fairly large city. If the city is big enough, the airport's catchment zone will not cover much of the city. By attaching some bus terminals to that airport you can move in passengers from farther in the city and 'transfer' them at the airport. Your planes will then pick up those transferred passengers and make more money.
You can do the same for things like goods for multiple cities from one station. One central train station receives goods on transfer, and local buses transfer goods from the train station (via attached depots) to local depots. These are often called 'feeder' systems, since they will 'feed' at a more constant rate than a train will.
Comment: but why don't you join local depots to the central station too, and instead of transfere goods with busses, goods would be 'received automatically'
Comment: from short distance it is not worth to transfer 'phisically' passengers in, but join to main station, and  from longer distances, i.e. from surrounding cities with bus?
Comment: Yes you could bring in passangers from surrounding cities. Remember this is the ultimate sandbox type of game, there is no set way of doing it, neither are there goals to win and making money is very easy once you are familiar with the game. Do what you think looks nice, is fun or lucrative.
Comment: Janos, I was thinking of one central train station supplying three separate towns. If you do not use a feeder system only one of the towns might receive necessary supplies, and even then only when a train arrives. You would have to time your trains such that at least one arrives each time. With feeder systems you can more accurately handle timetables for necessary supplies.


What does word 'shed' mean in this context?

Question: A lot of companies are shedding jobs
Does it mean that companies intentionally get rid of jobs or that they lose it?
Answer: Shed has a few meanings, one of which is

to get rid of something that is not wanted or is no longer necessary

In this case, "shedding jobs" actually fits this description, e.g.

The company shed a further 250 jobs this month.

So yes, the companies are intentionally getting rid of jobs as they are no longer wanted or no longer necessary
Read shed definition at this dictionary with examples
Answer: It is not entirely clear. A company can certainly shed jobs intentionally, as in this definition:

: to rid oneself of temporarily or permanently as superfluous or unwanted
// shed her inhibitions
// the company shed 100 jobs

However, it can also shed things unintentionally, as suggested by this headline:

Netflix sheds subscribers—and $170bn in market value
Can it tempt viewers back with advertising?

That being said, it is somewhat unusual for a company to lose jobs unintentionally. Workers can quit, but then we would usually say that the company "lost employees", not that it "shed jobs". Therefore, in this case it is likely that the companies eliminated the jobs intentionally.


Can load wire have power?

Question: I'm replacing a GFCI in my kitchen. I pulled out the old one without labeling the line and load wires. I flipped the appropriate breaker (I think) but still have power to one of the hot wires. Could I be getting a current back through the load wire?
Comment: please do not post a question until you are 100% certain that you flipped the correct breaker or if none of the breakers cut the power ....... the question is bogus otherwise
Comment: It could be that you did not flip the correct breaker. If you flip that breaker back on, does it power one of the black wires that is unpowered with it off? How many black wires did you have in the box? How many cables? (Each "Romex" NM cable will usually have one black, one white, one bare in one sheath.)
Comment: Thanks Jim I ended up going back to the beginning and found the 2 leads by experimenting then adding the 2 loads that connected to the 2nd GFCI and repeated the process. My first GFCI shared a box with my garbage disposal switch so the box was full of wires which in turn fed the 2nd box which shared a over the sink light with another GFCI that feeds other outlets down the line. Have A Blessed Weekend
Answer: Standard rule for a GFCI is
Part 1, hook up the LINE terminals only, then stop.  Do a test of the GFCI, run it through its paces and make sure it is fully operational.   If it won't behave normally, you hooked it up wrong, back up and iterate on that.
Part 2. Then, power off again and hook up the LOAD terminals.  If that doesn't work (typically it trips), then back up and iterate on that, but you only have to back up to your successful checkpoint in part 1.
Where people get in trouble, especially newbies, is when they try to do both steps at once.   Don't bother, ther are no brownie points for that.

Can load wire have power?


Is a Java package the equivalent of a .Net assembly?

Question: I am a .Net developer starting Java development for Android and would like to know if it's correct to think of Java packages like .Net assemblies.
Answer: No.
The best comparison would be with a Java ARchive (Jar) file.  Java uses packages to control the namespace, and is very similar to C#'s Namespaces.
Here is how I'd compare the environments
<code>Java                    .Net
====                    ====
Class                   Class
Package                 Namespace
Jar                     Assembly
</code>
Comment: I'll add that an Assembly in .Net has more subtle access modifiers than a Jar in Java (at least, that's how I understand it). This answer explains one such detail: http://stackoverflow.com/a/9808237/1168342
Answer: No, I think a Java package would be more similar to a namespace
And an assembly would be more like a jar (I'm not so sure about this, as I'm much more familiar with Java than .Net... correct me if I'm wrong)
Comment: @Joshua: I'm not sure what you mean, or why your comment is being upvoted.  Adding classes to the java.lang "namespace" (not sure what your def of namespace is here) would not require "creating a new package."  In fact "creating a new package" doesn't even make sense from a Java standpoint; a package isn't an entity, it's a naming structure.
Comment: There is zilch-all preventing me from adding classes to the java.lang namespace by creating a new package. One of the ways for breaking checked exceptions called for doing exactly that (overriding Exception & RuntimeException at compile time).
Comment: @Joshua: But in terms of malicious/fun/voodoo things you can do with that, yes I think it's possible but there isn't "zilch-all" preventing you from overriding Exception and RuntimeException...you would have to override the bootstrap classloader for starters.
Comment: @Joshua, adding classes to the java.lang package is possible only if you put the class in its own jar. It would also only work for the added class. If you were trying to replace the Exception class, I'm not sure its possible because the JRE loads that itself even if there is no CLASSPATH defined.
Comment: @Mark: that's true at runtime but the compiler doesn't know that. And the particular procedure I was following only required overriding at compile time, not runtime.
Answer: A Java package is like a namespace in .NET.
The equivalent to an assembly in Java is jar file.
Answer: A package in Java usually means just a namespaces for classes and interfaces, which in reality means a specific directory structure. Sometimes a .jar file is also referred to as a package. This is probably the closest you get to an assembly. A .jar file can also contain other data like images, or basically an kind of file since it is just a zip again with some specific content structure.
In any case: Usually when you read "package" in relation to "Java", some kind of namespaces (via folder structure, e.g.: com.mycompany.myproject) is meant. It doesn't help that some build tools refer to the process of building .jar file as "packaging" ;-)
Answer: Bear in mind that I'm far from a Java expert, but anyway, there it goes my take on this:
As pointed out by other answers, a package is not the equivalent to an Assembly. However, I don't fully agree with the idea of a .jar being the equivalent to an Assembly.
To me, a Java class (contained in a .class file) is closer to an Assembly than a .jar is. I'm saying this cause while the load unit for the CLR is the Assembly (which means all classes contained in that Assembly get loaded), the load unit for the JVM is a class (when the JVM needs a class, the ClassLoader does not load all the classes in the container jar, it just loads that specific needed class).
You can read more about java class loading here:
When does the JVM load classes?
and here:
http://www.lansa.com/support/notes/p0294.htm


USB charger with voltage different than 5 volt

Question: Can somebody explain why and how certain USB charger can supply higher voltage than the standard 5 volt? Apparently certain devices require higher voltage (e.g. ASUS Transformer tablet--requires 15 volts; or Motorola Droid  requires 9 or 9.5 volt. Somehow there is a handshake process when the USB plug is connected to the right device--then the charger knows how to switch to the higher voltage to enable charging. Without this proper handshake, the charger seems to politely issue the standard 5V. What kind of handshake is this, and what's the electronic/logic to determine the demanded voltage?
Comment: http://android.stackexchange.com/questions/18285/charging-the-asus-transformer-prime may answer your question.
Answer: Basically there are a number of options for doing this sort of higher voltage charging.
Older devices did that by using proprietary connectors where additional lines were used for higher voltages (the older Asus Transformer chargers are an example for that).
It would also be possible to have a specific wall ward outputting a higher voltage onto the 5V-USB-line and the device-side being set up to just accept that higher charging voltage. In case of a dumb wall ward there would be the risk that when plugging in any other "normal" USB device it could be damaged.
The cleverer solution is to have this sort of handshake going on where devices can agree higher charging voltages. Recently that was pushed and branded by Qualcomm as "Quick Charge 2.0". It basically works by having some ICs in both the charger and the charged device that are QC certified and have an agreed on handshaking mechanism. There is a patent describing the technology briefly.
On the charger side you will have a high-voltage dedicated charging port (HVDCP) interface IC (i.e. the CHY100) which basically checks the voltage on the USB-D-lines and adjusts the output voltage according to some lookup table (shown in the datasheet).
On the device side you will have a power controller IC (i.e. the FAN6100Q) that checks that the external charger is able to adjust its voltage and if so selects between different modes that result in different voltages requested from the QC-enabled charger.
Comment: @mkeith What is the problem? The question talks about USB wall warts (dedicated charging ports) where there is no handshaking/enumeration. They just charge. If they put a higher voltage (i.e. 15V) on the 5V-USB-line a specific device (as in the example the ASUS Transformer) may be set up to accept that higher voltage for charging faster. If I plug in any other "normal" USB device into that same wall wart and end up with 15V on my 5V line it may cause damage (depending on my circuit).
Comment: @mkeith I think I was mislead by the first example as the chargers I did find for the Asus Transformer were the old proprietary dumb wall wards with some extra signals. I have edited my answer to add a number of different options including the Quick Charge one which is probably what the OP was looking for...
Comment: One would hope that it will default to 5V unless the proprietary negotiation is successful.  This can be done at a high level if the charger is provisioned with enough smarts to respond to USB messages.  It only needs to enumerate as the specific style of charger and then receive a message from the device to increase voltage. It looks like some of the chargers use non standard conenctors that have extra pins that are ignored by the micro USB socket.
Comment: @og1L, When you don't know the answer to the question, just make a comment. Don't make a comment as an answer. And there isn't really any evidence yet that anything can or will be blown up. As long as the handshake (if it really exists) is reliable.
Comment: @og1L, maybe the OP edited the question after your response. But the question is very clearly and specifically asking for information about special chargers which DO have a handshake. Take a look. I am not saying those chargers exist, but if they do, they would be safe because they would only supply 5V until the secret handshake was completed.


What is the best animal to cryogenically freeze then revive?

Question: I had recently watched this https://www.youtube.com/watch?v=2tdiKTSdE9Y video on how scientists were using microwaves to revive hamsters after they've been frozen. Now Tom Scott mentions this doesn't work on humans as we are too big, however, say we are sending a spaceship to some distant place. What would be the best animal small enough, but smart enough to be able to complete some relevant goals? Maybe just push some buttons or react to warning signs. Or just have it genetically modified to be super intelligent. Anyway, thought this would be an interesting idea. Any info is appreciated.
Comment:  Perhaps a little more detail on the relevant goals? might be helpful in narrowing down 'smart enough'?
Comment: Also, why do you need animals? It seems like if you can build the spaceship, you can build robots...?
Comment: What's your own idea?
Answer: Frog Icicle

Some frogs freeze solid in the winter. Then when it warms up they thaw out and get back to eating bugs. See here.

tap tap tap
Answer: There are primates barely bigger than hamsters -- the pygmy marmoset, for instance, grows to only 4 1/2 to 6 inches (11 - 15 cm) length and a few tens of grams.  And yet, this is an actual monkey.  It should be well possible to train it to react to different colored lights (almost all primates have color vision much like ours, instead of being dichromats -- "color blind" like most mammals) or particular sounds.
Like most very small mammals, they don't live very long, but if you can keep them frozen, they might well "keep" for decades.
Comment: At that size crows probably outperform any primates of comparable body wieght?
Comment: Maybe so, but we know this works on small mammals.  Birds??  Dunno...
Answer: Border collie puppy.

source
Here is puppy 654958.  She is not the only puppy on this ship.  654959, 654960 and 654963 are her crewmates.  654961 had a freezer malfunction and did not get thawed - she is still in there, sleeping, waiting for season 2.  654962 is on board but he does not pay attention in puppy school and so pretty much just hangs out with them.  He is good company though.  He may or may not be a border collie; some suspect he is a black lab / pug mix.
The space pups are thawed and then raised by a fluffy robot dog mom.  They have a puppy school led by human and dog robots and they learn their jobs on the ship.
The puppies are crazy cute and are voiced by wonderful voice actors, as is Robot Dog Mom.  Each pup has its own role in their team of 4 (or team of 5 if you count 654962) and they solve problems and have adventures in their ship far from earth.


ASP.NET MVC Issue with Using Reflection Created Objects with the Default Model Binder

Question: I am having a weird issue in ASP.NET MVC with objects not being updated with UpdateModel when passed a formCollection. UpdateModel does not appear to be working properly when the object being updated is created through reflection.
Scenario: I have an application which has approximately 50 lookup tables--each of which includes exactly the same schema including typical fields like id, title, description, isactive, and createdon. Rather than build 50 views, I wanted to have a single view which could display the data from all of the lookup tables. I created an Interface called IReferenceEntity and implemented it in each of the POCOs representing my lookup tables.
Using this interface, I am able to easily populate a view with a record from the lookup table. (I pass the items to the view via the following.)
System.Web.Mvc.ViewPage<MyNamespece.IReferenceEntity>

From the database to the view, every thing works perfectly.
However, when I attempt to update the model on post, I am running into some problems.
If I explicitly declare an object reference like the following, every thing works perfectly and the values of my object are updated with the values from my form. Hence, I can then update the database.
AccountStatus a = new AccountStatus();

UpdateModel(a, formCollection.ToValueProvider());

Unfortunately, hard coding the object type would completely defeat the reason for using an interface.
(A primary objective of the application is to be able to dynamically add new tables such as lookup tables without having to do anything "special". This is accomplished by reflecting on the loaded assemblies and locating any classes which implement a specific interface or base class)
My strategy is to determine the concrete type of the object at postback and then create an instance of the type through reflection. (The mechanism I use to determine type is somewhat primitive. I include it as a hidden field within the form. Better ideas are welcome.)
When I create an instance of the object using reflection through any of the following methods, none of the objects are being updated by UpdateModel.
Type t = {Magically Determined Type}

object b = Activator.CreatorInstance(t);

UpdateModel(b, formCollection.ToValueProvider());

Type t = {Magically Determined Type}

var c = Activator.CreatorInstance(t);

UpdateModel(c, formCollection.ToValueProvider());

Type t = {Magically Determined Type}

IReferenceEntity d = Activator.CreatorInstance(t);

UpdateModel(d, formCollection.ToValueProvider());

Note: I have verified that the objects which are being created through relection are all of the proper type.
Does anyone have any idea why this might be happening? I am somewhat stumped.
If I was really "hard up", I could create factory object which would many instantiate any one of these reference entity/lookup objects. However, this would break the application's ability to allow for new lookup tables to be added and discovered transparently and is just not quite as clean.
Also, I could try deriving from an actual ReferenceEntity base class as opposed to an interface, but I am doubtful whether this would make any difference. The issue appears to be with using reflection created objects in the modelbinder.
Any help is appreciated.
Anthony
Answer: Augi answered this on ASP.NET forums. It worked with only a couple of minor modifications. Thank you Augi.

The problem is that [Try]UpdateModel methods allow to specify model type using generic parameter only so they don't allow dynamic model type specification. I have created issue ticket for this.
You can see TryModelUpdate method implementation here. So it's not difficult to write own overload:
public virtual bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IDictionary<string, ValueProviderResult> valueProvider) where TModel : class
{
    if (model == null)
    {
        throw new ArgumentNullException("model");
    }
    if (valueProvider == null)
    {
        throw new ArgumentNullException("valueProvider");
    }

    //Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
    IModelBinder binder = Binders.GetBinder( /*typeof(TModel)*/model.GetType());

    ModelBindingContext bindingContext = new ModelBindingContext()
                                             {
                                                 Model = model,
                                                 ModelName = prefix,
                                                 ModelState = ModelState,
                                                 //ModelType = typeof(TModel), // old
                                                 ModelType = model.GetType(),
                                                 // new
                                                 //PropertyFilter = propertyFilter,
                                                 ValueProvider = valueProvider
                                             };
    binder.BindModel(ControllerContext, bindingContext);
    return ModelState.IsValid;
}

Answer: Does your IReferenceEntity contain setters on the properties as well as getters?  I would think that the last sample would work if the interface had property setters, though you'd have to cast it to get it to compile.
Type t = {Magically Determined Type}

IReferenceEntity d = Activator.CreatorInstance(t) as IReferenceEntity;

UpdateModel(d, formCollection.ToValueProvider());

Normally the reason that it won't set a property on a class is because it can't find a public setter method available to use via reflection.
Comment: Thank you for your response. Unfortunately, UpdateModel and TryUpdateModel do not support dynamically typed parameters out of the box. Augi's solution overcame the limitation. Thank you for taking the time to help me though!
Answer: Just a quick "another thing to try":
UpdateModel(d as IReferenceEntity, formCollection.ToValueProvider());

Not sure if that will work, and I haven't tried it myself, but it's the first thing that came to mind.
If I get a chance later I'll peek at the Default Model Binder code and see if there's anything in there that is obvious...
Comment: It didn't quite work as I mentioned in my answer. However, I really appreciate your taking the time to answer. Thank you!