Xcode 4.4 on iOS 5.1 build succeeds but run hangs on simulator with debug message 'Failed to attach to process id '

Question: Symptoms: Running any iOS 5.1 application from Xcode 4.4 (and 4.4.1) will launch the iPhone simulator but result in a plain black screen. In the Xcode console, the message "error: Failed to attach process to id " is displayed,  being different each time. Attempting to 'Stop' the application from Xcode does nothing, and only Force Quit will return Xcode to a working state. Pressing the 'Home' button on the simulator shows that the app was successfully installed. Sometimes, opening the app from the simulator will show the UI, but no console messages are displayed, even after manually performing 'Product->Attach to process.'
Attempted Solutions: Xcode 4.3.x was originally installed on Lion, working charmingly. The problem started at installation of Xcode 4.4 in early August, for a project which was working before. I upgraded to Mountain Lion, didn't help. I reinstalled Xcode, didn't help. I upgraded to 4.4.1 Aug 7, didn't help. I deleted all trace of Xcode data, running: find / -name '[xX]code' and deleting all super-folders where it seemed relevant. That (not surprisingly) caused some OS issues, since subsequently reinstalling Xcode just didn't work. I then did it again, reinstalled Mountain Lion (to restore some OS files I probably killed), then reinstalled Xcode 4.4.1.
For projects, I typically ran new, single-view projects each time. Lately I've tried using this sample project from Apple, per link 3 below. I tried all the clean builds, etc., but honestly, one would assume opening a fresh project should just work. Just for kicks, I put a single 'Label' object in the iPhone storyboard at times.
After doing some homework I managed to find the following questions most similar to mine, but none are exact nor do any of the solutions work (in order of decreasing relevance):

xcode-4-4-ios-5-1-simulator-problems
crash-of-xcode-4-4-for-mac
failed-to-attach-to-process-id-xcode
unit-test-target-doesnt-run-on-xcode-4-5
xcode-4-4-freezing-on-project-close
simulator-keeps-crashing-in-xcode-4-4

Any help would be greatly appreciated. I apologize for the lack of brevity, but I've spent probably 15 hours trying to find/implement solutions to a seemingly trivial problem, and I would rather provide all relevant information than to have you guess at what I did. I'm not going to specify all the build info, just because it's whatever comes stock on the fresh install of Xcode.
Comment: I haven't looked at the posts you reference but I normally solve this by deleting the app from the simulator and perhaps deleting DerivedData (and restarting Xcode).
Comment: Per my comment to the answer below, tried this, and it did nothing.
Answer: I had similar problem (although with different configuration) and found incredibly simple solution by chance. I just used Product->Stop, then Product->Run (through keyboard shortcuts if that matters). Just once! Then the problem disappeared.
configuration: XCode 4.2, iPhone Simulator 5.0
symptom difference: process attaching didn't fail
It seems to me that the problem stems from the XCode-Simulator communication, and that's why I've shared my experience here despite the differences.
EDIT: It comes out Stop; Run didn't provide permanent solution for me. The problem is recurring from time to time. Still it is a temporary workaround for me.
Comment: I don't think this is relevant to the problem I was facing. It seems clear now that a bug arose from a bad upgrade that was fixed in the patch noted in the marked answer.
Answer: I got this a few times, especially when I kept running my app and cancelling it or interrupting it too often, it's not something you can put your finger on, but yes I always managed to get back up and running by deleting the app in the simulator, cleaning project and build folder, deleting derived data (in Xcode organiser > projects view), restarting simulator and Xcode.
This also happened a few times on the device, and I needed to restart the device, iPhone in my case. I hope these infos help you out.
Comment: It seems reasonable, but I tried all of this per the solutions in the attached posts. I deleted the derived data just by opening a terminal window. I couldn't find the 'Xcode Organizer -> Projects View' you're referring to. I also reset the simulator as well.
Answer: I got this to work by building and running the simulator using the Xcode 4.5 developer preview. I then closed it out and reopened Xcode 4.4.1 and it built and ran fine.
While none of the solutions above worked for me, thanks for putting this all together. I figured I'd answer here since this was the most comprehensive.
Comment: Thanks for the heads up! I have a university license and cannot download the developer preview. It seems I might have to wait for it to be released to all users.
Answer: While this isn't exactly a solution, after today's OSX 10.8.1 update from Apple, this issue has been resolved. It's safe to say that some bug arose in the process of installing Mountain Lion and Xcode 4.4 that was fixed with this update to OSX.
Answer: I think I've cracked this one for my particular case, and I admit it's somewhat a mistake only newbies should do but I had overrided
 <code> viewWillApear:(bool)animated {} </code>
in a ViewController of mine, without calling back
 <code> [super viewWillApear:animated] </code>
It might be a good idea to search for all view lifecycle methods in your project and see if you have similar problem.


How to get Views Selective Filters working with Country Field from Address Field Module?

Question: When I expose the country field from the address-field module as a selective exposed filter (to only show countries that are in the results of the view), the "selection" works, which means only the appropriate countries are shown in the dropdown of the filter. But after clicking "Apply" the results are zero.
I have tried to rewrite the field but to no avail. I think the problem is, that the country is taken from the core. If i try other fields from the address field, it works.
Any help appreciated! Thanks!
EDIT: I just found out about the checkbox on the field itself called: "Display the localized country name instead of the two character country code". If this is unchecked, the view and the filter are working. But now i have a unreadable list of country abbreviations in my dropdown.
Is there something i can do about this?
Answer: I found a workaround on this. In the content-type with the address field i created a new field with a token of the country-field that is now working like a charm with views-selective-filters.


Django for enterprise web application

Question: I wanted to know is Django a good choice for a big web applicatin(Social Network)? More specifically, I need some suggestion on performace when number of DB transactions increases and I want to know is the embedded OR Mapping included inside Django is a good choice or should I implement them.
Thanks
Comment: possible duplicate of [Does Django Scale?](http://stackoverflow.com/questions/886221/does-django-scale)
Answer:
performace when number of DB transactions increases.

Not a Django problem, really.
You can have a lot of concurrent Django sessions via Apache and mod_wsgi.  All of them will share a common database.
Therefore, this is entirely a database problem.  You should be able to configure enough Apache/Django sessions that your database is swamped.

OR Mapping included inside Django is a good choice or should I implement them.

Yes.  It's a really good choice.
Until you can prove that the ORM is your bottleneck, use it.
As you scale up, you will rework your database, your cache, and other architectural features.   Since the ORM has a cache (as does your database), you rarely have performance issues here.
You can.
But most of your performance problems will be downloading static media files through Apache.
Comment: So, would you suggest using another server for static files, like nginx or lighttpd, or perhaps offloading it to a CDN?
Comment: Not another server.  Another piece of your existing server.  Configure your server to send Django requests through mod_wsgi to Django.  Configure static media requests to be handled directly.  The Django docs cover this configuration in detail.
Comment: Well I host the static content under another domain in orther to prevent sending cookie and some other headers for each request. Thanks for the response
Comment: "prevent sending cookie and some other headers for each request"?  Seems like too much work for too little benefit.  Can you **prove** that this helps?
Comment: Definitely it helps when you are processing a lot of requests. So you need to reduce the request the request size by as much as you can.
Comment: http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
Answer: I should add that one big issue that enterprise applications may have when using the Django ORM is that it is somewhat limited in its capability (i.e. what queries it can express). I think this is manageable if you do two things:

Strive to express queries in the Django ORM as much as possible (without experience it may be too easy to dismiss a query as not possible in Django).
If the query is really impossible in Django (you can also ask the IRC #django channel or the django-users group if you are really unsure), store the query in a queries.py file that your dba's can manage or look at. (It can be a flat dictionary referenced by your models file.)

As an example of point 2: There's no reason you can't write a query storage manager that's used in the following way: Suppose you had an app named blogs with a model called Entry:
<code># models.py
class Entry(models.Model):
    objects = project.QueryStorageManager()
    author = models.ForeignKey(User)
    body = models.TextField()
    slug = models.CharField(max_length=512)
    published_date = models.DateField()

    @project.StoredQuery("getEntryMonthHistogram")
    def getEntryMonthHistogram(self, sql, author):
        return objects.runQuery(sql, author)

# queries.py
{
"getEntryMonthHistogram": """SELECT EXTRACT(MONTH FROM published_date),
                                    REPEAT('*', count(*)) histogram
                             FROM   blogs_entry
                             WHERE  author_id = %s""",
</code>
}
Answer: My company did just build such a system for a large scale enterprise based on Django including all mobile systems. With django the dev cost were low and runnability inside enterprise server stack was no problem. Even Django managed to let us pass the penetration and security test. with any other language we would not have been able to succeed with this project under extrem budget restrictions

Django for enterprise web application


corona same physics motion on different screen resolution

Question: I'm developing a game, as a tutorial, learning experience
Specs summary:

imagine something like icehockey, but with static obstacles on the field ( thumbtacks ).
turn based, each players shoots by dragging ball and applying linear impulse on opposite direction
all of this is MULTI-PLAYER

Basically, after you shoot, you tell the other player's app that it must apply "this" force to the ball. Considering it's the same engine, I imagined I would get the same result on both devices, therefore the only communication will envolve sending the force params when the time is right. This is correct AS LONG AS THEY HAVE THE SAME RESOLUTION. If I shoot a straight line, no obstacles, then everything seems fine ( I can't really see if there's a very small offset ), but with obstacles, collision etc. the motion is not the same ( not the same trajectory ) on different resolutions ( devices )
I need to know if there is some way I can make this work the same on all devices. I need to find a way so I can replicate in minute detail a movement ( complex, not straight line ) on different screen/resolution.
Some technical details:

I'm using the letterbox scale
1200w 800h resolution ( don't really know why I chose this :) ... it seems really dumb now ... but you get the picture, I'm using basically a resolution bigger than most of the devices I test on )
physics.setScale( 100 ) = this seemed important on some point.

PS: This is meant to be a tutorial; I'm aware that I can send the trajectory lines then compose the movement OR find another way to replicate the motion, but I need to understand EXACTLY this issue, since I'll have to confront it in future games.
Answer: I'm not sure if it works but you can try this:
<code>( forceVariable / 1200 ) * display.contentWidth
</code>
( Assuming, your width is still 1200 px
It worked with images for me
Comment: not really. The problem isn't the force, corona does a good job translating it to "real life" coordinates. But still, maybe some decimals got lost on the way, float is not that accurate and we're talking about dead center accuracy here


Review First Project Structure

Question: I have created my first project (after several tutorials and reading the Android Developers Dev Guide) and have a simple tiled background. Just to put my reading about supporting multiple screens to the test (http://developer.android.com/guide/practices/screens_support.html) I created a background tile for every dpi so I have one tile at 120 dpi, one at 160, one at 240, and one at 320. I put a letter in each tile respectively so the 240 has an H, 320 X etc. When I run the app in an AVD that supports the different densities the proper image is used. This is in perfect alignment with my reading.
What I am confused on is that I only have to have one drawable xml file and it can be about anywhere to work. Now the xml is all the same since I used the same image name just changed the dpi. So how does the system find my drawable file that is referenced from my layout xml? Does it search every drawable folder till it finds a match? If there are "common" purpose files such as this shouldn't I maybe have a "common" drawable folder?
background.xml (aka my drawable)
<?xml version="1.0" encoding="utf-8"?><bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/ironmikebackgrnd" android:tileMode="repeat" android:dither="true" />

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@drawable/background">

and my project folder structure (feel free to critique)....aaarrrgggg Guess I'm not allowed to post images yet. Go here to see the folder structure.
Eclipse Folder Structure
On further exploration I see that it get's auto generated into the gen > R.Java directory. So that is how it is found but as for the project structure what would you reccomend for storing "global" / "common" type files.
Answer: You can put your background.xml in "drawable" folder. (With no qualifiers)
So it shall match and can be used regardless of the current screen resolution.
Comment: Ahhhhh so I should have a drawable folder in my structure.

Review First Project Structure


Converting a value from negative to positive or positive to negative in JavaScript?

Question: I saw this answer on how to convert a negative number to positive, but have a slightly different situation: I'm doing some coding in Apache Cordova and getting accelerometer data I need to flip.
So when the accelerometer returns an X axis value of -5 I need to convert it to 5 and the opposite as well; if the X axis value is 5 the new X axis value should be -5.
I understand how to do -Math.abs() and such, but how can I accommodate a situation like this in my code?
Answer: You can do a simple math at this context, no need of Math.abs,
x_value = x_value * -1;

Or you can negate the value like,
x_value = -(x_value);

While negating, there is a chance to get -0, But we don't need to worry about it, since -0 == 0. Abstract equality comparison algorithm is telling so in Step 1 - c - vi.
Comment: @JakeGould Glad to help! :)
Answer: You can multiply any number by -1 to get its opposite.
Example:
 5 * -1 = -5
-5 * -1 =  5

Answer: Why do you need Math.abs?
x_value = -1 * x_value;

works for every scenario I can envision.
Answer: I suggest to use the multiplication assignment with -1.

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

value *= -1;

Answer: Well, my solution is to create a ternary like this to see if the x_value is greater than 0 or not and act accordingly:
x_value = x_value > 0 ? -Math.abs(x_value) : Math.abs(x_value);


Como exibir um Menu ao clicar no item do BottomNavigationView

Question: Minha aplicação esta dessa maneira:

Preciso que quando selecionar o quarto item, apareça um menu:

O código da minha Activity Main:
package br.com.friendlychat.navigationbottombar;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = (BottomNavigationView)
                findViewById(R.id.navigation);

        bottomNavigationView.setOnNavigationItemSelectedListener
                (new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        Fragment selectedFragment = null;
                        switch (item.getItemId()) {
                            case R.id.action_item1:
                                selectedFragment = ItemOneFragment.newInstance();
                                break;
                            case R.id.action_item2:
                                selectedFragment = ItemTwoFragment.newInstance();
                                break;
                            case R.id.action_item3:
                                selectedFragment = ItemThreeFragment.newInstance();
                                break;
                            case R.id.action_item4:
                                // QUERO ABRIR O MENU AQUI, CASO SEJA POSSIVEL
                                return true;
                        }
                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.frame_layout, selectedFragment);
                        transaction.commit();
                        return true;
                    }
                });

        //Manually displaying the first fragment - one time only
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, ItemOneFragment.newInstance());
        transaction.commit();

    }

}

