git fetch works from command line but not from the hook

Question: I was thinking whether the question belongs here or on SO. 4 days ago I created a question from command line ok but the hook (git)  on SO. So far no answer.
To make it quick and simple.... I want to fire 'post receive' when somebody does push to my remote repository. The hook will fetch the new stuff into another repository. Why? Redmine needs it like that so this repository is browse able.

when I run all necessary commands from the command line everything works.
when I run the same commands from the hook

there is no output from git when the hook executes git fetch
redmine tells 'The entry or revision was not found in the repository.'

I tried lots of stuff to make it work and have no idea what to do next :-)
Please read SO question for more details.
Comment: "When I do a `git fetch`, everything but the hook works." or "everything works, except the hook". I see what you meant but Dennis is right, it would be clearer with a "not"
Comment: Should your question title say `"git fetch works from command line but not the hook"` (add the word "not")?
Comment: to be honest ... English is not my first language and I was thinking about 'adding not'. I thought that but negates whatever is before but....
Answer: I do know exactly what and why but after git fetch executed via hook (I use gitolite) some files (maybe new ones) has permissions that redmine `doesn't like.
chmod -R 770 redmine_repo.git

did the trick


How to embed and choose entityform in custom content type?

Question: I have a D7 Website, and I am using entityforms module.
I want to include those entityforms which I created in my custom content type so that users can submit their details. For example: a node with multi-field comments box.
To achieve this, I added a field in custom content type of type "Entity reference" -> List.
As an admin, I get to choose all available entity forms but not as a custom user role for which it shows "access restricted" while choosing entity form type.
Please guide.
Comment: Your question needs more details. Let me see if I got this right: you want to create a new Content Type that has an Entity Reference field. Do you want this field points to Entityform types or to Entytform submissions? What do you mean by "made visible"? Do you want the entire submission  to be visible? The user to be redirected to the form? The form itself to become visible? The name of the form to become visible? As for the access restricted, go to /admin/people/permissions and set the right permissions for the new user role
Comment: Please check the updated one.
Answer: OK, so I gather the problem you are trying to solve is the fact that a non-administrator cannot pick an entityform from the list? The solution: go to /admin/structure/entityform_types, choose "Edit" for each Entityform and be sure to check the boxes in "Roles" for "authenticated user". That way anyone logged in should be able to see and use the form.
Comment: Thanks a lot for this. Just one more question, what if I want users to see specific entity, meaning they shouldn't get option to choose. Is that also possible ?
Comment: Go to  /admin/structure/entityform_types, click Edit on each of the entityforms, and disable access for the specific Roles that should not be able to see that form. Then go to /admin/structure/types, click "Manage fields" for the Content Type that contains the Entity Reference field. Click on the link "Entity reference" in the "Field type" column. Click on the "Edit" tab next to "Field Settings" and choose the default entityform you want the user to see by choosing it in the "Default Value" fieldset. You may want to start a new question if this explanation doesn't completely help.


How to get a URL from a new image using Cloud Function with Flutter?

Question: How I can get a URL from new Images in fire-storage with the Images name?
I am uploading an image with Flutter using firebase_storage plugin
Code in flutter:
StorageReference ref =
    FirebaseStorage.instance.ref().child("$stamp.jpg");
    StorageUploadTask uploadTask = ref.putFile(imageFile);
    Uri downloadUrl = (await uploadTask.future).downloadUrl;
    downloadableUrl = downloadUrl.toString();

but the image sizes are too big, thus I create a Cloud Function to generate lower quality images from this upload.
Cloud Fuction:
const functions = require("firebase-functions");
const gcs = require('@google-cloud/storage')();
const os = require('os');
const path = require('path');
const spawn = require('child-process-promise').spawn;

exports.onFileChange= functions.storage.object().onChange(event => {
    const object = event.data;
    const bucket = object.bucket;
    const contentType = object.contentType;
    const filePath = object.name;
    console.log('File change detected, function execution started');

    if (object.resourceState === 'not_exists') {
        console.log('We deleted a file, exit...');
        return;
    }

    if (path.basename(filePath).startsWith('resized-')) {
        console.log('We already renamed that file!');
        return;
    }

    const destBucket = gcs.bucket(bucket);
    const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
    const metadata = { contentType: contentType };
    return destBucket.file(filePath).download({
        destination: tmpFilePath
    }).then(() => {
        return spawn('convert', [tmpFilePath, '-resize', '500x500', tmpFilePath]);
    }).then(() => {
        return destBucket.upload(tmpFilePath, {
            destination: 'resized-' + path.basename(filePath),
            metadata: metadata
        })
    });
});

How I can get the resize-image Url in flutter? I need to use this URL in data registration
Answer: I'm pretty sure there is no easy way.
I would maintain a table in Firebase with the original file name as key and the new file name as value.
You create the entry from your cloud function above and read it from Flutter using Firebase database access (Realtime Database or Cloud Firestore)
Comment: This is indeed the most common approach, using the Firebase Realtime Database or Cloud Firestore as a signaling mechanism/message bus. I most commonly make the Cloud Function trigger on a database write, which I then do from the client-side code after the image has been uploaded. The Cloud Function reads the metadata, finds the file and resizes it, and then writes the response back to a pre-agreed location. Nowadays you can also consider using a [Callable HTTPS function](https://firebase.google.com/docs/functions/callable) for this.


How do I pull a field value from a form field in to my inline entity form?

Question: I'm trying to do something which I would think is fairly simple, but I'm just stumped right now, hoping somebody can help.
I have an entity called 'page', and in that entity I have inline entities called 'subpages'. Both of these entities have a field called 'group_reference' which tells the entity what 'group' the entities belong to.
Basically what I want to do is automatically change the group_reference form field value in my inline entity form to match the group reference in my page form. So far, I'm using inline_entity_form_entity_form_alter to access the inline entity forms values. I'm able to adjust the value to an arbitrary value like this:
function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#bundle'] == 'subpage') {
    $entity_form['field_group_reference']['und']['0']['#default_value']=X;
  }
}

X being the group id.
So the next step I want is to pull in the group id from the page group_reference field which is already set. That way, they will always match (the user is not able to change this value, it all should be done behind the scenes).
I've tried to include in my module a function that pulls out the value from the field, but I just can't seem to make it work:
function MYMODULE_grab_group_reference(&$form, &$form_state) {
    return $form['field_group_reference']['und']['#value'];
}

function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#bundle'] == 'subpage') {
    $groupid=MYMODULE_grab_group_reference();
    $entity_form['field_group_reference']['und']['0']['#default_value']=$groupid;
  }
}

I've tried a bunch of different variations. Am I not targeting my values correctly? Is this just an improper way to do it? I'm flummoxed. Any help would be greatly appreciated! Thanks!
Answer: Just want to share my solution to this problem. Turns out I didn't need another function, I had all the variables available in my MYMODULE_inline_entity_form_entity_form_alter function in the $form_state array.
I targeted: $form_state['input']['field_group_reference'][und]
And that got me the value of the field in my parent entity.
Comment: good job at finding a solution to your problem!


Checking for and indexing non-unique/duplicate values in a numpy array

Question: I have an array traced_descIDs containing object IDs and I want to identify which items are not unique in this array. Then, for each unique duplicate (careful) ID, I need to identify which indices of traced_descIDs are associated with it.
As an example, if we take the traced_descIDs here, I want the following process to occur:
traced_descIDs = [1, 345, 23, 345, 90, 1]
dupIds = [1, 345]
dupInds = [[0,5],[1,3]]

I'm currently finding out which objects have more than 1 entry by:
mentions = np.array([len(np.argwhere( traced_descIDs == i)) for i in traced_descIDs])
dupMask = (mentions > 1)

however, this takes too long as len( traced_descIDs ) is around 150,000. Is there a faster way to achieve the same result?
Any help greatly appreciated. Cheers.
Answer: While dictionaries are O(n), the overhead of Python objects sometimes makes it more convenient to use numpy's functions, which use sorting and are O(n*log n). In your case, the starting point would be:
a = [1, 345, 23, 345, 90, 1]
unq, unq_idx, unq_cnt = np.unique(a, return_inverse=True, return_counts=True)

If you are using a version of numpy earlier than 1.9, then that last line would have to be:
unq, unq_idx = np.unique(a, return_inverse=True)
unq_cnt = np.bincount(unq_idx)

The contents of the three arrays we have created are:
>>> unq
array([  1,  23,  90, 345])
>>> unq_idx
array([0, 3, 1, 3, 2, 0])
>>> unq_cnt
array([2, 1, 1, 2])

To get the repeated items:
cnt_mask = unq_cnt > 1
dup_ids = unq[cnt_mask]

>>> dup_ids
array([  1, 345])

Getting the indices is a little more involved, but pretty straightforward:
cnt_idx, = np.nonzero(cnt_mask)
idx_mask = np.in1d(unq_idx, cnt_idx)
idx_idx, = np.nonzero(idx_mask)
srt_idx = np.argsort(unq_idx[idx_mask])
dup_idx = np.split(idx_idx[srt_idx], np.cumsum(unq_cnt[cnt_mask])[:-1])

>>> dup_idx
[array([0, 5]), array([1, 3])]

Comment: I'm much more comfortable with this answer and it doesn't appear to take much longer than the dictionary answer above. Thank you for your time.
Answer: There is scipy.stats.itemfreq which would give the frequency of each item:
>>> xs = np.array([1, 345, 23, 345, 90, 1])
>>> ifreq = sp.stats.itemfreq(xs)
>>> ifreq
array([[  1,   2],
       [ 23,   1],
       [ 90,   1],
       [345,   2]])
>>> [(xs == w).nonzero()[0] for w in ifreq[ifreq[:,1] > 1, 0]]
[array([0, 5]), array([1, 3])]

Comment: I didn't know about this function. Thanks for bringing it to my attention.
Answer: Your current approach is O(N**2), use a dictionary to do it in O(N)time:
>>> from collections import defaultdict
>>> traced_descIDs = [1, 345, 23, 345, 90, 1]
>>> d = defaultdict(list)
>>> for i, x in enumerate(traced_descIDs):
...     d[x].append(i)
...
>>> for k, v in d.items():
...     if len(v) == 1:
...         del d[k]
...
>>> d
defaultdict(<type 'list'>, {1: [0, 5], 345: [1, 3]})

And to get the items and indices:
>>> from itertools import izip
>>> dupIds, dupInds = izip(*d.iteritems())
>>> dupIds, dupInds
((1, 345), ([0, 5], [1, 3]))

Note that if you want to preserver the order of items in dupIds then use collections.OrderedDict and dict.setdefault() method.
Comment: Personally I would prefer the numpy solution, but if you want to go this way, the standard library has you covered: from collections import Counter
Comment: Could you expand on exactly what isn't preserved by not using OrderedDict?
Comment: Note that this solution will create a lot of python objects, hence memory useage will explode; that's why staying within numpy is probably preferable, if you are dealing with large datasets.
Comment: @CarlM The output here could have been `[345, 1]`, as dicts have no order. An `OrderedDict` will make sure the output is `[1, 345]`.`
Answer: td = np.array(traced_descIDs)
si = np.argsort(td)
td[si][np.append(False, np.diff(td[si]) == 0)]

