Load Large Text in Android

Question: In my application I am trying to copy the text from a website and pasting it in my strings.xml file and after saving the strings.xml file I am not able to use that string in my textview and when I try to clean my project my R.java gets deleted and when I remove that text from the strings.xml I retain my R.java. I want to copy the text from the following website.
http://mygogolfteetime.com/term-of-use
my String value is:
<string name="terms_of_use">

Website Terms, Conditions, and Notices AgreementBetween Customer and GoGolf, L.P.
Welcome to the mygogolfteetime.com website (the "Website"). This Website is provided solely to assist customers in gathering tee time information, determining the availability of tee time-related goods and services, making legitimate reservations or otherwise transacting business with golf tee time suppliers, and for no other purposes. The terms "we", "us", "our" and "mygogolfteeetime.com" refer to GoGolf, L.P., a Texas limited partnership and/or our subsidiaries. The term "you" refers to the customer visiting the Website and/or booking a tee time through us on this Website, or through our customer service agents.
This Website is offered to you conditioned upon your acceptance without modification of all the terms, conditions, and notices set forth below (collectively, the "Agreement"). By accessing or using this Website in any manner, you agree to be bound by the Agreement. Please read the Agreement carefully. If you do not accept all of these terms and conditions, please do not use this Website. Be sure to return to this page periodically to review the most current version of the Agreement. We reserve the right at any time, at our sole discretion, to change or otherwise modify the Agreement without prior notice, and your continued access or use of this Website signifies your acceptance of the updated or modified Agreement.
Use of the Website
As a condition of your use of this Website, you warrant that
1. you are at least 18 years of age,
2. you possess the legal authority to create a binding legal obligation,
3. you will use this Website in accordance with this Agreement,
4. you will only use this Website to make legitimate reservations for you or for another person for whom you are legally authorized to act,
5. all information supplied by you on this Website is true, accurate, current and complete, and
6. if you have a mygogolfteetim.com account, you will safeguard your account information and will supervise and be completely responsible for any use of your account by anyone other than you. We retain the right at our sole discretion to deny access to anyone to this Website and the services we offer, at any time and for any reason, including, but not limited to, for violation of this Agreement.

Prohibited Activities

The content and information on this Website (including, but not limited to, price and availability of tee time services), as well as the infrastructure used to provide such content and information, is proprietary to us or our suppliers and providers. While you may make limited copies of your tee time itinerary (and related documents) for tee time reservations or services booked through this Website, you agree not to otherwise modify, copy, distribute, transmit, display, perform, reproduce, publish, license, create derivative works from, transfer, or sell or re-sell any information, software, products, or services obtained from or through this Website. Additionally, you agree not to:
1. use this Website or its contents for any commercial purpose;
2. make any speculative, false, or fraudulent reservation or any reservation in anticipation of demand;
3. access, monitor or copy any content or information of this Website using any robot, spider, scraper or other automated means or any manual process for any purpose without our express written permission;
4. violate the restrictions in any robot exclusion headers on this Website or bypass or circumvent other measures employed to prevent or limit access to this Website;
5. take any action that imposes, or may impose, in our discretion, an unreasonable or disproportionately large load on our infrastructure;
6. deep-link to any portion of this Website (including, without limitation, the purchase path for any tee time services) for any purpose without our express written permission; or
7. "frame", "mirror" or otherwise incorporate any part of this Website into any other website without our prior written authorization.
Supplier Rules and Restrictions
Separate terms and conditions will apply to your reservation and purchase of tee time - related goods and services that you select. Please read these separate terms and conditions carefully. You agree to abide by the terms and conditions of purchase imposed by any supplier with whom you elect to deal, including, but not limited to, payment of all amounts when due and compliance with the supplier's rules and restrictions regarding availability and use of fares, products, or services. You acknowledge that some third-party providers offering certain services and/or activities may require you to sign their liability waiver prior to participating in the service and/or activity they offer. You understand that any violation of any such supplier's rules and restrictions may result in cancellation of your tee time(s), in your being denied access to the applicable golf course product or services, in your forfeiting any monies paid for such reservation(s), and/or in our debiting your account for any costs we incur as a result of such violation.

Privacy Policy

GoGolf, LP. believes in protecting your privacy. Please click here to review our current Privacy Policy, which also governs your use of mygogolfteetime.com, to understand our practices: Privacy Policy.
Reviews, Comments and Other Submissions
We appreciate hearing from you. Please be aware that by submitting content to this Website by electronic mail, postings on this Website or otherwise, including any golf course reviews, photographs, video, questions, comments, suggestions, ideas or the like contained in any submissions (collectively, "Submissions"), you (a) grant GoGolf, LP. and its affiliates a nonexclusive, royalty-free, perpetual, transferable, irrevocable and fully sublicensable right to use, reproduce, modify, adapt, translate, distribute, publish, create derivative works from and publicly display and perform such Submissions throughout the world in any media, now known or hereafter devised; and (b) grant GoGolf, LP and its affiliates and sublicensees the right to use the name that you submit in connection with such Submission, if they choose. However, you acknowledge that GoGolf, LP may choose to provide attribution of your comments or reviews (for example, listing your name and hometown on a golf course review that you submit) at our discretion. You further grant GoGolf, LP the right to pursue at law any person or entity that violates your or GoGolf, LP rights in the Submissions by a breach of this Agreement. We take no responsibility and assume no liability for any Submissions posted or submitted by you. If you do not agree to these terms and conditions, please do not provide us with any Submissions.
You are fully responsible for the content of your Submissions, (specifically including, but not limited to, reviews posted to this Website). You are prohibited from posting or transmitting to or from this Website: (i) any unlawful, threatening, libelous, defamatory, obscene, pornographic, or other material or content that would violate rights of publicity and/or privacy or that would violate any law; (ii) any commercial material or content (including, but not limited to, solicitation of funds, advertising, or marketing of any good or services); and (iii) any material or content that infringes, misappropriates or violates any copyright, trademark, patent right or other proprietary right of any third party. You shall be solely liable for any damages resulting from any violation of the foregoing restrictions, or any other harm resulting from your posting of content to this Website. You acknowledge that GoGolf, LP has the right to control (e.g. use, publish, remove) any content you submit without notice to you. If you submit more than one review for the same hotel, only your most recent submission is eligible for use.
If you believe in good faith that materials hosted by us infringe your copyright, you (or your agent) may send us a written notice that includes the following information:
1. A clear identification of the copyrighted work you claim was infringed.
2. A clear identification of the material you claim is infringing the copyrighted work, and information that will allow us to locate that material on the Website, such as a link to the infringing material.
3. Your contact information so that we can reply to your complaint, preferably including an email address and telephone number.
4. A statement that you have a "good faith belief that the material that is claimed as copyright infringement is not authorized by the copyright owner, its agent, or the law."
5. A statement that "the information in the notification is accurate, and under penalty of perjury, the complaining party is authorized to act on behalf of the owner of an exclusive right that is allegedly infringed."
6. The notice must be signed by the person authorized to act on behalf of the owner of an exclusive right that is allegedly infringed.
Notices with respect to this Website should be sent to:: GoGolf, L.P., 13522 Pueblo Crossing San Antonio, TX 78232; email@example.com; by phone at 210.317.1210
We will review and address all notices that comply with the requirements above.
We suggest that you consult your legal advisor before filing a notice or counter-notice. Also, be aware that you may be liable for damages if you make a false claim of copyright infringement.
Pay Reservation Fee Now Online and Pay Green Fee Later at Golf Course
With all golf course, you will be responsible for paying green fees (cost to golf) at the golf course itself. You will be charged the amount in the currency that you select immediately for the Reservation Fee. You will pay later for all green fees and other associated fee the golf course may charge at the golf course itself, the golf course will charge you in the local currency of the relevant golf course at the time of your tee time. Tax rates and foreign exchange rates could change in the time between booking and stay.
GoGolf, LP. Change Or Cancellation Fees
GoGolf, LP. will not refund any booking fees once booking has been accepted by user. You can change or cancel your tee time booking online. You may still be subject to change and cancellation fees that our tee time suppliers impose and require us to pass on, as indicated in the rules and restrictions for the tee time reservation. Valid only for tee time bookings made after May 10, 2012. Golf Courses and other suppliers may impose their own change and/or cancellation fees. Change and cancellation requirements and penalties vary by golf course. Check your booking confirmation for details. To change or cancel your tee time booking, go online to www.mygogolfteetime.com. These terms and conditions may not be changed by any unauthorized person, including employees of GoGolf, LP.
You agree to pay the booking fees to GoGolf, LP and any golf course required cancellation or change fees that you incur. In limited cases, some golf courses do not permit changes to or cancellations of reservations after they are made, as indicated in the rules and restrictions for the tee time reservation. You agree to abide by the terms and conditions imposed with respect to your tee time reservations.

General Terms

GoGolf, LP.reserves the right to discontinue the participation privileges of any individual who engages in any fraudulent activity or uses the Program in a manner inconsistent with these Terms & Conditions or any federal or state laws, statutes, or ordinances. Discontinued participation privileges may result in the loss of all benefits. In addition to discontinuance of participation privileges, GoGolf, LP shall have the right to take appropriate administrative and/or legal action, including criminal prosecution, as it deems necessary. While you are enrolled in mygogolfteetime.com program, we may communicate with you via email regarding updates on your account or transactions. Except where prohibited, you agree that any and all disputes, claims, and causes of action arising out of, or connected with, the tee time reservations shall be resolved individually, without resort to any form of class action, and exclusively by the appropriate court located in Bexar County, Texas.

LIABILITY DISCLAIMER THE INFORMATION, SOFTWARE, PRODUCTS, AND SERVICES PUBLISHED ON THIS WEBSITE MAY INCLUDE INACCURACIES OR ERRORS, INCLUDING PRICING ERRORS. IN PARTICULAR, GOGOLF, LP. ITS SUBSIDIARIES AND CORPORATE AFFILIATESDO NOT GUARANTEE THE ACCURACY OF, AND DISCLAIM ALL LIABILITY FOR ANY ERRORS OR OTHER INACCURACIES RELATING TO THE INFORMATION AND DESCRIPTION OF THE GOLF COURSE AND OTHER PRODUCTS DISPLAYED ON THIS WEBSITE (INCLUDING, WITHOUT LIMITATION, THE PRICING, PHOTOGRAPHS, LIST OF GOLF COURSE AMENITIES, GENERAL PRODUCT DESCRIPTIONS, ETC.), MUCH OF WHICH INFORMATION IS PROVIDED BY THE RESPECTIVE GOLF COURSE. IN ADDITION, GOGOLF, LP. EXPRESSLY RESERVES THE RIGHT TO CORRECT ANY PRICING ERRORS ON OUR WEBSITE AND/OR ON PENDING RESERVATIONS MADE UNDER AN INCORRECT PRICE. IN SUCH EVENT, WE WILL OFFER YOU THE OPPORTUNITY TO KEEP YOUR PENDING RESERVATION AT THE CORRECT PRICE OR, AT YOUR OPTION, WE WILL CANCEL YOUR RESERVATION WITHOUT ANY CHANGE OR CANCELLATION FEES.

GOLF COURSE RATINGS DISPLAYED ON THIS WEBSITE ARE INTENDED AS ONLY GENERAL GUIDELINES, AND THE GOGOLF, LP. AFFILIATES DO NOT GUARANTEE THE ACCURACY OF THE RATINGS. THE GOGOLF, LP. COMPANIES, THE GOGOLF, LP.AFFILIATES AND THEIR RESPECTIVE SUPPLIERS MAKE NO GUARANTEES ABOUT THE AVAILABILITY OF SPECIFIC PRODUCTS AND SERVICES. THE GOGOLF, LP. COMPANIES, THE GOGOLF, LP. AFFILIATES AND THEIR RESPECTIVE GOLF COURSE MAY MAKE IMPROVEMENTS AND/OR CHANGES ON THIS WEBSITE AT ANY TIME.

