Download file with Angular

Question: I'm new to Angular. I am writing a small music blog with Django for the back-end and Angular for the front-end but I'm currently stuck. In my blog's detail page, I've succeeded in showing in displaying the music information.
Now my problem is to add a button that download the music file when clicked.
When I log the information returned from details.component.ts, I get the following:
{id: 1, artist: 'Artist_name', title: 'The_music_title', thumbnail: 'http://127.0.0.1:8000/media/image_file.png', audio_file: 'http://127.0.0.1:8000/media/name_of_music_file.mp3', …}

I can't use the code below because the file audio file is cross-origin. Whenever I click on the button, it only opens a new tab and start playing the song there

    <button type="button">Download</button>

EDIT:
I added a new url that accepts a music id, queries the database for a music object with that id and downloads the song.
So when tried visiting http://127.0.0.1:8000/music/download/1, it downloaded the song
Comment: By "I can't use the code below because the file audio file is cross-origin", you mean that the call to django backend returns in a cross-origin error?. Do you have a possibility to configure django-backend's allowed origins to have your frontend url (like http://localhost:4200)?
Comment: I've edited the the question
Comment: Don't nest a button inside a a-tag. If it is a link, use an a tag. If it is a button use a button tag. It's never both tags at the same time!
Comment: Thanks! I did ```Download``` and it worked. But is there a way I can avoid hard-coding the url
Answer: for hardcoding url I think you can declare a variable in ts and concatinate it with data.id
{{url + data.id}}

url: string = 'http://127.0.0.1:8000/music/download/';

Download file with Angular


How do I make two constraints match each other in iOS Storyboard?

Question: I have a view that is sized to the width of the screen with a 1x1 ratio of width to height (matching height). I have a view below that square view that is a set height from the bottom. What I want is for the top view to be centered in the blank space. So I would love to just set 1 constraint for the top and 1 constraint for the bottom to say, match. Then if there are x number of points of available, each constraint should be size x / 2.
So far, I haven't been able to find a constraint setting that can do this. Could someone describe how to do this?
Answer: Generally you add 2 transparent views, 1 above and 1 below, pin the edges to your existing views and set the 2 new views to have equal height.
Comment: I took that idea and did something a little different. I created a view that matched the space I wanted to center inside. Then I told my square view to center itself in that new view. I guess there just is not a way to do it using only constraints. Thanks.
Comment: @Gandalf458 I'd actually say your way is the better way to do it, rather than just having transparent views thrown into the UI for the sake of constraints...
Comment: I'll play with this idea. Thanks!


How to use Ubercart product SKU as a condition in Rules?

Question: I need to display a message on the cart page if one or more specific SKUs are added to the cart.
For example, if a product with SKU # ABC123 is added to the cart, the Rule should be triggered and thus display a message... if a product with SKU # XYZ789 is added to the cart, the Rule would not be triggered and no message would be displayed.
It seems like this should be a fairly simple function, but for the life of me I cannot find a way to accomplish this. Can anyone please point me in the right direction?
Thanks!
Comment: The closest I can get so far is to use the "Customer starts checkout" event and the "Check an order's products" condition. This does allow the Rule's Actions to commence, but they do so on the Checkout page... not on the desired Cart page location.
Comment: Do you only want this message to display once or every time the /cart page is hit for the current user?
Comment: @erier Preferably display it every time for the current user, as long as one of the qualifying products is in the cart.
Answer: This answer does not use Rules, but rather hard-coding inside of the cart template.
As the message should be displayed each time the user is on the /cart page, something like this might work. If page--cart.tpl.php doesn't exist, create it and add ...
<code>$items = uc_cart_get_contents();
foreach($items as $item) {
    if($item->model == 'ABC123') {
        drupal_set_message('Item ABC123 is in the cart');
    }
}
</code>


How to keep an image within layout with drag and drop

Question: I have the following XML:
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/palette2"
    android:id="@+id/fl" >

    <ImageView
        android:id="@+id/iv"
        android:layout_width="10dp"
        android:layout_height="10dp"
        android:src="@drawable/esquare" />

</FrameLayout>

Which gives the following image in my Android Phone

How can I code so that user can drag the image anywhere in a layout and the ImageView will always stay within the layout?
If X<0 it will be X=(X+imageview.width())
If Y<0 it will be Y=(Y+imageview.height())
If X>layout.width() it will be X=(X-imageview.width())
If Y>layout.height() it will be Y=(Y-imageview.height())?
Something similar to this:

So if the user drags outside of the view, the square image will stay in the last known location within the FrameLayout
I convert the layout background to a bitmap so I can use it to get the X and Y coordinate and convert to RGB value for my app.
f = (FrameLayout) findViewById(R.id.fl);
f.setOnTouchListener(flt);
iv = (ImageView) findViewById(R.id.iv);
f.setDrawingCacheEnabled(true);
f.buildDrawingCache();
bm = f.getDrawingCache();

I have the following code which works but every once in a while I get an error NPE for x must be <= layout.width() or y must be <= layout.height();. Sometime the app allows me to drag to the right or bottom out of the layout itself which shouldn't be happening because I have a condition for it to not allow it.
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int x = (int)event.getX();
        int y = (int)event.getY();
        if (x<0) {
            iv.setX(0);
            iv.setY(y);
            x=0;
            Toast.makeText(getApplicationContext(), "x=0", 2000).show();
        }
        if (y<0) {
            iv.setY(0);
            iv.setX(x);
            y=0;
            Toast.makeText(getApplicationContext(), "y=0", 2000).show();
        }
        if (x>bm.getWidth()) {
            x=bm.getWidth()-20;
            iv.setX(x);
            iv.setY(y);
            Toast.makeText(getApplicationContext(), "x=bitmap.maxwidth(}", 2000).show();
        }
        if (y>bm.getHeight()) {
            y=bm.getHeight()-20;
            iv.setY(y);
            iv.setX(x);
            Toast.makeText(getApplicationContext(), "y=bitmap.maxheight(}", 2000).show();
        }
        if (x>0 || x<bm.getWidth() || y>0 || y<bm.getHeight()) {
            int action = event.getAction();
            int pixel = bm.getPixel((int)x,(int) y);

            switch (action & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN: {
                    Log.i("COORDINATES","Touch coordinates : x" + String.valueOf(x) + "y" + String.valueOf(y));
                    iv.setX(x);
                    iv.setY(y);
                    inRed = Color.red(pixel);
                    inBlue = Color.blue(pixel);
                    inGreen = Color.green(pixel);
                    Log.d("Colors","R:" +inRed +" G:" +inGreen+" B:" + inBlue);
                    break;
                }
                case MotionEvent.ACTION_MOVE:{
                    Log.i("COORDINATES","Touch coordinates : x" + String.valueOf(x) + "y" + String.valueOf(y));
                    iv.setX(x);
                    iv.setY(y);
                    inRed = Color.red(pixel);
                    inBlue = Color.blue(pixel);
                    inGreen = Color.green(pixel);
                    Log.d("Colors","R:" +inRed +" G:" +inGreen+" B:" + inBlue);
                    break;
                }
            }
        }
        return true;
    }

With the below code, the X=0 and the Y=0 works just great! the imageview stays inside but the issue happens when I drag the X or the Y past the bitmap's width and height.
This is my LogCat if I drag too much to the right:
02-09 12:34:32.791: E/AndroidRuntime(12607): FATAL EXCEPTION: main
02-09 12:34:32.791: E/AndroidRuntime(12607): java.lang.IllegalArgumentException: x must be < bitmap.width()
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.graphics.Bitmap.checkPixelAccess(Bitmap.java:1155)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.graphics.Bitmap.getPixel(Bitmap.java:1107)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at com.example.dragdrop.MainActivity$1.onTouch(MainActivity.java:116)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.View.dispatchTouchEvent(View.java:7241)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2168)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1903)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1953)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1405)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.app.Activity.dispatchTouchEvent(Activity.java:2410)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1901)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.View.dispatchPointerEvent(View.java:7426)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3220)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3165)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4292)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4271)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4363)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:179)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:171)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl.doConsumeBatchedInput(ViewRootImpl.java:4342)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.ViewRootImpl$ConsumeBatchedInputRunnable.run(ViewRootImpl.java:4382)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.Choreographer.doFrame(Choreographer.java:530)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.os.Handler.handleCallback(Handler.java:725)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.os.Looper.loop(Looper.java:137)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at android.app.ActivityThread.main(ActivityThread.java:5195)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at java.lang.reflect.Method.invokeNative(Native Method)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at java.lang.reflect.Method.invoke(Method.java:511)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
02-09 12:34:32.791: E/AndroidRuntime(12607):    at dalvik.system.NativeStart.main(Native Method)

Comment: may give me your code bro or may see ??
Comment: I'm sorry I don't understand
Comment: SI8 im saying can i see your code?
Answer: Looks like you have so e typos that cause your problem.
Change
if (x>0 || x<bm.getWidth() || y>0 || y<bm.getHeight())

into this
if (x>0 && x<bm.getWidth() && y>0 && y<bm.getHeight())

Maybe that'll fix your issue.
Comment: To add to what you posted, I should encircle the X and Y separately I'm thinking... Will give it a go. Thanks. BTW do you think my condition checking is correct since I'm evaluating before going into the move and down event? Or should I do condition separately inside the move and down event?
Comment: Along with your suggestion, I made some more tweaks and (finger-crossed) it's working as expected!!!!!!!!!!!!!!!!! I AM SOOOO HAPPY!!! lol THANKS!
Comment: @Si8 ... hi, can you share your activity code, I need the same thing and I stucked in same problem as you were, NPE. It will be highly honored.
Comment: @Umair sorry didn't see this. Do you still need activity code?


What encoding does the "exec" function assume?

Question: When you call Python (2.7+) "exec" function, what assumptions, or actions, does it take with regard to decoding the provided string input?
(By way of comparison - if you want a source .py file in your project to contain unicode, you have to embed a "magic sequence" in the top of the file.)
What I've noticed is that exec seems to be okay with finding unicode in the string input, even though I don't try to indicate an encoding anywhere.
For example, I can pass this string through exec:
my_string = "That will cost you ¥ 800.00"

and the resultant my_string variable produced by exec will indeed have the Yen symbol in it. So it appears exec is assuming utf-8?
Michael
Answer: exec parses byte strings the same way as Python reads script files.
For Python 2.1–2.7 (as per PEP 263) that means you get ISO-8859-1 by default but you can change it using a coding-comment:
>>> exec 'print [hex(ord(c)) for c in u"\xC2\xA5"]'
['0xc2', '0xa5']