That gives you:
array([  1, 345])

I haven't figured out the second part quite yet, but maybe this will be inspiration enough for you, or maybe I'll get back to it.  :)
Answer: A solution of the same vectorized efficiency as proposed by Jaime is embedded in the numpy_indexed package (disclaimer: I am its author):
import numpy_indexed as npi
print(npi.group_by(traced_descIDs, np.arange(len(traced_descIDs))))

This gets us most of the way there; but if we also want to filter out singleton groups while avoiding any python loops and staying entirely vectorized, we can go a little lower level, and do:
g = npi.group_by(traced_descIDs)
unique = g.unique
idx = g.split_array_as_list(np.arange(len(traced_descIDs)))
duplicates = unique[g.count>1]
idx_duplicates = np.asarray(idx)[g.count>1]
print(duplicates, idx_duplicates)

Answer: np.unqiue for Ndims
I had a similar problem with an ndArray in which I want to find which rows are duplicated.
x = np.arange(60).reshape(5,4,3)
x[1] = x[0]

0 and 1 should be duplicates in axis 0.  I used np.unique and returned all options.  Then use Jaime's method to locate the duplicates.
_,i,_,c = np.unique(x,1,1,1,axis=0)
x_dup = x[i[1<c]]

I unnecessarily use return_inverse for clarity.  Here are the result:
>>> print(x_dupilates)
[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]
  [ 9 10 11]]]


Single choice selection dialog in android

Question: I am making an android program. In my app, I am using a single choice selection AlertDialog whose items are added programmatically. What I want to do is:

set a background color to the selected item next time user opens the dialog,
show selected item in the middle of the dialog(this is a problem because there are about 20 items).

Here is what I have:XML:
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dp" >

    <Button
        android:id="@+id/selectDateButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please, select date" />

</LinearLayout>

JAVA:
public class ExperimentListView extends Activity {

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static Calendar calendar = Calendar.getInstance();
private static Button selectDateButton;
private static String[] items;
private static int selectedDatePosition = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_view_ex);

    selectDateButton = (Button)findViewById(R.id.selectDateButton);
    selectDateButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            items = new String[20];
            for (int i = 0; i < 20; i++) {
                items[i] = DATE_FORMAT.format(calendar.getTime());
                calendar.add(Calendar.DATE, 1);
            }
            showListView();
        }
    });

}

private void showListView() {
    AlertDialog.Builder builder = new AlertDialog.Builder(ExperimentListView.this);
    builder.setTitle("Select date");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            selectedDatePosition = which;
            selectDateButton.setText(items[selectedDatePosition]);
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.getListView().setSelection(selectedDatePosition);
    alertDialog.show();
 }
}

I haven't been able to find a solution to this so far and I would be grateful if someone can help.
Thanks in advance.
Answer: Instead of using builder.setItem use builder.setSingleChoiceItems with selected item position passed as an argumet like
    builder.setSingleChoiceItems(strArray, selected_pos, new DialogInterface.OnClickListener ()
    {
         @Override
         public void onClick(DialogInterface dialog, int which)
         {

         }
    });

Comment: Single choice dialog sounds not to meet my need, because there is a point to select on which my custom style doesn't approve of. That is why I haven't used it.
Comment: I used single choice in the app, but I would be curious to know if someone finds the solution.
Answer: 1)To set the background color you can use custom view for your Alert Dialog
2)to show the selected item in the middle of the dialog you need to swap its position in the array which you are passing to list for alert dialog.
3)And as you want background color respected to the item previously selected ,use shared preferences to store item and background,and regain the background and item selected when user open the alert dialog.
And as Deepika said use setSingleChoiceItems for single choice selection.
Comment: Thanks for the response. The idea of swapping seems good, but I wanted something like scrolling to the selected item before UI is shown without notice of users. 3) In my case, I think no need for shared preferences since every time the default text is set to the button.


Which chord should be accented?

Question: I was looking at the Liszt transcription for Beethoven's 7th symphony for solo piano, and in the second movement there seems to be no accent on the first chord of every measure (75-98), yet when listening to the orchestral version, Katsaris's interpretation and a synthetic application rendering of the movement, they all play the first chord extremely loud, and the chord that is actually accented is played in a similar manner to it's surrounding chords (i.e. in a relatively low intensity), so I am asking as to why is this the case with the notation ?.
P.S: I did notice that the accented chord is a bit louder in the orchestral version, but still, it is far softer compared to the first chord which is unaccented.
Comment: Trust me, your English is fantastic! Honestly, I never would have thought by reading your post that you were not a native speaker.
Comment: May I ask what you mean by "a synthetic application rendering of the movement"?
Comment: A video on YouTube by Tomplay: https://youtu.be/x8StWgkSF7k.                                                    The only exception is a synthetic rendering by PianoCzarX, in which the transcription is played as I imagine it to be played according to the sheets: https://youtu.be/X-KKdCX-J1c
Comment: I am not a native English speaker nor have I been to an English-speaking country before, so please excuse my English, I try my best to learn.
Answer: Part of the basic concept of meter is that the first beat of a measure is accented. There is no need to specifically write out that default accent on beat one in notation.
If beat one gets an accent by default, it stands to reason the other beats are unaccented.
2/4 meter should have a kind of | BOOM pa | BOOM pa| feel where BOOM is the accented beat one. At least that is the basic idea. In a real performance a player can treat accent more subtly as phrases are played.
When the accent is written on beat two it is to make clear the feel should be | BOOM BOOM | BOOM BOOM |. Don't lighten up on beat two! Instead of the oscillating feel of strong and weak - sort of like a pendulum - the accent of beat two results in all strong beats. It creates an incessant feel more like a hammer than a pendulum.

Which chord should be accented?


What is the difference between null and System.DBNull.Value?

Question: Is there any difference between null and System.DBNull.Value? If yes, what is it?
I noticed this behavior now -
while (rdr.Read())
{
    if (rdr["Id"] != null) //if (rdr["Id"] != System.DBNull.Value)
    {
        int x = Convert.ToInt32(rdr["Id"]);
    }
}

While I retrieve data from the database using a sql datareader, though there is no value returned if(rdr["Id"] != null) returned true and eventually threw an exception for casting a null as integer.
But, this if I use if (rdr["Id"] != System.DBNull.Value) returns false.
What's the difference between null and System.DBNull.Value?
Comment: I'm not sure myself.  Here's one answer: http://stackoverflow.com/questions/4488727/what-is-the-point-of-dbnull/4488758#4488758 It's also possible that before nullable value types were around in C#, it would have been more of a hassle to deal with `null`.
Comment: I had an answer here, but I realised it was more suitable for http://stackoverflow.com/questions/4488727/what-is-the-point-of-dbnull/ - so I moved it
Comment: Well, they're unrelated.  One is a static instance of a class in `System.Data`, and the other is a special value signifying the lack of a referent.  They have nothing to do with each other.  Can you elaborate on what you're confused about?  Is your real question "why do `DataRows` and `DataReaders` put `DBNull.Value` inside of themselves instead of `null`?"
Comment: Well, my it wasn't initially but after learning from what you said, I am curious. Could you tell me why DataRows and DataReaders put DBNull.Value in themselves instead of null?
Answer: Well, null is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.
Comment: +1 A practical example: if you use `IDbCommand.ExecuteScalar()`, it can either return null (no records returned) or `DbNull` (first column in first record is a 'nonexistent value'). Without `DbNull` you would not be able to distinguish one from the other.
Comment: A null reference is perfectly valid. ☺
Comment: I would strongly recommend to use a language which forbids the use of Null, and does so at absolutely 0 extra cost. life is too short for "null object pattern"
Comment: @C.Evenhuis Well, there is another common advice: a function should return only one type of value. That is why people prefer well-typed TypeScript code. "What is the status of the execution" differs from "What is the computational result". Ie. they could have decided to implement this function somehow else (maybe an out parameter, or an object similar to HTTP request response objs). Sure, this is a not-really wanted complication, but if they had done that, maybe null could be used instead of DbNull.
Answer: From the documentation of the DBNull class:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.
Answer: DBNull.Value is annoying to have to deal with.
I use static methods that check if it's DBNull and then return the value.
SqlDataReader r = ...;
String firstName = getString(r[COL_Firstname]);

private static String getString(Object o) {
   if (o == DBNull.Value) return null;
   return (String) o;
}

Also, when inserting values into a DataRow, you can't use "null", you have to use DBNull.Value.
Have two representations of "null" is a bad design for no apparent benefit.
Comment: The sentiment of disgust we share re: your last statement is trumped only by the irony of showing up here to read this and finding out your username is "loathing"
Answer: DBNull.Value is what the .NET Database providers return to represent a null entry in the database.  DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.
http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx
Comment: DBNull is *not* "what the database returns" - it is simply how ADO.NET chooses to interpret it; personally I'm not sure that this interpretation is very valuable
Comment: p.s.  You should also use DBNull.Value to pass a null parameter to the database, otherwise it may be interpretted as the parameter was not passed.
Comment: @MarcGravell Yes, Marc, you are correct.  I worded that incorrectly.  ASP.NET translates the database null column value into DBNull.Value
Answer: DataRow has a method that is called IsNull() that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.
DataRow["col"]==null will allways be false.
use
DataRow r;
if (r.IsNull("col")) ...