THE GOGOLF, LP.COMPANIES, THE GOGOLF, LP.AFFILIATES, AND THEIR RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION, SOFTWARE, PRODUCTS, AND SERVICES CONTAINED ON THIS WEBSITE FOR ANY PURPOSE, AND THE INCLUSION OR OFFERING OF ANY PRODUCTS OR SERVICES ON THIS WEBSITE DOES NOT CONSTITUTE ANY ENDORSEMENT OR RECOMMENDATION OF SUCH PRODUCTS OR SERVICES BY THE GOGOLF, LP.COMPANIES OR.THE GOGOLF, LP.AFFILIATES. ALL SUCH INFORMATION, SOFTWARE, PRODUCTS, AND SERVICES ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. THEGOGOLF, LP.COMPANIES, THE GOGOLF, LP.AFFILIATES, AND THEIR RESPECTIVE GOLF COURSES DISCLAIM ALL WARRANTIES AND CONDITIONS THAT THIS WEBSITE, ITS SERVERS OR ANY EMAIL SENT FROM THE GOGOLF, LP.COMPANIES, THE GOGOLF, LP.AFFILIATES, AND/OR THEIR RESPECTIVE SUPPLIERS ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS. THE GOGOLF, LP.COMPANIES, THE GOGOLF, LP.AFFILIATES, AND THEIR RESPECTIVE GOLG COURSES HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION, SOFTWARE, PRODUCTS, AND SERVICES, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NONINFRINGEMENT.

THE GOLF COURSES AND OTHER SUPPLIERS PROVIDING TEE TIME OR OTHER SERVICES ON THIS WEBSITE ARE INDEPENDENT CONTRACTORS AND NOT AGENTS OR EMPLOYEES OF THE GOGOLF, LP.COMPANIES, OR THE GOGOLF, LP.AFFILIATES. THE GOGOLF, LP.COMPANIES AND THE GOGOLF, LP.AFFILIATES ARE NOT LIABLE FOR THE ACTS, ERRORS, OMISSIONS, REPRESENTATIONS, WARRANTIES, BREACHES OR NEGLIGENCE OF ANY SUCH SUPPLIERS OR FOR ANY PERSONAL INJURIES, DEATH, PROPERTY DAMAGE, OR OTHER DAMAGES OR EXPENSES RESULTING THEREFROM. THEGOGOLF, LP.COMPANIES AND THE GOGOLF, LP. AFFILIATES HAVE NO LIABILITY AND WILL MAKE NO REFUND IN THE EVENT OF ANY DELAY, CANCELLATION, OVERBOOKING, STRIKE, FORCE MAJEURE OR OTHER CAUSES BEYOND THEIR DIRECT CONTROL, AND THEY HAVE NO RESPONSIBILITY FOR ANY ADDITIONAL EXPENSE, OMISSIONS, DELAYS, RE-ROUTING OR ACTS OF ANY GOVERNMENT OR AUTHORITY.

IN NO EVENT SHALL THE GOGOLF, LP.COMPANIES, THE GOGOLF, LP.AFFILIATES, AND/OR THEIR RESPECTIVE SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF, OR IN ANY WAY CONNECTED WITH, YOUR ACCESS TO, DISPLAY OF OR USE OF THIS WEBSITE OR WITH THE DELAY OR INABILITY TO ACCESS, DISPLAY OR USE THIS WEBSITE (INCLUDING, BUT NOT LIMITED TO, YOUR RELIANCE UPON OPINIONS APPEARING ON THIS WEB SITE; ANY COMPUTER VIRUSES, INFORMATION, SOFTWARE, LINKED SITES, PRODUCTS, AND SERVICES OBTAINED THROUGH THIS WEBSITE; OR OTHERWISE ARISING OUT OF THE ACCESS TO, DISPLAY OF OR USE OF THIS WEBSITE) WHETHER BASED ON A THEORY OF NEGLIGENCE, CONTRACT, TORT, STRICT LIABILITY, OR OTHERWISE, AND EVEN IF THEGOGOLF, LP.COMPANIES, THE GOGOLF, LP.AFFILIATES AND/OR THEIR RESPECTIVE GOLF COURSES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

If, despite the limitation above, the GOGOLF, LP.Companies, the GOGOLF, LP. Affiliates or their respective suppliers are found liable for any loss or damage which arises out of or in any way connected with any of the occurrences described above, then the GOGOLF, LP.Companies, theGOGOLF, LP. Affiliates or their respective suppliers liabilities will in no event exceed, in the aggregate, the greater of (a) the transaction fees assessed for your transactions on this Website, or (b) One-Hundred Dollars (US$100.00).

The limitation of liability reflects the allocation of risk between the parties. The limitations specified in this section will survive and apply even if any limited remedy specified in these terms is found to have failed of its essential purpose. The limitations of liability provided in these terms inure to the benefit of the GOGOLF, LP.Companies, the GOGOLF, LP.Affiliates, and/or their respective suppliers.
Indemnification

You agree to defend and indemnify the GOGOLF, LP.Companies, the GOGOLF, LP.Affiliates, and/or their respective suppliers and any of their officers, directors, employees and agents from and against any claims, causes of action, demands, recoveries, losses, damages, fines, penalties or other costs or expenses of any kind or nature including but not limited to reasonable legal and accounting fees, brought by third parties as a result of:

(a) your breach of this Agreement or the documents referenced herein;
(b) your violation of any law or the rights of a third party; or
(c) your use of this Website.
Links To Third-Party Sites

This Website may contain hyperlinks to websites operated by parties other than GoGolf. Such hyperlinks are provided for your reference only. We do not control such websites and are not responsible for their contents or the privacy or other practices of such websites. Further, it is up to you to take precautions to ensure that whatever links you select or software you download (whether from this Website or other websites) is free of such items as viruses, worms, trojan horses, defects and other items of a destructive nature. Our inclusion of hyperlinks to such websites does not imply any endorsement of the material on such websites or any association with their operators.
Software Available On This Website

Any software that is made available to download from this Website ("Software") is the copyrighted work of UDIG dbaGOGOLF, LP., and/or our respective suppliers. Your use of such Software is governed by the terms of the end user license agreement, if any, which accompanies, or is included with, the Software ("License Agreement"). You may not install or use any Software that is accompanied by or includes a License Agreement unless you first agree to the License Agreement terms. For any Software made available for download on this Website not accompanied by a License Agreement, we hereby grant to you, the user, a limited, personal, nontransferable license to use the Software for viewing and otherwise using this Website in accordance with these terms and conditions and for no other purpose.
Please note that all Software, including, without limitation, all HTML code and Active X controls contained on this Website, is owned by UDIG dba GOGOLF, LP. Affiliates, and/or our respective suppliers, and is protected by copyright laws and international treaty provisions. Any reproduction or redistribution of the Software is expressly prohibited, and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.

WITHOUT LIMITING THE FOREGOING, COPYING OR REPRODUCTION OF THE SOFTWARE TO ANY OTHER SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY PROHIBITED. THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT.
Currency Converter

Currency rates are based on various publicly available sources and should be used as guidelines only. Rates are not verified as accurate, and actual rates may vary. Currency quotes are not updated every day. Check the date on the currency converter feature for the day that currency was last updated. The information supplied by this application is believed to be accurate, but the GoGolf, LP. Companies, the GoGolf, LP. Affiliates, and/or our respective suppliers do not warrant or guarantee such accuracy. When using this information for any financial purpose, we advise you to consult a qualified professional to verify the accuracy of the currency rates. We do not authorize the use of this information for any purpose other than your personal use and you are expressly prohibited from the resale, redistribution, and use of this information for commercial purposes.

Copyright and Trademark Notices
All contents of this website are copyrighted © 2012 UDIG dba GOGOLF, LP. All rights reserved.UDIG dba GOGOLF, LP is not responsible for content on websites operated by parties other than UDIG dba GOGOLF, LP, and the GoGolf and slogan "Gotta Sell It" Gotta Have It" are trademarks or registered trademarks in the U.S. and/or other countries of UDIG dba GOGOLF, LPa subsidiary of GoGolf, LP. Other product and company names mentioned herein may be the trademarks of their respective owners.
If you are aware of an infringement of our brand, please let us know by e-mailing us at firstname.lastname@example.com.
Claims Of Copyright Infringement

1. A clear identification of the copyrighted work you claim was infringed.
2. A clear identification of the material you claim is infringing the copyrighted work, and information that will allow us to locate that material on the Website, such as a link to the infringing material.
3. Your contact information so that we can reply to your complaint, preferably including an email address and telephone number.
4. A statement that you have a "good faith belief that the material that is claimed as copyright infringement is not authorized by the copyright owner, its agent, or the law."
5. A statement that "the information in the notification is accurate, and under penalty of perjury, the complaining party is authorized to act on behalf of the owner of an exclusive right that is allegedly infringed."
6. The notice must be signed by the person authorized to act on behalf of the owner of an exclusive right that is allegedly infringed.
We will review and address all notices that comply with the requirements above..
We suggest that you consult your legal advisor before filing a notice or counter-notice. Also, be aware that you may be liable for damages if you make a false claim of copyright infringement.
General

Your use of mapping available on this Website is governed by the terms of use set forth.
This Website is operated by a U.S. entity and this Agreement is governed by the laws of the State of Texas, USA. You hereby consent to the exclusive jurisdiction and venue of courts in Bexar County, Texas, USA, in all disputes arising out of or relating to the use of this Website. Use of this Website is unauthorized in any jurisdiction that does not give effect to all provisions of these terms and conditions, including, without limitation, this paragraph.

You agree that no joint venture, partnership, or employment relationship exists between you and theUDIG dba GOGOLF, LP Companies as a result of this Agreement or use of this Website.
Our performance of this Agreement is subject to existing laws and legal process, and nothing contained in this Agreement limits our right to comply with law enforcement or other governmental or legal requests or requirements relating to your use of this Website or information provided to or gathered by us with respect to such use. To the extent allowed by applicable law, you agree that you will bring any claim or cause of action arising from or relating to your access or use of this Website within two (2) years from the date on which such claim or action arose or accrued or such claim or cause of action will be irrevocably waived.
If any part of this Agreement is determined to be invalid or unenforceable pursuant to applicable law including, but not limited to, the warranty disclaimers and liability limitations set forth above, then the invalid or unenforceable provision will be deemed superseded by a valid, enforceable provision that most closely matches the intent of the original provision and Agreement shall continue in effect.
This Agreement (and any other terms and conditions referenced herein) constitutes the entire agreement between you and GoGolf, LP. with respect to this Website and it supersedes all prior or contemporaneous communications and proposals, whether electronic, oral, or written, between the customer and GoGolf, LP.with respect to this Website. A printed version of this Agreement and of any notice given in electronic form shall be admissible in judicial or administrative proceedings based upon or relating to this Agreement to the same extent and subject to the same conditions as other business documents and records originally generated and maintained in printed form.

Fictitious names of companies, products, people, characters, and/or data mentioned on this Website are not intended to represent any real individual, company, product, or event.
Any rights not expressly granted herein are reserved.
Service Help
For quick answers to your questions or ways to contact us, visit FAQ Or, you can write to us at:
Attn: Customer Service UDIG dba GOGOLF,
GoGolf PO Box 160732 San Antonio, TX 78280
Effective as of May 10, 2012 ©2012UDIG dba GOGOLF, LP. All rights reserved.
</string>

Comment: are you trying to copy from code? can u give me exact scenario?
Comment: Exactly which text are you trying to copy from this website? Show your string values which you are trying to copy .
Comment: please change the way of setting the text. you can store the text in database or file. from file or db you can easily set the text
Comment: I have edited my post plase check...
Comment: in your textview add the text type to be multipleline
Comment: @StyleMe my textview is not able to recognize the R.string.terms_of_use then how can move further to add multiple line
Comment: nah just forget about what i said above. just check my below answer.
Comment: Why don't you create an html page for this text and show it in the webview. Its much more better way to show your text rather than accessing from string.xml file.
Answer: You can do that using code. Because if you set these whole lines in the strings XML will not work as you need to edit every each line.
My advice is
<TextView android:id="@+id/mylargeText"/>