>>> exec '# coding=iso-8859-1\nprint [hex(ord(c)) for c in u"\xC2\xA5"]'
['0xc2', '0xa5']

>>> exec '# coding=utf-8\nprint [hex(ord(c)) for c in u"\xC2\xA5"]'
['0xa5']

The encoding of the script file that is calling exec doesn't influence the encoding of the code inside the string. (However of course the outer script encoding does determine what bytes are in the string if you're writing non-ASCII characters directly.)
Answer: AFAIK Python does not assume anything, and has not to. If you look at the Python Language Reference v2.6, you read :

The first expression should evaluate to either a string, an open file object, or a code object

what is also on my 2.7.3 manual. And doc for Python 2.7.10 does not explicitely state that anything has changed since 2.4 ...
I did some tests on a 2.7.3, writing non ascii characters in an encoded form to avoid the first interpolation.
If you use a simple string, it is interpreted as is. On a Latin1 system :
>>> exec "x = 'That will cost you \xa5 800.00'"
>>> x
'That will cost you \xa5 800.00'
>>> print x
That will cost you ¥ 800.00

On a CP850 system :
>>> exec "x = 'That will cost you \xbe 800.00'"
>>> x
'That will cost you \xbe 800.00'
>>> print x
That will cost you ¥ 800.00

... and print x is then wrong on both systems because neither of them is utf8 :-(
Things go different if the input string is unicode. In that case you will get an implicit UTF8 transformation : in both systems
>>> print u"That will cost you \u00a5 800.00"
That will cost you ¥ 800.00
>>> exec u"x = 'That will cost you \u00a5 800.00'"
>>> x
'That will cost you \xc2\xa5 800.00'

Of course if everything is unicode, all goes ok again on both systems :
>>> exec u"x = u'That will cost you \u00a5 800.00'"
>>> x
u'That will cost you \xa5 800.00'
>>> print x
That will cost you ¥ 800.00

If anyone here had a 2.7.10 to confirm or infirm that it would really be nice.
Comment: In my case, I'm populating python 2.7 str types from a text file containing utf8 characters, and thus ending up with strings such as: "a = '◀ unicode_test ▶'".   When I exec these, the unicode bytes making up those arrow symbols are "preseved" by exec. I am not prefixing "u" anywhere when reading in the file strings, or before exec'ing them.. I guess what I really want to know is if it's working in my case just because I'm getting lucky (ie default encodings along the way are helping me out) or if my approach is sound..
Answer: From the The Python Language Reference:

The first expression should evaluate to either a Unicode string, a Latin-1 encoded string, an open file object, a code object, or a tuple.

It appears as though the str are encoded based on the native system, although characters less than 127 can be passed of as utf-8 characters; sometimes with funny encoding results.
Comment: The ref you cited that it says it can be a "unicode string"... but it doesn't mention a specific encoding. I guess that means it's not really "decoding" the string per se.. it's probably just retaining whatever bytes it finds in the input string.. whatever encoding those bytes might represent. That's my hypotehsis anyway :)
Comment: In this case, I don't think Python used Unicode, since ¥ is part of Latin-1 as code value 165.
Comment: It took me some time to do tests, but I have to tell you that this answer is wrong at least for Python 2.7.3 . And I confirm that UTF8 or latin1 for  ¥ is `\xa5` or `\u00a5` code 165 or 0xa5.
Comment: Agreed as per the comments, although I haven't edited my question.
Answer: exec assumes utf-8 unicode for str automatically. Once exce'ed string literals (except unicodes) gets encoded as UTF-8.


How to move from Activity to Fragment from onActivityResult

Question: I am new in Fragment  activity and my situation is i have implemented payment gateway and successfully got result on Activity. My confirmation activity is in fragment so when i received result from payment gateway in activity  result in onActivityResult after success or failed condition of PG how to transfer to confirmationFragment
I am using android.app.Fragment;
and my code of PaymentActivity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PayUmoneySdkInitilizer.PAYU_SDK_PAYMENT_REQUEST_CODE) {

        if (resultCode == RESULT_OK) {
            Log.i(TAG, "Success - Payment ID : " + data.getStringExtra(SdkConstants.PAYMENT_ID));
            String paymentId = data.getStringExtra(SdkConstants.PAYMENT_ID);

        } else if (resultCode == RESULT_CANCELED) {
            Log.i(TAG, "failure");
            showDialogMessage("cancelled");
        } else if (resultCode == PayUmoneySdkInitilizer.RESULT_FAILED) {
            Log.i("app_activity", "failure");

            if (data != null) {
                if (data.getStringExtra(SdkConstants.RESULT).equals("cancel")) {

                } else {
                    showDialogMessage("failure");
                }
            }
            //Write your code if there's no result
        } else if (resultCode == PayUmoneySdkInitilizer.RESULT_BACK) {
            Log.i(TAG, "User returned without login");
            showDialogMessage("User returned without login");
        }
    }
}

In this above code i have some condition so according to these condition i have to move fragment.
and i have some confrimationFragments. I hope you understand or give me better way to do
My main Activity code
private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new BuyActivity();

            break;
        case 2:
            fragment = new SaleFragment();
            break;
        case 3:
            fragment = new MoneyFragment();
            break;
        case 4:
            //fragment = new CommunityFragment();
            break;
        case 5:
            //History
            fragment = new HistoryFragment();
            break;
        case 6:
            //about
            fragment = new AboutFragment();
            break;

        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}

thanks
Comment: use appv4.Fragment
Comment: if im using App.v4.Fragment i have to change whole application
Comment: Then use INTERFACE or Event bus
Comment: @Divyesh i have no idea about this
Answer: You must write onActivityResult() in your MainActivity.Java as follows
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
    fragment.onActivityResult(requestCode, resultCode, data);
}
}

after this your onActivityResult in fragment is called.
Comment: Thanks @mehul but getChildFragmentManager() is "Cannot resolve method" coz im using  android.app.Fragment
Comment: Then you have to change android.app.Fragment to app.fragment vs v4.app.fragment. and getChildFragmentManager() to getSupportFragmentManager();


Clearly explaining what the chromatic number of a particular graph is

Question: Given the graph below:
I need to find the chromatic number and explain clearly why this is the case.
I know that the chromatic number has to be at least 3 because the chromatic number of a pentagon-shaped graph is 3 (which in a sense is the "base" of this graph). Simply by trying I can tell that the graph needs to have one more colour, thus the chromatic number is 4.
What I'm stuck on is how do I explain clearly/prove that it is in fact 4. There are so many different ways of colouring it so do I really need to explain all of them? How do I do that in the clearest/most systematic way (if that really is the way to go about this)?
Answer: To prove that the chromatic number is at most $4$, simply exhibit a proper colouring with $4$ colors. I suppose you have already done this.
To prove that the chromatic number is a least $4$ would usually require checking a vast number of cases. This particular graph was cleverly constructed so that a short and simple argument works. Assume for a contradiction that the graph is properly coloured with only $3$ colours. Call the colours red, blue, and green, and assume that the central vertex is green. Thus, there are no green vertices on the inner ring.
For each vertex $v$ on the outer ring there is a vertex $v'$ on the inner ring such that $v$ and $v'$ have the same neighbours on the outer ring. If $v$ is coloured red or blue, leave it alone; but if $v$ is green, recolour $v$ to match the colour of $v'$.
After this recolouring we have a proper colouring of the outer ring with only two colours, red and blue.. This contradicts the fact that $C_5$ has chromatic number $3$.
There is a general construction (due to Jan Mycielski) which takes as input a triangle-free graph of chromatic number $k$ and outputs a triangle-free graph of chromatic number $k+1$. When the input graph is $C_5$, the output is the $11$-point graph in your question.
P.S. Actually, if you take advantage of the rotational symmetry of the graph you asked about, the "brute force" approach is easier than the "clever" argument. Colour the graph from the outside in. To start with, observe that there is only one way to properly colour the $5$-cycle with $3$ colours, up to rotations of the cycle and permutations of the colours. Once the outer ring is coloured, you can quickly see that all $3$ colours must occur on the inner ring, leaving no colour for the central vertex.
P.P.S. The graph in your question is the Grötzsch graph; it is the Mycielskian of $C_5$. The brute force argument works fine for proving that the Grötzsch graph is $4$-chromatic, but you need something like the first argument I gave if you want to prove that the Mycielskian of a $k$-chromatic graph is $(k+1)$-chromatic.
Comment: I didn't understand this part "If v is coloured red or blue, leave it alone; but if v is red, recolour v to match the colour of v′," since red is there twice. Do I recolour it or not? I know that one way I could show that it has to be 4 would be to consider the different blue and red combinations for the middle ring and then just show that for any of them it is impossible to colour the outer ring properly with just red, blue, and green.
Comment: Why do I recolour the green to match the colour of v'? As far as I can see, that automatically makes the colouring "not work". Or am I missing something? What do you mean by "we still have a proper colouring"?
Comment: I must have just done something in a different order than what you were thinking when I drew the diagram, but I do understand that it works for a pair v and v'. It is just a more difficult approach since the approach is to try to do something that cannot be done (colouring with three), whereas the "brute force" method is very clear and is more in line with the way I was originally thinking about this - I just didn't realise that it was so easily generalisable!


Uniform convergence and $L^p$-convergence