instead.
Answer: Null is similar to zero pointer in C++. So it is a reference which not pointing to any value.
DBNull.Value is completely different and is a constant which is returned when a field value contains NULL.


How common is to use the pitch correction (autotune) effect for vocals?

Question: Many vocal processors I see on the market feature and advertise the pitch correction. As I understand, they use the sound input from the instrument (analog or MIDI) to decide how the note should actually sound and "pull" the voice up or down to match the expected pitch. Or allow to configure the key in menu.
How often this machinery is used by the usual performers (not the absolute beginners)? Should I switch it off first thing to do if I think I am capable of singing in a right pitch for the particular song? I plan to buy a vocal processor for other effects like echo, etch.
Answer: My personal thoughts are that if a vocalist sings in tune, it won't be needed. If someone is a little iffy in the pitch department, then it's a darned good idea. In fact, in that case, it may be best for them not to count themselves as a singer anyway.
Sometimes, a vocalist will bend notes - and make a great job of the song because of it. Having pitch control on must be really frustrating for them.
Try with and without. If you feel that it's not helping - and maybe hindering, leave it off. Unless you want to use it as an effect, as per Cher, in which case, a bit of practice won't go amiss.
To answer the question, it is possibly used far more than it should, in studios (and karaoke!). And it must make singers pretty lazy when it comes to pitching correctly, but saves a lot of time re-recording, maybe.
Answer: Extremely common.
I have toured and recorded with major stars/producers and even great singers have it in their arsenal (live and studio). Even the greatest singer isn't pitch perfect every night, but they want to be.
And, lets face it - most huge pop stars aren't great singers.
Comment: *Even the greatest singer isn't pitch perfect every night,* I think there would be many classical singers that would take offense to that statement.
Comment: @Neil Meyer - Given the wide vibrato of some of those singers, the autotune might have a tricky job...
Comment: I think there might be just as many who would agree.
Answer: Autotune in auto mode is, in my experience, absolutely useless. We're told it's used live, in realtime.  Well, they must know some very special tricks.  Whenever I try an 'auto' autotune it constantly latches on to the wrong pitch.
But at the mixing stage, a bit of manual correction can sound good.  It won't turn a 'fluffed' note into a good one.  But when the singer produces a good strong note - but just a bit off pitch - it can rescue a take.


Porque meu icon n troca de cor msm usando o "color" no css o icon esta sendo usado como botao

Question: html

e no css
#center-text {
    position: fixed;
    width: 10px;
    bottom: 40px;
    color: #fff;
}

Answer: Nesse caso o seu código não está funcionando da forma que você gostaria por que você selecionou o id da div ou invés de selecionar a class do seu icon. O que eu fiz abaixo foi apenas selecionar a class do seu icon e adicionar uma cor a ele.

#center-text {
    position: fixed;
    width: 10px;
    bottom: 40px;
}

.fa-house{
    color:#fff;
}

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Cannot find Bundle Display Name in Info.plist

Question: If my app's product name was "AppName: Some Description", I just want "AppName" to show as a name underneath the app icon on iOS home screen. I did some searching and found this SO question (Change name of iPhone app in Xcode 4). I'm using Xcode 6 and I cannot find the Bundle Display Name in the Info.plist. Can someone please tell me how to do this in Xcode 6.
Thanks
Update:
Simply place your cursor to the Info.plist and click on the + button. Select "Bundle display name" and insert name in the value section.
Comment: We're these two questions not helpful?

http://stackoverflow.com/questions/19337639/how-do-i-change-the-display-name-in-xcode-5

http://stackoverflow.com/questions/9667582/bundle-name-and-bundle-display-name
Comment: There is no Bundle Display Name in the Info.plist in Xcode 6.
Answer: Bundle Name is what you have to set in  the info.plist to display the name on the iOS home screen
Edit:
you still have bundle display name in xcode 6. Just add it in the info.plist
Comment: you still have bundle display name in xcode 6. Just add it in the info.plist
Comment: I'm still confused. Why did they have both Bundle Display Name and Bundle Name before Xcode 6?
Comment: Wow. Time nicely wasted. Thanks so much.
Answer: To change the name appearing underneath your app icon, modify the CFBundleDisplayName key in your Info.plist.

Click the disclosure triangle next to the "Supporting Files" subfolder to reveal its content.
Select the Info.plist file to reveal a property list editor of keys and values.
By default, Xcode displays a human-readable string of a key rather than its actual name. So, search the property list for "Bundle display name". Skip to step 5 if your property list already shows Bundle display name.

If it doesn't, add it to your list as follows:
<code>  - Click on any entry in your list, then click the "+" button.
  - Choose Bundle display name from the ensuing pop-up menu.
</code>

Double-click in the Value column of Bundle display name.

Enter a new value for Bundle display name as shown in Figure

Technical Q&A QA1823


angular js array in model

Question: I am repeating a form using ng-repeat. the repetition is to create a new form.
I want to submit all forms data on single click. i am not able to find how I can assign multiple values in array.
Here is my form:

                   <input type="hidden" name="scrnid" ng-model="screen.scrnid" value="{{ screen.scrnid }}" />
            Name:
            <input type="text" ng-model="screen.bdayname" placeholder="Name" ng-required/>
            Date:
            <input type="date" ng-model="screen.bdaydate" placeholder="Date" ng-required/>

               <button class="btn" type="submit" ng-click="newBirthday()">Save</button>

        <input type="button" class="btn" ng-click="createScreen()" />Add

and it is my controller
app.controller('main', function($scope){

    $scope.screens = [{scrnid: "1"}];
    $scope.scrnid = 1;
    $scope.createScreen = function()
    {
            $scope.screens.push({scrnid: "" + ($scope.screens.length + 1)});
    };

    $scope.bdays = [];
    // Create the function to push the data into the "bdays" array

    $scope.newBirthday = function(){

        $scope.bdays.push($scope.screens.length);  // how to push mutiple records in array dynamically

        $scope.screen.bdayname = '';
        $scope.screen.bdaydate = '';
    };
});

help will be appreciated...
Comment: $scope.bdays.push()

here in this array if i want to send multiple values i will do it like this:
$scope.bdays.push([
{'name': 'name1'},
{'name': 'name2'}
]);

this is angularjs way to do.  But what should i do to insert the values from my html form that is repeated,  into this array...
Comment: `assign multiple values in array`, what are these multiple values?
Answer: I have edited the code to get the objects to be stored into the bday scope variable
var app=angular.module("birthdayToDo",[]);

app.controller('main', function($scope){

   $scope.screens = [{scrnid: "1"}];
  $scope.scrnid = 1;
    $scope.createScreen = function(){
            $scope.screens.push({scrnid: "" + ($scope.screens.length + 1)});

            console.log($scope.screens);
        };

        $scope.bdays = [];

    $scope.newBirthday = function(){

        for(i=0;i<$scope.screens.length;i++){
            $scope.bdays.push($scope.screens[i])
        }
        console.log($scope.bdays);

    };

    $scope.remove=function(item){
      var index=$scope.bdays.indexOf(item)
      $scope.bdays.splice(index,1);
    }

});

Comment: Here you have done it for single form .

To pass single form values i can pass them easily. But if you have noticed i am repeating this form and now i want to submit all forms data .

how will i manage it with form repetition...
Comment: check this fiddle https://jsfiddle.net/9fqfh8ty/ here multiple forms are being used and a save action for each form, I have also editted the answer above , let me know if this solves your issue
Comment: Here you have three forms with three buttons setting up the target buttons value to fill in array.
I want three forms with single buttons and adding all three records values in arrray.

do u have any idea for that...
Comment: you mean you have 3 forms but a single save button ?
Comment: yes and those three forms are created in ng-repeat means i am having single form which i am repeating n  have single save button i want to save these forms on single click to database, and repeating of forms is dynamic . forms can be 3 or 4 or 5 ....
Comment: can you upload you code into a fiddle so that I can play with
Comment: Here is the fiddle link for my code.

https://jsfiddle.net/trig_php/z1o9nvne/

i don't know why it's not working on fiddle bt if u will try on localhost u will see this working..
Comment: Hi I have used your code and created another working fiddle. Check this and let me know if this solves your issue https://jsfiddle.net/vvc15rxj/ I have also updated my answer above
Comment: but i am not getting values in bdays array in which values are pushed.

:(
Comment: when you click on save, check the console ... on click of save the bday array is being consoled
Comment: here on console bt i can not send it to my html in other edit form .
how will i display all values there ...
Comment: trig_php  you can have the other edit form within another controller and share data across controllers via creating a factory
Comment: thank @melwyn pawar u resolved my issue .. i will find ways for the rest.
this is very helpful.  :)
Comment: can you please tick right the answer, it may help others also :)
Comment: i tried it already but my reputation score is less than 15 , i can not do that , will do later.
Comment: i worked on the above but what is done here is u are pushing the count of repeated screens into the bdays array , what will be the way to get all the values into this array from all forms.

now i am stuck with this........   plz help me out....

angular js array in model


Does flatting or sharping a roman numeral indicate modal mixture?

Question: I'm wondering when I see chords in the form of: bIII, bVI, #v.
Does that mean I am borrowing a chord from the parallel key?
I am currently thinking that "b" is only used when I am currently in a major scale and I want to borrow from a minor scale. So "bIII" would mean I borrow the third chord from minor.
And "#" is when I am currently in a minor scale and I want to borrow from a major scale. so "#v" means I am borrowing the major key's fifth chord. Does this sound right?
Comment: Where does '#v' come from? In Cm, for example, that would be G#m, which is a chord neither in Cm *or* C major. In Cm, Ab maj. is found, and that's called VI, and it's 6, not 5.
Answer: Not quite. The accidentals on roman numerals often accompanies modal mixture, but not always. The accidental means that the chord's root should be raised or lowered from where it usually is. So, ♭III in C major is E♭ major. However, note that while this is modal mixture, there are times where modal mixture occurs without modifying the root. For example, in G minor, the major key's fifth chord is labelled V (not ♯v). The uppercase letter means major, the lowercase letter would mean minor. Also, note that there are basically no situations in which sharps are used in roman numeral analysis, because coming from a minor key to a major key usually uses natural signs (♮vi).
Comment: Don't understand why, in a minor key, the five chord would ever be '#v' It will either be V or v. Help!
Comment: @Tim I think OP may have confused uppercase letters and sharps.