in your main class
TextView largeTextView = (TextView) findViewById(R.id.mylargeText);

create raw folder in res . and then create file named term.txt
try {
   Resources res = getResources();
   InputStream in_s = res.openRawResource(R.raw.term);
   byte[] b = new byte[in_s.available()];
   in_s.read(b);
   largeTextView.setText(new String(b));
} catch (Exception e) {
   largeText.setText("Error: can't show terms.");
}

Comment: i have created the terms.txt file inside raw folder inside res and pasted the text in that file. but when I run the application i got the text as /res/raw/terms.txt not the actual text inside the file..
Answer: The most convenient way to load large text in Android is to use Raw Resources:

Go to /'YourProjectFolder'/app/src/main/res/ folder (path may be different)
Create folder named raw (if it doesn't exist)
Put your text into .txt file and place it in raw folder
In your code convert Raw Resource into String and set it to TextView

To get Raw Resource bytes (for futher converting it into String) we need to open InputStream. The most fastest (from the performance point of view) and safest way to convert InputStream into String (according to this answer) is to use ByteArrayOutputStream and inputStream.read.
To easily achieve this I wrote ready to use method:
@Nullable
private String getStringFromRawRes(int rawRes) {

    InputStream inputStream;
    try {
        inputStream = getResources().openRawResource(rawRes);
    } catch (Resources.NotFoundException e) {
        e.printStackTrace();
        return null;
    }

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            inputStream.close();
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String resultString;
    try {
        resultString = byteArrayOutputStream.toString("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }

    return resultString;
}

Use it like this:
String largeTextString = getStringFromRawRes(R.raw.yourLargeTextFile);
if(largeTextString != null) {  //null check is optional
    YourTextView.setText(largeTextString);
} else {
    //something goes wrong
}

P.S. you can easily override this kind of resources for different languages, OS versions, screen orientations, etc. using standard mechanisms.
Answer: Hi try the following method
Create a Web view in layout like terms.xml
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget63"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

   <WebView
    android:id="@+id/mWebView"
    android:layout_width="fill_parent"
    android:layout_height="410dp" />

  </RelativeLayout>

Then copy your text and create a Html file name as terms.html and copy the html file in assets folder and Now create a java file as Terms.java
copy the below code in it
 public class Terms extends Activity {
WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.terms);

    this.mWebView = ((WebView)findViewById(R.id.mWebView));
    this.mWebView.getSettings().setBuiltInZoomControls(false);
    this.mWebView.getSettings().setLoadWithOverviewMode(false);
    this.mWebView.getSettings().setUseWideViewPort(false);
    this.mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
    this.mWebView.loadUrl("file:///android_asset/terms.html");
    Button  back_btn = (Button)findViewById(R.id.back);
    back_btn.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view)
        {
            finish();
        }
    });

  }
@SuppressWarnings("unused")
private class Callback extends WebViewClient {
      @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      return(false);
    }
  }
}

Answer: Please check this link about String Formatting and Style
http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
Or try this
<string name="terms_of_use"><![CDATA[
// copy and paste large string data
]]></string>

Comment: I have tryed your code but I am getting NullPointerException error when i run the application
Comment: Totally the best answer!!! This is the right way to do it. Plus documentation of a bizarre hodge-podge of markup that .... might be useful. Why write non-trivial code when you can use the features that are already there?!
Comment: And if you're concerned about making a mess of your strings.xml file, you can just put it in its own values/license_string.xml file. There is no excuse NOT to use this solution.

Load Large Text in Android


Point such that sum of squares of distance to other points are minimized

Question: I need to find $P(x,y)$ such that sum of squares of distance to points $A(3,4), B(20,8), C(4,24)$ is minimized. So I had a general expression of distance,
$D_\alpha = \sqrt{(x_\alpha - x_P)^2 + (y_\alpha - y_P)^2}$
Then the sum is:
$S = D^2_A + D^2_B + D^2_C$
   $= (x_A - x_P)^2 + (y_A - y_P)^2 + (x_B - x_P)^2 + (y_B - y_P)^2 + (x_C - x_P)^2 + (y_C - y_P)^2$
Now it becomes a 8 variable function? Is it correct?
If so to find the critical points I need $$S_{x_A}, S_{y_A}, S_{x_B}, S_{y_B}, S_{x_C}, S_{y_C}, S_{x_P}, S_{y_P}$$
Or is there an easier way?
Answer: It is a 2 variable problem, the values of $x_A,y_A,x_B,y_B,x_C,y_C$ are all provided ($A,B,C$ above), the only unknowns are $x_P,y_P$. To find the solution, you need to compute $\frac{\partial S}{\partial x_P}$ and $\frac{\partial S}{\partial y_P}$.
Answer: So you have to find $P(x,y)$ such that :$\displaystyle \sum_{i=1}^3 d^2_i$ is a minimal , where :
$d^2_1=(x_P-x_A)^2+(y_P-y_A)^2=(x_P-3)^2+(y_P-4)^2$
$d^2_2=(x_P-20)^2+(y_P-8)^2$
$d^2_3=(x_P-4)^2+(y_P-24)^2$
Hence :
$\displaystyle \sum_{i=1}^3 d^2_i=3x^2_P+3y^2_P-54x_P-72y_p+1081$
In order to find minimum of this function you have to find critical points and after that to apply following theorem .
Answer: This is an optimization problem with two unknown variables, $x_P$ and $y_P$. The other point variables are considered to be constants. The goal is to minimize the quantity $S$, sometimes called the objective function. Since this is a homework problem, a good approach is to start by asking yourself the following:

Does minimizing the objective result in a single correct solution or many?
What property(ies) exist at the solution of the minimization, or at any optimization program? Hint: use your multivariable calculus here.
Can you use these properties to create an equation or expression that will help you compute the solution values?


Setting the field selection of a SELECT statement with the Stored Procedure's Input Variable

Question: The following simple Stored Procedure fails to return a result set, even though running this simple SELECT statement in isolation with the actual value works just fine.  Any ideas why?
ALTER PROCEDURE [dbo].[PageHeadingGetText]
    @PageType nvarchar(100)
AS

BEGIN
    SET NOCOUNT ON;

    SELECT @PageType FROM [dbo].[PageHeadingText]
END

Comment: I am *guessing* that you are trying to pass in a list of columns that you want to select. You **cannot** do this however, in T-SQL. You **cannot** parametrize the list of columns or the table name with variables. If you want to do this, you must use *dynamic SQL* (concatenating together your SQL statement inside the stored procedure, and then executing it)
Comment: `SELECT @PageType FROM [dbo].[PageHeadingText]` will return the value of `@PageType` as many times as there are rows in that table. Is that really the intended behaviour? If not what is it supposed to do?
Answer: You didn't ask directly but in the title you say "Setting the field selection of a SELECT".
You have to use dynamic SQL to dynamically build a statement :
ALTER PROCEDURE [dbo].[PageHeadingGetText]
    @columns nvarchar(max)
AS

BEGIN
    SET NOCOUNT ON;

    DECLARE @sqlCommand NVARCHAR(MAX)

    SET @sqlCommand = 'SELECT ' + @columns + ' FROM [dbo].[PageHeadingText]'

    EXECUTE sp_executesql @sqlCommand
END

Comment: Should probably mention SQL injection.
Comment: Which you just did :) But you are right it could be prone to sql injection, please have a look to this *really great* resource : http://www.sommarskog.se/dynamic_sql.html
Comment: Yes it is, this is just an example on how to use dynamic sql. If this is not just intended to use internally, you should not use this syntax. Please read more about sql injection at this address http://www.securiteam.com/securityreviews/5DP0N1P76E.html
Comment: So this scenario holds true for every time we need to use an input variable in place of any of the query's components?  And could you please let me know what you mean by SQL injection?  Is this query prone to SQL injection?


Run out on wide ball

Question: If any batsman or non-striker batsman gets run out on a wide ball, will that ball be counted as a legal delivery, or still be called a wide with extra run ?
Answer: A wide is always a wide, and always gives one run to the batting team. It doesn't matter if the batsman was out from the ball, whether that be run out, stumped or any of the other ways a batsman can be out from a wide.
This is explicitly covered in (what was in 2015) Law 25.5:

Penalty for a Wide

A penalty of one run shall be awarded instantly on the call of Wide ball. [...] this penalty shall stand even if a batsman is dismissed, and shall be in addition to any other runs scored, any boundary allowance and any other runs awarded for penalties.

As of 2023, this is now Law 22.6 with essentially the same wording.

Run out on wide ball


Prove the identity $[L_X,L_Y]\omega=L_{[X,Y]}\omega$ for the Lie derivative of a $k$-form $\omega$

Question: Let $X$ and $Y$ be vector fields on $\mathbb{R}^n$.
Show that for $\omega$, a $k$-form on $\mathbb{R}^n$, $(L_XL_Y-L_YL_X)\omega=L_{[X,Y]}\omega $.
I try using Cartan's magic formula and get that
$\begin{align}
(L_XL_Y-L_YL_X)\omega &= (L_XL_Y)\omega-(L_YL_X)\omega \\
&= L_X(L_Y\omega)-L_Y(L_X\omega) \\
&= L_X(i_Yd\omega+d(i_Y\omega))-L_Y(i_X(d\omega)+d(i_X\omega)) \\
&= i_Xdi_Yd\omega+i_Xd^2(\cdot) + di_Xi_Yd\omega+di_Xdi_Y\omega \\
&- i_Ydi_Xd\omega-i_Yd^2(\cdot) - di_Yi_Xd\omega-di_Ydi_X\omega \\
&= i_Xdi_Yd\omega + di_Xi_Yd\omega+di_Xdi_Y\omega - i_Ydi_Xd\omega - di_Yi_Xd\omega-di_Ydi_X\omega \\
&= [i_Xdi_Y-i_Ydi_X]d\omega+d[i_Xi_Y-i_Yi_X]d\omega+d[i_Xdi_Y-i_Ydi_X]\omega
\end{align}$
For the other part I get
$L_{[X,Y]}\omega=i_{[X,Y]}d\omega+di_{[X,Y]}\omega$
From here I am now stuck.
For the first part of the question (which I have not posted) you are asked (and I am able to) show that $(L_XL_Y-L_YL_X)f=L_{[X,Y]}f$. Not sure whether this is relevant to my question about $\omega$.
Comment: Do you know the formula for $L_X\omega(Z_1,\dots,Z_k)$? Just compute! Or use $L_X\omega = i_X(d\omega) + d(i_X\omega)$
Answer: Now apply the magic formula again:
$$
L_X(\eta)=i_Xd\eta+di_X\eta
$$
where $\eta=i_Yd\omega+di_Y\omega$
and get
$$
L_X(L_Y\omega)=i_Xd(i_Yd\omega+di_Y\omega)+di_X(i_Yd\omega+di_Y\omega)
$$
use that $d$ is linear
$$
i_Xd(i_Yd\omega)+i_X(di_Y\omega)+di_X(i_Yd\omega)+di_X(di_Y\omega)
$$
Subtract $L_Y L_X\omega$ and compare with
$$
L_{[X,Y]}\omega=i_{[X,Y]}d\omega++di_{[X,Y]}\omega
$$
(you should prove:)
$$
[L_X,i_Y]=[i_X,L_Y]=i_{[X,Y]}
$$


Logar com o usuário do Facebook

Question: Como eu faço uma rotina em c# ou Razor em meu site, para ao invés do cara unicamente pelo login da página, ter a opção de logar pelo usuário do facebook?
Não estou pedindo código pronto, apenas como eu faço isso.
Answer: Dê uma olhada nesses dois artigos. Acho que poderá ajudá-lo.
https://docs.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
http://www.eduardopires.net.br/2013/08/autenticando-usuario-asp-net-mvc-facebook/