Question: Let $f_n,f \in L^p$ and $f_n \to f$ uniformly. Further let $g \in L^q$. Now, clearly $\int (f_n - f) g$ is defined. How do I show that
$$\int |f_n - f||g|$$
can be made arbitrary small if I choose $n$ large enough? If we just naively apply Hölder we will not be able to make it small but just finite. Further, we cannot just replace $|f_n - f|$ by the bound "$\epsilon$" because that is larger than this. Does someone have a hint?
Comment: Try choosing a set $A$ of finite measure for which $\int_{A^c} |g|^q$ is small.
Answer: Outside of a sufficiently large compact set, $\|g\|_q <\epsilon$. Use Hölder naively, and on that portion the integral is bounded above by $(\|f_n\|_p + \|f\|_p)\epsilon$. On the inside of the compact set $\|g\|_1 \leq C \|g\|_q$ where $C$ is given by the volume of the compact set. Then you can replace $|f_n - f|$ by $\epsilon$.
Note that this requires $\|f_n\|_p$ be uniformly bounded, which would be true if you additionally assume $f_n \to f$ in $L^p$. If you don't assume that:
Consider over $\mathbb{R}$, take $f_n = \frac1n \chi_{[2^n,2^{n+1}]}$, where $\chi$ denotes the characteristic function. $f_n \to 0$ uniformly as a sequence of functions (i.e. $f_n\to f$ in $L^\infty$). For this sequence $\|f_n\|_p = \frac1n \cdot 2^{n/p} \nearrow \infty$ (unless $p = \infty$). (Note that since it is not a bounded sequence, you cannot assert that it has a weakly converging subsequence.)
Now take $g$ be the function such that $g(x) = 2^{-n/(q-\delta)}$ if $2^n < |x| \leq 2^{n+1}$. By construction it is a function in $L^q$.
But $|f_n - f| |g| = \frac1n \cdot 2^{-n / (q - \delta)} \chi_{[2^n,2^{n+1}]}$. If you integrate it, you get
$$ \frac1n \cdot 2^{n( 1 - \frac{1}{q - \delta}) }$$
So unless $q = 1$ and $p = \infty$, you can always choose $\delta$ sufficiently small such that the exponent in the integrated expression is positive, and provide a counterexample to what you want proved. (And of course, in the case where $p = \infty$, you can just replace $|f-f_n|$ by $\epsilon$ and be done with it.
Comment: Hum, that's a good question. It has to do with the interplay between compactness of the domain and the compactness inside the function space. See, if instead of $\mathbb{R}^d$, you worked on a space with finite total measure, then uniform convergence in $L^\infty$ will imply boundedness in $L^p$ also. This means that any possible modes of failure **must** take advantage of the fact that the support of $f_n$ can run off to infinity.
Comment: Thanks. I got the case where the $f_n$ are uniformly bounded in $L^p$ but not where this is not true. Is it possible to give an intuitive meaning why it should be false for the $f_n$ not uniformly bounded in $L^p$?
Comment: Now, if $f_n$ are uniformly bounded, and their supports run off to infinity, then they converge weakly to zero, which means that what you want is also true. So necessarily a counterexample will require $f_n$ to be unbounded. As to an intuitive meaning: I guess one way to think about it is that while on sets of finite measure, the topology given by $L^p$ is finer than that of $L^q$ if $p > q$, on sets of infinite measure, it is possible that the topology given by $L^p$ and $L^q$ be not comparable for $p\neq q$.
Comment: (Sorry for the poor explanation. The extent to which this is intuitive to me is just that there are certain lack of inclusions between Lebesgue spaces on non-compact domains, and a bit of concentration compactness for sequences in Lebesgue spaces. Which is to say, not very intuitive at all.)


rdiff-backup -r is not working with QT

Question: I am using rdiff-backup to get previous version of the files from server with this command:
rdiff-backup --no-hard-links --force  -r "DATE" "USERNAME@IP::SERVER PATH" "CLIENT PATH"

I can do this with command prompt  manually easily , but when i run this command via Qt i cannot get anything back . I can execute the command via QT locally.I mean there is no any problem with calling cmd and running command on it. Also i do not have enter password etc. to have an server access, but  When i want to execute the command with server via QT, i do not get anything.
rdiff-backup -l USERNAME@IP::SERVER PATH

For example i can execute this command with my application by calling cmd. But it does not work with  " --restore" command. Am i doing something wrong ?
Sorry if i did any mistake with my asking. Thank you in advance.
Comment: Qt is a graphics toolkit. What are you talking about?
Answer: The mistake i made here is sending path names with double quotations. If i send them without any quotation, then it works perfectly. When i write commands in command prompts with double quotation it works, but when i said command with QT then it does not work, but both do the same thing. So be sure that you do not include double quotation while sendind a command.

rdiff-backup -r is not working with QT


Compiling a gstreamer app using cmake on Windows

Question: I am trying to use the gstreamer library under windows, using cmake.
Here is my simple test code:
#include <gst/gst.h>

int main (void)
{
    gst_init (NULL, NULL);
    return 0;
}

I got the lib ("gstreamer-1.0-devel-x86-1.6.1.msi") from here: http://gstreamer.freedesktop.org/data/pkg/windows/1.6.1/
and try to compile the program with the following CMakeList.txt:
cmake_minimum_required(VERSION 2.8.12)

project(test_g)

SET(CMAKE_CXX_WARNING_LEVEL 4)
if (MSVC)
        add_definitions("/W4")
else()
        add_definitions("-Wall -Wextra")
endif ()

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

file(
        GLOB_RECURSE
        source_files
        ./*
)

file(
        GLOB_RECURSE
        gst_files
        ${CMAKE_CURRENT_SOURCE_DIR}/deps/lib/*.a
        ${CMAKE_CURRENT_SOURCE_DIR}/deps/lib/*.lib
)

add_executable(
        test_g
        ${source_files}
)

  set(GSTREAMER_INCLUDE_DIRS "./deps/include/gstreamer-1.0" "./deps/include/glib-2.0" "./deps/lib/glib-2.0/include" "./deps/lib/gstreamer-1.0/include")
  if (WIN32)
   set(GSTREAMER_LIBRARIES ${gst_files})
  else()
    message(FATAL_ERROR "Gstreamer not found")
  endif()

include_directories(${GSTREAMER_INCLUDE_DIRS})
target_link_libraries (test_g ${GSTREAMER_LIBRARIES})

I would like to avoid using pkgconfig because my goal is to make it easy to compile.
Unfortunately, this does not work:
[ 33%] Linking CXX executable test_g.exe

C:/Users/toto/Documents/GitHub/test_gst/deps/lib/libgstreamer-1.0.a(libgstreamer_1.0_la-gst.o): In function `init_post':
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gst.c:719: undefined reference to `_imp__glib_micro_version'
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gst.c:719: undefined reference to `_imp__glib_minor_version'
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gst.c:719: undefined reference to `_imp__glib_major_version'
C:/Users/toto/Documents/GitHub/test_gst/deps/lib/libgstreamer-1.0.a(libgstreamer_1.0_la-gstinfo.o): In function `parse_debug_level':
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gstinfo.c:1771: undefined reference to `_imp__g_ascii_table'
C:/Users/toto/Documents/GitHub/test_gst/deps/lib/libgstreamer-1.0.a(libgstreamer_1.0_la-gstinfo.o): In function `gst_path_basename':
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gstinfo.c:467: undefined reference to `_imp__g_ascii_table'
C:/Users/toto/Documents/GitHub/test_gst/deps/lib/libgstreamer-1.0.a(libgstreamer_1.0_la-gstinfo.o): In function `gst_info_dump_mem_line':
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gstinfo.c:1931: undefined reference to `_imp__g_ascii_table'
C:/Users/toto/Documents/GitHub/test_gst/deps/lib/libgstreamer-1.0.a(libgstreamer_1.0_la-gststructure.o): In function `gst_structure_parse_simple_string':
C:\MinGW\msys\1.0\home\Jan\cerbero\sources\windows_x86\gstreamer-1.0-1.6\gst/gststructure.c:2221: undefined reference to `_imp__g_ascii_table'
C:/Users/toto/Documents/GitHub/test_gst/deps/lib/libgstreamer-1.0.a(libgstreamer_1.0_la-gststructure.o): In function `gst_structure_validate_name':
... Many other errors ...

My questions are the following:

Should I use both .lib and .a files?
Why it does not compile? The file libglib-2.0.dll.a is in the lib directory, so I am not sure to understand what the issue is during the linkage...

Thanks!
Comment: Where is your call to `FindGStreamer.cmake`? With other words: Don't set GSTREAMER_INCLUDE_DIRS and GSTREAMER_LIBRARIES by hand, use CMake!
Comment: I know FindGstreamer would be better, but the thing is that there is no one supporting Windows, so I need to find the solution by myself :)
Answer: Ok, I found what the problem is.
I only need to take *dll.a files, so the code is now:
file(
        GLOB_RECURSE
        gst_files
        ${CMAKE_CURRENT_SOURCE_DIR}/deps/lib/*dll.a
)

I suppose we can do it in a proper way, so if someone has a better idea, I would be interested.


Expected Value of Poisson

Question: This is assignment question so I don't need an answer but just a hint. How do you find out expected number of certain values that are less than or greater than certain number. We've only covered E(X) = lambda formula. We haven't covered anything like E(X<#) or E(X>#). Is there such formula?
Comment: If you mean something like $E(X<6)$, then I wonder if you mean $P(X<6)$, and if not, then I don't know what you have in mind.
Comment: The question asked for "the expected number of values which are < 18." All I know is how to find expected value of distribution that doesn't have constraint like this one.
Comment: If you observe the value of a Poisson-distibuted random variable, you observe _one_ value.  So my guess is you mean you have an i.i.d. sequence of Poisson-distibuted random variables, rather than just one.
Comment: The mean is given(17) and there are 300,000 values and the question ask to find "expected # of values among 300,000 which are < 18"
Answer: OK, I'm going to go with the guess I made in the comments.  Suppose $X_1,X_2,X_3,\ldots,X_n$ are independent random variables, each with a Poisson distribution with expected value $\lambda$, and what you want is the expected number of these that are less than some particular number $x_0$.  Then you have $p=P(X_1 < x_0) = \sum\limits_{0\le x<x_0} P(X=x)$.  That's the probability of "success" on one trial.  So you want the expected number of successes in $n$ trials, with probability $p$ of success on each trial.  That's just $np$.  The number of successes in $n$ independent trials with probability $p$ of success on each trial is a random variable with a binomial distribution, so the expected value of such a random variable is what you're looking for.
Comment: Sorry for late reply. Thanks that what I was looking for.

Expected Value of Poisson


Prove or disprove $\lim_{n\to\infty} b_n = 0$

Question: Problem :
Let $a_n$ is positive sequence satisfies  $\sum a_n < \infty$
Define $$b_n=\sum_{k=1}^\infty a_{kn}$$
Then $\lim_{n\to\infty}b_n = 0$?

I think an answer is 'Yes' but I can't construct details.
This is my attempt :
Since $\sum a_n < \infty, \lim_{} a_n = 0$.
And, when $n$ goes large, sum has fewer terms, so $b_n$ is positive decreasing sequence so it converges definitely, but I can't sure it converges to $0$.
Answer: Hint: Given $a_n \ge 0$ for all $n$, you can show that
$$b_n \le \sum_{k=n}^\infty a_k = \left|\sum_{k=1}^\infty a_k - \sum_{k=1}^{n-1} a_k\right|.$$


O que é a Máquina de Turing?

Question: O que é essa tal Máquina de Turing que o fez o Turing ser reconhecido como o "Pai da Computação"? Como é o seu funcionamento e como ela faz pra ler uma fita de binários?
Comment: Acredito que o termo seja usado muito como licença poética. É complicado fazer tal afirmação quando na verdade várias pessoas contribuíram muito para a base da computação moderna, uma sem a outra não serviria para nada do que temos hoje.
Comment: Será que é duplicata dessa? (que consideraram duplicata e eu achei que não é, mas não vou mexer por conta própria) http://pt.stackoverflow.com/q/102452/101. Relacionadas ou pelo menos que fazem citações práticas: http://pt.stackoverflow.com/q/101683/101, http://pt.stackoverflow.com/q/35547/101, http://pt.stackoverflow.com/q/99642/101, http://pt.stackoverflow.com/q/46983/101, http://pt.stackoverflow.com/q/7740/101, http://pt.stackoverflow.com/q/81854/101, http://pt.stackoverflow.com/q/113985/101, http://pt.stackoverflow.com/q/28297/101, http://pt.stackoverflow.com/q/30749/101, entre outras
Comment: A pergunta é boa, mas acho ser duplicata sim :P
Comment: @bigown acho que essa sua resposta http://pt.stackoverflow.com/a/35548/14262 já responde essa pergunta
Comment: Onde ele é conhecido como o pai da computação ?
Comment: https://www.google.com.br/search?q=pai+da+computacao&oq=pai+da+computacao&aqs=chrome..69i57.2527j0j7&sourceid=chrome&ie=UTF-8

Mas acredito que o termo mais correto seria, pai da criptografia moderna :)
Comment: Talvez o que salve a pergunta seja "Como é o seu funcionamento e como ela faz pra ler uma fita de binários?"
Comment: @MarceloBonifazio não sei, vamos ver o que outras pessoas acham, pode ser que possa sair algo mais específico. Talvez a segunda parte caiba sozinha.
Comment: Concordo que a pergunta é boa (a parte funcional)... E levando em consideração a colocação do @bigown, fico confortável com o termo "um dos Pais"...
Comment: So lembrando que a maquina de turing corroborou para a [criação de uma das áreas mais importantes e complexas da computação](http://www.ufrgs.br/alanturingbrasil2012/Maquina_de_Turing.pdf) (autômatos), dai para o porque ele é considerado "um dos" pais da computação moderna, não da pra atribuir todo o estado da arte como sendo obra somente dele, tivemos outras grandes mentes na evolução da computação, vide George Boole, Von_Neumann, entre outros
Comment: @bigown eu acho que o mais próximo que essas respostas devem estar é uma que diz que a linguagem tem que obedecer uma maquina de turing, mas o que é e como ela funciona eu não acho que essas perguntas respondem. MarceloBonifazio, eu penso que pai remete à ideia de ser um só... mas concordo que podem haver controvérsias à esse título e que ele seja polêmico
Comment: Para quem gosta de assistir Faustão no Domingo, fica a dica : https://www.youtube.com/watch?v=eqzuLlY6cJA
Comment: http://morphett.info/turing/turing.html
Comment: @guijob a resposta aceita foi apagada porque é plágio. Se tiver interesse, agora tem outra resposta se quiser aceitá-la.
Answer: Segundo a Wikipedia a Máquina de Turing é um modelo matemático de computação que descreve uma máquina abstrata que manipula símbolos em uma fita de acordo com uma tabela de regras. Apesar da simplicidade do modelo, ele é capaz de implementar qualquer algoritmo de computador.
Em termos bem leigos é a forma como uma pessoa resolve um problema matemático.
Note que não o termo não se refere a uma máquina real, embora possamos construir uma máquina que atende o modelo que ela define. Ou quase, já que ela prega memória infinita, o que não é possível no mundo real.
Em 1936 o termo algoritmo foi formalizado como sendo um conjunto finito de instruções simples e precisas, que são descritas com um número finito de símbolos.
Qualquer dispositivo, seja hardware ou software, que se conforme com o modelo definido pelo Alan Turing, seu criador, pode ser considerado um dispositivo Turing Complete, portanto ele atende aos critérios da Máquina de Turing. A ideia do algoritmo iniciou-se a partir daí através da proposição de Alonzo Church:

Qualquer processo aceito por nós homens como um algoritmo é precisamente o que uma máquina de Turing pode fazer

Estritamente falando nada real pode ser Turing Complete, então a infinitude costuma ser desconsiderada.
De fato, algumas máquinas foram produzidas para demonstrar o conceito.

Seguindo a Wikipedia, a máquina opera em uma fita de memória infinita dividida em células discretas, cada uma das quais pode conter um único símbolo extraído de um conjunto finito de símbolos chamado alfabeto da máquina. Possui uma "cabeça" que, em qualquer ponto da operação da máquina, é posicionada sobre uma dessas células, e um "estado" selecionado a partir de um conjunto finito de estados. A cada passo de sua operação, a cabeça lê o símbolo em sua célula. Então, com base no símbolo e no estado atual da própria máquina, a máquina escreve um símbolo na mesma célula e move a cabeça um passo para a esquerda ou para a direita, ou interrompe a computação. A escolha de qual símbolo de substituição escrever e qual direção mover é baseada em uma tabela finita que especifica o que fazer para cada combinação do estado atual e o símbolo que é lido.
Se desejar pode experimentar a máquina virtualmente.
O modelo foi importante para que o Turing tivesse um parâmetro do que faria para atingir os objetivos da criação de um computador, como é o computador moderno que usamos hoje.
Dispositivos de software podem se conformar com a Máquina de Turing também. E de fato a definição do que é uma linguagem de programação passou adotar essa capacidade, já que a Máquina de Turing é capaz de executar computações arbitrárias, exatamente o que se espera de uma linguagem de programação, que vai além do que outras linguagens mais simples podem oferecer. Alguns testes podem ser feitos para determinar isso. Exemplo de linguagem que não passa no teste, sendo que universalmente temos o Teste de Turing. E um que passa. A linguagem pode ser fora do comum ou ser inútil na prática. Pode-se ver mais sobre o assunto. Também.
Existem variantes da máquina para atender cenários específicos, e justamente uma variante que aceita a finitude é usada na maioria dos casos. É possível ter máquinas determinísticas e não determinísticas, ter mais de uma fita, etc.
Daí surgiu a Teoria dos Autômatos e o Problema da Condição de Parada.

Ainda que existam pessoas que dizem que não é a completeza de Turing que define o que é uma linguagem de programação, há muito material e apoio dessa ideia, e nenhuma ideia superior claramente é apresentada para dar uma definição melhor.
Como não é fácil fazer uma demonstração do funcionamento da MT e para não incorrer em plágio, como a outra resposta existente (quem sabe não mais quando ler isso), vou deixar alguns links que pode ajudar:

http://wiki.icmc.usp.br/images/6/61/MT1_2011.pdf
https://epxx.co/artigos/touring.html
https://webpages.ciencias.ulisboa.pt/~ommartins/seminario/vonnewman/NetMenu/maquina_de_turing.htm
http://www.decom.ufop.br/anderson/2_2011/BCC244/MaquinasDeTuring.pdf

O que é a Máquina de Turing?


perl regex match with numbers

Question: I am trying to match the following (the below is in an array called @abc):
goo foo tool: 1.2.1 (a3 change: 234342 @ 2014/02/19 14:20:27)

with
my $match = "goo foo tool: (\d+)\.(\d+)\.(\d+) \(a3 change: \d+ @ #DATE# #TIME#\)";

and in my code,
 78     foreach (@abc){
 79         print "$_\n";
 80         if ($_ =~ m/$match/){
 81             print "$1\n";
 82         } else {
 83             print "not matched\n";
 84         }
 85     }

I am not seeing why it is printing "not matched\n";
anyone else sees why?
Comment: Because #DATE# and #TIME# are string constants.
Comment: It is not necessary to specify `$_` when you are using `m//` or `s///`.  They default to operating against `$_`.  That's why `$_` exists.
Answer: The #DATE# and #TIME# string constants aren't goingt to match the dates you have.  Simply adjust to regex to actually match those values:
my $match = "goo foo tool: (\d+)\.(\d+)\.(\d+) \(a3 change: \d+ \@ \d+/\d+/\d+ \d+:\d+:\d+\)";

Comment: The `@` is okay only because it is followed by whitespace. If it was anything else then Perl would try to interpolate the array of that name into the string. It is safer to escape `@` in every case: `\@`.
Comment: @Borodin Agreed, that is a good practice and was one of the first thoughts I had as well when reviewing his question.  I've edited the answer to reflect that.

perl regex match with numbers


Problema no código do meu buscador

Question: Como não consigo usar o searchview decidi usar um edittext e uma logica q achei em um forum, mas passo por dificuldades tem alguma ideia?

MainActivity.class
public void CarregarEncontrados()
{

   int textlength = et.getText().length();

   //Limpa o array com os estados encontrados
   //para poder efetuar nova busca
   lstEstados_Encontrados.clear();

   for (int i = 0; i < item.size(); i++)
   {
       if (textlength <= item.get(i).getResId())
       {
           //Verifica se existe algum item no array original
           //caso encontre é adicionado no array de encontrados
           if(et.getText().toString().equalsIgnoreCase((String)item[i].subSequence(0, textlength)))
           {
               lstEstados_Encontrados.add(item.get(i));
           }
       }
   }
}

Answer: O que eu entendi da sua pergunta é que você está com problema na linha 129 da imagem.
Se realmente for isso, acredito que o problema seja que você tenta acessar um elemento da ArrayList com [], porém o correto é com o get(int index), ou seja, similar ao que você faz na linha 125.
Answer: Tente substituir por este código:
Exemplo
public void CarregarEncontrados()
{

   int textlength = et.getText().length();

   //Limpa o array com os estados encontrados
   //para poder efetuar nova busca
   lstEstados_Encontrados.clear();

   for (int i = 0; i < item.size(); i++)
   {
       if (textlength <= item.get(i).getResId())
       {
           //Verifica se existe algum item no array original
           //caso encontre é adicionado no array de encontrados
           if(et.getText().toString().equalsIgnoreCase(item.get(i).subSequence(0, textlength)))
           {
               lstEstados_Encontrados.add(item.get(i));
           }
       }
   }
}

Problema no código do meu buscador


Existence of positive real number whose square is $a$?

Question: My book proves the existence of a positive real number whose square is $a$, where $a>0$.
Proof: Let $S=\{x\in\mathbb{R}^+|x^2 \le a\}$. Now the completeness property of $\mathbb{R}$ implies that supremum of $S$ exists. So let $u=\text{sup}(S)$. Note that $u>0$.
To prove the existence, we need to show that $u^2=a$. We also need to show that set $S$ is bounded above. Now we know by completeness property of $R$ that set $S$ is bounded above so we let u=$sup(S)$. I wanted to know why $u^2 = a $ proves the existence of such positive numbers. Now after reading comments and answers I reached to a conclusion i.e if $u^2$ is not equal to a or if $u$ is not equal to $ \sqrt{a }$, the it contradicts our assumption that supremum of set $S$ exists in $R^+$ .
Now my other doubt is the way we choose the set $S$ itself assumed that such number exists and its belongs to set $S$. So I want to know is this a valid way to prove ? Because we already assumed the existence such number. I think the if we choose set $S=\{x\in\mathbb{R}^+|x^2 < a\}$ then proof is valid.
Comment: the stated proof is wrong, as you need to show that $S$ is not empty and bounded to say that it have a supremum
Comment: If $u$ exists and is a positive real number and its square is $a$ then what does that say about the existence of a positive real number whose square is $a$? In what other way can you parse the statement that is to be proved? (The flaws in how we got to that step of the proof are another matter.)
Comment: You also want $S=\{x\in\mathbb{R}^+\mid x^20$ there is a $u>0$ with $u^2=a$ then that says there is a positive real number whose square is $a$, namely $u$
Comment: Yes Arthur its my mistake now I have edited my question.
Comment: You don't understand how $u^2=a$ proves there exists a number whose square is $a$? Is it the "positive" part that gives you trouble?
Comment: My trouble is what is the relation between existence of positive number whose square is a and the supremum of the set S? In other words why we need supremum of set S to prove the existence of the number ? I am missing here something . I am unable to connect supremum and existence of number
Comment: You might wish to reword your final sentence. From your latest comment, it seems that you *do* understand that **once it is proved that** $u>0$ and $u^2=a$, "the existence of a positive number whose square is $a$" immediately follows. So your question, it seems, is **how to prove that** $u>0$ and $u^2=a$.
Comment: " why we need supremum of set S to prove the existence of the number ? I am missing here something "  Well, that's because the proof hasn't been done yet.   We have the set $S$.  And the book is claiming that $u =\sup S$ exists.  Now the task we have to prove (but which *hasn't* been proven yet) is that $u^2 =a$.  So far there is nothing in the definition of $S$ and $u=\sup S$ that indicates that $u^2=a$. But ***WHEN*** we prove that we will be done.  We will have found that $\sup S$ was just the number we need.
Comment: Ah... I see your problem "To prove the existence, we need to show that $u^2=a$".  No.  You don't need to $u^2=a$ in order to prove $u$ exists.  We *know* $u = \sup S$ exists by completeness theorem.  But we don't (yet) know what $u^2$ is equal to.  Once we show that $u^2$ does indeed equal $a$ *then* we will have shown that a real number whose square is $a$ does exist .... because $u$ is just such a number.
Comment: Maybe you should think of it this way.  A professor asks "does there exist a real number whose square is $a$".  I answer. "I don't know. I'm going to do something else. Let's take a walk in a park.  By the way I like this set $S$.  And $u =\sup S$ exists.  I wonder what $u^2$ is equal to.... Hmm, doing stuff, I see that $u^2 = a$.  Hmm, I guess $u$ is a number whose square is $a$... That means there is such a number because $u$ is just such a number.  I'm done with your proof".
Comment: May I ask why this question is getting downvoted?
Answer: Maybe it would be conceptually easier of you take a special case, like $a = 2$.
$u = \sup S$ is the smallest upper bound of $S$.
Then I think it's fairly clear that
$$ u^2 < 2$$
is impossible, as $u$ wouldn't be an upper bound, and
$$ u^2 > 2$$
is impossible, as $u$, in that case, would be an upper bound, but not the smallest such.
Only one option remains.
Answer: Answering to the questions you posted in the comments and the post. You need to understand what motivates the set $S$ and then you will understand your other question on the comments on why do we need the $\sup S$.
The proof relies on the fact that you can't just take $\sqrt{a}$ because you don't know its existence, so you phrase the question on terms of things you know exist but are related to the problem you have. You need to fabricate that number $u$ and the completeness property gives you an object which exists. So instead of asking which is the square root of a you ask for those numbers whose squares are less than $a$. Why? because you can always square things, and you "know" from working with these things that if any number will satisfy the condition of $u^2=a$ then it must be the supremum of those numbers, as squaring is an increasing function. Besides, if any number surpasses $a$ when squaring, you know that number is not going to be on the set $S$ nor any of those greater than it.
That is the reason you take the set $S$ and why you choose the supremum (you must prove it is non-empty and bounded for the supremum to actually exist, which is not hard to prove). Now with regards to actually proving that idea you had works, you use the continuity of squaring to prove that $u=\sup S$ must fulfill with $u^2=a$. If it were $u^2< a$ or $u^2>a$ then there is space for you to disprove this is actually a supremum (I know this last comment might be a little vague, but it is for you to think about it and ultimately ask in the comments)


My Linq to SQL query paging logic is not executing in the database

Question: How can I make my Linq to SQL query logic execute on the server?
I have a created a Linq query and returned it as an IEnumerable. Subsequent operations on the query such as .Count() or .Take(5) are evaluated on the client in CLR, rather than on the server.
Answer: Converting to IEnumerable will cause the query to be executed - as a result the data is now on the client side.
If you want to execute paging on the server side, you should perform those operations while it is still a late executing IQueryable.
Answer: IEnumerable was the problem. Returning the Linq.DataQuery as an IQueryable allows Linq to SQL to add additional operations to the query. Figured this out as I was describing the problem.
Comment: You should add this as a comment to the question and not as as an answer. Beside, it would be nice if you accepted David answer
Comment: Sorry. I'm new here. In fact, I joined just to solve this problem. I would accept David's answer if I could see how.
Comment: OK, figured that out with the checkbox. The answering my own question was a little silly, but I was stuck on this for an hour until I actually wrote down the word "IEnumerable" in the post and went and chased after that.


How does the variance measure the information about the data?

Question: Variance measures the amount of information in the data set. How?
Mathematically, the variance is the measure of the variability in the data. So, how this can be explained as a measure of the amount of information in the data? Could you please explain this with a simple example?
I read the following post, here, which makes me confused about, how the variance measures the information about the data? I thought it is just a measure of how the point is far away from the mean.
Answer:
Variance measures the amount of information in the data set. How?

Information is a slippery concept, so it pays to be a little concrete. So specialize to the case of a regression model. You have some variables $x_1, x_2, \dotsc, x_p$, say, which you wants to use to predict or explain $Y$. Lets say now that all the observations of $x_1$ are equal, so its variance is zero. This variable will not be useful for explaining $Y$. If you want to study, say, the relationship between education level and income, but your sample only includes college graduates without any post-graduate education, how useful will that be?  It is in this sense that variance can be a measure of information in the data.
But this will only make sense in relationship to some given model. "Information" in the abstract, without any qualification, does not make sense.  To see that more clearly, another example: let's say your observations are repeated measurements of the same specimen, length, weight, whatever. The ideal case is that all are equal — no measurement error. Variance in this case represents measurement error, and higher variance corresponds to less information!
Answer: This is not about variance but rather about PCA and principal components. PCA searches for orthogonal principal components (a linear combination of variables) which maximize explained variability (or equivalently minimize the squared distance from the points to the line; think of it as $R^2$ - the higher it is the more variability we explained, which means the points are closer to the fitted line).
When we do this we say that the first PC explains most of the data, i.e. it explains most of the variability, i.e. it contains most of the information about the data, because it's what we can explain best, given our data. However, this does not necessarily mean that this information is of any value to us, the model may be learning associations which are perfectly clear to us or which are not of interest.
In conclusion, this is not about variance, but rather about "explained variance", which is distributed among the PC's and which is interpreted (by some people) as "how much information this particular PC holds given all the rest".
Answer: One way to think about the amount of information in a dataset is to see how spread out the data points are.
For example, if you had a dataset of five identical body weights x = [120, 120, 120, 120, 120], there is very little information here as there is no spread or variability at all - knowing the weight of one person tells us the weight of the others.
Now, the variance tells us how spread out the data are, by taking the average squared deviations from the mean. So the more spread out our data are, the larger the variance. In x above, the variance is 0, which is consistent with the observation that there is very little information in x.
Edit
This is an oversimplified and misleading explanation - please refer to kjetil b halvorsen's answer above for a more nuanced and correct explanation.
Comment: The mean, median and other similar single-number summaries of your dataset would give you an idea of what the _typical_ individual or observation looks like rather than focusing on how spread out the data are. You might use different measures to summarize the data you've got in a meaningful manner, depending on the shape and distribution of the data at hand. In the data above, you'll notice that the mean = median = mode = 5, which is another hint that there isn't much information in the data as different measures of the _typical_ weight all yield the same result.
Comment: kjetil b halvorsen's answer provides a nice counterexample.
Comment: Thanks. But why the variance? Why not median, mean, or other quantities? Is that because variance is commonly used in finance? So, it is important for financial maker-decision.
Comment: Completely agree, thank you Richard - another reminder of the dangers of providing oversimplified examples.
Answer: Say you have a dataset about persons with two features: weight and number of eyes. Which of these two features do you think is more informative for describing persons, i.e. given a data point, which feature makes it easier for you to identify the person it represents?
Here, given enough data, weight will have a much greater variance than number of eyes, whose variance will be close to zero. Therefore, we can conclude that weight is more informative than number of eyes.
Answer: Others already answered conveying perfectly some concepts but the major misunderstatement remains to be clarified: variance IS NOT information, is not even vaguely linked to information. In some application as PCA it is a parameter that allows you to evaluate how much information you can extract from your data with that specific tool, but this is not a measure of information of the data at all. I will not go into mathematical explanation because it is probably better to give basic ideas first (and there are very good formal explanation out there): information is the reduction of uncertainty, lack of variance in data does not correlate in any way with the information, it just means that the phenomenon is steady and this is a big amount of information because it reduces the a priori uncertainty about that phenomenon. The key concept is that information depends on the relation between the observer and the data, not on the data itself: if you think to source coding (data compression as an example) small variance means that you can use less symbols to encode the data and so it means less information, but if you think to channel coding (a repetition code for example) in a large set of "1" there could be no "useless" symbol because every symbol carries part of the original information, there are codes way better than the repetion code to increase the amount of information carried by each symbol, still it is the proof that having n+1 equal values conveys more information than n equal values and so even with 0 variance the information increases. Example: you receive a boolean information on a noisy channel with 0.5 cross-channel probability, if you receive "1" you have exactly 0 bit of information because there is no way to know if the sended bit was 0 or 1, if the sender repeats his message 3 times and you receive "111" you know that the probability that the message was 1 is 0.875 and with 0 variance you have a lot of information, passing from no information at all (1) to very good confidence (111).
Comment: Re "not even vaguely linked to information." That begs some definition of "information," because the *Fisher Information Matrix* is intimately related to variances of maximum likelihood estimates.  The issue here is that "information" is a heavily overloaded term that has distinct meanings in statistics, engineering, physics, linguistics, philosophy, and even colloquially.
Comment: Since variance is often characterized as being a part of uncertainty, even such a vague characterization as "reduction of uncertainty" does not rule out the role of variance in understanding information.  Your post reads like you have adopted an unnecessarily limited concept of variance (as being purely a descriptive statistic of a stream of bits) and of how it might be used to understand uncertainty and information.  The statistical concept of *sampling variance* would be a more relevant one to discuss.
Comment: Readers will appreciate seeing that instead of discussing the question you have resorted to an *ad hominem* attack (based on no evidence or information) and (unverifiable) claims about university degrees.  Neither approach carries any weight here on CV.  Please see our [help] for our expectations about behavior on this site.
Comment: I already gave the definition used in scientific fields (don't know about humanities), that is, by the book, "reduction of uncertainty". Variance and information are two complitely different concepts as are sound and FT, FT is not a sound, it is just one of the many quantitative tools you can use to study a restricted subset of features of a sound. I think the original misunderstanding arose from this: someone said var=info instead of "I treat only the part of information linked to the number of different symbols and their occurrences without regarding their position measured by var"
Comment: Please, I know I can not prove it but I also know I am a PhD in EE and I teach courses of Information Theory at University, so believe me, even if you do not still comprehend the concept, this is not "my definition", nor it is vague, this is the only scientific accepted definition of information. I understand that you lack the basics, unfortunately it is difficult to explain everything from 0 in a comment, I recommend the classic book https://books.google.com/books?id=eKvhiI2ogwEC&printsec=frontcover&dq=Information+theory&hl=it&sa=X&ved=2ahUKEwi_goX00en4AhUni_0HHXSsBrgQ6AF6BAgEEAM
Comment: Nice, 3 comments saying I gave "my definition" as I was not believable enough and refusing to do basic check (even Wikipedia reports the same definition) but this is not ad hominem attack. Btw you were searching for authority fallacy, speaking of which I gave the right definition, explanations and examples but you did not accepted the logic or reasoning, you wanted a book...Good luck!


Trending time-series and structural breaks

Question: I am looking to find structural breaks in a time series, using the strucchange breakpoints function in R. I wonder whether I need to detrend my data beforehand. Detrending might explain away valid structural breaks. There is a well-fitting quadratic trend, but I suspect that there are underlying reasons for this quadratic relationship that can. What would be the standard way to approach this?
Answer: Since no answer is given yet, let me take a stab with some quick biased thoughts plus demonstration. Foremost, I don't think  there are such things as standard practice for your question; rather it depends all  on the nature of the problems at hand as well as the domain knowledge.
Mathematically or statistically speaking, detrending a time series may or may not affect the detection of structural breaks, depending on what structural breaks are defined with respect to. For example, if there is a change in the mean somewhere in the time series, removing the linear trend will not affect the detection. Also, if the time series is just a quadratic trend curve, there is no "structural break" at all if the base model is a quadratic model, but there will be some "structural breaks" if the base model is a linear model.  In other words, there are two moving pieces here: (1) what forms of the trend is being removed (e.g., linear, quadratic, or other forms), and (2) what base model is used to fit the time series (e.g., piecewise linear, piecewise quadratic, or other forms)?
With that said, here is a demonstration on a simulated quadratic time series curve using a Bayesian changepoint detection package Rbeast my group developed (https://github.com/zhaokg/Rbeast):
set.seed(123)
y = 0.05*(-14:15)^2 + rnorm(30,1) # an artificial time series
plot(y)

Try to detect any "breaks" in the quadratic data using a pricewise linear model:
library(Rbeast)

o = beast(y, season='none')
o = beast(y, season='none', torder.minmax=c(0, 1) )

# the two lines above are equivalent: the order of piecewise models are limited
# to 0 (flat line) and 1 (linear model).
plot(o)

Not surpassingly,  there are some breakpoints if a piecewise linear model is used. In the figure below, the Pr(tcp) subplot shows the changepoint occurrence probability over time, with the peaks indicating the most likely breakpoints. In this case, there are two breakpoints needed to fit the quadratic curve well.

Instead, for the same data, if fitting with a piecewise quadratic model by specifying torder.minmax=c(0,2) where 2 means the 2nd order model.
# Fit a piecewise quadratic model
o = beast(y, season='none', torder.minmax=c(0, 2) )
plot(o)

For the same time series, no breakpoint is detected (i.e., the flat changepoint probability occurrence curve close to zero) if the quadratic model is used as the base model to define structural beaks, as shown below.

As a further demonstration, we first remove the linear trend before detecting the breaks by setting detrend=TRUE, again using the piecewise linear model to define structural breaks,
o=beast(y, season='none', torder.minmax = c(0,1), dtrend=TRUE)
plot(o)

We got the same result as in the first figure. Removing a linear trend from the data will not affect the detection based on a piecewise linear model.


4th order differential equation from Euler-Lagrange

Question: I am trying to extremise the functional $\int{[y + \frac{1}{2}y^2 - \frac{1}{2}(y^{''})^2]}dy$ and so from Euler-Lagrange I get the differential equation
$1 + y + y^{(4)} = 0$ and I have no idea how to solve it. It's supposed to be an easy question so there must be a trick.
I have the initial conditions $y(0) = -1, y'(0) = 0, y(\pi) = \cosh(\pi), y'(\pi) = \sinh(\pi)$.
Just to check, I'm using the E-L equation, $\frac{\partial f}{\partial y} - \frac{d}{dx} \frac{\partial f}{\partial y'} + \frac{d^2}{dx^2} \frac{\partial f}{\partial y^{''}} = 0$
Can someone help?
Thanks
Comment: Your functional has no explicit $x$-dependence, so were it not for the $y''$-dependence you could simply appeal to the Beltrami identity ([Wikipedia](https://en.wikipedia.org/wiki/Beltrami_identity)). That obviously won't work directly here, but the derivation of said identity in the Wikipeda link can perhaps be adapted to the case at hand.
Comment: You got a sign wrong, it seems. The E-L equation becomes $1+y-y^{(4)}=0$ instead.
Comment: Just in case you are interested, your equation is related to Bernoulli-Euler beam equation, which is a classical way to describe the bending of beams at small frequencies.
Comment: I was too lazy to figure out whether or not my comment above was actually valid, so I posted a question re: generalizing the Beltrami identity [here](http://math.stackexchange.com/q/1773305/137524).
Comment: Thanks, it's nice to have some background. This is a past exam question for my course, so I don't get any context for it
Answer: I think your equation should be $1+y-y^{(4)}=0$, but in any case it's a linear differential equation with constant coefficients, so you get the particular solution $y_p(x)=-1$ and solve the homogeneous differential equation
$$y_h^{(4)}-y_h=0$$
The trial function is $y=e^{rx}$ leading to the characteristic equation $r^4-1=(r+1)(r-1)(r+i)(r-i)=0$, so the general solution is
$$y(x)=-1+c_1\cos x+c_2\sin x+c_3\cosh x+c_4\sinh x$$
Applying initial conditions, $y(0)=-1=-1+c_1+c_3$, $y^{\prime}(0)=0=c_2+c_4$, $y(\pi)=\cosh(\pi)=-1-c_1+c_3\cosh\pi+c_4\sinh\pi$, $y^{\prime}(\pi)=\sinh\pi=-c_2+c_3\sinh\pi+c_4\cosh\pi$, we should be able to get a solution.
EDIT The solution turns out to be very simple, as might have been expected from the initial conditions: $c_3=1=-c_1$, $c_4=0=-c_2$.


jQuery val undefined for dynamically generated HTML

Question: I use the following code to dynamically generate input fields, which I want to parse in a jQuery UI dialog. First, the user enters systems. After a click on the "Confirm systems" button, new input fields for each system are generated. Now, I want to access the data entered in the dynamically generated input fields. However, these values are always undefined.

$(document).ready(function() {
  var systemsArray;
  var div = $("

");
  div.append("
" +
    "Systems:" +
    "<input id=\"systems\" size=40></input>" +
    "<button id=\"systems_btn\">Confirm systems</button>" +
    "
");
  $("body").append(div);
  $("#dialog").dialog({
    autoOpen: true,
    modal: true,
    width: 800,
    height: 500,
    buttons: [{
      text: "Execute",
      click: function() {
        $("#items").children(".input").each(function() {
          alert(this.val().join(", ") + ". "); // <-- val undefined
        });
        $(this).dialog("close");
      }
    }]
  });
  $("#systems_btn").click(function() {
    $("#items").empty();
    var fieldSet = $("<fieldset id=\"items\"></fieldset>");
    systemsArray = $("#systems").val().split(",");
    for (const systemID in systemsArray) {
      var label = $("" + "Items for " + systemsArray[systemID] + ":" + "");
      var input = $("<input id=\"" + systemID + "\" size=40></input>");
      fieldSet.append(label);
      fieldSet.append(input);
    }
    $(this).parent().append(fieldSet);
  });
});
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />

For clarity, this is what the dialog looks like before pressing the "Execute" button (which crashes, because val() is undefined):
Answer: There are two things:
1.:  .children(".input") would select elements with the class input, thats not the case in your code, so i changed to .children("input") which will select elements of type input
2.: this.val() will not work as .val() is a jquery method, i changed it to $(this).val() e.g adding a jquery wrapper to the domelement and voilâ, the alert shows the entered value ;-)

$(document).ready(function() {
  var systemsArray;
  var div = $("

");
  div.append("
" +
    "Systems:" +
    "<input id=\"systems\" size=40></input>" +
    "<button id=\"systems_btn\">Confirm systems</button>" +
    "
");
  $("body").append(div);
  $("#dialog").dialog({
    autoOpen: true,
    modal: true,
    width: 800,
    height: 500,
    buttons: [{
      text: "Execute",
      click: function() {
        $("#items").children("input").each(function() {
          alert($(this).val());
        });
        $(this).dialog("close");
      }
    }]
  });
  $("#systems_btn").click(function() {
    $("#items").empty();
    var fieldSet = $("<fieldset id=\"items\"></fieldset>");
    systemsArray = $("#systems").val().split(",");
    for (const systemID in systemsArray) {
      var label = $("" + "Items for " + systemsArray[systemID] + ":" + "");
      var input = $("<input id=\"" + systemID + "\" size=40></input>");
      fieldSet.append(label);
      fieldSet.append(input);
    }
    $(this).parent().append(fieldSet);
  });
});
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />

Comment: Or `this.value`
Answer: That is because you are using not jQuery object, but JS object that does not have .val()
Try doing $(this).val()


Java: how do you find out the cap height and x-height of a font?

Question: FontMetrics doesn't have getters for cap height and x-height of a font.
How can I obtain these values?
As far as cap height goes, there's no guarantee for a particular capital letter that the letter's ascent is the same as the cap height. (e.g. a capital H isn't guaranteed to be flat on the top)
As far as x height goes, I assume it's probably the same as the height of an "x", but again, there's no guarantee.

edit: Grr! I just tried FontMetrics.getBounds() and FontMetrics.getLineMetrics() for specific character sequences, and I always get the same answer for heights (getBounds() does differ for widths, obviously). There's a note in the hasUniformLineMetrics() method about a fontmetrics having several fonts to cover the character set, but that covers character groups, not individual characters.
Comment: There is an interface `java.awt.font.OpenType` which could be used to retrieve font tables, and thus get the `x-height` defined by the font. However, that interface is not used apparently: http://stackoverflow.com/questions/33716004/how-do-i-use-the-opentype-interface-in-java
Answer: What you are looking for is the screen render box that tells you the exact size of text.
This means that you will need to supply information at some point about the surface you are drawing on and the string you are drawing. The reason is that the system simply does not know the visual result until late in rendering. I used:
Graphics2D g;
g.getFont().createGlyphVector(g.getFontRenderContext(),"abc").getVisualBounds();

You might also try:
Graphics2D g;
g.getFont().getMaxCharBounds(g.getFontRenderContext());

I too have trouble keeping all those font methods straight.
Answer: I've not worked with it, but the GlyphView.GlyphPainter class has getAscent, getDescent and getHeight methods. That might be something to check out.
Comment: Ascent is usually larger that cap height.
Answer: Well, if you're trying to make a box with text that fits the text, i think you can just make the height the font size itself
Im not sure, but i think that is what i've done in the past
Answer: As for the x-height, the following code woks fine for me:
    public double getXHeight(Font font)
    {
        FontRenderContext fc = new FontRenderContext(null, false, false);
        TextLayout layout = new TextLayout("x", font, fc);
        return layout.getBounds().getHeight();
    }

Comment: Sorry to be pedantic, but the height of an "x" character is not necessarily the same as the x-height of a typeface.


O que fazer para ler uma coluna no excel com números muito grandes?

Question: Como fazer para quando ler uma coluna do excel cujo número é muito grande e evitar que o mesmo seja interpretado com estouro?
No Excel a coluna está com o número 26468314801. Como é um número ele carrega 2.6468314801E10 , procurei a solução e alguns colegas orientaram que transforme a coluna em texto, mas não tenho como controlar o usuário final.
Como faço para que eu consiga carregar corretamente sem este problema?
Answer: Marcelo,
Transforme a celula da seguinte forma: new BigDecimal(cell.getNumericCellValue())), ou utilize DecimalFormat.


Pegar valor do atributo quando a página for carregada e ou select modificado

Question: Tenho um select. Preciso pegar o valor do atributo data-idconta quando a página for carregada e tambem quando o select for trocado.
Estou tentando:
$(document).ready(function() {

  $('#formaEntrada').on('ready change', function() {
    var IDConta = $("#formaEntrada option:selected").attr('data-idconta');
    $("#contaBancaria").val(IDConta)
  });

});

Já tentei: ready, load, onload, live...
Mas sem sucesso.
Answer: Você precisa exibir o idconta assim que a página estiver pronta.
Você está somente configurado o evento, mas #formaEntrada nunca é inicializado.
Veja um exemplo de como proceder:

function getIDConta(){
 return $("#formaEntrada option:selected").attr('data-idconta');
}

$(document).ready(function() {

  $('#formaEntrada').on('change', function() {
    $("#contaBancaria").val(getIDConta())
  });

  $("#contaBancaria").val(getIDConta())

});
label {
  display: inline-block;
  width: 120px;
}

Tipo de Entrada
<select id="formaEntrada">
  <option data-idconta= "10000-0">Tipo de Entrada 1</option>
  <option data-idconta= "20000-0">Tipo de Entrada 2</option>
</select>

Conta Bancária
<input type='text' id='contaBancaria' readonly />

O campo é inicializado depois que você configura o evento e não dentro dele.
Answer: Ao invés de:
$('#formaEntrada').on('ready change', function() {
    var IDConta = $("#formaEntrada option:selected").attr('data-idconta');
    $("#contaBancaria").val(IDConta);
})

Utilize:
$('#formaEntrada').change(function() {
    var IDConta = $("#formaEntrada option:selected").attr('data-idconta');
    $("#contaBancaria").val(IDConta)
})

Comment: O evento `change` executará quando a página for carregada?
Answer: Pegando carona na resposta do Fabiano Salles, com o JQuery você pode evocar um evento com o método .trigger().

$(document).ready(function() {

      //Configura o evento change
      $('#formaEntrada').on('change', function() {
        var IDConta = $("#formaEntrada option:selected").data('idconta');
        $("#contaBancaria").val(IDConta)
      });

      //evoca o evento configurado
      $('#formaEntrada').trigger('change');

});
label {
  display: inline-block;
  width: 120px;
}

Tipo de Entrada
<select id="formaEntrada">
  <option data-idconta= "10000-0">Bradesco</option>
  <option data-idconta= "20000-0">Santander</option>
</select>

Conta Bancária
<input type='text' id='contaBancaria' readonly />


Get value from QJsonObject by index

Question: In my app I use json object to get result from remote database. Usually response string looks like:
{
    status:"ok",
    data: [
        { field1:"value1", field2:"value2", field3:"value3" },
        { field1:"value4", field2:"value5", field3:"value6" },
        { field1:"value7", field2:"value8", field3:"value9" }
    ]
}

It looks good and I can get value from speciified row/col by:
QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
QJsonObject responseObject = jsonResponse.object();
if(responseObject.value("status").toString() == "ok") {
     QJsonArray dataObject = responseObject.value("data").toArray();
     // and here I can get the value, for example 2-nd row, field2
     QString value = dataObject.at(1).toObject().value("field2").toString();
}

But sometimes I need to get the value not by name but by index. Ok, I do following:
QJsonObject obj = dataObject.at(1).toObject();
QString key = obj.keys().at(1); // I use index here instead of name
QString value = obj.value(key).toString();

But unfortunately it looks that keys() not preserves field order so key with index 0 not exactly will be first field in its QJsonObject.
So my question - how can I get appropriate field from QJsonObject by index and not by name only?
Answer: first suggestion :
    maybe you can use this code instead, which is more readable
responseObject["status"].toString() == "ok"

and here is your question suggestion
maybe you can try iterator, the below code just the example:
QJsonArray dataObject = responseObject["data"].toArray();
QJsonArray::iterator it;
for (it = dataObject.begin(); it != dataObject.end(); it++) {
    QString key = it->first;
    QString value = it->second;
}

Get value from QJsonObject by index


bonding driver in centos 5.5,mode balance-rr not work

Question: i've creat a bonding interface in centos 5.5,i chose mode balance-rr,using slave eth6 and eth7,and the link of eth6 and eth7 is ok,here is the configuration file:
[root@50:B3:42:00:00:A3 network-scripts]# cat ifcfg-bond1
DEVICE=bond1
IPADDR=172.16.252.225
NETMASK=255.255.0.0
GATEWAY=172.16.0.1
MTU=9000
ONBOOT==yes
BOOTPROTO=none
USERCTL=on
BONDING_OPTS="mode=balance-rr miimon=100"

[root@50:B3:42:00:00:A3 network-scripts]# cat ifcfg-eth6
DEVICE=eth6
USERCTL=no
ONBOOT=yes
MASTER=bond1
SLAVE=yes
BOOTPROTO=none
[root@50:B3:42:00:00:A3 network-scripts]# cat ifcfg-eth7
DEVICE=eth7
USERCTL=no
ONBOOT=yes
MASTER=bond1
SLAVE=yes
BOOTPROTO=none

and the bonding interface is been created succeefully,the parameters in sysfs:
[root@50:B3:42:00:00:A3 network-scripts]# cat /sys/class/net/bond1/bonding/slaves
eth6 eth7
[root@50:B3:42:00:00:A3 network-scripts]# cat /sys/class/net/bond1/bonding/mode
balance-rr 0
[root@50:B3:42:00:00:A3 network-scripts]# cat /sys/class/net/bond1/bonding/mii
miimon      mii_status
[root@50:B3:42:00:00:A3 network-scripts]# cat /sys/class/net/bond1/bonding/miimon
100

[root@50:B3:42:00:00:A3 network-scripts]# cat /proc/net/bonding/bond1
Ethernet Channel Bonding Driver: v3.4.0 (October 7, 2008)

Bonding Mode: load balancing (round-robin)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: eth6
MII Status: up
Link Failure Count: 0
Permanent HW addr: 50:b3:42:00:00:74

Slave Interface: eth7
MII Status: up
Link Failure Count: 0
Permanent HW addr: 50:b3:42:00:00:75

and i can ping the bond interface ,the link status is normal:
# ping 172.16.252.225
PING 172.16.252.225 (172.16.252.225) 56(84) bytes of data.
64 bytes from 172.16.252.225: icmp_seq=1 ttl=64 time=1.88 ms
64 bytes from 172.16.252.225: icmp_seq=2 ttl=64 time=0.122 ms
64 bytes from 172.16.252.225: icmp_seq=3 ttl=64 time=0.112 ms
64 bytes from 172.16.252.225: icmp_seq=4 ttl=64 time=0.110 ms
64 bytes from 172.16.252.225: icmp_seq=5 ttl=64 time=0.117 ms

then, i use IOmeter to do flow reading and writing to disks via the bonding interface ,to see the distribution of the data flow,the mode of the bonding interface is balance-rr,i use command to analyse the data flow:
sar -n DEV 2 100

but the result is not the same as expected:
# sar -n DEV 2 100
Linux 2.6.18-194.17.1.el5 (50:B3:42:00:00:A3)   04/28/2012

06:32:32 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
06:32:34 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
06:32:34 PM      eth0    318.78   4316.24  19691.88 439105.58      0.00      0.00      0.00
06:32:34 PM    inner0      0.00      0.51      0.00     47.72      0.00      0.00      0.00
06:32:34 PM      eth5      1.02      0.00     93.40      0.00      0.00      0.00      0.00
06:32:34 PM      eth6   4499.49      0.00 2631274.62      0.00      0.00      0.00      0.00
06:32:34 PM      eth7    236.55      0.00  14350.76      0.00      0.00      0.00      0.00
06:32:34 PM      eth8      0.00      0.00      0.00      0.00      0.00      0.00      0.00
06:32:34 PM      sit0      0.00      0.00      0.00      0.00      0.00      0.00      0.00
06:32:34 PM     bond0      0.00      0.00      0.00      0.00      0.00      0.00      0.00
06:32:34 PM     bond1   4736.04      0.00 2645625.38      0.00      0.00      0.00      0.00

we can see that the data flow is not balance ,most of the data flow is on eth6, mabye some parameters was not been set correctly, or there be some other errors ,can you help me?thank you very much!!!
machine and system info:
Linux 2.6.18-194.17.1.el5 x86_64  GNU/Linux

bonding driver version:
 v3.4.0 (October 7, 2008)

NIC:
intel 82574L 1000Mb/s

switch:
H3C S5800

# interface GigabitEthernet1/0/7 port link-aggregation group 1
# interface GigabitEthernet1/0/9 port link-aggregation group 1
# interface GigabitEthernet1/0/12 port link-aggregation group 1
# interface GigabitEthernet1/0/22 port link-aggregation group

My machine is connected to these 4 ports on the switch. At the same time I configured the link-port type of corresponding interface to be access.
Answer: You don't show your switch configuration. Generally, the balance-rr mode requires an Etherchannel (Cisco) or trunk configuration on the switch to work properly. Do you have a grouping established on the H3C S5800 switch?
See the notes here.
The balance-rr, balance-xor and broadcast modes generally
require that the switch have the appropriate ports grouped together.
The nomenclature for such a group differs between switches, it may be
called an "etherchannel" (as in the Cisco example, above), a "trunk
group" or some other similar variation.

Comment: thanks very much for your reply,i've have my switch configrured, but i'm not sure whether it was right or not,here is the configuration:`#
interface GigabitEthernet1/0/7
 port link-aggregation group 1
#
interface GigabitEthernet1/0/9
 port link-aggregation group 1
#
interface GigabitEthernet1/0/12
 port link-aggregation group 1
#
interface GigabitEthernet1/0/22
 port link-aggregation group 1
`   my machine connected to this 4 ports on the switch.at the same time,i configured the **link-port** type of corresponding interface to be **access**
Comment: And the terminal printed messages like this **Port member GigabitEthernet1/0/7 of aggregation group BAGG1 becomes ACTIVE!** but this still not work.
Comment: @Jak.Ding I have the certain feeling that there is something missing on the switch-side - something that corresponds to the balance-rr mode.


Should I make a SOAP or a REST service to receive files from a .Net WCF Service?

Question: I need to implement a web service client in drupal 7 using the Web Service Client module,  which receives files from a .Net WCF Service.
Should I make a SOAP Service or REST service using WCF such that the web service client can easily implement the file receiving logic in Drupal/PHP?
Answer: I have implemented SOAP based web service. And for file transfer I have sent the file contents as an array of bytes and it was successfully received in PHP.


Why additional user on Ubuntu uses my $NVM_DIR?

Question: I installed nvm as recomended in docs:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.1/install.sh | bash

Next, I added additional user node-user on Ubuntu 18.04:
sudo useradd -m node-user

Where flag -m meaning "with home directory".
But when I trying login via terminal under this user:
sudo -u node-user -s

I have warn:

┌──────────────────────────────────────────────────────┐
│               npm update check failed                │
│         Try running with sudo or get access          │
│         to the local update config store via         │
│ sudo chown -R $USER:$(id -gn $USER) /home/me/.config │
└──────────────────────────────────────────────────────┘

Where me it's my user name. And if I to do:
node-user@host:~$ echo $NVM_DIR
> /home/me/.config

So, why additional user uses my $NVM_DIR?
Answer: After I ask Ubuntu, @steeldriver point me to related question.
All works fine when I created system user and login in shell like this:
sudo -H -u node-user -s

So flag -H resolved my problem.


How do I prepend text from one textbox to another?

Question: Basically I'm making a simple program to help take notes at my job.  I have a one line textbox1, and a multiple line textbox2.
I want to be able to type whatever in textbox1, and then press "enter" and it show up in the first line in textbox2.  Any help would be appreciated.
    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    private void textbox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }
}

Comment: using WinForm or WebForm?Have you try any luck?
Answer: //in form constructor, or InitializeComponent method
textBox1.Validated += DoValidateTextBox;

//in another place of your class
private void DoValidateTextBox(object sender, EvenArgs e) {
  textBox2.Text =  ((TextBox)sender).Text + Environment.NewLine + textBox2.Text;
}

Comment: @Boneyards if you created the textbox1_TextChanged with the Visual interface, just go to TextBox1, choose the Validated event and add "DoValidatedTextBox" in the field. Remove the "textbox1_TextChanged" from the "TextChanged" field, paste the second part of code near the `private void textobx1_TextChanged` (which you can remove).
Comment: Here is my code:public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void textbox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }
    }
Comment: I'm not sure where to add that code that you posted, and also not sure how to properly format.  Sorry
Answer: This should work:
private void textBox1_KeyDown(object sender, KeyEventArgs e) // Keydown event in Textbox1
{
  if (e.KeyCode == Keys.Enter) // Add text to TextBox2 on press Enter
  {
    textBox2.Text += textBox1.Text;
    textBox2.Text+= "\r\n"; // Add newline
    textBox1.Text = string.Empty; // Empty Textbox1
    textBox1.Focus(); // Set focus on Textbox1
  }
}

If you want to add text at the firstline of your textbox, then replace in the code above:
textBox2.Text = textBox1.Text + "\r\n" + textBox2.Text;

Comment: this will add Text at last line, not first one.
Comment: Then replace with: textBox2.Text = textBox1.Text + textBox2.Text; or textBox2.Text = textBox1.Text + "\r\n" + textBox2.Text;
Answer: It depends on what you want the final result to be.  If all you want is the first line of the second textbox to equal the first then:
void myEvent()
{
    textbox2.Text = textbox1.Text;
}

If however you want whatever is in textbox1 to be appended to textbox2 every time you press a button, then you are better off using a ListView:
void myEvent()
{
   myListView.Items.add(textbox1.Text);
}

If you specifically want a textbox though (with the data always appended to the first line):
void myEvent()
{
   textbox2.Text = textbox1.Text + Environment.NewLine + textbox2.Text;
}

Comment: I tried the last one but the Newline() was giving me errors.  I took out the () and when in typed in textbox1 it was showing the whole word on first line of textbox2, then whole word minus one letter on line 2, etc etc in real time.
Comment: I just copied and pasted the code in a blank form and I'm not getting that problem.  Have you made sure that the 'Multiline' property on textBox2 is set to true?  Also it's "Environment.NewLine" without the brackets and with the capital 'L'.


How to convert x, y, z coordiate data to geometry (vertex, face) in three.js?

Question: I have sets of [x,y,z] coordinate data, which forms one space.
e.g.
(0,0,-3000),(1848,0,-3000),(1848,-5177,-3000),(0,-5177,-3000),
(0,0,0),(1848,0,0),(1848,-5177,0),(0,-5177,0)
I would like to render the space coordinates using three.js.
I'm trying to create a function which creates geometry object to render.
However, it seems quite tricky to set vertices and faces.
Is there a simple way to render xyz coordinate to geometry in three.js?
Or is it possible to draw 2D shape(with x, z) and make it 3D(with z)?
because for each geometries, it has even height as you see at the given coordinate example.
Comment: Do you have a list of faces?
Comment: No I only have the set of xyz coordinate data. I would like to make a function which creates faces.
Comment: There are several ways to generate faces from a vertex list. Is your vertex count a multiple of 3 ?
Comment: The set of coordinates should be vertices, but I couldn't figure out how to  generate triangles out of the coordinates.
Comment: A very simple way to do is to generate a face (a triangle) every 3 vertices (this requires to have a multiple of 3 vertices).
Comment: Thank you for your comments. Do you have any idea how I should create a multiple of 3 vertices out of given coordinates?
Answer: Concept
To define geometry in 3D you need:

Points in 3D space; and
Information about how your points connect.

For an arbitrary shape, you need to specify faces which join 3 or more of your points.
Alternatively, if you make assumptions about your shape (for instance, from your example coordinates, it seems like you are drawing an upright box) you may only need to supply coordinates.
Example
From your example above, your box seems to have:
height: 3000 ; width: 1848 ; depth:5177
which enables you to use:
<code>geometry = new THREE.BoxGeometry( 1848 , 3000 , 5177 );
</code>
Side note: a box should have 8 vertices, not 10. You have included [0,0,-3000] and [0,0,0] twice.
Comment: Thanks for your comment. I have many sets of space data, it could also be other shapes (e.g. pentagon upright box or etc). The coordinates should form a room shape and the room shapes will form a building. Is there any way to draw polyline(using x, y values) and make it upright box with given z value(height)?
Comment: And, when I use BoxGeometry, could I give the center/location for the box?
Comment: This is where my knowledge of three.js reaches its limit, but logically you would either have to define the faces on the outside, or extrude a 2D shape upwards.

Check out the source code from [this page](https://stemkoski.github.io/Three.js/Shapes.html), which includes many basic shapes:
Comment: Thank you so much. Helped me a lot!