Estou desenvolvendo no Android Studio.
Alguém conhece uma maneira de fazer isso?
Answer: resolvi colocando esse trecho de codigo:

PopupMenu popup = new PopupMenu(MainActivity.this, findViewById(R.id.action_item4));
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.main, popup.getMenu());
popup.setGravity(Gravity.LEFT);
popup.show();


Which would you prefer? SVG, HTML5 or regen'd-PNG for graphs & charts?

Question: I'm developing a new site that graphs some operational metrics.  As such about a dozen charts/graphs will be displayed on the site.  I want to be able to have them dynamically scale down (within reason) based upon the size of the browser.
I'm debating the pros/cons of generating these as one of these options:

SVG.  Great for scaling but may have limited support,
HTML5.  Clearly a great choice for the future and for FF customers, IE?
PNG.  This would
require that I regenerate the PNG
based upon the size of the DIV &c.

Which is the preferable option?  I'm leaning towards PNG just for ubiquitous support, but would like to have client-side scaling.  What is the best solution given the state of affairs of SVG and HTML5 canvas support in browsers?
Comment: 4. Flash. Would be cross-browser and be very fast/responsive. Plus you can code some fancy effects/interactions.
Comment: Secured environment.  No flash option.
Answer: I prefer SVG over HTML5 canvas or PNG for charts. Canvas and PNG zoom as bitmaps in Firefox. (Canvas provides a vector API, but it's a drawable bitmaps surface--not a vector store.) SVG zooms as vector graphics in Firefox.
I ofter run with the view zoomed, so I appreciate real vector zooming.
(Canvas makes sense for games that can't handle the perf hit of retained mode graphics.)
Comment: I may need to start another question, but how would SVG dynamically scale in say a resized DIV?
Comment: In browsers that don't have full-page zoom and have only text zoom, you need to wrap the SVG element in an em-sized div and make the SVG box size to 100% of the containing div. My concern above was having vector zooming of the chart with the full-page zoom in Firefox >= 3.5, and to make that work, the em/div trick isn't necessary.
Answer: You could do worse than explore a new charting library:
http://g.raphaeljs.com/
You won't believe it at first.
Answer: Now you can use SVG anywhere
Comment: Secured environment. No flash option.
Answer: SVG is supported by all modern browsers.
Canvas is supported by all modern browser.
Internet Explorer supports neither.
A partial API for SVG, with fallback mechanism for IE exists in Raphaël (raphaeljs.com)
A partial Canvas-implementation for IE exists in ExCanvas
I'd say say its not a question of "Canvas or SVG", but what high-level library exists that best covers your needs.
Comment: Well, I'll be employing gnuplot which can produce any of the above for the most part with a flick of the output terminal switch.  I should mention that this needs to be without client plug-in, I'll need to read more as to this ExCanvas.
Answer: The best option would be SVG or HTML5 that will fall back on PNG if the others aren't available.
Comment: An option is to generate PNG/JPGs from the SVG files serverside for the clients that don't support SVG.
Comment: If the  tag is used however, then one could default a PNG request inside should the SVG not be requested...might be best.
Answer: ExplorerCanvas brings <canvas> support to IE. So, it would be an amalgamation of 1 & 2. The benefit would be that (a) as more browsers add support for <canvas>, you would automatically get the benefits of already supporting it and (b) you would get scaling with browser size.
Answer: You can use SVG with a png fallback just using CSS as it is described in this answer: https://stackoverflow.com/a/13575068/418711


Coefficient of 0.001 with p < 0.005

Question: This should be a simple inquiry. Doing a regression analysis I found that the coefficient of a predictor has a(n) (infinitesimal) positive effect of 0.001 that is significant at the 0.005 level.
I cannot help wondering how a similar phenomenon may be possibile. Do you think it might depend on the fact that my variables are not (yet) scaled? As soon as I have rescaled all the predictors, do you think that the magnitude of the effect in point would change?
I hope someone is able to clarify this puzzle.
Comment: Thank you all for you enlightening answers!

I have just recoded the relevant predictor along the same scale and, as you pointed out, the magnitude of the coefficient rocket up to 0.15xxx with p < 0.001. Super!
Answer: A simple thought experiment: suppose your predictor was a length, originally expressed in millimetres. If you express it instead in kilometres and fit the model again, you have not really changed anything meaningful about the relationship, but your coefficient will drop by several orders of magnitude.
You can also get significant results with very low coefficients if you have a very large dataset.
Comment: In fact, after switching to kilometers, the coefficient will drop by exactly six orders of magnitude.
Answer: This is a known phenomenon, as p-values depend both on the effect size and the sample size.
As you get many observations, you get convincing evidence that a tiny effect is real.
In other words, that coefficient probably isn't zero; you have a very unusual result for a situation where the coefficient isn't zero.
However, the effect isn't necessarily enough to interest an investigator.
"Yep, it's not zero, but it's not big enough to care."
What you say about scaling might matter. For instance, $0.001$ light years is still a pretty far distance if the other measurements are in centimeters.

Coefficient of 0.001 with p < 0.005


Comandos no terminal do Mac

Question: Tentei instalar o Composer no OSX 10.10.3 seguindo as instruções do site:
curl -sS https://getcomposer.org/installer | php

e depois disso não estou conseguindo mais executar os comandos curl, ls, entre outros. O terminal não executa estes comandos e me retorna a seguinte mensagem:
-bash: curl: command not found

Como posso corrigir isso?
Comment: O `dir` não existe (até onde eu saiba), e o `curl` pode não vir como padrão no Mac (não sei). Tem certeza de que o problema ocorre com o `ls` também? Ou algum outro comando comum, tipo `cd`?
Comment: `dir` realmente não funciona `-bash: dir: command not found`, ao digitar `curl` aparece `curl: try 'curl --help' or 'curl --manual' for more information`, `ls` lista os arquivos e diretórios. Como @Gabe mencionou, é estranho `ls` não funcionar, você realmente testou?
Comment: O seu `PATH` pode ter sido alterado. Você editar sua pergunta e colocar o seu `PATH` (`echo $PATH`)? E também um `which cd`, só pra saber onde tá?
Comment: Provavelmente o script de instalação alterou o teu ~/.bash_profile . Geralmente algo é adicionado no final do arquivo com comentários pertinentes. Dá uma conferida e comenta qualquer linha suspeita que tenha a variável PATH envolvida.
Comment: Isso mesmo, o comando `ls` retorna o mesmo erro, o `curl` tambem retorna o mesmo erro. `-bash: curl: command not found`. Os comandos `cd` e `pwd` funcionam normalmente.
Comment: Qual a versão do OS X? Os comandos pararam de funcionar em algum momento específico?
Comment: A versão do OS X é a 10.10.3, Parou de funcionar quando eu fui instalar o composer rodando este comando `curl -sS https://getcomposer.org/installer | php` , ai deu a mensagem de erro e não funcionou.
Comment: Eu passei o olho no instalador do Composer, e não consegui encontrar nada que pudesse ter causado o problema. Tem certeza de que tudo funcionava antes? Qual o resultado do seu `echo $PATH`?
Comment: `echo $PATH`
`/Library/Frameworks/Python.framework/Versions/3.4/bin::/bin:"/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home"/bin`
Answer: use : wget https://getcomposer.org/installer | php
ou
curl -k https://getcomposer.org/installer | php

Comandos no terminal do Mac


What data structure is best suited for VirtualStringTree?

Question: I guess everyone who had ever used Delphi's VirtualStringTree will agree that it is a great control. It is a "virtual" control (your data must be held somewhere else) so I was thinking what data structure is the best suited for such a task? IMO that data structure must support hierarchy, it must be fast and easily expandable. The easiest implementation would be using a record and that's what most of the documentation which can be found is suggesting. But what if you need to do some fast lookups, calculate totals, etc? What data structure you are using together with VirtualStringTree?
EDIT1: I'm using Delphi 2010.
OK, I'll try to give some more details about my requirements.
Data size can be very variable, from 1 to thousands of items. Each item can hold multiple string, integer values. I need random access, my data can change many times during the application lifetime. Good performance is very desirable. I also need data saving and reloading.
EDIT2:
Got 1 answer so I'll try to comment my opinion. Thanks, Dorin for your answer but
I don't think your structure is very convenient.
1) It doesn't deal with hierarchy.
2) Having separate TStringList's or TList's for each node is not very effective IMO. With this implementation I can only lookup the current node's data, but can't effectively search in the whole tree.
I think this data structure must be like a tree. It must have nodes with ability to add children. Then I just could get node's data in OnInitNode event, check if my node has some children, set ivsHasChildren flag if so, then in OnInitChildren event set correct children count. Later in OnGetText event I could just fetch needed data from my node structure and set it to CellText based on the Column index. My idea is to have a separate data structure and do all the needed operations with it without a need to use VirtualStringTree. Hope someone got my point :).
EDIT3: I've found quite interesting JclTrees unit which at first sight could be used to achieve what I'm looking for. It belongs to JCL library. Lack of decent documentation makes it hard to quickly investigate it's functionality. I'll probably look deeper into it when I have some more time.
Comment: @Linas Random access means you need an array.
Comment: @Linas Could you tell us more about the data you are wishing to store. How big is it? How does it change during your process lifetime? Do you need random access? What are the performance constraints? At the moment I feel your question is too general to offer meaningful advice.
Comment: @David a TList would be more suitable IMHO, but arrays are fine as well.
Comment: @dorin TList is an array
Comment: @David yes, it's an array of pointers, BUT it's easier to play with :-) that's my point.
Comment: @Dorin, TList is an array of . It's an array of pointers only if  is an pointer :)
Comment: @Linas I get your point. I think I have got it all along. What did you mean when you said that you wanted random access? Could you elaborate on that. Technically random access means O(1) access which usually implies an array. Do you really mean that?
Comment: @David By saying random access I meant ability to do fast lookups based on selected index (key column). Sorry for misunderstanding.
Comment: @Linas, what's an "index" in a tree? You might want to elaborate a bit on exactly what you're trying to do. If the "key column" is something uniquely linked to the data, look into a HashTable (the TDictionary from Generics.Collection), it's supposed to provide O(1) access, so it's a good match for your "random access" requirement.
Comment: @Cosmin I know what TDictionary is capable of and You are right, it is probably the best solution for making an index.
Comment: @Linas, TDictionary is a nice modern probabilistic data structure, but it has nothing to do with "hierarchy" and if the indexes are sequential it's slow compared to an array. I'd like to contribute an answer but I still don't understand exactly what you want to do: Where does your data come from? What kind of operations do you need, and the biggest one, do you *really* need O(1) random access? My imagination is probably failing me, but I can't think of an algorithm where you need a tree structure AND you need random access to any node.
Comment: @Cosmin Random access is not an issue. Don't get me wrong, I do not desperately need  O(1) random access. Besides, it's not very difficult to implement that if I ever need it.
Answer: OK, because given answers didn't solved my issues I've written my own tree data structure which imitates TVirtualStringTree and handles all the problems I mentioned in my question. Now I can optionally use only my data structure and all the changes in it will automatically update the VirtualStringTree. I think I will upload source code somewhere later and post the link here. Thanks for all the answers.
EDIT: I've uploaded source to the Google code: svTrees. There is a little demo that shows how it works.
Comment: good that you have worked it out but I would comment that a significant reason for you not getting an answer that satisfied you was that your question was somewhat vague.
Comment: @David Maybe you are right but the solution was not easy to implement. Maybe because of that complexity it was not easy for me to describe my problem.
Comment: probably just trying to explain it here helped you understand the problem better! It often works that way.
Answer: You haven't specified your Delphi version, so:
I suggest using records(I'm not sure in which version of Delphi they added methods for records, I moved from D7 to D2010) so you can have something like:
type
  TMyRecordWithMethods = record
    function GetMeAResult: Integer;
    procedure DoSomething(const AInParam: Integer; var AOutParam: Integer);
  end;

if your version of Delphi does not support records with methods and you really need methods for nodes, then you will have to use objects to accomplish this, also have a look at generics.
Since you will only need to hold a few thousand items, I suggest using generics(no need to reinvent the wheel IMHO) i.e.
uses ..., Generics.Collections;

type
  TMyNode = class(TObject)// you can leave this out if you like
    MyIntList: TList<Integer>; // you can do lookups, you have to implement your own saving/loading methods
    MyStringList: TStringList or TList<string>; // you can do lookups in both cases, use TStringList for save/load of data
  end;

Now I assume that you would like to store all items from the virtual tree and load them later, you can do this by defining your own file structure, i.e.
type
  TMyFileHeader = record
    CountItems: Integer; // number of items in the tree
    ...
  end;

const
  szMyFileHeader = SizeOf(TMyFileHeader);

type
  TMyItemEntry = record
    CountInt: Integer; // number of integer values
    ...
  end;

const
  szMyItemEntry = SizeOf(TMyItemEntry);

now you will need to implement the load and save, I suggest saving and loading using TFileStream -- very straightforward,
pseudo code, sorry not time for partial code :-\
a) saving the content:

save the number of items in a TMyFileHeader variable and write it to file
for each item in the tree, save the integer list, save the string list

b) loading the content:

read file header -- so that you know how many items you need to read from the file
do a for Index := 0 to Count -1 read the item from the file

Note: that you can save the string list from each item directly to the current position in the file stream, however it would be wise to save it directly by using:
FileStream.WriteBuffer(PChar(AStringList.Text)^, Length(AStringList.Text) * SizeOf(Char));

I hope this helps, the actual implementation of the code is up to you, have fun!!
Comment: this doesn't address the issue of hierarchy
Comment: @David Heffernan depending on his "actual" needs he can make compromises, if he needs to create maybe a million nodes, using objects will eat a lot of memory(now it all goes down to target system of course), however records will eat less, ANYHU you're more than welcome to come with a good answer :-P
Comment: @Dorin I said nothing about objects. For what it's worth I think that records are fine. That said, objects don't use any more memory - TObject has no member fields. My point is that the question is about the hierarchy, not how to store the information in a node.
Comment: I've mentioned in my question that records are quite good solution but using records doesn't address some issues as David said.
Comment: @David come on man, don't get so defensive :) but regarding "That said, objects don't use any more memory" -- why would anyone use objects without fields? same applies to records, but if you add one integer field in a object and one integer field in a record, you will see the difference when you look at .InstanceSize, now that being said, multiply by number of items(and subitems) and you get a lot of memory wasted + the create and free process which will take quite a few CPU cycles(again if there are many items).
Comment: @Linas you still haven't provided too much details regarding your end goal, i.e. how many items do you expect to show, WHY do you need to sub class, remember that you could also use helper methods on records or maybe, just maybe, objects is what you need to get the job done clean and fast.
Comment: @Dorin Why would you use objects rather than records? Inheritance, polymorphism, ability to implement interfaces. InstanceSize for the TObject subclass with a single integer is 12 bytes. So, yes it costs to use objects, but that cost is often insignificant.
Comment: @Dorin He didn't say anything about subclassing. He wants advice on a data structure that lives in parallel to the tree view. But you are right that the question is lacking the details that would make it possible to answer well.
Comment: @David no he didn't say anything regarding sub class, I assumed that that's the end goal, having nodes with special methods, fields, etc. since a tag is "data-structures" I also assume he might have a database that he didn't mention...
Comment: @Dorin: Don't want to be nit-picking but "data-structures" has nothing at all to do with a "database"
Comment: @Smasher well correct me if I'm wrong, but the purpose of a database is to hold "data" -- which can be anything from byte values to integer to strings to blobs(raw data), for example in one particular project I save the user preferences into the database -- no matter from where a user logs in, he will ALWAYS have his preferences restored from previous session. I "assumed" that he has something to do with database, for example for all tables in my database I have a class called (T + table name) which is a child of a class that can perform various tasks on database. What am I missing?
Comment: It's just that the implication `a tag is "data-structures" -> he might have a database` does not make sense to me. (+1 for the answer by the way which is certainly helpful)
Comment: well come to think of it now, it doesn't really make too much sense..., maybe because I've been dealing only with database related apps. I have a trigger that says: database in the back of my head, "assuming" does make an ass at least of me right now :-P
Answer: You can use a TXMLDocument.
If you want more control over what you put in there I would suggest that you create a xsd describing the structure you want and use the XML Data Binding Wizard to generate Delphi code that you can use.
This schema

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:complexType name="itemType">
        <xs:sequence>
            <xs:element name="id" type="xs:int"/>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="itemlist" type="itemlistType" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
    <xs:complexType name="itemlistType">
        <xs:sequence>
            <xs:element name="item" type="itemType" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="itemlist" type="itemlistType"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