Logar com o usuário do Facebook


Finding all compact subsets of a given set

Question: Let $K=\{0\} \cup \{ \frac{1}{n} : n \in \mathbb{Z} ^{+} \}$. I know that $K$ itself is compact, because for every open cover there is a finite subcover which must include the open set that contains $0$. $0$ being an element of $K$ is crucial. But I am stuck for finding a criterion to describe all compact subsets of $K.$
Comment: Every subset $L$ of $K$ is compact, except those that contain $0$, and there doesn't exist some $n\in\mathbb N$ such that for $m>n$, $\frac1m\in L$.
Comment: @DonThousand Could you elaborate a little more? Why is it that $L$ should not include 0?
Comment: Which topology on $K$ are you considering in your question?
Comment: @J.-E. Pin Euclidean
Answer: Hint: take $C \subset K$. If $C$ is finite, it is compact. Assume now that $C$ is infinite, so that $C$ contains some of the terms of the sequence $a_n = 1/n$, and possibly zero.
Recall that since $C \subset K$ and $K$ is compact, the set $C$ will be compact if and only if it is closed. On the other hand, regardless of wether $0 \in C$ we know that $C \setminus \{0\}$ can be ordered as a subsequence of the former sequence, i.e. $C \setminus \{0\} = (a_{n_k})_k$. Try to extend what you know about $K$ and $K \setminus 0$, which is the case $n_k = k$.

 If $0 \not \in C$, then $a_{n_k} \to 0$ is a sequence in $C$ but $0 \not \in C$, hence $C$ is not closed and in particular, it is not compact. On the other hand, if $0 \in C$, any convergent subsequence $(b_k)$ in $C$ either contains $0$ or is a convergent subsequence of $(a_n)_n$, and thus $\lim b_k = \lim a_n = 0 \in C$. This shows that $C \subset K$ is compact if and only if $0 \in C$.  If you need to use covers, here's a possible argument: suppose that $0 \not \in C$. Then you should not be able to extract a cover from $\{(a_{n_k},+\infty) \cap K\}_k$ since this covers a finite amount of terms of the sequence (recall that $a_n = 1/n$). If $0 \in C$ and $\mathcal{U}$ is a covering of $C$ by open sets, then we have some open set $U \ni 0$ of the covering which then has to contain all but finite elements of $C$. To extract a finite subcover, pick an element of $\mathcal{U}$ for each point in $C \setminus U$.
Comment: I cannot use sequences argument unfortunately. (We haven't covered it). I figured that all finite subsets should be compact, but not sure about infinite subsets.
Comment: Okay, let me rephrase my hint then :)
Comment: Okay, I think this works now. In the spoiler above I have included two arguments, one using that $C \subset \mathbb{R}$ is compact iff it is closed and bounded, and the other using covers. The formatting is a bit off, so feel free to ask any questions (but do think about this before looking at the solution!).
Answer: If $C \subseteq K$ is a subset then $C$ is compact iff $C$ is finite or $0 \in C$.
Comment: Yes, but why? I understand the finite case but not very sure about the includes 0 case.
Comment: @floridablue in any open cover of $C$ the cover element that contains 0 will contain almost all of $C$. And any set without 0 is discrete and so when compact must be finite.


How create data to two store in indexedDB in onupgradeneeded

Question: Can I ask how i can create data in two store(table) in indexedDb in time when store are created?
In this code: jsfiddle
$( document ).ready(function() {

function open() {
  indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

    var version = 1;
    var request = indexedDB.open("appaa", version);

    request.onupgradeneeded = function(e) {
        db = e.target.result;

        e.target.transaction.onerror = indexedDB.onerror;

        if(db.objectStoreNames.contains("tab1")) {
            db.deleteObjectStore("tab1");
        }

        var storeColl = db.createObjectStore("tab1", {
            keyPath: "id", autoIncrement : true
        });
        storeColl.createIndex("name", "name", { unique: true });
        storeColl.createIndex("description", "description", { unique: false });

        storeColl.transaction.oncomplete = function(event) {
            var collObjectStore = db.transaction("tab1", "readwrite").objectStore("tab1");
            collObjectStore.add({name: "a", description: "b"});
            collObjectStore.add({name: "c", description: "d"});
        };

      if(db.objectStoreNames.contains("tab2")) {
            db.deleteObjectStore("tab2");
        }

        var storeColl2 = db.createObjectStore("tab2", {
            keyPath: "id", autoIncrement : true
        });
        storeColl2.createIndex("name2", "name2", { unique: true });
        storeColl2.createIndex("description2", "description2", { unique: false });

        storeColl2.transaction.oncomplete = function(event) {
            var collObjectStore2 = db.transaction("tab2", "readwrite").objectStore("tab2");
            collObjectStore2.add({name: "a2", description: "b2"});
            collObjectStore2.add({name: "c2", description: "d2"});
        };

    };

    request.onsuccess = function(e) {
        db = e.target.result;

    };

    request.onerror = function(){

    };

  };

open();

});

If i create only one store, data are added. But If i create two store, data are created only in second store.
Answer: Although storeColl references two different object stores, both calls to storeColl.transaction return the same transaction object - the "versionchange" transaction automatically created as part of the upgrade process. So when your code does:
storeColl.transaction.oncomplete = ...;

...

storeColl.transaction.oncomplete = ...;

The second assignment to oncomplete overwrites the first, and only the last handler assigned to oncomplete runs.
A simple fix would be to use storeColl.transaction.addEventListener('complete', ...); instead, since you can add multiple event listeners that way.
Answer: You do not need to wait for createObjectStore to complete. You can immediately store data using the event.target.transaction. This is not a recommended practice. However, here is an example:
function onUpgradeNeeded(event) {
  // ...

  // Create the object stores
  var db = event.target.result;
  var tab1Create = db.createObjectStore("tab1", {
    keyPath: "id", autoIncrement : true
  });

  var tab2Create = db.createObjectStore("tab2", {
    keyPath: "id", autoIncrement : true
  });

  // ...

  // Time to add some data:
  // Get a reference to the current transaction. The transaction
  // type is 'versionchange', which allows for 'readwrite' operations
  var transaction = event.target.transaction;

  // Access the object stores using the transaction and add objects
  var tab1 = transaction.objectStore('tab1');
  tab1.add({name: "a", description: "b"});
  tab1.add({name: "c", description: "d"});
  var tab2 = transaction.objectStore('tab2');
  tab2.add({name: "a2", description: "b2"});
  tab2.add({name: "c2", description: "d2"});
}

Comment: Yea, it works, if don't mind that i don't wait for complete?
Comment: You do not need to wait for createObjectStore to complete when inside the onupgradeneeded function, because the function is synchronous (it starts executing immediately and later statements wait to start until it finishes).


R Qualtrics API in Parallel?

Question: I am pulling data from qualtrics using the qualtRics package and I need the data in two forms, one with the breakout_sets option set to TRUE and another version where it is set to FALSE. Is there a way to potentially ping these two versions in parallel to make this process go faster?
library(qualtRics)

qualtrics_api_credentials(api_key = "API KEY",base_url = "url",install = TRUE,overwrite=TRUE)

split_qualtrics <- fetch_survey(surveyID = SURVEYID,
                                unanswer_recode     = -99,
                                unanswer_recode_multi = 0,
                                breakout_sets = TRUE,
                                label = TRUE,
                                force_request = TRUE,
                                verbose = FALSE)

nonsplit_qualitrics <- fetch_survey(surveyID = SURVEYID,
                                       unanswer_recode = -99,
                                       unanswer_recode_multi = 0,
                                       breakout_sets = FALSE,
                                       label = TRUE,
                                       force_request = TRUE,
                                       verbose = FALSE)

Answer: You can use the "parallel" assignment operator %<-% of the future package.  For example,
library(qualtRics)

library(future)                  # parallel assignment operator %<-%
plan(multisession, workers = 2L) # increase for more parallel workers

qualtrics_api_credentials(api_key = "API KEY",base_url = "url",install = TRUE,overwrite=TRUE)

split_qualtrics %<-% fetch_survey(surveyID = SURVEYID,
                                  unanswer_recode     = -99,
                                  unanswer_recode_multi = 0,
                                  breakout_sets = TRUE,
                                  label = TRUE,
                                  force_request = TRUE,
                                  verbose = FALSE)

nonsplit_qualitrics %<-% fetch_survey(surveyID = SURVEYID,
                                      unanswer_recode = -99,
                                      unanswer_recode_multi = 0,
                                      breakout_sets = FALSE,
                                      label = TRUE,
                                      force_request = TRUE,
                                      verbose = FALSE)

This will cause the two function calls to run in parallel at the same time.  The moment you "touch" split_qualtrics, e.g. try to print its value, your R prompt will block until split_qualtrics is available (nonsplit_qualitrics keeps running in the background).  Same rule applies to nonsplit_qualitrics.  So, if you do a lot of these, they will all run in the background.

R Qualtrics API in Parallel?


How to find the number of clusters when more than one datasets are aggregated as one?

Question: Suppose 3 datasets has 3 ,7, 4 clusters in their respective dataset.
When I aggregated them as one dataset what's the safest number of cluster to choose as perimeter for kmeans or any supervised clustering?
Already tried by considering average(3,7,4) but not giving me near to good solution as the dataset can vary with dimensions, number of samples etc.
Answer: It depends on the degree of overlap between the clusters across datasets.
For example, imagine data points fall within the clusters below, which are colored according to the dataset: red for dataset 1 (3 clusters), green for dataset 2 (7 clusters), blue for dataset 3 (4 clusters). The clusters might be completely disjoint (left plot), giving the maximum of 14 clusters in the aggregated data. At the opposite extreme (middle plot), the clusters might overlap such that they merge into a single cluster in the aggregated data. Or, there might be partial overlap (right plot), yielding some intermediate number of clusters in the aggregated data.

So, assuming the initial clusters are all correctly identified, the aggregated data could contain anywhere between a single cluster and 14 clusters (the total number of initial clusters). The number can't be narrowed down beyond that without further assumptions.
Comment: I don't think one can realistically expect to identify the number of clusters for the aggregate dataset based only on the number of clusters in the original datasets. Some additional analysis/modeling would be needed, looking at the actual structure of the clusters and/or data.
Comment: What kind of assumptions can help or be considered to reduce the number of clusters rather than considering the max i.e 14 in the above example?
Comment: @ShihabUllah As an example, suppose the clusters present in each dataset were sampled from a global set of well-separated clusters. In this case, clusters wouldn't 'blur' together (as in the middle plot) when the datasets are aggregated. So, the minimum number of clusters would be 7. This is is different than reducing the maxium number of clusters as you asked about, but it's an example of an assumption that would narrow down the range of possibilities (from 1-14 to 7-14).
Answer: @user20160's response is correct. You really have no way of knowing the number of clusters the combination will create, because you don't know how those clusters might overlap. I suppose you could try to estimate it by calculating cluster overlap somehow before merging the datasets, but that might be complicated depending on the dimensionality of your data. Alternatively, you could try to answer the question "How many clusters are in this dataset?" using a different clustering algorithm.
Centroid-based clustering algorithms like k-means are generally not the tool for this task.* If your datasets are large, you might consider a density-based algorithm such as DBSCAN or HDBSCAN. If it is quite small (<100), hierarchical clustering might be all you need.
Both of those have their own drawbacks/nuances†, but I believe they would both be more useful to you in trying to solve this problem.
I suppose if you needed to, you could use those algorithms to inform your choice of a value of $k$ to then use in k-means, but I don't exactly know what the implications of that would be, or how useful the result would be beyond the output of the first algorithm.
*If you are set on k-means, I suppose you could analyze all possible values of $k [1, x]$ where $x = \sum(k_i)$ for all of your datasets $i$, but I think you might benefit from other methods.
 †Density-based approaches generally require hyperparameter tuning, hierarchical clustering requires you to choose a linkage function and set a cutoff point for pruning the dendrogram