Tirar números juntos a letra com o str_replace

Question: estou querendo tirar uma parte de uma string, mais especificamente números junto a letra, como por exemplo:
<code>$string = "Parte da string - 60h"
</code>
Pois bem, uso o str_replace da seguinte forma:
<code>$string = str_replace(' - ', '', $string);
$string = str_replace('[ˆ0-99]h', '', $string);
</code>
O problema é que obtenho a seguinte string : Parte da string60h. Me parece que o segundo uso do str_replace não está sendo feito. Alguem pode me ajudar?
Answer: O str_replace não aceita expressão regular, você pode usar o preg_replace ().
<code>$string = preg_replace('/[0-9]+h/', '', $string);
</code>
Comment: PERFEITO! Exatamente o que eu queria.


Statistical analysis on several data sources - possible?

Question: I have a formulation of a statistical problem in mind and haven't been able to find any literature/references about it. As professors that I asked also couldn't help, I thought I'd ask here.
Consider the problem of performing statistical analysis on patient records from several hospitals. For example, we want to determine whether some medication is effective for treating a particular disease. In a case where all the hospitals involved use the same type of patient record system, we just merge the data tables together and perform the relevant type of analysis.
Now consider the case where data structure differs among hospitals, e.g. two different hospitals have different sets of measurements about the patient. Some variables in a table of first hospital cannot be found in a table of a second one, and vice versa. We have explicit knowledge about how these sets correspond to each other, for example, we know that variable systpres in the first hospital's data set corresponds to pressure_systolic in the second hospital's data set. How do we do inference?

Find what variables are available in both tables and disregard all other information. Merge 'cropped' tables. - This way we lose useful data.
Merge original tables and try to impute all missing information. - This way we don't use the fact that the nature of 'missingness' is known and explicit knowledge about what data will be missing where is available.

Is it possible to somehow use the knowledge about data structure correspondence in a statistical analysis? Has that type of problem been solved somewhere?
Any pointers/ideas could  be useful!
Thank you.
Comment: Assume that you perform two regressions for two hospitals. For one regression you have factors $x_1, x_2, x_4$ (and weights $\beta_1, \beta_2, \beta_3$), for the second $x_1, x_3, x_4$ (weights $\gamma_1, \gamma_2, \gamma_3$). Why don't you just fit two regressions with shared weights? Fit them jointly by introducing the constraints: $\beta_1 = \gamma_1$, $\beta_3 = \gamma_3$.
Comment: Could you explain what you mean by "data structure correspondence"? It sounds like you mean that `systpres` is the same as `pressure_systolic`. But since you say we know those correspondences, I can't see any reason to impute any data values. On the other hand, if you mean Hospital A records a variable that Hospital B does not, what correspondence are you referring to? Or are you referring to automatically matching up those two fields with different names but the same data? Sorry, but I'm confused.
Comment: Could you be a bit clearer about the "explicit knowledge" that imputation would ignore?
Comment: Scortchi, I've updated the question. Does that clarify?
Comment: Dmitry, yes, that sounds like a good idea for linear regression. Also, I can think of some interesting adjustments to well-known algorithms to perform other tasks like clustering or classification  in the described case. What I wanted was to find out the *name* of this class of problems and maybe a reference to   some work in this area.
Comment: That makes it sound trivial - matching fields that happen to be named differently. Surely that's not all you're asking about.
Comment: Odd that you couldn't find good information about this sort of problem.  You've tagged the question with "missing-data":  just clicking on that tag brings up hundreds of threads on this site, and a generic web search identifies such a great variety of books, articles, tutorials, and trainings that would be relevant.
Answer:
Hello Martin,
Here are my thoughts about the problem:

Certainly, treat the variables like "systpres" and "pressure_systolic" as the same (and give them the same name to avoid confusion).

Concerning the remaining variables which are distinct in different hospitals, in general it's hard to find the answer, but, depending on the background knowledge and the nature of your problem, it may be possible.

Construct new 'score variables'-weighted linear combinations of the variables (possibly normalized to the same range) which are unique for each hospital to obtain a 'score'-one new variable which will summarize what you want to compare. This is similar to credit scoring of debtors in a bank.
However, this is where your background knowledge should be applied, since rapidly different combinations of variables will give very different results, rendering scores non-informative. It may also be a good idea to include variables of the same type in one score, i.e. only the count variables or only the continuous ones, etc.
In case of OLS regression with manual variable selection for each hospital, compute correlations of the unique variables with shared variables for each hospital or try to understand how they're dependent. (I.e. in Dmitry's example, x_2 with x_1 and x_4 for hospital 1, and x_3 with x_1 and x_4 for hospital 2). If x_2 is highly correlated with x_1 and x_3 is highly correlated with x_4, you don't need to care about them and can safely compare using only x_1 and x_4 for the hospitals.
Try to find such shared variables which approximate the unique ones well (i.e. proxy variables) (again, separately for each hospital). For this you can run regression of some shared variables on the unique ones and compare regression fit.
If possible, in each hospital try to find the same proxy for as many unique variables as possible, then compare the proxies. Or ask for further observations of new proxies, which must be the same across hospitals.
Methods to look up in relation to proxies and their estimation are:

simultaneous equations (systems of regression equations) (http://en.wikipedia.org/wiki/Simultaneous_equations_model)
instrumental variables
Two-stages least squares (to solve simultaneous equations)

They are all well described, for example, in
http://www.ozon.ru/context/detail/id/3608597/
or in W.H. Greene "Econometric Analysis"

Although I am not an expert on ANOVA, the problem very much reminds me about Unbalanced Incomplete Block Designs, or Unbalanced Factorial Designs, depending on the nature of the variables. See references in Montgomery's book "Design & Analysis of Experiments". In 5ed. it's pages 600-604.

Hope you will find this useful.
Regards,
Vasily


New guitar nut when changing to a lighter gauge?

Question: I currently have a Fender Strat which I set up with 12-56 strings about 2 years ago and have been playing comfortably since, using mostly standard tuning. However, I've decided to switch my strings to 9-42s as the heavy set doesn't fit my playing style anymore. Because of this, I'm wondering whether i'll need to buy a new nut as my current nut has been filed for 12 gauge strings so the grooves might be too wide? I'll clearly need to do a complete setup of my guitar and adjust my truss rod, but will my nut need changing as well?
Answer: In all the guitars onto which I've put much lighter strings, (dozens, if not more) there's not been a problem. The tension will pretty well keep the strings from rattling round in the slots. Should there be a problem - very unlikely - then a tiny strip of paper will sort it out.
Obviously, the intonation will alter, needing adjustment of the saddle positions; the neck tension may need changing, and the action will probably need a tweak. You may even want to move the pups slightly higher, too.
Answer: You don't normally need to worry about the nut slots being a little wide - usually the break angle of the string over the nut plus the tension on the string is sufficient to keep the string in place. This assumes that the nut slot has been correctly filed into a suitable (roundish) U- or V- shape - if it's filed too flat at the bottom, that increases the potential for lateral movement of the string.
Try it, and don't try to deal with the problem unless you find there actually is one.
Comment: In my experience this is generally true, though I had a guitar with an inexpensive nut that was not fitted well to begin with that didn't tolerate light gauge strings very well until I replaced it.  It took several weeks to pinpoint the issue and I wouldn't think it's particularly common on a guitar that has been performing fine already.  More common in my experience is nuts that are too narrow to put heavier strings on.  A quick fix that keeps that from making tuning a nightmare is to scribble with a pencil onto a small piece of paper until it's covered in graphite, then rub it into the slot.
Comment: @DarrenRinger sometimes if you don't have proper files and you are 'feeling lucky', an old string of a similar gauge to the one you want to put on can be pulled through the slot in a 'sawing' action to widen a slot in a somewhat controlled way. I'm not saying it's the right tool for the job but if the nut in question is on a beater guitar that cost you less than a decent file would, it's an option!
Comment: @DarrenRinger - yet another reason why I prefer guitars with a zero fret !
Comment: @Tim - yes, that's a good argument indeed for zero frets.  But do they sound exactly the same as no zero fret?  At least theoretically, the strings could lose more energy in rubbing side to side on the zero fret when open.  But it might well be that this effect is negligible- I've never tested it myself.
Comment: @ScottWallace - On my weapon of choice for the last 40 yrs, there's no difference between the sound of the open string because of its zero fret, as far as I can tell. Sounds like any guitar with just a nut. They can't really rub any more than they do at the other end. It's a node with theoretically no movement.
Answer: I changed from 10s to 9s on my Strat and because of the now-too-wide nut slots, it buzzes like crazy on all open strings.


HTML relative paths issue for script src

Question: I have an issue with a website I built from angular. In index.html, there are references to javascript files, but my problem is this: in the HTML, the paths are relative to the file but the browser looks for the files in the root dir:
<!doctype html>

  <meta charset="utf-8">
  <title>RasaBE</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

This works fine when everything is in the root folder of my website, but I wanted to have everything in a subfolder /bo/. So index.html is in localhost/bo/index.html and so are all the scripts. Since it's a relative path in the code I'd expect my browser to look for localhost/bo/script.js, but instead it looks for localhost/script.js.
A screenshot to show what's wrong:

I tested this in Chrome and I have the same issue. It's a bit complicated to change the paths directly since it's compiled from angular, and I'd probably have to change it every time it compiles. Is this an issue with Firefox and the way it deals with relative paths?
I should also add that host/bo/inline.bundle.js exists and can be found by the browser but the it looks for it in the root folder instead of the same folder as index.html.
Comment: Can you adding "/" before js name to make it relative.
Answer: This "base" element sets the default location for the page.
Remove
<base href="/">

OR
<base href="/bo/">

Comment: I can't remove it, because it's necessary in other parts of the angular code apparently (I didn't write it, I'm setting it up), but changing it to /bo/ worked well.
Answer: If you want your Angular Webapp run from every subfolder without touching the code
Change
<base href="/">

To
<base href=".">

Removing the "base" element won't work since Angular throws then an error complaining about the missing element.
Answer: It turns out it was all because of the  tag that is added by angular, editing it to <base href="/bo/"> makes it work. since it's just one line to change I consider it fixed.


ios app runs perfectly in debug mode but crashes in release

Question: My app crashes in certain moments in release build. I don't know if it is important but I use mainly c++ with cocos2d-x framework. I tried setting optimization level to none but it won't work too. I get this output in console :
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: map::at:  key not found

This is part of the crash log:
Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread:  0

Thread 0 Crashed:
0   libsystem_kernel.dylib          0x3870d1f0 0x386fa000 + 78320
1   libsystem_pthread.dylib         0x38777792 0x38774000 + 14226
2   libsystem_c.dylib               0x386bdfd8 0x38675000 + 298968
3   libc++abi.dylib                 0x379eccd2 0x379ec000 + 3282
4   libc++abi.dylib                 0x37a056aa 0x379ec000 + 104106
5   libobjc.A.dylib                 0x3814af86 0x38147000 + 16262
6   libc++abi.dylib                 0x37a031c4 0x379ec000 + 94660
7   libc++abi.dylib                 0x37a02d28 0x379ec000 + 93480
8   libobjc.A.dylib                 0x3814ae12 0x38147000 + 15890
9   CoreFoundation                  0x2d3d2f80 0x2d3cb000 + 32640
10  CoreFoundation                  0x2d3d2cee 0x2d3cb000 + 31982
11  GraphicsServices                0x3230565e 0x322fc000 + 38494
12  UIKit                           0x2fd1e168 0x2fcb0000 + 450920
13  BumpRace iOS                    0x00044b1e 0x4000 + 264990
14  libdyld.dylib                   0x38657ab4 0x38656000 + 6836

Any help would be apprieciated.
Comment: are you generating any rand variable?
Answer: You must use iOS instruments tool. To debug you memory leaks. As possible to conclude from youre ERROR message.
Small useful link.


SQL not liking the word SplitList

Question: Why does SQL not reconice SplitList?
This is my code and SQL dont like the word SplitList.
Message is "Invalid object name"
Where FirstName IN (Select * from SplitList(@CustomerName, ','))

Comment: When SplitList is a table valued function without an explit schema, call it in this way: `dbo.SplitList(@CustomerName, ',')`
Comment: @TimSchmelter - Should be an answer probably...
Answer: There's nothing like SplitList built-in to T-SQL or ANSI SQL.
The code sample that you're using appears to assume that you already have a user-defined function called SplitList.
If you do already have a user-defined SplitList function then you probably just need to specify its schema when you call it:
WHERE FirstName IN (SELECT * FROM dbo.SplitList(@CustomerName, ','))
-- or
WHERE FirstName IN (SELECT * FROM yourschema.SplitList(@CustomerName, ','))

Answer: If SplitList is a table valued function without an explit schema, call it in this way:
Select * from dbo.SplitList(@CustomerName, ',')

If no schema is provided, SQL Server will assume dbo is the default schema.
By the way, you can change the schema of a database object in this way:
ALTER SCHEMA [NewSchema] TRANSFER dbo.SplitList

http://msdn.microsoft.com/en-us/library/ms173423.aspx

SQL not liking the word SplitList


Data Analysis for ranking data?

Question: I want to compare three types of designs(A, B and C). After showing the images of three designs to each user, I have asked the user to rate/rank these 3 designs as Best, Worst and Average.
Users response were: A-Worst, B-Average, C-Best and so on. For data analysis, when user rated a design as best, I gave a score of 3, for an average- score of 2, and for worst- score of 1.
I asked each user 5 questions (criteria) to rank these designs. So data collected would look like as follows:

How should I analyse this data (which test/procedure I should use)?
Does usage of ANOVA valid here?
Also, I would like to use Tukey's pair wise comparison along with ANOVA to find any significant difference among the means.
I will be thankful for the responses.
Comment: https://stats.meta.stackexchange.com/a/3181
Comment: Your example seems unrelated to your description, which indicates the data could be represented as a table with one column for each design, one row for each subject and question, and values of just "1", "2", or "3" in each row.  What do the numbers you have shown mean?  Would they be the *sums* of your numeric codes?  If so, then these aren't actually your data--they are a digest of them--and you should consider analyzing the raw data before performing any such summations. For the purpose of asking this question you at least need to explain what you want to learn from the data!
Comment: There are 30 subjects mentioned under column 'Sub'. These numbers are just serial numbers or subject IDs. Under A, B or C is rating score of for each design which I want to compare. I want to know which is better. e.g. Sub1 rated C as best (high score based on the 5 questions). Hope this explanation will be helping.
Answer: By adding up the ranks you have implicitly stated that they are interval level, rather than ordinal.  This is not technically right (although it is very commonly done). But, once you've done that, you can use ANOVA as you would on any other data set.

Data Analysis for ranking data?


Qual a diferença entre usar o input() e usar o sys.stdin.readline()?

Question: Qual a diferença entre usar o input() e usar sys.stdin.readline()?
Comment: Além das diferenças já citadas na resposta abaixo, também há diferença quando ocorre um EOF (por exemplo, quando você digita Ctrl-D no Linux): `input` lança um [`EOFError`](https://docs.python.org/3/library/exceptions.html#EOFError), enquanto `sys.stdin.readline()` retorna a string vazia.
Answer: Direto da boca do cavalo:
>>> input()
bla
'bla'
>>> input("digite algo: ")
digite algo: bla
'bla'
>>> import sys
>>> sys.stdin.readline()
bla
'bla\n'
>>> sys.stdin.readline(5)
blaaaaaaaaaaaa
'blaaa'

Como se vê, input() não inclui o caractere de fim de linha, enquanto o outro inclui. readline() aceita um parâmetro opcional que é o tamanho máximo da string a ser retornada.
Me parece que input() é mais apropriado para interação com humano enquanto readline() é mais voltado quando o programa será parte de um pipe.
Comment: Outra diferença é que `input` aceita como parâmetro uma string que é exibida antes de pedir a entrada dos dados
Comment: @hkotsubo adicionei este caso no exemplo, vlw


Mapping Linking Table with 3 PK's in Hibernate

Question: right now I'm having trouble mapping a linking table with Hibernate.
First of all I want to explain what I want to map:
I have 3 tables: Product , DocumentType, Language.
One Product can have each DocumentType (at the moment we have 7 DocumentTypes) in each specific Language (at the moment we have 3 Languages)
That means product "1" can have DocumentType "A" in language "EN", "ES" and "FR".
I created a linking table with 3 foreign keys which are also composite primary key.
Here is how my sql looks like.
CREATE TABLE Person(
  id int PRIMARY KEY AUTO_INCREMENT,
  name varchar(255)
);

CREATE TABLE DocumentType(
  id int PRIMARY KEY AUTO_INCREMENT,
  name varchar(255),
  key varchar(255)
);

CREATE TABLE Language(
  id int PRIMARY KEY AUTO_INCREMENT,
  name varchar(255),
  code varchar(2)
);

CREATE TABLE Person_DocumentType_Language(
  person_id int NOT NULL,
  doc_id int NOT NULL,
  lang_id NOT NULL,
  FOREIGN KEY(person_id)
    REFERENCES Person(id),
  FOREIGN KEY(doc_id)
    REFERENCES DocumentType(id),
  FOREIGN KEY(lang_id)
    REFERENCES Language(id),
  PRIMARY KEY(person_id, doc_id, lang_id)
);

With the last linking table I could tell which Person has which DocumentTypes and in which Languages.
I'm mostly interested in the information which DocumentType has which Language for one Person.
Say I'm Person A. Now I want to know which DocumentTypes I have with which Languages. In SQL it would look like this I think:
Select doc_id, lang_id from Person_DocumentType_Language where person_id=1

Does that make sense? And how could I map this in Hibernate?
Answer: One approach is have a Map from DocumentType to Language. I'm a bit rusty on the exact annotation, but here is a start:
public class Person {

    @Id
    public int id;

    @OneToMany(targetEntity=Language.class)
    @MapKeyClass(Integer.class)
    @CollectionTable(name="Person_DocumentType_Language")
    @MapKeyColumn(name="doc_id")
    public Map<DocumentType,Language> docTypeLang;
}


Modeling temporal change with 2 data points

Question: Study Context:
I am studying the relationship between a biomarker of cellular aging (telomere length) and menopause.
We have 2 datapoints for a subset of the women. Therefore, our participants could fall into the following categories:

Pre-menopausal at baseline and post-menopausal at follow-up
Post-menopausal at baseline and post-menopausal at follow-up
Only one measurement (baseline)
Only one measurement (follow-up)

We also have the timing of menopause, and when the samples were taken. Thus, one of our questions is "Does going through menopause (and how long since) affect the rate of change in telomere length between baseline and follow-up?"
Modeling:
I've come across 3 approaches that might work.

Autoregression
Difference Score
Linear mixed effects model (with participant as a random factor).

I've been convinced about the advantages of linear mixed effects models to model change over time. However, our data only has 2 time points. My understanding from Singer and Willett 2003 is that fitting LMEs to 2 time points doesn't really make sense (because the intra-individual correlation will always be 1 and the error 0). For this reason, I've sort of abandoned thoughts of using LMEs.
I found good introductions to autoregression and difference-score methods here. This led me to believe that the difference-score approach is superior, because it attempts to model questions about intraindividual change (as we trying to do).
However, there is published work showing that 'controlling' for baseline telomere length in delta models (autoregression and difference-score) overestimates non-zero estimates of measurement error and can lead to false positives (if the baseline values are already quite different). Based on this study, LMEs seem to perform well.
Stats questions:

Are LMEs a bad choice to model data with only two time points like this?
If LMEs are acceptable, how would I model the timing of menopause relative to the first and second measurement? Because each participant has 2 rows, I assume I would need to factor the timing of menopause into the model for both rows somehow.
If LMEs are not acceptable, is there a way to model deltas (change) without including baseline measurement in the model, which appears to bias estimates.

I've used nlme and lmer, so bonus for helping me figure this out using R!
Comment: A [paper you cite](https://royalsocietypublishing.org/doi/full/10.1098/rsos.190937) says "to avoid invalid inference, models of telomere attrition [telomere-length (TL) difference] should not control for baseline TL by including it as a covariate." That's a well known problem in general; see [this answer](https://stats.stackexchange.com/a/481452/28500) and its links. Regressing a _change_ against a baseline can be problematic. Regressing a final value against an initial value is OK. See [this question](https://stats.stackexchange.com/q/482664/28500), closely related to yours.
Comment: Thanks for taking the time to comment @EdM. If I can model 2 time points with LMEs, do you have thoughts on question 2? (How would one model time difference, which is a single measure, when you have 2 rows for each participant)? Write the time difference once in each row (duplicated)? Or some other way I'm not thinking of? Also, any idea why it's so common to use (and [promote](https://quantdev.ssri.psu.edu/sites/qdev/files/05_TwoOccasionChange-WISC-_2020.html)) the difference-score model as a way to model intra-individual change? I may need to push back on co-authors/reviewers.
Answer: You seek to model the rate of change (e.g., base pairs per year) of telomere length, and whether menopause affects that rate of change. So why not model the rate of change directly, taking into account the time elapsed pre- and post-menopause between measurements for each individual? Then you reduce your data set to just one row per individual and avoid most of the problems you otherwise anticipate.
There is absolutely no problem with modeling the intra-individual difference in telomere length as the outcome. That by itself provides a very useful control for the telomere length at first measurement, similar to a paired t-test. The problem is if you try to regress that difference against the initial telomere length as a predictor. So don't do that, despite what some web sites might promote. In your own field, that approach has already been shown to be invalid, as you note.*
To evaluate the rate of change, you include elapsed_time between measurements, in some form, as a predictor. Putting aside the menopause issue for the moment, a coefficient of elapsed_time, with length difference as the outcome, is then an estimate of the rate of change of telomere length over time.
To evaluate the role of menopause, you extend that approach to include separate predictors for pre-menopause_elapsed_time and post-menopause_elapsed_time. If the rate of change differs post menopause, then those coefficients should differ.
To this point, the model is simple:
telomere_length_difference ~ pre-menopause_elapsed_time + post-menopause_elapsed_time

Now, think about the intercept of this model. It will be the predicted telomere_length_difference with pre-menopause_elapsed_time and post-menopause_elapsed_time both at values of 0. Ideally, that intercept should thus be close to 0. If not, you need to rethink the assumptions underlying the model, for example whether telomere length decreases linearly with time both pre- and post-menopause. Or might menopause itself leads to something like a step-change in telomere length that needs also to be modeled?
Your ultimate model might also need to account for other factors associated with telomere length changes. That will require some care in how to model those other factors, whether to examine their interactions with either or both of the elapsed_time predictors, etc, based on your understanding of the subject matter. Depending on how you model the other predictors, the simple interpretation of the intercept presented above might not hold. But this simple model should get you pointed in a helpful direction.

*If someone think that changes occur proportionately to initial values, an assumption that might lead some to do such a regression of differences against initial values, perhaps modeling should be of differences in logs of telomere lengths as outcomes, equivalent to the log-length-ratio, again without the initial length as a predictor.
Comment: Thank you @EdM. That approach seems appropriate and simple enough to implement, interpret, and explain to reviewers and co-authors! I agree about the inclusion of other covariates. For those other covariates (e.g. BMI), would you then also include e.g. BMI_difference? Or simply include baseline BMI and call it a day? What about in cases where we are actually interested in whether the change (say in BMI, for example) is associated with the change in TL? Thanks again for your help - I've had a hard time getting clear answers about modeling longitudinal data like this with only 2 points.
Comment: @Calen you have to use your understanding of the subject matter, and the limits imposed by the size of your data set, to choose how best to model covariates--whether as baseline values or changes. Inclusion of covariates might complicate the simple interpretation above of the intercept, however. Also, you should decide whether to include interactions of the covariates with either or both of the `elapsed_time` predictors. Those decisions should be based on what you and your colleagues and your audience think is important to evaluate. The statistical issue is to avoid overfitting your data.
Comment: Yes that all makes sense. The approach you suggest is much easier to get my head around, and I see how the details about the covariates is a separate issue. Thanks again @EdM.


stackoverflow exception in simple mine sweeper game

Question: I am calling a recursive function (left click on the square) and I can't find where the problem is.
It is supposed to change the background image to the correct number, set it to "pressed" and if it the number of mines near the square is 0, it will leftclick all the squares near it.
"board" is 2d array of squares(Mine class)
private void leftClick(int x, int y)
{
    if (!board[x][y].pressed)
    {
        if (board[x][y].bomb == true)
        {
            board[x][y].BackgroundImage = Properties.Resources.bomb;
            if (MessageBox.Show("You lost! new game?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Form.ActiveForm.Hide();
                Form form2 = new MineSweeper.mainForm();
                form2.ShowDialog();
            }
            else
                Application.Exit();
        }
        else
        {
            switch (board[x][y].numOfMines)
            {
                case 0:
                    board[x][y].BackgroundImage = Properties.Resources._0;
                    if (x - 1 >= 0 && y - 1 >= 0 && x - 1 < row && y - 1 < column && board[x-1][y-1].pressed==false)
                        leftClick(x - 1, y - 1);
                    if (x >= 0 && y - 1 >= 0 && x < row && y - 1 < column && board[x][y - 1].pressed == false)
                        leftClick(x, y - 1);
                    if (x + 1 >= 0 && y - 1 >= 0 && x + 1 < row && y - 1 < column && board[x + 1][y - 1].pressed == false)
                        leftClick(x + 1, y - 1);
                    if (x - 1 >= 0 && y >= 0 && x - 1 < row && y < column && board[x - 1][y].pressed == false)
                        leftClick(x - 1, y);
                    if (x + 1 >= 0 && y >= 0 && x + 1 < row && y < column && board[x + 1][y].pressed == false)
                        leftClick(x + 1, y);
                    if (x - 1 >= 0 && y + 1 >= 0 && x - 1 < row && y + 1 < column && board[x - 1][y + 1].pressed == false)
                        leftClick(x - 1, y + 1);
                    if (x >= 0 && y + 1 >= 0 && x < row && y + 1 < column && board[x ][y + 1].pressed == false)
                        leftClick(x, y + 1);
                    if (x + 1 >= 0 && y + 1 >= 0 && x + 1 < row && y + 1 < column && board[x + 1][y + 1].pressed == false)
                        leftClick(x + 1, y + 1);
                    break;
                case 1:
                    board[x][y].BackgroundImage = Properties.Resources._1;
                    break;
                case 2:
                    board[x][y].BackgroundImage = Properties.Resources._2;
                    break;
                case 3:
                    board[x][y].BackgroundImage = Properties.Resources._3;
                    break;
                case 4:
                    board[x][y].BackgroundImage = Properties.Resources._4;
                    break;
                case 5:
                    board[x][y].BackgroundImage = Properties.Resources._5;
                    break;
                case 6:
                    board[x][y].BackgroundImage = Properties.Resources._6;
                    break;
                case 7:
                    board[x][y].BackgroundImage = Properties.Resources._7;
                    break;
                case 8:
                    board[x][y].BackgroundImage = Properties.Resources._8;
                    break;
            }
        }
        board[x][y].pressed = true;
    }
}

Comment: Rather than recursion, could you store all of the coordinates in a list and add to them and then process the list? That way you wont nest into recursion so much that you blow the stack.
Comment: I would consolidate all that bounds-checking logic--simply click the square whether or not it's on the board, have the click logic simply return if passed invalid coordinates.
Answer: Set board[x][y].pressed = true; before leftclicking the other mines. If you don't, the other mines might leftlick the original mine again.
if (!board[x][y].pressed)
{
    board[x][y].pressed = true;
    ... do the other stuff here
}

Comment: Something completely different: It is easier to create the board as a 2-D array in one bunch instead as of a jagged array and create the rows one by one. `Mine[,] board = new Mine[Width, Height];`. Then you can access the mines like this: `board[x, y].pressed = true;`
Answer: Besides the one that Olivier pointed out there's another recursion problem here that you haven't hit yet and almost certainly wouldn't in testing.
if (MessageBox.Show("You lost! new game?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Form.ActiveForm.Hide();
                Form form2 = new MineSweeper.mainForm();
                form2.ShowDialog();
            }

Rather than playing the game again in the same form you're creating a new form and hiding the old one.  While this recurses only one layer per game it's using up GDI resources (they are not anything like infinite, if you leak them it's easy to run out) and thus will blow if the user plays enough games.
Comment: hmm ok i found solution..
i have made reset function so i stay in the same form.
Comment: you are right. how should i reload the form without leaking memory?


MySQL syntax error - Java Bukkit / Spigot plugin

Question: I'm getting this error when I'm trying to connect my Java Plugin to the local MySQL database:
<code>[01:15:44 INFO]: [BetterStaff] Could not connect to database:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Reportslog' ('SenderName' varchar(32), 'Message' string)' at line 1
</code>
The code from my plugin is:
<code>    this.db.openConnection();
    Statement statement = this.db.getConnection().createStatement();
    statement.executeUpdate("CREATE TABLE IF NOT EXISTS 'Reportslog' ('SenderName' varchar(32), 'Message' string)");
</code>
Can you help me or correct my SQL syntax please?
Comment: Remove the ' from your code.
Comment: Should I remove all '? Something like this:  "CREATE TABLE IF NOT EXISTS Reportslog (SenderName varchar(32), Message string)" ?
Comment: Yes, the only reason to use quotes is when you assign labels (for people who want to have spaces in their table or column names).
Comment: also there is no ['string'](https://dev.mysql.com/doc/refman/5.0/en/string-types.html) type
Comment: What should I type to replace something like 'string' type in Java. I'm just going through MySQL only if it's a must, I don't know much about it.
Answer: Quotes are not allowed in the table name or fields:
<code>String sql =
   "CREATE TABLE IF NOT EXISTS Reportslog (SenderName varchar(32), Message varchar(32))";

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
</code>
Comment: Thanks a lot, you saved my last few hours. :))
Comment: What means "conn" from PreparedStatement preparedStatement = conn.prepareStatement(sql);
Comment: its a `java.sql.Connection` instance, same as `db.getConnection()` in your case


How to estimate probability of a bill passing the U.S House of Representatives

Question: For a bill to pass the U.S. House of Representatives, a simple majority of members have to vote yes. If every member votes this will be 218 of 435. If some members vote "present", their votes are not tallied, and a majority of the remaining votes need to be yes.
Say I have a probability assigned to the likelihood of every individual member voting for, abstaining, and voting against a bal (e.g. $P(\text{member A will vote yes})=.50$, $P(\text{member A will vote no})=.50$ and so on). How do I then calculate the probability (through direct calculation or through simulation) of the bill passing?
Comment: For sake of simplicity, let's assume independence.
Comment: In terms of  an analytic solution: note that the situation where every member votes is a [Poisson binomial distribution](https://en.wikipedia.org/wiki/Poisson_binomial_distribution), which is already lacking in closed forms. Adding the chance of abstaining further complicates matters, and is much more easily handled with simulation. You might be able to directly compute the answer with convolution, though.
Comment: How would I simulate it? For every round I select 435 votes, with my given probability for a member applied to each selection?
Comment: Are Reps' votes independent?
Comment: Got it. Do you mind posting your comment as an answer so I can upvote it?
Answer: If we assume independence of Reps' votes, then the problem is easy: each Rep is represented as a Bernoulli trail with a specific probability of voting "yes." You can estimate a probability of passage by repeating many such Bernoulli trials.
Voting "yes" is modeled here, because you've asked about a bill's passage, as opposed to the complete vote tally.
The complement of a "yes" vote is voting "not yes," which encompasses No and Present votes: by the model you've outlined, $P(yes)+P(no)+P(present)=1$. Notably, if you go this route, you've ignored the possibility that a rep is absent (this can happen for any number of reasons: death, travel, or taking a different post like Rep. Price when he became HHS secretary -- his House seat will be empty until the special election, so there are effectively 434 seats as of this writing).
If you want to simulate each option, you'll need to use a multinomial probability distribution instead but the mechanics are precisely the same.

This R code should get you started.
set.seed(13)

B <- 2000 # number of simulations to run
p <- rbeta(435, 2, 2) # probability a rep votes yes
expr <- expression(rbinom(435, size=1, prob=p)) # expression object containing number of trials

results <- replicate(B, eval(expr)) # simulation results

num_votes <- colSums(results)
sum(num_votes > 435/2)/B # estimated prob that it passes

png('passage.png')
    plot(density(num_votes, from=0, to=435), xlab="Yes Votes", main="Histogram of Simulation results")
    abline(v=435/2)
dev.off()

This model uses a beta distribution over vote probabilities, which means that the probability of voting yes is actually a beta-binomial distribution, by the property of conjugacy. This observation could streamline the code, but I left it this way for clarity. Changing p to match the real data is just a drop-in fix this way.
If votes are assumed to be dependent in some way, things are more complicated. You'll need a model that accounts how each member's vote is influenced by their peers. This is more realistic because Reps' votes aren't independent:

They tend to vote in blocs (Freedom Caucus, Tuesday Group, Black Caucus, etc.).
They "horse trade,"
They face pressure from leadership, the national party, their state's leadership, and the president to vote a particular way.
And a bill typically won't be put to a vote unless House leadership can guarantee passage (see also the Hastert Rule), so getting a whip count right is important to avoiding embarrassment -- a model of random voting throws that into disarray.
To the extent that Reps vote their constituency, and different constituencies share values, the feelings "back home" can make a big difference, and undermine the independence assumption. Rural Ohio and rural Pennsylvania probably have more in common than rural Ohio and Northern Virginia, so Reps' votes from rural Ohio are a reasonable proxy for Reps' votes in Pennsylvania but not Northern Virginia.
Even whip counts can influence the margin of a vote: sometimes leadership would prefer for a measure to fail by 10 or more votes instead of it failing by 1, since the dealmaking to get those other 9 votes has costs and tradeoffs which will all be for naught if the measure fails anyway. (Whether a doomed bill makes it to the floor at all depends on the aims of the leadership: the GOP staged numerous symbolic ACA repeal votes, knowing full well that the Senate and/or President would kill the measure, while in other contexts, doomed measures are remanded to committees for revisions.)
Additionally, the actions of the Senate and President can mean that stunt votes like the 2014 ACA repeal attempts can be undertaken while the members know full well that it will never become law -- so the contents and effects of the bill hardly matter at all. This implies that the Senate's and President's predicted actions will directly bear on how these votes happen: Reps can vote in support of a measure they know to be flawed or incomplete to please the leadership and never face any policy blowback because it will never become law. On the other hand, if the Senate and President are likely to approve the measure, then its consequences and contents are important. This is essentially why ACHA passage is suddenly so fraught after being a cornerstone of the GOP platform for years.

Accounting these factors will make the problem more challenging; however, ignoring dependence, especially in this example, where there are many well-known causes of dependence, will result in a model that is extremely misleading.
Comment: @MatthewGunn Oh, to be sure, I am also concerned that assuming independence is misleading. But OP clarified in a comment that the question assumes independence for similarity. You can see that the post ends by listing many reasons to believe votes are **dependent** and that the randomization model is inappropriate.
Comment: @Sycorax I appreciate your answer and agree with much of your content in the second section. My objection isn't as much to your answer as the assumptions of the OP's question. What if someone asked, "How long would it take a car to stop? And for simplicity, let's assume no friction." Maybe that's a well formed question? It also brings to mind the Yiddish phrase, "If my grandmother had balls, she'd be my grandfather." Some hypotheticals are so far from reality that they confuse rather than enlighten.
Comment: @MatthewGunn On the other hand, these are questions that students in low-level physics classes answer all the time: how fast does an object fall, assuming no air resistance? It's a simplification. In this case, it's simplified so much that there's little resemblance to reality, but I can still imagine it appearing in a homework assignment for a low-level quantitative social science class. (And how do we assess the probability of supporting a specific measure in the first place, all bills being unique?)
Comment: This assumes every Rep votes, correct? How do I account for the possibility of a Rep abstaining and their vote not being counted?
Comment: I'm concerned that inference based upon *atrociously false* assumptions (eg. that the votes of members of Congress are statistically independent) can be *highly* misleading.
Answer: This is a fantastically difficult problem. IMHO, this question is too broad.
Some problems even formulating the question:

What does passing a bill even mean?

Bills change! If a bill is amended and then passes, does it count as the original bill passing? What if the bill is so heavily amended that is unrecognizable?
It's hard to even define the outcome variable!

If you observe outcome $\omega$ how do you define random variable $Y(\omega)$ telling you whether the bill passed?

It is entirely wrong to think that Congress schedules a vote for time $t$ and then we observe the outcome like a coin flip.

Let $X_t$ be the time that a vote on a bill is completed. This isn't a fixed time. It's a random variable itself, a stopping time! If the House Leadership wants a bill to pass and the bill is in danger of not passing, they will pull the bill or reschedule the vote.

The problem is even worse than this because you don't know (from simply looking at votes) whether a vote is the final vote on a bill. There's always the possibility of a motion to reconsider.

Further problems...
Members of Congress are immersed in a massively complicated, game theory type problem with asymmetric information. Think of something like poker but with more cards, more players, and massive collusion between parties.
A few ideas almost certainly emerge.

A theme in game theory is that controlling the order of decisions can exert massive influence on the outcome. House Leadership can force certain outcomes by eliminating alternatives preferred by some members.
Sycorax does a good job of discussing all kinds of voting blocks.

If I were modeling this...
For me, my starting point would NOT be some absurd model where every Congressional vote is an independent coin flip. My starting point would be something motivated more by the median voter theorem.

Can I reduce the issue to a single dimension?
Who is the median voter in Congress along this dimension?

For example, several key aspects of the Affordable Care Act were structured so as to gain the support of Senator Ben Nelson of Nebraska as he was marginal voter that the Democrats needed to get to a filibuster proof majority of 60 votes.
If you were forecasting whether the ACA would pass, it eventually got to the point of forecasting what Ben Nelson would do. On the Supreme Court, forecasting the outcome often has been a question of what will Justice Kennedy do?
Identify swing voters, and make sure you model the extent to which they can swing together?
Disclaimer: I'm not a political science guy. Undoubtedly there are quantitative, statistical political scientists who study these types of questions.
Comment: Ben Nelson is a great example -- the bills are dynamic, agents can have outsize influence, votes aren't random because the process itself is about achieving a certain consensus.


How do I gracefully prevent crashes in react native?

Question: I would like to gracefully show an empty View when any error occurs (syntax, undefined, type errors, etc.)
This is what I've tried, but it doesn't seem to fail gracefully. The whole app still crashes with this implementation.
const Parent = (props) => {
    try{
        return (<Child/>) //if Child logic crashes for any reason,  return a blank view.
    }catch(err){
        return <View/>
    }
}

Answer: You can use ErrorBoundary https://reactjs.org/docs/error-boundaries.html
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return
Something went wrong.
;
    }

    return this.props.children;
  }
}

Using in root project (example App.js)
<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Comment: @RajendranNadar in `componentDidCatch` you can log native errors, using for example https://rnfirebase.io/crashlytics/usage
Comment: some suggest use https://www.npmjs.com/package/react-native-error-boundary library, if we can you directly then why this library required?
Comment: just check source code https://github.com/carloscuesta/react-native-error-boundary/tree/master/src you can do this yourself without library
Comment: I just go through the code. yes right we can implemented our own.
Answer: Installion
just install
yarn add react-native-error-boundary

HOC
make HOC like this
const CustomFallbackComponent = (props: { error: Error, resetError: Function }) => (
  <View>
    <Text>Something happened!</Text>
    <Text>{props.error.toString()}</Text>
    <Button onPress={props.resetError} title={'Try again'} />
  </View>
)

const withErrorBoundries = (props) => (
  <ErrorBoundary FallbackComponent={CustomFallbackComponent}>
    {props.children}
  </ErrorBoundary>
)

Usages
wrap every that component with can throw exception like this
export default withErrorBoundries(ComponentA);

or
export const ComponentC=withErrorBoundries(ComponentB)

Answer: If you wanted to make full proof crash less app so you should implement both in react native

Component Based Error
Javascript Based Error

Component Based Error Handling
Most common approach is using Error Boundary which you can implement by using this library https://www.npmjs.com/package/react-native-error-boundary
Javascript Based Error Handling
https://www.npmjs.com/package/react-native-exception-handler
Answer: use the ?. operator and the try{} catch(error){} it will prevent your app from  crashes.  here is the example you can try in functional programming.
import React, {useEffect, useState } from 'react';
import {Text, TouchableOpacity , View} from 'react-native'

// in order to prevent app from crash use this method

function ShowErrorMessageCompnent () {
    const [error, setError] = useState(false)
    const [item, setItem] = useState({
        id:"1",
        name:"ab"
    })
    const [showerrormessage , setShowErrorMessage] = useState("")
    // if you have an object but unsure of the attibute sof that use this

    useEffect(() => {
       try{
          let fathername = item?.fathername?.a   // this will thro no Errror
           //let fname = item.fathername.a   // this will throw Error
            //setUnknowfunction("Erro")  // as i dont have this function so it will thorw error
       }catch(err){
        console.log(err)
        setShowErrorMessage(err.message)
        setError(true)
       }
    },[])

    if(error){
        return(
            <TouchableOpacity style={{flex:1,justifyContent:"center", alignItems:"center",}}>
                <Text style={{color:"#000"}}>{showerrormessage}</Text>
            </TouchableOpacity>
        )
        }

    return (
            <View style={{flex:1, justifyContent:"center", alignItems:"center",}}>
                <Text style={{color:"#000", fontWeight:"bold"}}>No error</Text>
            </View>
    )

  }

  export default ShowErrorMessageCompnent;

Answer: All you need is ErrorBoundary, the preferred way is to set up a HOC(Higher-order component) that can handle errors and prevent the app being crashed. You can also create ErrorBoundary component. Here is an example of HOC that might help you.
import React, { Component } from 'react';

export const withErrorBoundary = WrappedComponent => (
  class extends Component {
    constructor(props) {
      super(props);
      this.state = { error: null, errorInfo: null };
    }

    componentDidCatch = (error, errorInfo) => catchFunc(error, errorInfo, this)

    render() {
      if (this.state.errorInfo) {
        return handleError(this)
      }
      // Normal, just render children
      return <WrappedComponent {...this.props} />;
    }
  }
);

const catchFunc = (error, errorInfo, ctx) => {
  // catch errors in any components below and re-render with error message
  ctx.setState({
    error: error,
    errorInfo: errorInfo
  })
  // log error messages, etc.
}

const handleError = (ctx) => (
  // Error path

Something went wrong.

      {ctx.state.error && ctx.state.error.toString()}

      {ctx.state.errorInfo.componentStack}

);

const styles = {
  error: {
    backgroundColor: '#f98e7e',
    borderTop: '1px solid #777',
    borderBottom: '1px solid #777',
    padding: '12px',
  }
}

export default withErrorBoundary;

Here, the withErrorBoundry is a higher-order component responsible to capture any error in wrapped component through componentDidCatch. All you need to do is just export your component with error boundary HOC and it will take care of the underlying error. Here is the example usage.
import React from 'react';
import { Text } from 'react-native';
import withErrorBoundary from './withErrorBoundary';

const ExampleComponent = (props) => (
    <Text>{ props.user.name }</Text>
);

export default withErrorBoundary(ExampleComponent);

Alternatively, You can also create an ErrorBoundary component but using HOC is much simpler as compared to the ErrorBoundary component.
Cons
Error boundaries do not catch errors for,

Event handlers
Async code (e.g. setTimeout or requestAnimationFrame callbacks)
Server-side rendering
Errors are thrown in the error boundary itself

At this point you'll need to wrap error-prone code to try-catch block and throw Exceprion from catch block which will be further handled by outer HOC. Read more at official docs
Comment: for native exception handling, you can use this. https://www.npmjs.com/package/react-native-exception-handler
Comment: Good question @RajendranNadar, Please check the updates on the answer.


Identifying middlemen in a social network

Question: I have a data set and I want to examine an hypothesis in there and probably Network Analysis should prove or reject my theory.
I have a list of products and a group of people who give the product to each other. Anyone can sell it to another in any price he want (hopefully someone will buy it).
So, imagine a chain of products transfers between the people. Except the sell price, one will also take a percentage of the sale only of the next one who will re-sell the product. And also, if I sell for the first time a product, I will take a percentage forever for every sale.
Example:
A -> B -> C
Person A will take the money from sale to Person B. Person B will take the money of the sale to person C and Person A will take a percentage of this sale as the previous owner and the creator of the chain. If person C sell the product to someone else, only person B will take the previous percentage, but person A will take the percentage of the creator.
I believe that there are people that try to exploit the system and create small or bigger circles to take advantage of these percentages of next sales to "hide" themselves.
Is there any way to identify those people?
Answer: The closest concept I can think of in network science is betweenness centrality. Suppose you're interested in studying some node $u$. First, for every pair of nodes in your network (excluding $u$), you identify all possible shortest paths. Then, you count how many of them are passing through $u$. Some variants normalize this number in various ways, but, basically, that's it. The highest the value, the more central $u$.
In your case, there's some kind of attenuation effect, so maybe you should also look at the matrix-based centralities, such as the Eigenvector centrality, Katz centrality, PageRank centrality, Alpha centrality, HITS scores, and there are certainly others. With Katz centrality, in particular, the centrality of a node depends mainly on the centrality of its 1st order neighbors, then a bit less of its 2nd order neighbors, and so on.
You can find tens of centrality measures in the literature. I'm not sure if one of them corresponds exactly to what you're looking for, but it's certainly worth having a look there, first. There's a classic paper by Freeman, and more recent reviews, such as (Landherr et al. 2010).
Answer: There is a paper discussing the same problem:

J. Borondo,   F. Borondo, C. Rodriguez-Sickert & C. A. Hidalgo, To Each According to its Degree: The Meritocracy and Topocracy of Embedded Markets, Scientific Reports 4, 3784 (2014)

From its abstract:

[...] A system is topocratic if the compensation and power available to an individual is determined primarily by her position in a network. [...] individual compensation is based on the number of shortest paths that go through them in the network. [...] the distribution of payoffs is meritocratic only if the average degree of the nodes is larger than a root of the total number of nodes.

So in short:

the quantity you are asking is betweenness centrality (as Vincent have already mentioned),
you can exploit only some systems, where there are not many connections.


How does one prove that $\sum\limits_{n=1}^{+\infty} \frac{1}{n^{1+2p}} \leq \frac{1+2p}{p}$?

Question: Got stuck on this while reading a paper. How does one prove that for $p>0$ the following inequality holds?
$$\sum\limits_{n=1}^{+\infty} \frac{1}{n^{1+2p}} \leq \frac{1+2p}{p}$$
So far I got that the series' sum is the value of the Riemann $\zeta$-function at $z=1+2p$. But this gets me no further.
Answer: Note that since $x\to1/x^{1+2p}$ is decreasing in $[1,+\infty)$,
$$\sum\limits_{n=1}^{+\infty} \frac{1}{n^{1+2p}}=1+\sum\limits_{n=2}^{+\infty} \frac{1}{n^{1+2p}}\leq 1+\sum\limits_{n=2}^{+\infty}\int_{n-1}^{n} \frac{dx}{x^{1+2p}}= 1+\int_{1}^{\infty}\frac{dx}{x^{1+2p}}=1+\frac{1}{2p}.$$
Comment: Nice. That was really nice. Thanks.
Answer: Using the Abel summation formula we have $$\sum_{n\leq N}\frac{1}{n^{1+2p}}=\frac{1}{N^{2p}}+\left(2p+1\right)\int_{1}^{N}\frac{\left\lfloor t\right\rfloor }{t^{2p+2}}dt$$ where $\left\lfloor t\right\rfloor $ is the floor function, so $$\sum_{n\geq1}\frac{1}{n^{1+2p}}=\left(2p+1\right)\int_{1}^{\infty}\frac{\left\lfloor t\right\rfloor }{t^{2p+2}}dt\leq\left(2p+1\right)\int_{1}^{\infty}\frac{1}{t^{2p+1}}dt=\frac{2p+1}{2p}.$$


Image, preimage and set operation in mappings

Question: Not the best title but I don't know how to better describe it.
So the image of a set is usually written as $f(B)$, my question is, can I use sets in the place of variables in the expression of my mapping?
The reason I'm asking is, I have to show something along the lines of
$f^{-1}(A)=B\times C$
So I have to show both sides of the inclusion, so to show this I'm thinking of inserting the (supposed)preimage in the function and see if it gives A, but I'm not sure this kind of operation is legal. If not, what would be a general way to do it?
Answer: What you seem to have in mind does not work properly. This because $f(f^{-1}(A))$ does not necessarily equalize $A$. We have $f(f^{-1}(A))\subseteq A$ but $f(f^{-1}(A))= A$ demands that $A$ is a subset of the image of $f$.
The equality you mention can be handled by showing that for each $x$: $$f(x)\in A\iff x\in B\times C$$
Comment: Hey, thanks for the answer. I tried to do it but was met with some problems. Some tips on work around would be greatly appreciated. I've edit my post.


html/css: table/grid of input elements enclosed in parenthesis

Question: I need a table/grid of 2x2 input elements, enclosed in parenthesis.
The objective is, in a page with a mathematics test, allow user to introduce the values of a matrix. The matrix must appear in the usual form of parenthesis enclosing it.
That is, starting from this code or anything equivalent:

A + B =

        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>
        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>

        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>
        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>

two corrections must be done:

mandatory: the 2x2 matrix/grid/table of input elements must be enclosed in big parenthesis
nice to have: the characters "A+B=" should appear in the same line than the matrix, centered vertically.

Note: the page supports MathJax, thus, solutions using MathJax are also valid.
Answer: Here's a way to do it using the table that you already have. Note that I used inline styles merely for the demo. You can create a style class as needed

    A+B=

    (
        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>
        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>

      )

        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>
        <input type="text"  $INPUT_PATTERN  name="a11" autofocus/>