will give you these interfaces to work with in delphi
  IXMLRoot = interface(IXMLNode)
    ['{16C6C960-58B7-400C-9E46-7ACC7BEF276F}']
    { Property Accessors }
    function Get_Itemlist: IXMLItemlistType;
    { Methods & Properties }
    property Itemlist: IXMLItemlistType read Get_Itemlist;
  end;

{ IXMLItemlistType }

  IXMLItemlistType = interface(IXMLNodeCollection)
    ['{59F80BAC-887E-48DF-8288-95276BF9DCE7}']
    { Property Accessors }
    function Get_Item(Index: Integer): IXMLItemType;
    { Methods & Properties }
    function Add: IXMLItemType;
    function Insert(const Index: Integer): IXMLItemType;
    property Item[Index: Integer]: IXMLItemType read Get_Item; default;
  end;

{ IXMLItemType }

  IXMLItemType = interface(IXMLNode)
    ['{1218DD35-C3EF-40E6-831A-1A4AA0782C36}']
    { Property Accessors }
    function Get_Id: Integer;
    function Get_Name: WideString;
    function Get_Itemlist: IXMLItemlistType;
    procedure Set_Id(Value: Integer);
    procedure Set_Name(Value: WideString);
    { Methods & Properties }
    property Id: Integer read Get_Id write Set_Id;
    property Name: WideString read Get_Name write Set_Name;
    property Itemlist: IXMLItemlistType read Get_Itemlist;
  end;

Comment: Interesting solution but I'm not a big fan of TXMLDocument because of it's external dependencies.
Comment: XML is still a great structure for a tree so if you do not like TXMLDocument you can use something else to access and modify the XML data structure.
Comment: I don't even want to imagine the slowness of this solution.


Google Drive API Authorizing with Google + Sign in

Question: I have implemented google drive api in my website(in php) with the Oauth 2 authorizing method where different users have to enter their own client id and client secret to access files in his/her google drive.
But to make it more user friendly I am planning to implement  Google+ Sign-in method as in this url https://developers.google.com/drive/about-auth.
Can anyone provide me with a tutorial on how to use google + sign in to get the refresh token for google drive api requests?
Answer: These are the steps ...

Call the auth URL with your app/client ID and the scopes you require. Include the "email" scope.
Google will walk the user through login the and (if the first time through) authorisation dialogues
Eventually the browser will redirect back to your oauthcallback url, and pass you an auth code
Call google to convert the auth code to a refresh token. This will also return the user's google ID and an access token.
Store the user ID in your session so you can identify the user subsequently
Persist the refresh token alongside the google user id in a database

On subsequent visits...

If you have the google user id in the your session, you can retrieve the refresh token from your database and use it to generate access tokens as you need them.
If you do NOT have the google user id in your session, go through the steps above. This time, google will NOT prompt the user for authorisation (since it's already authorised), and the refresh token will be blank (since you already have one stored).

Everything you need to know is within the oauth playground page. If you click through the buttons, you will see that it is following the steps I outlined above.
You then need to deal with the possible error situations, eg

user declines permission
user withdraws permission
google expired the refresh token (happens a lot) so you need to re-auth
timeouts
Comment: Here does each user need to create his own client id?  What I am trying is to provide an area where user can access his google drive files simply using his username and password.
Comment: Client Id refers to your application. The google documentation variously refers to it as client-id, application id,and I've seen another permutation somewhere. So the answer is no, the user does not need to create a client id.
Comment: @pinoyyid Do you have any pointer/url to step 4 "Call google to convert the auth code to a refresh token. This will also return the user's google ID and an access token."?
Comment: if you go through the steps using the Oauth Playground, you can see the calls


How to get out of infinite loop for ROBIRG's maze when the "right_is_clear" for next four position?

Question: def turn_right():
    turn_left()
    turn_left()
    turn_left()

#Roborgs maze is (5,5)
#Roborgs position and face of direction will be random in a maze.
while not at_goal():       #till the robot reaches the goal this loop continues running
    if right_is_clear():   #roborgs check whether the right side is clear or not? If yes, turn right
        turn_right()
        move()             #problem is this maze has four positions where there is no wall on the right side, when the roborgs are being placed at that position, the loop gets infinite. Position are (4,3) , (4,4) , (3,3) , (3,4).
    elif front_is_clear():
        move()
    else:
        turn_left()
        if wall_in_front():
            turn_left()
        else:
            move()

Answer: I see this is old and I'm not sure how optimized it is, but this is what I came up with to not get caught in a loop:
def turn_right():
    turn_left()
    turn_left()
    turn_left()
def find_goal():
    if right_is_clear() == True:
            turn_right()
            move()
        if right_is_clear() == True:
                turn_right()
                move()
            if right_is_clear() == True:
                    turn_right()
                    move()
                if right_is_clear() == True:
                    if front_is_clear() == True:
                        move()
                    else:
                        turn_left()
    elif front_is_clear() == True:
        move()
    else:
            turn_left()
        if front_is_clear() == True:
            move()
        else:
            turn_left()
            move()
while not at_goal():
    find_goal()

Comment: Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach?


Triangle inscribed in another triangle with same proportion on the sides

Question:
As shown in the figure below, $\triangle DEF$ is a triangle inside $\triangle ABC$.

Given $$AD:DB=BE:EC=CF:FA=1:x$$

Such that the area of $\triangle ABC$ is two times the area of $\triangle DEF$.

Find $x$

I have no idea here. My first thought is that we could make parallel lines on $D, E, F$, though that would split $\triangle DEF$ into parts, which isn't ideal.
Another idea was similar triangles, due to the fact that the sides are proportional. But the angles don't seem to be the same.
Please help!
Comment: *"the angles don't seem to be the same"* - what the angles look like is irrelevant to the mathematical fact. If you can prove similarity, they are similar.
Answer: Recall that, when two triangles have one angle equal, their areas are proportional to the product of the adjacent sides. This is, for example, embodied in so-called sine formula.
So, as $AD=\frac{1}{1+x}AB$ and $AF=\frac{x}{1+x}AC$, then $A(\triangle ADF)=\frac{x}{(1+x)^2}A(\triangle ABC)$. The areas of $\triangle BED$ and $\triangle CFE$ end up the same, so altogether (taking away the areas of those three triangles from the area of $\triangle ABC$):
$$A(\triangle DEF)=A(\triangle ABC)\left(1-3\frac{x}{(1+x)^2}\right)$$
and now, all you need to do is solve the equation $1-\frac{3x}{(1+x)^2}=\frac{1}{2}$. This has two solutions: $x=2+\sqrt{3}$ or $x=2-\sqrt{3}$.
Answer: Hint: Can you show that $AD = \dfrac{AB}{1+x}, ~AF = \dfrac{x \cdot AC}{1+x}$?
So, what is $[ADF]$ in terms of $[ABC]$?
And then show that $~[BDE] = [CFE] = [ADF]$
Finally use $ \displaystyle [BDE] + [CFE] + [ADF] = \frac 12 [ABC]$ to find $x$.
Answer: A linear algebra based approach:
Let $\vec{u}=\vec{AB}, \vec{v}=\vec{AC}$.  Then the area of $\Delta (ABC)$ is just $$\frac12|\vec{u}\times \vec{v}|$$
We have \begin{eqnarray*}
\vec{DF}&=&\vec{DA}+\vec{AF}=\frac{-1}{1+x}\vec{u}+\frac{x}{1+x}\vec{v}\\\\\vec{DE}&=& \vec{DB}+\vec{BE}=\frac{x}{1+x}\vec{u}+\frac{1}{1+x}(\vec{v}-\vec{u})=
\frac{x-1}{1+x}\vec{u}+\frac{1}{1+x}\vec{v}
\end{eqnarray*}
Thus \begin{eqnarray*}\Delta(DEF)&=&\frac12|\vec{DF}\times\vec{DE}|\\\\&=&
\frac12\left|\left(\frac{-1}{1+x}\vec{u}+\frac{x}{1+x}\vec{v}\right)\times\left(\frac{x-1}{1+x}\vec{u}+\frac{1}{1+x}\vec{v}
\right)\right|\\&=&
\frac12|\vec{u}\times \vec{v}|\left|\frac{x^2-x+1}{(1+x)^2}\right|\\&=&
\Delta(ABC)\left|\frac{x^2-x+1}{(1+x)^2}\right|
\end{eqnarray*}
Thus we must solve $$\frac{x^2-x+1}{(1+x)^2}=\pm\frac12.$$
Either $$x^2-4x+1=0,\qquad{\rm or}\qquad x^2+1=0.$$
Only the first of these has real solutions:  $$x=2\pm\sqrt{3}.$$


How to input quarter tones in Garageband

Question: How can one play an instrument in Garageband but with quarter tones instead of the usual ones?
On my keyboard I can change the scale and it works, but this is not recognized by Garageband and it seems that I cannot find how to change scale to quarter tones in Garageband.
Comment: No, 64 is just a number and will show up in any number of places, especially with MIDI, since most MIDI parameters take values up to 127 and 64 is the halfway point. I'm talking about a setting on the software synths or virtual instruments you're trying to control in GarageBand called "key tracking" or something similar. If you can set the instrument to only track the keyboard at 50% it will produce quarter-tones.
Comment: I haven't used GarageBand, so this might not be the answer, but you could try looking for a "key tracking" feature or some similar name. Basically, all midi insts will default to 100% key tracking, which means every half-step move sent to the inst is rendered to sound like a half-step. If you can set it to 50% (which could be a setting of 50 or 64 depending on the unit) then every half-step sent to it will be rendered as a quarter step. An octave will sound like a tritone, two octaves will sound like one octave, etc. Worth a look, but I don't if GarageBand has the feature in its instruments.
Comment: I recognize the number 64 from my keyboard. Do you mean I should change those numbers in my keyboard? That could probably work but there has to be a faster and smoother way to fix this problem.
Answer: GarageBand is a bit limited compared to Logic Pro X, but there's a hack that you can use. It's sort of cumbersome though, but it should work. Essentially, you're going to create 2 software instruments and add the AUPitch plugin to one of them detuning it by a quarter tone (up or down, doesn't matter).

Create 2 tracks (of the same instrument)
Move to one of the two instruments and click on the smart controls button
Click on the i to show the inspector
Scroll down on the inspector until you see Audio FX and click on a slot to add an effect
Go to Audio Units -> Apple -> AuPitch
On the Pitch control, double-click where it says 0 cents and change it to either 25 cents or -25 cents