Alinhar dados tbody com theady

Question: Tenho dados consumidos por uma API para popular uma table no html, eles estão vindos OK, mas não estou conseguindo fazer o alinhamento entre o theady e o tbody que populo em tempo de execução, vocês poderiam me ajudar?
Ela está ficando assim na tela:

Segue baixo codigos:

                    Username
                    Name
                    E-mail
                    City

                    Albums

Answer: São dois os motivos que geram o seu problema.
Primeiro motivo é que para cada  criada você está perdendo a sua referencia. Quando faz:
var username = document.createElement('td').innerHtml = line.username;

É o mesmo que fazer:
var username = document.createElement('td').innerHtml;
username = line.username;

Ou seja a variável username não chega a referenciar a  recém criada, username recebe o valor da propriedade .innerHtml e logo em seguida passa a referenciar a string line.username e isso se repete em username, name , email, city e tdAlbums. Implicando que ao fazer:
tr.append(username, name, email, city, tdAlbums);

Ao de adicionar cinco  você está adicionando na primeira célula uma string formada pelas strings username, name , email, city e tdAlbums.
O segundo problema se dá ao consertar o primeiro:
var username = document.createElement('td');
username.innerHtml = line.username;

Ao setar a propriedade username.innerHtml você esta trocando o conteúdo do elemento por uma string e novamente isso se repete para username, name , email, city e tdAlbums e novamente ao fazer:
tr.append(username, name, email, city, tdAlbums);

Você não estará adicionando cinco  a
 mas estará adicionando mais uma vez na primeira célula uma string formada pelas strings username, name , email, city e tdAlbums.
Para concertar seu código basta atribuir as variáveis suas devidas referências:
var username = document.createElement('td');
var name = document.createElement('td');
var email = document.createElement('td');
var city = document.createElement('td');
var tdAlbums = document.createElement('td').

E então use a propriedade innerText ao invés de innerHtml:
username.innerText = line.username;
name.innerText = line.name;
email.innerText = line.email;
city.innerText = line.address.city;
tdAlbums.innerHtml = albumCount;

Ou no seu código:

var vUsers = [];
var vAlbums = [];
var length;

$(document).ready(function() {
  $.ajax({
    url: 'https://jsonplaceholder.typicode.com/users',
    async: false,
    success: function(data1) {
      vUsers = data1;
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert(thrownError);

      return false;
    }
  });

  $.ajax({
    url: 'https://jsonplaceholder.typicode.com/photos',
    async: false,
    success: function(data2) {
      vAlbums = data2;
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert(thrownError);

      return false;
    }
  });

  var table = document.getElementById('table');

  function contaAlbums(lineId) {
    length = 0;

    vAlbums.forEach(function(album) {
      if (album.userId == lineId) {
        length++;
      }
    });

    return length;
  };

  vUsers.forEach((line) => {
    var lineId = line.id;
    var albumCount = contaAlbums(lineId);

    var tr = document.createElement('tr');

    var username = document.createElement('td');
    var name = document.createElement('td');
    var email = document.createElement('td');
    var city = document.createElement('td');
    var tdAlbums = document.createElement('td');

    username.innerText = line.username;
    name.innerText = line.name;
    email.innerText = line.email;
    city.innerText = line.address.city;
    tdAlbums.innerText = albumCount;

    tr.append(username, name, email, city, tdAlbums);
    table.append(tr);
  });
});

      Username
      Name
      E-mail
      City
      Albums

Comment: Bom dia Augusto, tudo bem? Cara funcionou perfeitamente a parte da table, mas ainda continuo com o mesmo problema do contador na função contaAlbums() e me surgiu um novo problema agora também, se você perceber, coloquei no AJAX async: false por causa das variaveis globais que preciso tratar fora do AJAX, mas está demorando demais, existe uma outra forma de PEGAR essas variaveis fora do AJAX sem que tenha que usar o ASYNC?
Comment: O JQuery Ajax tem a opção [`async: false`](https://api.jquery.com/jquery.ajax/) para o caso de precisar fazer requisição síncronas. Dê uma olhada no [Axios](https://github.com/axios/axios) e mais fácil de usar que *$Ajax*.
Comment: Quanto ao contador eu nem analisei o restante do código eu me foquei no que estava na pergunta que era sobre alinhamento da tabela.
Comment: Olhando os dados por cima, acredito que se pegar o `username` e contar quantas ocorrência  surjam na lista será a quantidade de álbuns.
Comment: Augusto desculpe a ignorancia de não saber sobre o Axios, mas to sem tempo de estudar, preciso entregar isso até o fim da tarde de hoje to sem tempo. Quanto ao contador estava passando o indice errado no IF dentro da função.
Agora preciso resolver esse problema mesmo do ASYNC do AJAX
Comment: Entendi, não e melhor abrir outra pergunta específica sobre o contador pois o escopo dessa pergunta aqui é formatação de tabela e o formato do site não permite essa mudança de escopo numa pergunta depois de respondida.
Comment: Sim é verdade Augusto, vou abrir, muito obrigado pela ajuda.
Answer: Assim como você utilizou o .append() para colocar elementos no tr, você pode utilizá-lo para colocar o texto nos elementos td que o resultado sairá correto. Por exemplo:
var name = document.createElement('td');
name.append(line.name);

E o resultado:

Alinhar dados tbody com theady


HP MSA2000 SAN configuration concerns - setup critique (msa2324sa)

Question: I'm working on a project with a client who recently had a large system replacement for a dedicated ERP application. I'm inheriting this hardware setup and want to understand what it means.
The server is a ProLiant DL580 G7 (4 x 8-core CPUs, 64GB RAM). The customer has a set of ~500GB of data that historically grows 1-2% per year. The system has plenty of onboard storage in the form of 8 x 300GB 6G SAS internal disks. The server is connected to an MSA2324sa SAS-attached SAN unit, fully populated with 24 x 146GB disks. This SAN has two SAS controllers and the server has two HBAs, each connected via SFF8088 cable to one port on each controller. This is the only server connected to the SAN.
While this is fine and appears to be a standard cabling setup, the confusion comes in the presentation to the OS. The server is running RHEL 5.7. Once I gained access to the system, I noticed the following df and fdisk output:
Here's a pastebin of the lvdisplay, vgdisplay and pvdisplay output.

This seems odd to me. Unfortunately, I can't find any information to confirm the validity of this setup. Most of my experience has been with Smart Array controllers and "dumb" JBOD expansion units, but I tend to use HP's facilities to carve LUNs and manage volumes.
Looking at this setup, why was it necessary to use LVM striping? Is this uncommon? Does it have more to do with the multiple SAS connections to the server? The vdisk/volume arrangement of the MSA seems like it would provide the necessary flexibility. As-is, it seems like this SAN has no room for additional servers or provisions for spare disks, etc.
I just want to check with engineers who are more familiar with these deployments. Is there anything wrong with this setup?
Comment: I was not aware of that 16-drive limit. Does that mean that the only way to leverage that amount of space is to split things up and use software RAID? Does that 16-drive limit depend on RAID level?
Comment: Thank you. Do you think there's a performance implication with the above setup? Would it have made more sense to just use a JBOD enclosure like an HP D2700, since this SAN is basically being used a direct-attached storage?
Comment: Moved; and now it looks like you talk to yourself. =]
Comment: URGHH... SAN→ Storage Area Network. It does not mean a Storage Subsystem. (pet peeve of mine)
Comment: Hmm? I'm not sure what the issue is?
Comment: @MikeyB, The MSA2000sa is capable of distributing shared or dedicated storage to several host systems. It's certainly not just a JBOD or similar enclosure.
Answer: The MSA2000 can only put 16 disks in most array types, hence two arrays software striped. The 16 drive limit is on all arrays except RAID50 and 60 (which is 32 drives); this is for G2 units (ref: hpcollateral.com/Files/… [end of page 15]) and G3 units might be different (I haven't had the pleasure yet). You could still use a hardware RAID HBA on the MSA's logical drives to present a single drive to the OS too.
I wouldn't think there would be much, if any performance penalty. However I would be concerned that if one cable fails the array goes down (I'm not sure of this, but suspect so). The D2700 probably would have been quite a bit cheaper to begin with, but I doubt you'd see enough performance change to justify it now.
Take all this with the caveat that I have not used a MSA2000sa, only the "i" (iSCSI, have this inhouse) and "fc" (Fibre Channel, customer site). The "sa" units are somewhat rare as the connection medium is quite limiting.
Comment: Ever find this update ? We just acquired another MSA2000sa and just hit the 16drive limit using the latest published firmware. Short of a new firmware we will be using LVM to stripe 2 volumes.
Comment: Oh Also one cable failure should not effect access to either volume. There are two controllers in the MSA A and B, if either controller is lost (or the path to the controller) the other one will take over the vdisks it was responsible for. (Assuming your running multipath on Linux) try multipath -l from some informative output.
Comment: I've never seen an update that changes the aforementioned limits (16 drives in R10 or R5/6; and 32 drives for R50/60). The G2 hasn't got much attention since the G3 series came out. Using more than 16 drives in a R10/5/6 setup is highly inadvisable as the risk of dataloss during rebuild is quite high.
Comment: I spoke with an HP technician who said that a firmware update made it possible to allocate more than 16 physical drives in a single vDisk. He was unable to point me to the specific update that included this functionality, but he insisted that the feature is available.
Comment: @ChrisS The client never took my recommendation. Today, I'm seeing `mptscsih: ioc0: attempting task abort! (sc=ffff8101a159a0c0)
sd 1:0:0:2:` messages on one of the SAS paths to the array. @StevenWilliamson, I checked `multipath -l` and there's no output. I don't think there's any multipath.


How to find the inverse modulo $m$?

Question: For example:
$$7x \equiv 1 \pmod{31} $$
In this example, the modular inverse of $7$ with respect to $31$ is $9$. How can we find out that $9$? What are the steps that I need to do?
Update
If I have a general modulo equation:
$$5x + 1 \equiv 2 \pmod{6}$$
What is the fastest way to solve it? My initial thought was:
$$5x + 1 \equiv 2 \pmod{6}$$
$$\Leftrightarrow 5x + 1 - 1\equiv 2 - 1 \pmod{6}$$
$$\Leftrightarrow 5x \equiv 1 \pmod{6}$$
Then solve for the inverse of $5$ modulo 6. Is it a right approach?
Thanks.
Answer:
One method is simply the extended Euclidean algorithm:
\begin{align*}
31 &= 4(7) + 3\\\
7 &= 2(3) + 1.
\end{align*}
So $ 1 = 7 - 2(3) = 7 - 2(31 - 4(7)) = 9(7) - 2(31)$. Viewing the equation $1 = 9(7) -2(31)$ modulo $31$ gives $ 1 \equiv 9(7)\pmod{31}$, so the multiplicative inverse of $7$ modulo $31$ is $9$. This works in any situation where you want to find the multiplicative inverse of $a$ modulo $m$, provided of course that such a thing exists (i.e., $\gcd(a,m) = 1$). The Euclidean Algorithm gives you a constructive way of finding $r$ and $s$ such that $ar+ms = \gcd(a,m)$, but if you manage to find $r$ and $s$ some other way, that will do it too. As soon as you have $ar+ms=1$, that means that $r$ is the modular inverse of $a$ modulo $m$, since the equation immediately yields $ar\equiv 1 \pmod{m}$.

Another method is to play with fractions Gauss's method:
$$\frac{1}{7} = \frac{1\times 5}{7\times 5} = \frac{5}{35} = \frac{5}{4} = \frac{5\times 8}{4\times 8} = \frac{40}{32} = \frac{9}{1}.$$
Here, you reduce modulo $31$ where appropriate, and the only thing to be careful of is that you should only multiply and divide by things relatively prime to the modulus. Here, since $31$ is prime, this is easy. At each step, I just multiplied by the smallest number that would yield a reduction; so first I multiplied by $5$ because that's the smallest multiple of $7$ that is larger than $32$, and later I multiplied by $8$ because it was the smallest multiple of $4$ that is larger than $32$.  Added: As Bill notes, the method may fail for composite moduli.

Both of the above methods work for general modulus, not just for a prime modulus (though Method 2 may fail in that situation); of course, you can only find multiplicative inverses if the number is relatively prime to the modulus.
Update. Yes, your method for general linear congruences is the standard one.  We have a very straightforward method for solving congruences of the form $$ax \equiv b\pmod{m},$$
namely, it has solutions if and only if $\gcd(a,m)|b$, in which case it has exactly $\gcd(a,m)$ solutions modulo $m$.
To solve such equations, you first consider the case with $\gcd(a,m)=1$, in which case $ax\equiv b\pmod{m}$ is solved either by finding the multiplicative inverse of $a$ modulo $m$, or as I did in method $2$ above looking at $\frac{b}{a}$.
Once you know how to solve them in the case where $\gcd(a,m)=1$, you can take the general case of $\gcd(a,m) = d$, and from
$$ax\equiv b\pmod{m}$$
go to
$$\frac{a}{d}x \equiv \frac{b}{d}\pmod{\frac{m}{d}},$$
to get the unique solution $\mathbf{x}_0$. Once you have that unique solution, you get all solutions to the original congruence by considering
$$\mathbf{x}_0,\quad \mathbf{x}_0 + \frac{m}{d},\quad \mathbf{x}_0 + \frac{2m}{d},\quad\ldots, \mathbf{x}_0 + \frac{(d-1)m}{d}.$$
Comment: @Chan: Your definition of "a lot of work" needs revising, if you plan on studying more number theory and maths. The above is surprising *little* work, in my estimation...
Comment: @Arturo Magidin: Thanks, it's a lot of work :(. I thought it's just a simple calculation.
Comment: @Arturo Magidin: Thanks for the advice. However, I have many other things that I want to study. I like Number Theory, but also Geometry, Computer Graphics, Algorithm, C++, Ruby, Compiler, AI..., plus my school classes. I wish a day could have 48 hours.
Comment: the euclidean algorithm is simple and easily programed...
Comment: @Chan: Just for your information: the Euclidean Algorithm is considered a *very fast* algorithm; certainly faster than factoring and many other calculations that one often needs to do. In fact, many factoring algorithms work by making educated guesses and then computing gcds by using the Euclidean Algorithm in the hope of getting a nontrivial factor that way, precisely because the Euclidean Algorithm is so efficient.
Comment: @user314 Please tell how your algorithm computes $\,1/7\pmod{30}\ \ $
Comment: @user314 And what *algorithm* did you use? Where did $13$ come from? You simply pulled the inverse out of a hat, like magic!
Comment: @Chan: Trust me, you aren't the only one making that wish. But I really don't know what it is you think that the above methods are "a lot of work". Even the Euclidean algorithm method works, in this case, in two simple steps. Did you hope that just a sum and a product would do it every time?
Comment: @Arturo: It should be emphasized that the "play with fractions" method may fail for composite moduli. See the link to "Gauss's method" in my answer.
Comment: @user314 The point is that if you apply what I call [Gauss's algorithm](http://math.stackexchange.com/a/174687/242) for non-prime moduli then it may fail due to occurrence of non-invertible denominators, and there may be no way to workaround that. You can find many worked examples in [my posts.](http://www.google.com/search?q=site:math.stackexchange.com+dubuque+%22gauss%27s+algorithm%22) Note: the name "Gauss's algorithm", and its *fractional* interpretation are due to me.
Comment: @user314 Arturo and I refer to a *specific algorithm* that I extracted out of a proof *Disq. Arith*. We are not referring to *arbitrary* modular manipulation of fractions. Said algorithm may or may not succeed in computing inverses wrt composite moduli. Follow the links to learn more.
Comment: @user314 The method I attribute to Gauss is a (deterministic) *algorithm*. There are indeed plenty of (non-algorithmic) ways to "fiddle" with fractions to compute inverses etc (see my posts for many examples). But these are not *algorithms*. My comment to Arturo refers to the specific *algorithm* that I named after Gauss (which Arturo learned from me here or on sci.math).
Comment: @ArturoMagidin Good exposition. Maybe you could complete your part one mentioning, for the OP, the Extended Euclidean Algorithm which provides a brainless (and deterministic) process to get the coefficients of a Bezout relation.
Comment: @Arturo Magidin: Yes, I thought exactly like you said, because in the book that I read, it does not show step by step. It just jumps right to the answer.
Comment: @Arturo Magidin: Thanks, I really didn't know the the Euclidean Algorithm was that fast. I will practice it more. By the way, could you take a look at my update?
Comment: @Arturo Magidin: Thank you very much for your update answer. I really appreciate it.
Comment: @Bill: Thanks for the heads-up.
Comment: @BillDubuque You said the method "may fail with composite moduli", but OP explicitly said that "the only thing to be _careful_ of is that you should only multiply and divide by things _relatively prime to the modulus_". It was clearly emphasized. If you follow what he said, you'll never have any problems with composite moduli.
Comment: @BillDubuque I'm repeating: he clearly emphasized that "_you should only multiply and divide by things relatively prime to the modulus_". If you do that, the method will never fail for composite moduli. You were wrong in saying that the exact method described by Arturo (method 2.) may fail.
Comment: @BillDubuque All we need (to use the method) is two facts: 1) $\frac{1}{b}\equiv \frac{c}{bc}\pmod m$ whenever $(b,m)=1, (c,m)=1$; 2) $b\equiv d\pmod m\implies \frac{1}{b}\equiv\frac{1}{d}\pmod m$ whenever $(b,m)=1$. I can prove them if you wish. None of them require $m$ being composite and they are the only ones used in the method.
Comment: @BillDubuque And I can also prove that the method can always produce the actual inverse: $b^{-1}\mod m$ is defined (where $(b,m)=1$), and so I can always find a number $a=b^{-1}\mod m$ such that $\frac{1}{b}\equiv\frac{a}{ba}\equiv a\pmod m$ (we know that $(a,m)=1$).
Comment: @BillDubuque $\frac{1}{7}\equiv\frac{1\cdot 13}{7\cdot 13}\equiv \frac{13}{91}\equiv \frac{13}{1}\equiv 13\pmod {30}$.
Comment: @BillDubuque I didn't read that the method requires you to multiply by a number that makes the reduction as minimal as possible. Though you can still do this using the actual method: $\frac{1}{7}\equiv\frac{7}{49}\equiv\frac{7}{19}\equiv\frac{49}{133}\equiv\frac{19}{13}\equiv\frac{133}{91}\equiv\frac{13}{1}\equiv 13\pmod{30}$.
Comment: This might be outdated, but thanks for this amazing comment. This method will save me a lot of time when finding multiplicative inverses. +1
Comment: In option 1, I am having difficulty making the jump from 7−2(31−4(7)) to 9(7)−2(31). I see it as 7-2(31)+8(7) -> 7+56, which is 63 or 1 in Mod(31), but that does not give me a multiplicative for 7 (7 continues to stand alone).  Can someone provide more details?
Comment: @SpacemanScott group the sevens together. You have $7+8(7)-2(31) = 7(1+8)-2(31)=7(9)-2(31)$. And then $1 = 7(9)-2(31) \equiv 7(9) \pmod{31}$, so $7$ times $9$ is $1$ modulo $31$.
Comment: @ArturoMagidin  Thanks. The 7 + 2*4(7) = 7(1)+7(8) = 7 (1+8) was what I didn't see.
Answer: We know that $(7,31) = 1$. So you can use the extended Euclidean  algorithm. In particular, you can find two integers $s,t$ such that $7s+31t = 1$. So $7s \equiv 1 \pmod {31}$.
Answer: A hint: Try to use Fermats Little theorem:
$a^{p-1}=1 \mod p$ for $p$ prime, and all $a\in \mathbb{Z}$.
Comment: [7^29 mod 31](http://www.wolframalpha.com/input/?i=7^29+mod+31) certainly works in this case, but for larger numbers it might be a bit of an effort compared with the Euclidean algorithm, and it would get more complicated by involving Euler's totient function for a non-prime modulus.
Comment: You can use binary exponentiation for high powers.
Answer: We can visualize the solution to $7x \equiv 1 \pmod{31}$ as the intersection of the two "lines"
$\ \ \ \ \ y \equiv 7x \pmod{31}$ and $y \equiv 1 \pmod{31}$.
The first line is closed under addition and subtraction, since it passes through the origin. If $(x_1, y_1)$ and $(x_2, y_2)$ are points on the line $y \equiv 7x \pmod{31}$, then so are $(x_1+x_2, y_1+y_2)$ and $(x_1-x_2, y_1-y_2)$.
To find a point where the lines intersect, we start with the two points $(1, 7)$ and $(0,31)$ on the first line, and repeatedly subtract one point from another until the $y$-coordinate is 1.
$\ \ \ \ \ (0,31) - (1,7) = (-1, 24)$
$\ \ \ \ \ (-1, 24) - (1,7) = (-2, 17)$
$\ \ \ \ \ (-2, 17) - (1, 7) = (-3, 10)$
$\ \ \ \ \ (-3, 10) - (1, 7) = (-4, 3)$
$\ \ \ \ \ (1,7) - (-4, 3) = (5, 4)$
$\ \ \ \ \ (5,4) - (-4, 3) = (9,1)$
Therefore, $x \equiv 9 \pmod{31}$.
You can speed up this procedure by subtracting a multiple of one point from another point instead. This leads to the Euclidean algorithm.
Answer: There are many methods available, e.g. the extended Euclidean algorithm, $ $ or a special case of Euclid's algorithm that computes inverses modulo primes that I call Gauss's algorithm. $ $
The calculations are usually simpler using modular fraction arithmetic e.g.  see here, and here and here for circa $20$ motley worked examples via a handful of methods (and see the sidebar "Linked" questions lists there for many more).

Update $ $ March $16, 2020\!:\,$ for completeness we apply some of the linked methods below.

$\!\!\bmod 31\!:\,\ \dfrac{1}{7}\equiv \dfrac{4}{28}\equiv\dfrac{-27}{-3}\equiv 9\  $ by Gauss's algorithm.

$\!\!\bmod 31\!:\,\ \dfrac{1}{7}\equiv \dfrac{1}{-6}\,\dfrac{1}{4}\equiv \dfrac{-30}{-6}\,\dfrac{32}{4}\equiv 5\cdot 8\equiv 9$

As here: $ $ the freedom to choose  $\rm\color{#c00}{even}$ residue reps $\!\bmod\!$ odds makes division by 2 easy:
$\!\!\bmod 31\!:\,\ \dfrac{1}{7}\equiv\dfrac{\color{#c00}{32}}{\color{#c00}{-24}}\equiv\dfrac{4}{-3}\equiv\dfrac{-27}{-3}\equiv 9$

By the fractional extended Euclidean algorithm, or associated equational form
$ \begin{align}  \bmod 31\!:\ \  \dfrac{0}{31}\overset{\large\frown}\equiv\color{#c00}{\dfrac{1}7}\ \, &\!\!\!\overset{\large\frown}\equiv\color{#0a0}{\dfrac{-4}3}\overset{\large\frown}\equiv\color{#90f}{\dfrac{9}1}\\[.7em]
 \text{said equationally}\ \ \ \
 [\![1]\!]\ \ \ \   31\, x&\,\equiv \ 0\    \\
[\![2]\!] \ \ \ \ \ \    \color{#c00}{7\,x}&\ \color{#c00}{ \equiv\ 1}\!\!\!\\
[\![1]\!]-4\,[\![2]\!] \rightarrow [\![3]\!]\ \ \ \ \ \ \color{#0a0}{3\,x} &\ \color{#0a0}{\equiv\ {-}4}\   \\
[\![2]\!] -  2\,[\![3]\!] \rightarrow [\![4]\!]\, \ \ \ \ \ \ \ \   \color{#90f}{x}&\ \color{#90f}{ \equiv\ 9}
\end{align}$

Below we explain the basic idea behind the method of Inverse Reciprocity.
$\!\!\bmod 31\!:\,\ n \equiv \dfrac{1}7\equiv \dfrac{1+31\color{#c00}k}7.\ $ For an exact quotient we seek $\,k\,$ with $\,7\mid 1\!+\!31k,\,$ i.e.
$\!\!\bmod 7\!:\,\ \begin{align}0&\equiv 1\!+\!31k\\ &\equiv 1 + 3k\end{align}\!$ $\iff\! \begin{align}3k&\equiv-1\\ &\equiv\,\ 6\end{align}\!$ $\iff \color{#c00}{k\equiv 2},\ $ so $\ n \equiv \dfrac{1\!+\!31(\color{#c00}2)}7\equiv 9\pmod{\!31}$

Or $\rm\ (a,m)\!=\!1 \overset{\rm Euler\  \phi}\Longrightarrow\ a^{-1} \equiv a^{\phi(m)-1}\!\pmod{\! m},\,$ quickly computable by repeated squaring. It suffices to find any (small) period $\rm\,e,\,$ of $\rm\,a,\,$ i.e. $\rm\,e\,$ such that   $\rm\,a^{\large e}\equiv 1\,$ (e.g. by Euler's totient or Fermat's little theorem or Carmichael's lambda theorem), since this implies $\rm\,a^{-1}\equiv a^{e-1}$.
Remark $ $ The latter yields a simple closed form for CRT (Chinese Remainder Theorem)
$\quad$ if $\rm\,\ (m,n)\!=\!1\,\ $ then $\rm\quad \begin{eqnarray}\rm x\!&\equiv&\rm a\ \ (mod\ m)\\ \rm x\!&\equiv&\rm b\ \ (mod\ n)\end{eqnarray} \iff\ x\equiv a\,n^{\phi(m)}\!+b\,m^{\phi(n)}\ \ (mod\ mn)$
More generally see the Peirce decomposition.
Comment: @BillDubuque can we invert if totient is unknown?
Comment: @777 Yes, see the other two methods I mentioned above.
Comment: @BillDubuque which ones? all seems to use factorization of $m$ or $\phi(m)$ and nothing avoids these.
Comment: @777 The extended Euclidean algorithm and Gauss's algorithm do not use factorization. Follow the links to learn these methods.
Comment: @BillDubuque so both these methods do not need factorization of $m$ or knowledge of $\phi(m)$. Then doesn't that help to get decryption key $d$ in RSA from encryption key $e$?
Comment: @777 If we know $\,\phi(n)\,$ (or a multiple) then it is fast. But no fast was of computing $\phi(n)\,$ is known.
Comment: @BillDubuque then what about 'can we invert if totient is unknown or factorization is unknown?'?
Comment: @777 The inverse depends on the modulus, e.g. $\!\bmod{\,2n\!-\!1}\!:\,\ 2^{-1}\equiv n\,$ by $\,2n\equiv 1\ \ $
Answer: An alternative way to solve would be to use the fast powering algorithm.
$a^{-1}≡a^{p-2} \mod p$ for $p$, $a\in \mathbb{Z}$.
$7^{-1} \mod 31 = 7^{29} \mod 31 ≡ 9 \mod 31$
According to An Introduction to Mathematical Cryptography by Hoffstein et al, in practice this is about the same time complexity as the extended Euclidean algorithm given in other answers.
Before using the fast powering algorithm I would first check to see if a and p are relatively prime, so that you know an inverse exists before performing the calculation.
Comment: Binary exponentiation
Answer: Solve $7x \equiv 1 \pmod{31}$.
$\quad 7x = 1 + 31y \implies 3y \equiv 6 \pmod{7} \implies y \equiv 2 \pmod{7}$
and
$\quad y : 2 \;  \mid \; 1 + 31y = 63 \quad \quad \text{AND is divisible by } 7$
So,
$\tag{ANS} 7^{-1} \equiv 9 \pmod{31}$

Here is another more interesting example:
Solve $25x \equiv 1 \pmod{41}$.
$\quad 25x = 1 + 41y \implies y \equiv 4 \pmod{5}$
and
$\quad y : \;\,4 \;  \mid \; 1 + 41y = 165 \quad \quad \text{NO GOOD!}$
$\quad y : \;\,9 \;  \mid \; 1 + 41y = 370 \quad \quad \text{NO GOOD!}$
$\quad y : 14 \;  \mid \; 1 + 41y = 575 \quad \quad \text{AND is divisible by } 25$
So,
$\tag{ANS} 25^{-1} \equiv 23 \pmod{41}$

Here is another more interesting example:
Solve $23x \equiv 1 \pmod{41}$.
$\quad 23x = 1 + 41y \implies 18y \equiv 22 \pmod{23} \implies 9y \equiv 11 \pmod{23}$
Sub Solve: $9y \equiv 11 \pmod{23}$.
$\quad 9y = 11 + 23z \implies 2z \equiv 1 \pmod{3} \implies z \equiv 2 \pmod{3}$
and
$\quad z : \;\,2 \;  \mid \; 11 + 23z = 057 \quad \quad \text{NO GOOD!}$
$\quad z : \;\,5 \;  \mid \; 11 + 23z = 126 \quad \quad \text{AND is divisible by } 9$
So,
$\quad 9y \equiv 11 \pmod{23} \text{ iff } y \equiv 14 \pmod{23}$
Continuing where we left off with the original problem,
$\quad y : \;\,14 \;  \mid \; 1 + 41y = 575 \quad \quad \text{AND is divisible by } 23$
So,
$\tag{ANS} 23^{-1} \equiv 25 \pmod{41}$
Comment: Thank you. How you come up with $3y \equiv 6 \pmod{7}$ in $\quad 7x = 1 + 31y \implies 3y \equiv 6 \pmod{7} \implies y \equiv 2 \pmod{7}$?
Comment: If $7x=1+31y$ then $0 \equiv 1 + 31y \pmod7$ then $31y \equiv -1 \pmod7$ then $\big[(4\cdot7 +3)y \equiv 6 - (1\cdot7) \big]\pmod7$ then $3y \equiv 6 \pmod7$.
Answer: The Arithmetical Progression f(n) = a + (n-1)d has only a finite number of terms for any modulus d and where a is the "initial" value, f(1), even when n is allowed to range over ℤ, so no holds barred trying negative values to quickly reach a coefficient of 1 or a -1.
In this example all moduli are to 31, starting from coefficient 7 one possibility is:
<code>7x ≡ 1

⇒ -24x ≡ 32 (subtracting the modulus on the left and adding the modulus to the right)
⇒  -3x ≡ 4 (∵ gcd (12, 31) = 1)
⇒ -30x ≡ 40
⇒   1x ≡ 9
</code>
The above is an application of congruence article in the chapter on theory of numbers in Higher Algebra By H.S. Hall and S.R. Knight May 1887 (pdf probably available online).
Answer: $$7x\equiv 1\pmod{31}$$
We are seeking integer solutions of the equation,
$$7x+31y=1$$
Find a linear transformation $\begin{pmatrix}\cdot & \cdot \\ \cdot &\cdot\end{pmatrix}$ consisting of integer entries which maps the vector $\begin{pmatrix}7\\ 31\end{pmatrix}$ to some vector of the form $\begin{pmatrix}1\\ \cdot\end{pmatrix}$ or $\begin{pmatrix}\cdot\\ 1\end{pmatrix}$.
The identity transformation:
$$\begin{pmatrix} 1 & 0\\ 0 & 1\end{pmatrix}\begin{pmatrix} 7\\ 31\end{pmatrix} =\begin{pmatrix}7\\31\end{pmatrix}$$
Now apply successive elementary row operations on the augmented matrix until you get the desired form on the RHS.

$$\Longrightarrow \begin{pmatrix}
9 & -2\\
-4 & 1
\end{pmatrix}\begin{pmatrix}
7\\
31
\end{pmatrix} =\begin{pmatrix}
1\\
3
\end{pmatrix}$$
$$\Longrightarrow 7( 9) +31( -2) =1\\
\Longrightarrow x\equiv 9\pmod{31}$$
This is just a different perspective to the extended Euclidean algorithm. I think this is useful, if you want to code the algorithm :)
Ideally, if you are up for finding $x$, you would not calculate the values on the second column because those are of no use.
Comment: This *forward* form of the extended Euclidean algorithm was already [linked](https://math.stackexchange.com/a/85841/242) in my answer long ago (I show a simpler fractional version in my answer). [Here](https://math.stackexchange.com/a/616893/242) is a worked example.
Comment: @BillDubuque I did not see that. It is very detailed. Should I delete this post or let it be?

How to find the inverse modulo $m$?


Search only for the currently active language

Question: How can I restrict the results from a default search in Drupal 7, to bring only the nodes that are in the current language?
My website has a three language switcher; the user chooses what language he wants to use when viewing the site. If he searches something, the result page bring results from other languages. Today I have only 3 enabled languages, but we plan to expand this to 6 or more.
Answer: There's a really elegant way to do this using the apparently undocumented hook_query_node_access_alter():
function yourmodule_query_node_access_alter(QueryAlterableInterface $query) {
  $search = FALSE;
  $node = FALSE;

  // Even though we know the node alias is going to be "n", by checking for the
  // search_index table we make sure we're on the search page. Omitting this step will
  // break the default admin/content page.
  foreach ($query->getTables() as $alias => $table) {
    if ($table['table'] == 'search_index') {
      $search = $alias;
    }
    elseif ($table['table'] == 'node') {
      $node = $alias;
    }
  }

  // Make sure we're on the search page.
  if ($node && $search) {
    $db_and = db_and();
    // I guess you *could* use global $language here instead but this is safer.
    $language = i18n_language_interface();
    $lang = $language->language;

    $db_and->condition($node . '.language', $lang, '=');
    $query->condition($db_and);
  }
}

Note: this code is 100% based on the excellent Search Config module.
User's vs Content language
Some sites might have language detection configured to show the interface in the user's preferred language, while the page content is shown based on the URL or content language.
In that case, consider replacing
$language = i18n_language_interface();

with
$language = i18n_language_content();

Comment: Works perfect, but will it affect any query on site, like query generated from views module, or any based drupal query rather than the default "search/node/%" ?
Comment: @mohamadsalama this will affect all search queries that affect node access; in other words most views queries should be affected unless you specifically disable node access checks in the advanced settings (off the top of my head & unconfirmed).
Comment: This isn't an undocumented hook - it's actually the hook_query_TAG_alter() hook, where the tag is 'node_access'.  My own code also checks to make sure there isn't already a language condition in the query, but otherwise is quite similar.
Answer: I had the same requirements, and I used the Custom search module, which includes a submodule called Custom Search Internationalization : "search content from all or current language only, and all label and selectors translation handling" (note this module provides also several other helpful features like custom search blocks). Works perfectly.
Answer: You can use the global $language to know in which language you are.
In Views, you can filter using "content:language -> current user language."
Comment: how does this help? could you replace the search page with a node? does this have any drawbacks?
Answer: I don't sure search core support it.
I see the project i18nluceneapi but it doesnot support version 7 at the moment.
I'm using searchapi and create facets Language :). It can use for your case, create facets and default filter on search page.
Answer: You can use the Display suite module where you can choose the option View Mode->Language
which gives the search results in the current language that is in the current site language.


Showing KL divergence is $0$ iff two distributions are the equal almost everywhere

Question: It is clear that the KL-divergence $D_\text{KL}(P\parallel Q) = 0$ if $P = Q$ almost everywhere*, for two distributions $P$ and $Q$.
However, I don't know how to show the converse, i.e. that if $D_\text{KL}(P\parallel Q) = 0$, then the density functions are equal, i.e. $p(x) = q(x)$ $(P$-)almost everywhere. Since
$$D_\text{KL}(P\parallel Q) = \ln\frac{p(x)}{q(x)} p(x)\,dx $$
and $\ln \frac{p(x)}{q(x)}$ could take on any real value, isn't it possible that the integral could be zero by the cancellation of some negative and positive contributions of the integrand? What would be the correct approach to showing the converse statement?
*(and should this be "with respect to the distribution $P$"?)
Comment: I wonder what it means to say two distributions are equal almost everywhere. To say that their _densities_ are equal almost everywhere is what I suspect was intended.
Comment: Yes that is what I meant. Thanks!
Answer: Let $f(t)=-\ln t$. Then $f$ is strictly convex. We have $0=\int f(\frac {q(x)} {p(x)})p(x)\,dx \geq f(\int \frac {q(x)} {p(x)}p(x)\,dx)=f(1)=0$. Since equality holds in Jensen's inequality and $f$ is strictly convex it follows that $\frac {q(x)} {p(x)}$ is a constant, hence $=1$  almost everywhere. Hence $P=Q$.
Comment: Thanks! -- especially for the pointer to the iff conditions for equality in Jensen's inequality.


Factoring a quartic polynomial over the integers with roots that are not integers

Question: The quartic polynomial
$$
1728(x - 3) - x^2(12^2 - x^2)
$$
factors "nicely" as
$$
(x^2 - 12x + 72) (x^2 + 12x - 72) = (x^2 - 12x + 72)(x - 6\sqrt{3} + 6)(x + 6\sqrt{3} + 6) \, .
$$
(Note that $1728 = 3(24^2)$.)  How is this factorization obtained?
Answer: $$
\begin{align}
1728(x - 3) - x^2(12^2 - x^2) & = x^4 - 144 x^2 + 1728 x - 5184 \\
 & = x^4 - 12^2 x^2 + 12 \cdot 12^2 x - 36 \cdot 12^2 \\
 & = x^4 - 12^2(x^2 - 2 \cdot 6 \,x + 6^2) = \\
 & = x^4 - 12^2(x-6)^2 = \\
 & = \big(x^2 - 12(x-6) \big)\big(x^2 + 12(x-6)\big) = \cdots
\end{align}
$$
Comment: @AgalnamedDesire `Would that allow a, b, c, and d to be evaluated` Yes, his comment uses the method of undetermined coefficients, and the equations you wrote down are correct. The next step is to eliminate $b,d$ between the three remaining equations, which gives a cubic in $a^2$ namely $a^6 - 2\cdot 12^2 a^4+2 \cdot 12^4 a^2 - 12^6=0\,$ with the (somewhat) obvious root $a^2=12^2$ i.e. $a=\pm 12$.
Comment: Thanks for providing a clear explanation, again.
Comment: Another member offered an explanation.  I think that she used the factorization of the given quartic polynomial into a product of two quadratic polynomials that I provided in the post.  When I asked her how she would get that factorization, she said to take compare the coefficients in the product (x^{2} + ax + b)(x^{2} + cx + d) with the coefficients in the given quartic polynomial.  Would that allow $a$, $b$, $c$, and $d$ to be evaluated?
Answer: We have
$$
(x^2-12x+72)(x^2+12x-72)=x^4 - 144x^2 + 1728x - 5184=x^2(x^2-12^2)+1728(x-3),
$$
The factorization is of the form $(a^2+b)(a^2-b)=a^4-b^2$, with $a=x$ and $b=12x-72$.
Comment: I got $c = -a$, and so, $-a^{2} + b  + d = -12^{2}$, $a(d - b) = 12^{3}$, and $bd = -3(12^{3})$.
Comment: How would you get the values of $a$, $b$, $c$, and $d$ from these equalities?
Comment: If I had not provided the factorization in the post and if I had only given the quartic polynomial $1728(x - 3) - x^2(12^2 - x^2)$ to be factored, what would you do?
Comment: I would multiply it out, then look for rational roots using the rational root test, and then write my polynomial as $(x^2+ax+b)(x^2+cx+d)$, compare coefficients - and obtain a positive result!
Comment: If you are saying that $x^{4} - 12^{2}x^{2} + 12^{3}x - 3(12^{3}) = (x^{2} + ax + b)(x^{2} + cx + d)$, ...
Answer: This solution was suggested by dxiv.
Solution
The given quartic polynomial factors into a product of two monic, quadratic polynomials:
\begin{equation*}
x^{4} - 144x^{2} + 1728x - 5184 = (x^{2} + ax + b)(x^{2} + cx + d) ;
\end{equation*}
\begin{equation*}
(x^{2} + ax + b)(x^{2} + cx + d) = x^{4} + (a + c)x^{3} + (ac + b + d)x^{2} + (ad + bc)x + bd .
\end{equation*}
Since $c = -a$,
\begin{equation*}
d - b = \dfrac{12^{3}}{a}
\qquad \text{and} \qquad
b + d = a^{2} - 12^{2}
.
\end{equation*}
So,
\begin{equation*}
b = \frac{1}{2a} \Bigl(-12^{3} - 12^{2}a + a^{3} \Bigr)
\qquad \text{and} \qquad
d = \frac{1}{2a} \Bigl( 12^{3} - 12^{2}a + a^{3} \Bigr) .
\end{equation*}
Moreover, since $bd = -5184 = -3(12^{3})$, and
\begin{equation*}
bd = \frac{1}{4a^{2}} \Bigl(a^{6} - 2(12^{2}) a^{4} + 12^{4} a^{2} - 12^{6}\Bigr) ,
\end{equation*}
\begin{equation*}
a^{6} - 2(12^{2}) a^{4} + 2(12^{4}) a^{2} - 12^{6} = 0 .
\end{equation*}
$\pm12$ are roots of this polynomial equation in the variable $a$. If $a = 12$, $b = -72$, $c = -12$, and $d = 72$; if $a = -12$, $b = 72$, $c = 12$, and $d = -72$. In either case,
\begin{align*}
&x^{4} - 144x^{2} + 1728x - 5184 \\
&\qquad = (x^{2} + 12x - 72)(x^{2} - 12x + 72) \\
&\qquad = \bigl(x - 6\sqrt{3} + 6\bigr)\bigl(x + 6\sqrt{3} + 6\bigr)(x^{2} - 12x + 72) .
\end{align*}


Why do some organs have multiple keyboards?

Question: I've seen very different organs: pipe organs, bubble organs, electric organs, steam organs and etc.
Why do some have one keyboard while others have two-three or even more?
Comment: The keyboards are called *manuals* in this context.
Answer: So you can play two, or three, or four different sounds at the same time. Like a split-keyboard on a synthesizer.
Note that many professional keyboard players have several keyboards on stage that they can play at the same time.
Regarding old-world pipe organs, there are many aspects of European churches that are meant to be grand, impressive, imposing, and awe-inspiring. The Catholic Church has gathered vast amounts of wealth in their history, and one of the uses of that wealth has been to gather and inspire congregations.
As music is an important part of worship, it has been part of the missions of churches throughout the centuries to provide high quality music (that continues to this day with modern instruments and technology). The peak of music production for a few hundred years was certainly the pipe organ.
As the technology evolved, churches wanted more pipes, more stops, and just basically more sound. Getting a whole orchestra and their instruments together was not easy. Finding a capable keyboard player and putting all the sounds of a full orchestra at their fingertips was less of a challenge.
As the number of pipes and stops grew, and as churches grew larger and had larger congregations, it became desirable to have bigger and bigger sounds from the organs. With multiple manuals (the organ term for keyboards), the organist can both create layers of sounds for richer textures, as well as switch between different sounds rapidly.
Multiple manuals add to the cost and weight. For smaller organs or even portable organs, multiple manuals are often too much of a liability. Pipe organs that are not going anywhere might as well have as many bells and whistles (literally!) as the church can afford, so having five manuals plus the pedals is justified.
Comment: This is certainly the main reason. But having to play a 1-manual-organ in one church I noticed another reason: sometimes your two hands will get in one another's way when playing on one manual while the piece was inteded to be played on two.
Comment: ...and then there's that the various divisions are specialised. The Choir division, for instance, is meant for relatively soft accompaniment, the Grand is meant to be full-voiced ( a _tutti_ sound), Récit or Solo are indeed for solos, Swell works with a pedal to vary the dynamics, and so forth.


Start playwright driver session but not incognito

Question: Currently i open a new browser session using the code below, but it always starts as incognito, can I start a new chromium session but not as incognito?:
from behave import *
from playwright.sync_api import sync_playwright
import time

class session_driver:
    driver = None

    def open_browser(self, url):
        playW_sync_instace = sync_playwright().start()
        global browser
        browser = playW_sync_instace.chromium.launch(headless=False)
        browser.new_context(record_video_dir="videos/",
        record_video_size={"width": 640, "height": 480})
        self.driver = browser.new_page()
        self.driver.goto(url)

Comment: If you want peristency, you can use chromium.launch_persistent_context, see here: https://playwright.dev/python/docs/api/class-browsertype#browser-type-launch-persistent-context This allows you to save the storage state (cookies, etc.) to the local disk and re-use it multiple times.
Answer: from playwright.sync_api import sync_playwright
import os
user_dir = '/tmp/playwright'

if not os.path.exists(user_dir):
  os.makedirs(user_dir)

with sync_playwright() as p:
  browser = p.chromium.launch_persistent_context(user_dir, headless=False)
  page = browser.new_page()
  page.goto('https://playwright.dev/python', wait_until='domcontentloaded')

Answer: This is what I have done in Typescript code base. But this would leverage the existing logged-in session, and it would not ask for fresh user login.
const userDataDir = 'C:/Users/yuv****dir/AppData/Local/Temp/tjwmm3m0.hmt';
context = await chromium.launchPersistentContext(userDataDir,{
headless: false,
args: [    ]
});
I hope this is like above only what is there in Python code.


classification of simply connected Riemann surfaces

Question: Where can I read a proof that every simply connected Riemann surface is isomorphic to the upper half plane, the complex plane, or the Riemann sphere?
Comment: What about any standard book on Riemann surfaces? For example, Forster's book?
Comment: Or even check the wikipedia page https://en.wikipedia.org/wiki/Uniformization_theorem for references, especially de Saint-Gervais.
Comment: http://touch-geometry.karazin.ua/list
Answer: You can read it in "Canadian Journal of Mathematics (Aug.1972)". I personally learned the proof from this paper, Uniformization of Riemann Surfaces.
They actually provide three methods of proof, and I found the first of these the easiest to follow. Its not too difficult to go through the proof in detail if you know a bit of topology and complex analysis. The idea is to construct a global analytic function by minimizing a Dirichlet integral. Then, by working out the properties of "flow lines" - on which the function has constant imaginary part - you can get a good idea of what the map looks like, and then show that it is either a mapping onto the Riemann sphere, the Riemann sphere with the origin removed (equiv to the complex plane) or the Riemann sphere with a line segment removed (equiv to the open unit disk).
The second method they provide relies on triangulating the surface. The proof constructs the mapping inductively on larger and larger sets of triangles, using the Riemann mapping theorem to construct maps and the Schwarz reflection principle to join them together.
They also provide a third method, based on sheaf cohomology, although I am not so familiar with this method. The idea is to construct geometric realizations of projective structures on the Riemann surface. However, it does not seem to be quite complete, and there are some unresolved problems posed at the end.
Comment: The paper in your link does not provide detailed proofs.
Comment: @Moishe Cohen If you are not satisfied, you can also read the book by J. Hubbard, Teichmuller theory and its applications.
Comment: I am not talking about myself (I know several proofs) but about your answer. It makes no sense to refer to a sketch when there are many places where a detailed proof is given.
Comment: I am sorry, sir.