The "cumbersome" part of this method is that you'll have to record notes separately on each track and then play them together to get the desired effect.
Answer: If you have a hardware instrument with quarter-tone support, you can certainly record audio from it into Garageband. However, none of the virtual instruments in Garageband will support quarter-tones played from a MIDI controller. But within Garageband, you can use any virtual instrument that uses the AU (Apple Audio Unit) protocol. If you can find a third-party virtual instrument that supports and provides the scales with quarter-tones that you need to work with, you can figure out how to make it work in Garageband.
Comment: Yes my keyboard have this function where you can change the tones to make it sound middle eastern, but somehow I failed to make garageband recognize that.
Comment: Garageband will not be able to interpret quarter-tone MIDI signals coming from your keyboard. But Garageband can simply record the *audio* output from the keyboard, through an external audio-to-USB interface. So if the quarter-tones are so important to you, why not do that?


How big are differences between "classic" and "pop" vocal studies?

Question: Some teachers advertise themselves as teaching "classic singing" and others as "pop singing". My child is currently learning "pop" but I have discovered a highly experienced "classic" teacher that is also geographically placed much more conveniently. We are not far with learning yet and we have no very obvious preference, so I am thinking about the possible switching.
Are "pop" and "classic" studies significantly different or is some part of the obtained knowledge transferable? How difficult is to switch between these two ways of singing later?
For instance, if to learn singing the Beatles "Let It Be" from the book I have - there is a melody line written on the scales (there are also piano chords as well). Is this significantly different from singing something more classical?
Comment: I could be wrong, but I think it has more to do with the style and approach to singing than the genre.
Comment: @TimSeguine You are correct, but often the genre is the main influence on style and approach.
Answer: I don't mean to sound like I am belittling Pop music, but Classical music is always more complicated, and usually more difficult to sing/play. The differences are merely due contrasting styles, not musical inferiority. I was trained as a chorister in a church choir but listen to large amounts of pop music, and that is where my knowledge is from.
Possibly one of the main things that your daughter won't learn if she studies pop music is Italian words - these are very rarely used in pop and so if she attempts to transfer from pop to classical after having spent too long learning pop, she will be quite behind in terms of the musical language she should be able to understand.
Also, the style of voice and diction required for classical music is different to pop music, in that classical music is far stricter as far as annunciation is concerned; pop musicians have far more flexibility and therefore often sound sloppier (from a classical perspective). Another example of differences Classical singers are taught to  sing each note individually (unless specified otherwise by the composer), whereas pop vocalists often 'slide' between notes. This can be a difficult habit to break for a pop singer who wants to sing classical, but not a difficult ability to develop for a classical singer who wants to sing pop.
Essentially, if your daughter wants to be able to sing classical and pop, then she should learn classical. This will also assist her in theoretical studies of classical music, if she chooses to learn about the theory behind the music she sings.
Hope this helps.
Comment: Opera especially is much more difficult than pop music - you have to sing at the same volume, but without a microphone.
Comment: Actually, portamento - the deliberate slide between notes - Is one aspect of the operatic style that I find irritating.  At least they do it on purpose!
Answer: There's an in-between style - let's call it 'Musical Theatre singing' (though it isn't confined to the stage) where vowels are pure, diction is clear and the paramount aim is to convey the information in the lyrics.  It's not 'all about the voice' or 'all about the attitude', it's 'all about the song'.
This is the type of teaching I recommend, if you can find it.  The sort of teaching that takes If I Loved You from Carousel and demands a beautiful tone on the vowel of 'loved' followed by just the right amount of final 'd' (because 'If I loved you' and 'If I love you' mean two quite different things).
Record producers used to do this.  Maybe the Beatles came into the studio naturally equipped with the almost theatrical clarity of diction we hear on their recordings, but I doubt it.   And there's no point in a song like Strawberry Fields or Penny Lane if you can't hear the words.


Password from associated website not retrieved in app via Smart Lock API

Question: I've associated my https website and app to share stored credentials and received confirmation that the association is live, but when I call the CredentialsApi.request() method in my app, I am not able to retrieve any credentials from my website that were saved with the Chrome password manager. How can I fix this?
Answer: After submitting the data to associate your app and https website, and receiving confirmation that the association is live, here are some things to check:

if you've just saved a new credential, wait a couple minutes for synchronization between Chrome and Android and across devices
try a real device (Android 4+) and not an emulator, ensure that the device is running the latest version of Google Play Services (8+) and has an active internet connection
ensure that you are signed in to Chrome with the same account as your Android device, and that the account is in good state (doesn't require password re-entry and meets any corp policy requirements, e.g. is in sync and receives push email notifications, for example)
if the association just went live recently and you were testing the API integration in the app on your device before it was enabled, visit passwords.google.com and delete any existing entries for your website / app to force removal of any cached data
visit your website in Chrome, sign in as normal and save your password when prompted, confirm that the password was saved and appears in chrome://settings/passwords and passwords.google.com under the https domain specified in your association (fully visible if you mouse over the domain shown in the UI)
call the API on Android using an apk with package name matching your submission and signed with the same keystore as your Play Store app, keep in mind that the debug keystore may be different if you are in a development environment with non-release keys or you move to another computer.
note that if there are multiple credentials available, the API callback may not immediately be success as you might need to handle multiple stored credentials and invoke UI to allow the user to select a credential

Note that if you save a credential in the app, Chrome will offer to auto-fill in web forms on associated https websites after the association has been live for about 24 hours (and the credential will also be available via the Chrome Credentials API). If you're looking for a complete guide to testing a Smart Lock integration, check out this post.
Comment: Steven can you please check this question: https://stackoverflow.com/questions/77758835/saved-password-between-app-and-website-is-not-sync


Binding object in Spring

Question: Binding error in spring and jsp, I would appreciate if someone could help.
I have proper getter and setter of these attribute,
private int sydinv;
@NotNull(message="You must specify the inventory in Melbourne warehouse")
private int melinv;

And when I use them in jsp file, error message says "Bean property 'sydinv' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?"
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form action="${pageContext.request.contextPath}/products/save" method = "post" commandName="product">
Title
<form:input  path="title" /> <form:errors path="title"/>

 Description
<form:input type = "text" path= "description"/>

Price
<form:input  path= "price" /><form:errors path="price"/>
Image
<form:input  path= "imageUrl" /><form:errors path="imageUrl"/>
sydinv
<form:input  path= "sydinv" /><form:errors path="sydinv"/>
Inventory
<form:input  path= "inventory" /><form:errors path="inventory"/>
<form:input type="hidden" path="productId"/>

<input type = "submit" value = "Submit"/>

<input type = "reset" />
</form:form>

And here is my controller
@RequestMapping("/edit/{productId}")
public String edit(@PathVariable int productId, Model model){
    //add your code here to find a product based on its id
    //and put it in the model
    Product product = pdao.getProductById(productId);
    System.out.println("@@"+product.getSydInv()+"##"+product.getMelInv());

    model.addAttribute("product", product);
    return "product";
}

The jsp file can read all of the attribute except syd_inv, can anyone gives me some hint? Cheers
Comment: What is the actual error?
Answer:
Bean property 'sydinv' is not readable

here your sydinv  is written in simple but your getter method is pointing to a SydInv writen in capital getSydInv() .i think your getter and setter methods are  wrong
change it to
setsydinv(int sydinv){this.sydinv = sydinv}
int getsydinv(){return sydinv}

Comment: Thanks so much, I change the name in parameter list same as the class attribute, it works, thanks so much for you help.

Binding object in Spring


ASP Login Control - Checking login status

Question: I want to use my code behind (C#) to check and see if a user is logged in or not on page load. I assume this is really basic, but I'm still new to .net
This is basically what I want:
if(loggedIn == true){ do something }

Comment: On a side note, when checking if something is true or false and the property is a boolean value, you can just use `if (booleanProperty)` or `if (!booleanProperty)`. First one is `if(true)` second is `if(false)`
Answer: If you are using the built in .net Forms Authentication, then you can use the following
if ( HttpContext.Current.User.Identity.IsAuthenticated){
     do something
}

Make sure you have your settings in the web.config set up for using FormsAuthentication
Answer: if (User.Identity.IsAuthenticated)
{
    // do something
}

assuming you're using FormsAuthentication.
If however, you're using a Session based login, you can do a nullable check, just like this:
if (HttpContext.Current.Session["somevalue"] != null)
{
    // do something
}

Answer: Check User.Identity.IsAuthenticated property.
Answer: Check whether User.Identity.Name is an empty string or not.
Answer: If you are using Membership you can just call GetUser() with no arguments. It results the logged in user if the user is logged in.
http://msdn.microsoft.com/en-us/library/fcxcb339.aspx
Membership.GetUser()


iOS8 CLLocationManager returns Null in Background State

Question: in iOS8 when i m putting my app in back ground the CLLocationManager returns Null in location ,i have also unable Location updates in Background Modes and also do requestAlwaysAuthorization
<code>    CLLocationManager *lm = [[CLLocationManager alloc] init];
    lm.delegate = self;
    lm.desiredAccuracy = kCLLocationAccuracyBest;
    lm.distanceFilter = kCLDistanceFilterNone;
    [lm requestAlwaysAuthorization];
    [lm startUpdatingLocation];
</code>
Comment: I have implemented same things and its work fine for me in background mode. Please check few things , you have strong reference of CLLocationManger . Create property in header .
Comment: can you please confirm if you have place NSLocationAlwaysUsageDescription in your plist and use delegate - - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Comment: yes i have implemented that both the things..it works fine in my iOS7 device but not in iOS8
Comment: @Santu C ...after making it property in header. CLLocation *CurrentLocation sometimes getting null.
Comment: Please try with in this way @property (strong, nonatomic) CLLocationManager *locationManager;
Comment: Or can you please post full method code   - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Comment: Santu C is right,you have to put `CLLocationManager` into header file as a property, not a local variable.That should fix your problem.
Comment: @Santu C & @ Benson Tommy sorry for late replay ..i want to implement background functionality in one of my project so i have made demo for background and in this demo only i assign the last location  in  - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ self.CurrentLocation = [locations lastObject];
}
Comment: did you try with CLLocationManager with strong reference
Comment: @Santu C..yes i have also try with that..i have putted nslog in didUpdateLocations but it does not print anything so i have also try with another thing that when on buttons click i have call method on nstimer and on that method calling while app goes into back ground i do code as evry time in lm trying to get new location and then try nslog..but does not work..:(
Comment: @Santu C..can u please share ur code it might help me..
Comment: @JaydeepChauhan In my project there have lots of thing , let me write a demo project for you . I will share with you later of day.
Comment: @Santu C..thnx buddy..
Comment: @Santu C..problem solved...i have put all above things in view didLoad..which i have wrote in function..about  CLLocationManager *lm
Answer: Please find below code for getting location on background mode -
Please enter text for NSLocationAlwaysUsageDescription in plist file .
Please select location updates on background mode from project settings -

AppDelegate.h
<code>//
//  AppDelegate.h
//  LocationTest
//
//  Created by Santu C on 28/05/15.
//  Copyright (c) 2015 company. All rights reserved.
//

#import <UIKit/UIKit.h>
#import<CoreLocation/CoreLocation.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property(strong,nonatomic) CLLocationManager *locationManager;

@end
</code>
AppDelegate.m
<code>//
//  AppDelegate.m
//  LocationTest
//
//  Created by Santu C on 28/05/15.
//  Copyright (c) 2015 company. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate
@synthesize locationManager;

#define CONST_TIME_INTERVAL 60.0

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    [self location];

    // Override point for customization after application launch.
    return YES;
}

-(void)location
{

    NSLog(@"location called");

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    self.locationManager.pausesLocationUpdatesAutomatically = NO;

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000

    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
    {
        [self.locationManager requestAlwaysAuthorization];
    }
#endif

    [self.locationManager startUpdatingLocation];

}

- (void)startUpdatingLocation
{
    NSLog(@"startUpdatingLocation called");

    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{

    NSLog(@"locationManager didUpdateLocations");

    CLLocation *newLocation = (CLLocation *)[locations lastObject];

    NSLog(@"dLongitude : %f", newLocation.coordinate.latitude);
    NSLog(@"dLatitude : %f", newLocation.coordinate.longitude);

}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

     [self startUpdatingLocation];
}

@end
</code>
Hope this will help you
Answer: do put code in viewDidLoad about CLLocationManger
<code>CLLocationManager *lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBest;
lm.distanceFilter = kCLDistanceFilterNone;
[lm requestAlwaysAuthorization];
[lm startUpdatingLocation];
</code>
Problem solved..


Sequelize: how to do nested subquery in one to many field?

Question: I have two tables; one is "user" another is "post". User has a one-to-many relationship with "post". "post" has a foreign key field named user_id.
user table:
+----+--------------------------------------+--------+------------+-----------+------------------+----------+------+---------------------+---------------------+
| id | uuid                                 | name   | first_name | last_name | email            | password | role | createdAt           | updatedAt           |
+----+--------------------------------------+--------+------------+-----------+------------------+----------+------+---------------------+---------------------+
|  1 | 37b4e543-ae46-45ef-a216-dea4ee79d6f7 | riyad  | 0          | 1         | email@example.com  | 123456   |    1 | 2021-11-22 17:56:56 | 2021-11-22 17:56:56 |
|  2 | d63c3414-db52-4784-9de8-b99a6659f1c9 | riyad2 | 6          | 7         | firstname.lastname@example.com | 123456   |    5 | 2021-11-22 20:01:36 | 2021-11-22 20:01:36 |
+----+--------------------------------------+--------+------------+-----------+------------------+----------+------+---------------------+---------------------+

post table:
+----+---------+--------+---------+--------------------------------------+---------------------+---------------------+
| id | title   | body   | user_id | slug                                 | createdAt           | updatedAt           |
+----+---------+--------+---------+--------------------------------------+---------------------+---------------------+
|  1 | title 1 | body 1 |       1 | 6e95b4a2-f101-48cd-8fea-8b53850c54b0 | 2021-11-22 17:57:56 | 2021-11-22 17:57:56 |
|  2 | title 2 | body 2 |       1 | 47d0cdbe-af3b-446a-badf-5197d8796133 | 2021-11-22 17:58:02 | 2021-11-22 17:58:02 |
|  3 | title 3 | body 3 |       2 | 347e200b-bffd-423d-b481-48d1b74ecc75 | 2021-11-22 20:02:04 | 2021-11-22 20:02:04 |
+----+---------+--------+---------+--------------------------------------+---------------------+---------------------+

Now I want to get the users who posted from 2021-11-22 15:00:00 to 2021-11-22 20:00:00.
In this case the first two posts (post id 1 and 2) were made in this time which were posted by user_id 1. Now I want to get that user(s) details in single query.
This is the SQL query I would do like use:
select *
from user
where id = any(select user_id from post
               where createdAt >= "2021-11-22 15:00:00"
                 and created_at <= "2021-11-22 20:00:00")

Now how can I write that in sequelize?
Answer: You want this Sequelize doc page.
Long story short (at least in my opinion), sub queries will be hard to handle in any ORM. I would advise to use raw SQL instead.


Prime Ideal of a Polynomial Ring

Question: I am wondering how to show that the ideal (x,y) is prime and maximal in $\mathbb{Q}[x,y]$.
Comment: Look at the ring homomorphism $\varphi: \mathbb{Q}[x,y] \rightarrow \mathbb{Q}$ such that $\varphi(f)=f(0,0)$. What is the kernel of this map?
Comment: @Prometheus: the kernel is exactly (x,y) and the image of the homomorphism is Q, and then using the first isomorphism to conclude that (x,y) is maximal because Q[x,y]/(x,y) is a field
Answer: Look at the quotient ring $\mathbb{Q}[x,y]/(x,y)$. Then use that an ideal $I \subset R$ is maximal iff $R/I$ is a field. Using the fact that $I$ is prime iff $R/I$ is an integral domain, you will also be able to show that $(x,y)$ is prime (and all maximal ideals are).
Answer: Hint $ $ (excerpted from one of my old posts - which shows even more)

Even  easier: $\ \,$  the ideals $\rm\ \ (x)\:\ \subset (x,y)\ \subset\ (1)\ $ are distinct primes$\ \ \, $  [or $(1)$]
since their residue rings $\rm\, \mathbb Q[y]\ \supset\ \ \ \mathbb Q\ \ \ \ \supset\ (0)\ $ are distinct domains [or $(0)$]
Comment: Why is this easier: is it not exactly equivalentto what was proposed by Sebastian and by Prometheus  in his comment?
Comment: @Mariano: You misunderstand: the "easier" refers to the post from where it was excerpted.
Comment: Similarly for  $(p)\subset (p,x) \subset (1)=\Bbb Z[x]\,$ as [here](https://math.stackexchange.com/a/666569/242) $\ \ $
Answer: Let $I$ be an ideal of $\mathbb{Q}[x,y]$ such that $(x,y) \subsetneq I \subseteq \mathbb{Q}[x,y]$.  Choose $a \in I$ with $a \not \in (x,y)$.  Then $a \in \mathbb{Q}$ and we conclude $I = \mathbb{Q}[x,y]$ (why?) and $(x,y)$ is maximal.
Now let $F, G \in \mathbb{Q}[x,y]$ with $FG \in (x,y)$.  Note $F$ and $G$ cannot both have a constant term, so one must be in $(x,y)$.  So $(x,y)$ is prime.
We could have deferred to the fact that all maximal ideals are prime.  Also, Sebastian's answer is probably more practical (it is surely how I would approach this problem).  However, sometimes I like seeing definitions work and thought others might as well.

Prime Ideal of a Polynomial Ring


Quais são as principais diferenças entre programação orientada a protótipos e programação orientada a classes?

Question: Depois de ter aprendido um pouco mais sobre JavaScript, percebi que, mesmo tendo uma construção class, classes (de fato, como em C# ou Java) não existem no JavaScript. Isso não passa de açúcar sintático para a programação orientada a protótipos da linguagem.
Já sei como a programação prototípica funciona, mas não sei de fato as diferenças entre ela e uma programação orientada a classes (verdadeiras, como em Java ou C#).
Então, a pergunta é:

Quais são as principais diferenças entre a orientação a objetos via protótipos e a orientação a objetos via classes?
Quais as vantagens e desvantagens de cada um desses padrões?
Answer: Bom, a pergunta não foca na implementação específica, como é a de JavaScript, então não falarei tanto dos pontos que JS escolheu assim, ainda que seja a implementação mais popular dessa forma de orientação a objeto.
Vou começar pedindo para você ler Qual a diferença entre uma classe e um objeto?.
Não existindo a classe o modelo é o próprio objeto. E isso pode ser considerado vantagem ou desvantagem já que não precisa escrever o modelo, escreve direto um objeto, o que é mais simples, mas muda um pouco o modelo mental, que fere um dos pontos principais que a orientação a objeto foi criada que é pensar sobre o que é aquele objeto.
Uma desvantagem clara é que qualquer meta informação precisa estar dentro do próprio objeto, em alguns casos carregados em todos objetos ou em objetos específicos. Isso é claramente menos eficiente. A flexibilidade cobra um preço.
É bem flexível modificar o protótipo da maneira que for melhor para casa caso, mas ao mesmo tempo torna os contratos mais frágeis. Tudo é mais fácil nele, inclusive cometer erros.
As linguagens que optaram pela classe, em geral, são de tipagem estática e prezam mais pelos contratos, afinal a classe (real) é um contrato rígido. Nada impede dessas linguagens terem uma forma de protótipo ou classe falsa de forma mais ou menos conveniente, e assim dar mais flexibilidade também, da mesma forma que elas podem dar dinamismo opcional para tipagem. Quando opta-se por não ter classe fica faltando elementos e essas linguagens nunca podem ter as mesmas características que as que optaram pela classe.
O protótipo torna muito difícil manter a tipagem estática, cada alteração no objeto tem potencial de mudar seu tipo.
A classe tem a ver com ser mais explícito. Com o protótipo tudo pode acontecer, você tem que estar mais preparado, o que é curioso porque a facilidade que ele dá cobra um preço que torna mais difícil, e se você não souber o que está fazendo terá que contar com sorte, o compilador pode fazer pouco por você.
A classe falsa já pode ajudar muito, que é o que JavaScript, e principalmente TypeScript, fizeram. Ela dá informações que ajudam o compilador tomar decisões e muitos dos problemas citados são resolvidos. Mas ela não torna o objeto mais eficiente, ele ainda tem o peso de um protótipo, conta com a infraestrutura para dar flexibilidade não usada (naquele ponto). É o mesmo que colocar tipos estáticos nas variáveis em linguagens como JS, Python, PHP, Ruby ou outra, ajuda dar robustez, mas o preço do objeto dinâmico continua lá.
Então podemos dizer que isso tem um pouco a ver com o velho problema sobre o que é orientação a objeto e tem ligações com as duas escolas desse paradigma secundário (veja mais). O protótipo agrada mais ao fãs do Alan Kay e a classe agrada mais os fãs do Bjarne Stroustrup.
Pra mim as diferenças, vantagens e desvantagens são quase as mesmas da tipagem dinâmica e estática. Ela não te cobra pra entrar, te cobra por tudo o que faz depois.
Tabela da MDN:

Categoria
Com base em classe
Com base em protótipo

Classe vs. instância
Classe e instância são entidades distintas
Todos os objetos podem herdar de outro objeto

Definição
Defina uma classe com uma definição de classe; instancie uma classe com métodos construtores
Defina e crie um conjunto de objetos com funções construtoras

Criação de um novo objeto
Crie um único objeto com o operador new
Idem

Construção da hierarquia de objetos
Construa uma hierarquia de objetos usando definições de classe para definir subclasses de classes existentes
Construa uma hierarquia de objetos atribuindo um objeto como o protótipo associado a uma função de construtor

Modelo de herança
Herde propriedades seguindo a cadeia de classes
Herde propriedades seguindo a cadeia de protótipo

Extensão das propriedades
A definição de classe especifica todas as propriedades de todas as instâncias de uma classe. Não é possível adicionar propriedades dinamicamente em tempo de execução
A função construtora ou protótipo especifica um conjunto inicial de propriedades. Pode adicionar ou remover propriedades dinamicamente para objetos individuais ou para todo o conjunto de objetos

Acho que vale a leitura de JavaScript é uma linguagem Orientada a Objetos?. E Existe classe em JavaScript?.
Para mais aprofundamento quase sempre as melhores fontes estão na mãe das wikis.
Coloquei no GitHub para referência futura.
Answer: A herança prototípica é um modelo bastante simples de reutilização de código, o código pode ser reutilizado de maneira direta e ajuda-nos a reduzir a redundância.
As desvantagens são a falta de variáveis privadas e protegidas e os tipos não seguros.


DAX: Unwanted cartesian product lines?

Question: Please help to calculate/understand properly lastDate and rankDate measures for following simplified example (download):

Desired result:

Reality (incorrect subtypes):

Why relationship is broken?
How to avoid this cartesian product lines?
My Measure (I commented workaround, because it's kind of postfilter, not prefilter):
rnkDate =
VAR t =
    CALCULATETABLE(
        VALUES(tstTable[Date]),
        REMOVEFILTERS(tstTable[Date])
    )
RETURN
    //IF( MAX(tstTable[Amount])<>BLANK(), // WORKAROUND To hide unwantedd rows
        RANKX(
            t,
            LASTDATE(tstTable[Date])
        )
    //)

P.S. Mess happens only if I use fields from dimensional table dimType[Type] (within one table everything is Ok):
Answer: The problem is that the query generated by Power BI performs the cartesian product and filers the result by checking the result of the measure.
in our case is something similar to
SUMMARIZECOLUMNS(
  'dimType'[Type],
  'tstTable'[subType],
  'tstTable'[Date],
  "MinAmount", CALCULATE(MIN('tstTable'[Amount])),
  "lastDate", 'tstTable'[lastDate],
  "rnkDate", 'tstTable'[rnkDate]
)

SUMMARIZECOLUMNS doesn't use relationships when iterating on different tables, it applies them when evaluating the measures. There is an article explaining what is the equivalent DAX code executed by SUMMARIZECOLUMNS
Introducing SUMMARIZECOLUMNS
the problem is that RANKX evaluated on an empty table retuns 1. This can be seen executing this on dax.do
EVALUATE
VAR t =
    FILTER ( ALL ( 'Date'[Date] ), FALSE )
RETURN
    { RANKX ( t, [Sales Amount] ), CALCULATE ( [Sales Amount], t ) }

so the solution is to first check that the table t is not empty, which is the reason because the workaround that you implemented solved the issue
lastDate =
IF( NOT ISEMPTY(tstTable), // checks fact table in particular context
    CALCULATE(
        LASTDATE(tstTable[Date]),
        REMOVEFILTERS(tstTable[Date])
    )
)

rnkDate =
VAR t =
    CALCULATETABLE(
        VALUES(tstTable[Date]),
        REMOVEFILTERS(tstTable[Date])
    )
RETURN
    IF( NOT ISEMPTY(tstTable),
        RANKX(
            t,
            LASTDATE(tstTable[Date])
        )
    )

Comment: thank you for detailed answer. But if you remove `subType` from matrix, empty "cartesian" rows appears again (updated source file, on `rnkDate3 page`). Found out, if you use `NOT ISEMPTY(tstTable)`, instead of `NOT ISEMPTY(t)` it resolves the problem. Is it this approach correect?
Comment: Yes, it's better
Comment: FYI, why still not accepted: There is another   [discussion branch](https://community.powerbi.com/t5/Desktop/Two-identical-visuals-with-different-output-how-it-s-possible/m-p/3016473/highlight/true#M1028205). Just curious about Greg Deckler theory/hypothesis that you could&should avoid explicit `CALCULATE` usage. May be he will offer more elegant solution. This question is kind of test for this theory...

DAX: Unwanted cartesian product lines?


Given is a binary relation. Determine the Hasse diagram for it and two upper bounds

Question:
Given is the set $A = \left\{1,2,3,4,5,6,7\right\}$ with relation $R =
\left\{(1,2),(3,2),(2,4),(5,4),(4,6),(4,7)\right\}$
Determine the Hasse diagram for the reflexive-transitive closure of
  $R$ and determine two upper bounds of $\left\{2,5\right\}$ in this
  reflexive-transitive close of $R$.

So I've read about Hasse diagrams and the good thing is that you can ignore edges that are transitive and reflexive. So basically, if my understanding is correct, it's sufficient if I just draw the Hasse diagram for the given relation $R$:
<code> 6     7
  \   /
   \ /
    4
   /|
  / |
 5  2
   / \
  /   \
 1     3
</code>
Is the Hasse diagram correct like that?
But I'm not sure how I solve the problem with those upper bounds now. It's mentioned to find two lower bounds of $\left\{2,5\right\}$. But now I don't know where to look at in the Hasse diagram? I understand it like that that $\left\{2,5\right\}$ means that we need to look at the "nodes" $2$ and $5$ in the Hasse diagram and check their children. $5$ has no child and thus no lower bound, so we look at $2$. It has as children nodes $1$ and $3$ thus the two lower bounds are $1$ and $3$?
I hope you can tell me because if they ask such a question in an exam I feel pretty helpless : /
Answer: No, your diagram is incorrect.  You may be confusing reflexive and symmetric, but I can't be sure.  For example, your diagram shows 2R3, but in actuality we have 3R2.  Similarly, the diagram shows 4R5 instead of 5R4.  It doesn't make sense to address the rest of your question until you fix the diagram.
You are confused about upper and lower bounds, I think.  A lower bound of a set $S$ is just an element $b$ such that $b\le s$ for every $s\in S.$  Similarly, an upper bound of a set $S$ is just an element $b$ such that $b\ge s$ for every $s\in S.$  Here I'm writing $a\le b$ instead of $aRb$ because it's more intuitive.
So an upper bound of $\{2,5\}$ is an element $\ge 2$ and $\ge 5.$  In the diagram, there are $3$ to choose from: $4,6,7.$  As an aside, in the case, $4$ is the least upper bound. Not only is it a lower bound, but it's smaller than all the other lower bounds.
Comment: I'm going to enlarge my answer.  I'm a slow typist, so it may be a few minutes.
Comment: Yes, that's right.  That's typical usage in math, not just in Hasse diagrams.  If there are 1000 elements in a set, an upper bound for the set is $\ge$ every one of them.
Comment: Thank you, I have edited the Hasse diagram and I believe it's correct now because it seems to "create" every element which belongs to reflexive-transitive closure of $R$ but I still don't understand the second part of the question with the lower bounds, do you? I understand it like that that $\left\{2,5\right\}$ means that we need to look at the "nodes" $2$ and $5$ in the Hasse diagram and check their children. $5$ has no child and thus no lower bound, so we look at $2$. It has as children nodes $1$ and $3$ thus the two lower bounds are $1$ and $3$?
Comment: Thank you for the edit and help! :) Just one last question to your last paragraph the first sentence. The element really needs to be $\geq 2$ AND $\geq 5$?
Comment: Alright thank you very much I understood this now!! :D
Comment: It was my pleasure.


How to draw line between two nodes placed in different Panes / Regions

Question: I am tryin to draw a genealogy tree. In my tree, I store information about ex partners. So the Panel (Region) for person shoud looking like this
Z * * * Z * * * Z * * * X --- Y

Where Z represent exPartner,  X represent Persion and Y represent current Wife / Husband
And now I would like to draw line to connect current relation  with  children. And ec relations with children.  (graphicaly there will be a line beetwen Z and *)
But when the person is in the other region LayoutX and LayoutX property return  relative value.
 How Can I do that, and how dynamicaly resize this Panel ? I would like that Z should be allways at middle of line Horizontal line connecting children.
Comment: Can you give a little more detail on the relevant part of the scene graph structure? Presumably the nodes you are connecting have some common ancestor in the scene graph? What are you intending to use as the parent of the `Line`?
Comment: The common ancessos is AnchorPane.  And next the Panels will extend Region or AnchorPane... I dont have any idea how it should be drawing.  Maybe as Panel ext AnchorPane containing list of Panels.. etc.. ?
Comment: So you would just add the lines directly to the anchor pane that is the common ancestor, presumably?
Answer: Given any node, you can get its bounds in the coordinate system of any other node in the same scene graph with:
Node nodeOfInterest = ... ;
Node anotherNode = ... ;

// ...

Bounds boundsInScene = nodeOfInterest.localToScene(nodeOfInterest.getBoundsInLocal());
Bounds boundRelativeToAnotherNode = anotherNode.sceneToLocal(boundsInScene);

So assuming you have some kind of pane which is a common ancestor to two nodes you want to connect, you can do this:
Pane commonAncestor = ... ;
Node n1 = ... ;
Node n2 = ... ;

Bounds n1InCommonAncestor = getRelativeBounds(n1, commonAncestor);
Bounds n2InCommonAncestor = getRelativeBounds(n2, commonAncestor);
Point2D n1Center = getCenter(n1InCommonAncestor);
Point2D n2Center = getCenter(n2InCommonAncestor);

Line connector = new Line(n1Center.getX(), n1Center.getY(), n2Center.getX(), n2Center.getY());
commonAncestor.getChildren().add(connector);

// ...

private Bounds getRelativeBounds(Node node, Node relativeTo) {
    Bounds nodeBoundsInScene = node.localToScene(node.getBoundsInLocal());
    return relativeTo.sceneToLocal(nodeBoundsInScene);
}

private Point2D getCenter(Bounds b) {
    return new Point2D(b.getMinX() + b.getWidth() / 2, b.getMinY() + b.getHeight() / 2);
}

Comment: didn;t work for me :(  The line is draw from 0.0.   In my case, I think that I want to draw my tree in recurency. So For Head I wil create object Panel extending AnchorPane for example. In this Pane I will have a HBox with Panels to represent children.. etc... What do you thinking about this solution ?  or could we take a point ensemble ?
Comment: @VANILKA I assume you are computing these after layout, right? It all works for me, so if it's not working you need to edit your question with a [MCVE].
Comment: @VANILKA I meant after layout had been performed (e.g. in response to a user event). Simply setting something's `layoutX` and `layoutY` properties will not cause layout to be performed. (A node's bounds are only computed as part of the layout pass.)
Comment: Ok when I set  LayoutX and Y for . First element I remarked la difference. Extept the line is not drawing from center but from left corner to left corner of element : http://imgur.com/hacq84A
Comment: Ok it works..  The size of  Rectangle was 0..  Thx for your help


What is this parameter estimation strategy called?

Question: Let $X_1, X_2, \ldots, X_n$ be a random sample from a normal distribution with mean $\mu$ and variance $\sigma^2$. Consider the problem of estimating $P(X > 100)$.
One way to accomplish this is to calculate $n^{-1}\sum_{i=1}^n \mathbb{1}(X_i > 100) $. This "plug-in" estimator is consistent, and its bias and MSE are easy to compute.
A smaller group of my students came up with another way to approach the problem: calculate
$$
1 - \Phi\left(\frac{100 - \bar{x}}{s} \right).
$$
This can be motivated by the fact that $P(X > 100) = 1 - \Phi[(100 - \mu)/\sigma].$
This estimator is also consistent, but its bias and MSE are more difficult to compute.
My question is this: does this kind of strategy have a name? I ask because we are still plugging things in, but this is not a so-called plug-in estimator.
Comment: Isn't this just the Gaussian MLE?
Comment: I would call the second one the "plug-in" estimator, while the first one is the moment estimator.
Comment: @shadowtalker yeah it'd be the invariance principle if you were using the MLE for the variance, but we are not as long I define this sample variance as the one where you divide by $n-1$.
Comment: The second method is much more powerful because it uses the distributional assumption of normality. However $\frac{100-\bar x}{s}$ is not normally distributed due to the uncertainty in $s$. Look up the $t$ distribution with $n$ degrees of freedom.
Comment: It's Rao-Blackwellized...but that isn't very specific
Answer: Your second estimator is the "plug-in" estimator, based on the invariance property of MLE's it is the maximum-likelihood estimator (under the normal assumptions). The first estimator could be called a moments estimator, but could also be seen as non-parametric, as it is unbiased without need for normality assumption.
So you could try to find a better unbiased estimator using Rao-Blackwell theorem.
Comment: thanks (+1) I'm not sure if you saw the discussion above, but I believe $s^2 = \sum_i(x_i - \bar{x})^2/(n-1)$ is not the MLE for iid normal data.
Comment: Yes, so replace with $n$ as divisor. Rao-Blackwellization at least can be done approximately by simulation, exact calculation I am not so sure ...


Why does $g(x)=(x^2−1)/3$ map $[-1,1]$ to $[-1/3, 0]$?

Question: This is a particular part of a fixed-point problem I don't understand. The problem says:

Let $g(x)=\dfrac{(x^2−1)}3$. Does $g$ have a fixed point on the interval $[−1,1]$?

So naturally we have to see what $g$ maps $[-1,1]$ to. My professor says it maps to $[-1/3, 0]$. My understanding is that, in general, if we have an interval $[a,b]$, then $g$ would map this to $[\min(g(a),g(b)), \max(g(a),g(b))]$. In which case, $g$ does not map $[-1,1]$ to $[-1/3, 0]$, but to $[g(-1),g(1)]=[0,0]$ instead.
If I am correct in what I say, then this means my professor has made a mistake and means to say the interval in question is $[0,1]$, which does indeed map to $[-1/3,0]$.
What is going on here?
Comment: Your general understanding is flawed: Consider sin on $[0,2\pi]$, its image is certainly not only 0.
Comment: @T'x Yes indeed, you're right. I'm forgetting that the image of $g$ is the mapping of ALL elements on $[-1,1]$, not just the end points.
Answer: Your understanding is wrong; in general, a function doesn't even necessarily map an interval to an interval, let alone the interval you mention. A continuous function does map intervals to intervals. But it is not true that the interval $[a,b]$ is then mapped to $[\min\{g(a),g(b)\},\max\{g(a),g(b)\}]$. Instead it is mapped to
$$\left[\min_{x\in[a,b]}g(x),\max_{x\in[a,b]}g(x)\right].$$
That is, your should consider the values of $g$ on the entire interval, not just the endpoints.
As a side note to your original question; you don't need to see where $g$ maps the interval $[-1,1]$ to. You just need to ask yourself whether there exists some $x\in[-1,1]$ such that $g(x)=x$.
Answer: You make a mistake here,  the plot of $g$, it decreases in $[-1,0]$ from 0 to $-\frac{1}{3}$,  then increases.
Answer: That's immediate it is an even function, so the image is the same as the  image of $[0,1]$, and on the latter interval, $g$ is monotonically increasing.


Logic variables support for .NET

Question: I am looking for a library/assembly that allows me to work with logical variables in F#. I want to avoid reinventing the wheel in implementing the required union-find datastructure, unification code and so on.
I have found Prolog.NET, but the manual is a bit sparse. I do not want a full-fledged Prolog implementation, but only its treatment of logical variables and the manual is kind of lacking in that respect.
Here's what I want to be able to do:

declare new logical variables
bind a log.var. to a term (perferably the library allows complete Herbrand terms for that)
equalize log.vars. (i.e. unification)
meta-treatment of log.vars. (is it ground? to which other log.vars. has it been equalized?...)
eventually, the library even supports matching, i.e. one-sided unification.

Does anyone know any library that does all this, or libraries that might at least be used as a starting point?
Comment: Is anyone aware on any progress on this since the last answers below? (2010)
Answer: I have a basic embedding of logic programming in F#.  I developed it for the course I teach on "Programing Paradigms", which uses F# throughout and includes a couple of lectures on logic programming.
The code uses imperative updates to reflect substitutions due to unification, and it uses success continuations.  So it is relatively different from, e.g., Kanren.
I'm not sure how much sense the notes will make by themselves, but you can find this embedding at the end of:
   http://undergraduate.csse.uwa.edu.au/units/CITS3242/16-logic-prog.pdf
I can provide a refined version of this embedding on request.
Answer: I don't know a library offhand that does what you want.  However, I do have an implementation of "union-find in F#" in this blog entry.  And from my college days, I seem to recall some popular book on Scheme had a basic unification algorithm in it which I used to code up a 'mini-prolog' implementation back in the day.  So I feel like this is something that someone with the right experience could put together in a weekend, in case someone out there is looking for a project.  (Perhaps I'll add it to my own weekend TODO list.)
Comment: That's all fine. But as I said above I was looking for existing code. It's not that I am unable to implement it all on my own, but it would be a waste of time if someone else already did that work.
Comment: Maybe you're thinking of The Reasoned Schemer? It defines a DSL called mini-kanren that integrates pretty well with Scheme, and a translation to F# shouldn't be hard.
Answer: Mini-Kanren has been implemented for Scala.  I'm not a .NET programmer, and can't say how useful this is to you, but Mini-Kanren fits  your requirements in terms of a programmatic logic-variable language: if the Scala embedding in .NET has properties compatible with what you are after, then you should be there.

Logic variables support for .NET


distance measure

Question: how to measure similarity? and what edit or transformation distance means?
I have looked in the literature and all give some complicated, fancy explanations, except one who used the Simpson family to demonstrate how to calculate the distance measure
Still really don't get what edit distance term means ? should we narrow the differences to reach the similarity? but for how far and what is the threshold to consider two or more objects similar or different
Answer: Similarity is usually inverse proportional to the distance between two objects. What a distance between any two objects mean is typically very application specific.
Consider for instance the Levenshtein distance (also string edit distance)[1], where you want to measure the distance between two strings a and b.
"the edit distance d(a, b) is the minimum-weight series of edit operations that transforms a into b."[1]. In this statement, it is still left out, how we define "edit operations", which in case of the Levenshtein distance are
1. Insertion (of a character of the string)
2. Deletion (of a character of the string)
3. Substitution (of a character of the string)
but this could be also others! (E.g. some other distances use only Insertion+Deletion).
So, the L. distance is basically asking: Given these 3 operations, how can I reach from one string a, another string b "in the fastest way"? And how long is that way (i.e. number of operations)?
Example: d("car", "star") = 2
-> 1. Substitute "c" with "t"
-> 2. Insert "s"
So, for your application you're basically free to decide on how distance is computed and from that similarity can be derived. (The smaller the defined distance, the more similar are two objects). Note however, that distances must obey following properties:
d(x,x) = 0
d(x,y) = d(y,x)  (Symmetry)
d(x,z) <= d(x,y) + d(y,z) (Triangle inequality)
I don't get quite what you mean by "how far and what is the threshold[...]". Usually, you set up a distance metric for some other algorithm, which uses it and comes up with a final configuration (e.g. K-Means where you get K clusters of your data given your distance).
A very interesting and relatively new research topic related to that is the so called "Metric Learning" [2] where you can use learning algorithms that will find a suitable distance for your dataset.
[1] https://en.wikipedia.org/wiki/Edit_distance
[2] Kulis, Brian. "Metric learning: A survey." Foundations and Trends® in Machine Learning 5.4 (2013): 287-364.
I hope that helps a bit! :)
Comment: Nice answer--welcome to our site!

distance measure