Probability getting King

Question: Card is drawn without replacement from a deck. What is the probability that the 22nd card drawn is a king?
Attempt:
Let Case X represent a scenario where the first 21 cards contain X number of Kings.
Case 0: 48C21 * 4C1
Case 1: 4C1 * 48C20 * 3C1
Case 2: 4C2 * 48C19 * 2C1
Case 3: 4C3 * 48C18 * 1C1
No Restrictions: 52C22
Ans:  (Case 0+1+2+3) / No Restrictions
Is this right? Hmm
Comment: Maybe I'm misunderstanding, but why would this be different than the probability that the first card drawn is a king ($4/52 = 1/13$)?
Answer: Yes, you want
$$\dfrac{\binom{48}{21}\color{silver}{\binom{4}{0}}}{\binom{52}{21}}\dfrac{\binom{4}{1}}{\binom{31}{1}}+\dfrac{\binom{48}{20}\binom{4}{1}}{\binom{52}{21}}\dfrac{\binom{3}{1}}{\binom{31}{1}}+\dfrac{\binom{48}{19}\binom{4}{2}}{\binom{52}{21}}\dfrac{\binom{2}{1}}{\binom{31}{1}}+\dfrac{\binom{48}{18}\binom{4}{3}}{\binom{52}{21}}\dfrac{\binom{1}{1}}{\binom{31}{1}}= \dfrac{4}{52}$$
However, while correct, you are way overcomplicating this.
Any one of the fifty-two cards in the deck might be in twenty second place with equal probability, and there are four kings in the deck.
The probability is thus...
Comment: Oh yea! true. So its still 1/13
Comment: Hi why is it that i just cant do 52 choose 22. for the denominator
Comment: @RStyle As the 22nd place is *special*, you are choosing for two categories.  The first 21 and the 22nd (and the remainder go to the last 30).  $\binom{52}{21}\binom{31}{1}\color{silver}{\binom{30}{30}}$ counts the ways to divide a 52 items in three piles of 21, 1, and 30.
Comment: "As above, so below."  You count ways to select the first 21 cards and *then* the 22nd in the numerator, and so must do likewise for the denominator.  The distinction being that the numerator counts ways to do so to produce the favoured event.
Answer: As others have pointed out there is no need to overcomplicate this. Without any other knowledge (for example what cards have passed before), any card can be in the 22nd position and there are 4 cards that are Kings. So the probability is $4/52 = 1/13$
But let's try to do it your way. That is, define distinct cases where the first 21 cards have 0, 1, 2, 3, kings, and then (the 22nd card) a king is drawn.
My feeling is that you wanted to enumerate all possible draws for each case and then divide the sum of the number of draws with the all the possible ways you can draw 22 cards. (I don't really know what you had in mind, since you dive straight into some formulas. I am just making a guess based on the pattern of mistakes, and what seems intuitive to me.)
But if we want to count all possible ways to draw, we should be working with permutations of cards not combinations of cards. Of course the problem can be solved working with combinations as the accepted answer nicely shows. But thinking in combinations seems harder to me, and you seem to be confused as well by the choice of the denominator. So here's a solution looking at number of different draws, which means using permutations:
Case 0 Kings: (possible draws for 21 cards that are not Kings) $\times$ (possible draws for the 22nd card to be King).
$$_{48}P_{21} \cdot\space _{4}P_{1} = \frac{48!}{(48-21)!} \cdot\space 4 $$
This is very similar to your first formula, I am just using permutations instead of combinations to count all possible draws.
Case 1 King: (possible draws for 20 non-King cards and one King card) $\times$ (possible draws for the 22nd card to be King).
This is a bit trickier. Someone could say that the possible draws for 20 non-King cards and one King card are equal to the possible draws for one King card times the possible draws for 20 non-King cards, so $_{4}P_{1} \cdot\space _{48}P_{20}$ Then we just multiply with the possible draws to get a king at the 22nd card, resulting in a formula very similar to yours $_{4}P_{1} \cdot\space _{48}P_{20} \cdot\space _{3}P_{1}$ (again, we now have permutations instead of combinations)
But this is not correct. This assumes that the King in the 21 cards is in a specific position (say the first). We need to multiply this with the possible ways you can place one card in 21 cards or equivalently pick a card from 21 cards. This is just 21 choose 1. So the correct number of possible draws is:
$$_{4}P_{1} \cdot\space _{48}P_{20} \cdot\space _{21}C_{1} \cdot\space_{3}P_{1} = 4 \cdot\space \frac{48!}{(48-20)!} \cdot\space \binom{21}{1} \cdot\space 3$$
Similarly for the remaining two cases.
Case 2 Kings: (possible draws for 19 non-King cards and two King cards) $\times$ (possible draws for the 22nd card to be King).
$$_{4}P_{2} \cdot\space _{48}P_{19} \cdot\space _{21}C_{2} \cdot\space_{2}P_{1} = \frac{4!}{(4-2)!} \cdot\space \frac{48!}{(48-19)!} \cdot\space \binom{21}{2} \cdot\space 2$$
Case 3 Kings: (possible draws for 18 non-King cards and three King cards) $\times$ (possible draws for the 22nd card to be King).
$$_{4}P_{3} \cdot\space _{48}P_{18} \cdot\space _{21}C_{3} \cdot\space_{1}P_{1} = \frac{4!}{(4-3)!} \cdot\space \frac{48!}{(48-18)!} \cdot\space \binom{21}{3} \cdot\space 1$$
We sum all these numbers of draws and we divide them with the all ways we can draw 22 cards out of a deck of cards: $_{52}P_{22} = \frac{52!}{(52-22)!}$. The result is $\frac{1}{13}$
$$\frac{\frac{48!}{(48-21)!} \cdot 4 + 4 \cdot \frac{48!}{(48-20)!} \cdot \binom{21}{1} \cdot 3 + \frac{4!}{(4-2)!} \cdot \frac{48!}{(48-19)!} \cdot \binom{21}{2} \cdot 2 + \frac{4!}{(4-3)!} \cdot \frac{48!}{(48-18)!} \cdot \binom{21}{3} \cdot 1}{\frac{52!}{(52-22)!}} = \frac{1}{13}$$
Comment: Hello sir, you have some really wonderful answers in game theory. Do you mind if I ask you for some tips? For the next 2 hours 23 min I will be here. IRC chat. #algorithms channel. Thanks. You can join here if you feel like. https://webchat.quakenet.org/ (no registration required)
Comment: I will be grateful.

Probability getting King


2000 foot power line

Question: I have a large piece of property and want to run a 2000' powerline from the power company meter to the house. Ideally, I would like 120/240 service with at 200 amps.
I think the power company can give me 480v service at the meter. I'm considering using 600V step up/step down transformers and 1-1-1 alum wire to keep the budget within reason.
The power company is not willing to extend their primary line any closer but I do have the equipment to install my own underground service between the meter an the house.
Does this project seem possible? Thanks for any suggestions!
Comment: Generally better to have (and pay for) the power company extend their line, and locate the transformer closer to your house, since their connection is already high voltage, and they are in the business of moving power long distances.
Comment: @AKHomestead please [edit] your question to include this info. As you can see, it's vital to help keep the answers focused and on track. The more info, details & background you can give up front, the less time people have to spend guessing and suggesting things that are already out of the picture.
Comment: If you'll take the [tour], you'll note that this is a Question & Answer board, not a general discussion forum. This is a statement of a couple of facts. What, exactly, is your question? Please [edit] your question to clarify.
Comment: IIRC You get into a bunch of different rules above 1000V (used to be above 600V, but that's changed due to code revisions to allow for HV PV systems) and your wire shopping may still eliminate a lot of  "readily available" to have wire insulation above 600V.
Comment: See also https://diy.stackexchange.com/q/152378/18078 and https://diy.stackexchange.com/q/138169/18078 and https://diy.stackexchange.com/q/157675/18078 and https://diy.stackexchange.com/q/191642/18078
Comment: @Ecnerwal we were at the end of the line and no higher voltages were available.
Comment: Yes, if they refuse you're on your own. In many cases folks opt to "roll their own" and end up spending as much or more as the line extension (if PoCo is willing) would have cost.
Comment: You'd probably have to boost the voltage up to about 1.5kV (just a rough guess) to get the current low enough for 2000' of #2 to not suffer excessive voltage drop. A 50kVA transformer will probably cost you at least $2.5 - $3k (one on each side) ... how does that compare to the cost of the fat aluminum cables you'd need without the transformers ?
Comment: @brhans and add the cost of clearing the cable path, burying it and then reinstalling the plants and terrain back to satisfy the planning & environmental controls… Yes, we had to do that - makes the cable the cheap bit…
Comment: Thanks for the good info! Burying the line is not a problem for me since I have all the equipment. The power company is not willing to extend the primary line to me so I'm on my own. It sounds line the transformer route is my best bet.
Answer: 480V is problematic because it's 3-phase
Generally speaking, 480V comes as "3-phase" and is a commercial service with potentially more costs and fees, and demands on how you load it.  Especially if you are rural, the power company may have a problem with you heavily loading one of the three phases.  You need to talk with them about that.
Converting 3-phase to single phase evenly is very complicated and requires an intermediate conversion to DC - probably something you don't want to get into unless you're heavily into battery systems for extended grid-down operations.  (which frankly is an option: have a substantial solar system and half a Tesla Model S's used battery pack, 50 KWH for about $9000... and cut the cord!  Part of that is conservation, i.e. factoring the house's systems for off-grid power, not being wasteful.  Note the upside of "no outages and, no electric bill, ever".)
However, if the power company is simpatico with the way you'll load their 480V distribution, then I would say, crunch the numbers but consider forgetting the step-up to 600V. Carry it the distance at 480V.  After all, 480V gear is cheap commodity - I see it going by all the time on Craigslist.  600V is more bespoke, and that means having to search harder and spend more for transformers. Particularly a 480/600V transformer (a bog-standard 240/480--120/240V transformer could probably be set up in "boost mode", but the overcurrent protection on that would be super custom as the whole shebang needs to trip together) will be a tough find.  The upshot is, it's probably better to stay at 480V and "throw aluminum at it".  Then you will have a system any commercial electrician will instantly recognize.
Pole line may be cheaper
That kind of distance really screams "pole line".  Not least, you are freer to use higher voltages on a pole line.  A 2000' underground conduit is a daunting affair, and also at risk of wire theft.  Direct burial 2000' of wire is a huge exposure risk for a wire cut due to rock penetration and settling.  Just because there's so much of it.
A neat feature of pole line is you can step the voltage up to thousands of volts.  Now you are limited only by wire insulation, or not even that if using separate wires spaced correctly. Remember, you really want a lightning arrestor wire up top.
#1 aluminum is not realistic
I don't know what voltage drop calculator is telling you #1 wire is OK, but that is totally unworkable and verging on insane.  I get the impression that somebody didn't even bother doing a voltage drop calculation, and just "upsized the wire 1 size" - as if this covers all situations LOL.  No, you'd be in for 11-20% voltage drop if you did that.
If you aim to jumper the transformer "to compensate", it doesn't work that way. Voltage drop is not a constant figure; it varies based on the current in the cable at that instant.  So if you "cleverly" up-jumper the transformer to compensate for voltage drop at peak currents, then at low currents your voltage will be much too high.  I have a factory building full of burned out sodium lights because some genius did exactly that.
One should aim for sub-5%, 6% at the absolute outside at 100% load. Assuming you run 600V transmission, so 80A@600V, then 4/0 wire (much larger than #1) gives you 5.75% at 100% load and 4.6% at 80% load.
Assuming you run 480V, so 100A@480V, then 350 kcmil wire (3 sizes larger) gives you 5.99% at 100% load and 4.79% at 80% load.
That's as low as I'd go.
#1 is totally unrealistic. I don't know who came up with that idea. That would work for a service size of 50-60A tops, which was the classical service size for an all-gas home, but out of the question for a heavily electric home where the owner says "200A service".
By the way, you don't need three large conductors if you're doing transformers, only two.  I think running a ground wire is silly on a doubly isolated "2 transformers back to back" setup, but you should put in whatever size ground your AHJ makes you install.  For price reference:

3 wires 2000' of #4 ACSR overhead line = about $1800
2 wires 2000' of #1 = about $3000
2 wires 2000' of #4/0 = about $6000
2 wires 2000' of 350 kcmil = about $12,000

Remember, regular wires are only rated to 600V, so even if NEC has been revised to allow higher voltages, you can't use them unless the wires are rated for it.
Answer: We did this for a 3 phase connection.
We had two matched transformers made to increase the voltage to 1000V and then dropped it at the other end.
The transformers had multiple connections to go +/- some small percentages so we could deal with the voltage drop as this was for a wind turbine and the effects can be interesting. We were measuring and monitoring 3 phase power and phase angle and we also fitted a power factor correction unit but I don't think you will have to go that far.

2000 foot power line


Which destiny game to buy?

Question: I'm new to destiny, and I intend to purchase a copy for PlayStation 4.
I am aware that you can purchase Destiny, Destiny: The Taken King or a bundle of the two.
What are the advantages or disadvantages of choosing one over the other?
Comment: I don't think this should be closed.

The problem is destiny now comes in 2 bundles, with or without DLC and players may want a subjective list showing the difference between the two.

Also, someone has already provided a nicely upvoted answer specifying these differences and how they effect what you get.
Answer: There is only one Destiny "game" at the moment.
The difference is that you can either buy just the base game, or you can buy the legendary edition/Taken King edition, which also includes all 3 DLCs.
Buying the base game would be cheaper on it's own, but you will have to pay even more to get all the DLCs (you need both year 1 DLCs to buy The Taken King). This would be more expensive than just buying the Legendary edition in the first place You are also limited to select activities which excludes most current "end-game" features. Without The Taken King you will only be able to level to 34, while the current max is 40.
Buying the Taken King edition gets you all the DLC for a bundle price, and is the cheapest way to go if you want everything Destiny has to offer. If you have friends that play Destiny, or have tried playing before and really enjoyed it this would be the best option.
Comment: Please note that if you are new to the game you are better off buying the taken king bundle, you will not have access to a lot of the stuff you should without it....

Which destiny game to buy?


c# how to save IO.Stream to MemoryStream and save to PDF file on local folder

Question: I am calling a third party service, which return a pdf file by IO.Stream. I need to change to MemoryStream, and save to a pdf file.
Comment: Could you please share your attempted code ?
Comment: The format thing drives me crazy
Comment: figure out. Hopefully helps!
Answer: You could do the following.
using (Stream stream = response.GetResponseStream())
using(MemoryStream memStream = new MemoryStream())
{
  memStream = new MemoryStream();
  stream.CopyTo(memoryStream);
  // TODO : Rest of your task
}

More details on Stream.CopyTo on MSDN
Comment: you did not declare "memoryStream"
Answer: cRequestString = ".....";//You need to set up you own URL here.
            //Make the API call
            try
            {
    byte[] bHeaderBytes = System.Text.Encoding.UTF8.GetBytes(GetUserPasswordString()); //user and pa for third party call.
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cRequestString);
                request.Method = WebRequestMethods.Http.Get;
                request.PreAuthenticate = true;
                request.ContentType = "application/pdf";
                request.Accept = "application/pdf";
                request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bHeaderBytes));
                MemoryStream memStream;
                WebResponse response = request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    memStream = new MemoryStream();
                    //read small blocks to show correctly
                    byte[] buffer = new Byte[1023];
                    int byteCount;
                    do
                    {
                        byteCount = stream.Read(buffer, 0, buffer.Length);
                        memStream.Write(buffer, 0, byteCount);
                    } while (byteCount > 0);
                }
                memStream.Seek(0, SeekOrigin.Begin);//set position to beginning
                return memStream;
            }
            catch
            {
                return null;
            }

//save MemoryStream to local pdf file
 private void SavePDFFile(string cReportName, MemoryStream  pdfStream)
        {
            //Check file exists, delete
            if (File.Exists(cReportName))
            {
                File.Delete(cReportName);
            }
            using (FileStream file = new FileStream(cReportName, FileMode.Create, FileAccess.Write))
            {
                byte[] bytes = new byte[pdfStream.Length];
                pdfStream.Read(bytes, 0, (int)pdfStream.Length);
                file.Write(bytes, 0, bytes.Length);
                pdfStream.Close();
            }
        }

Comment: Have added an answer. Hope it helps


Should I have my old ceiling vacuumed before installing insulation?

Question: My house (built about 1890) has no insulation in the roof and so I plan to put in insulating batts.  There is a lot of old dust and a few possum droppings up there, and I have heard that the dust can contain lead from the leaded-petrol days.  Should I get someone out with one of those big roof vacuums to clean it up before adding the batts?
Answer: You can get simple lead test kits at your local hardware or box store. Check the "dust" for lead. If you don't feel comfortable testing it yourself, hire a pro to do it.  Try not to disturb the dust until it is determined to be lead free. Lead is only bad for you when airborne, so keep it in place, don't disturb it. Wear a dust mask or respirator to be safe.  If it is lead contaminated, do not use a vacuum to collect it. You will need to contract a lead remediator to do this with specialized equipment. Do NOT attempt to do this yourself or hire a non licenced person to remove it.  If there is no lead, you can remove the droppings and dust with a shop vac or hire it done.  Any no-lead dust is not big deal, but I would be inclined to remove any rodent droppings before installing your insulation.


What are the effects of aging and health?

Question: My captain's been slowing down in combat lately, I assume this has got something to do that he is now 39 years old and in poor health. What effects do age and health have? Can I improve my health or mitigate the effects of aging somehow?
Answer: Health affects the speed of your attacks and the speed of completing dance moves.
In order to slow the aging process you can buy mystical spices and herbs from the Mysterious Traveler in taverns.
The game ends when you divide the plunder at age 50.
Comment: Dance moves? Pretty sure those depend on the actual dance, I've certainly never seen my character to fall behind or get ahead of the other dancers. Isn't the age when you're forced to retire when dividing plunder dependant on health and therefore health-improving items? How much do items improve your health? Are they retroactive?
Comment: @kotekzot since there isn't a definitive guide out there about anti-aging items, and trying to come up with that information would take months this is all I have to offer.
Answer: The best choice to help prevent this (too late if you've already progressed in the game, but for next time) is to select the "Skill at Medicine" when creating your character. This basically reduces the rate at which you age and lose various speed in skills. The screenshot below may not look like your version depending on platform.

The other thing is to prevent getting captured (by losing swordfights or sieges) because you "rot in a jail cell" which causes you to age, and reduces your health. I use save games effectively to prevent this if my skill isn't high enough.


Disposing Objects in WebAPI

Question: I am going to maintain one existing API implementation. When i look into the code i got that there are some issue with object dispose.
The following are my Base Controller which acts as parent controller for all.
[LoggingFilter]
[System.Web.Http.Authorize]
public abstract class BaseV1Controller : ApiController
{
    private ModelFactoryV1 _modelFactoryV1;
    private MyDBContext __db;
    private MyLoggingService _loggingService;
    private int _customerId;

    protected string __IPAddress;
    protected ILogger __logger;
    protected const int PAGE_SIZE_NORMAL = 20;
    protected const int PAGE_SIZE_MEDIA = 2;
    // GET: Base
    protected string __loggingResourceName = "Undefined - base controller";
    private void InitLogger()
    {
       Log.Logger.ForContext<BaseV1Controller>();
    }

    protected MyDBContext _db
    {
        get { return __db; }
        set { __db = value; }
    }

    public BaseV1Controller()
    {
        IEnumerable<string> values;
        __db = new MyDBContext();
        _loggingService = new MyLoggingService ();
        InitLogger();
    }

    public BaseV1Controller(MyDBContext db)
    {
        __db = db;
        _loggingService = new MyLoggingService ();
        InitLogger();
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        _loggingService = null;
    }

  }

We are not overriding dispose method in the controller. In the controller we are calling Repository classes to do CRUD operations .
Sample implementation below;
Controller:
   [LoggingFilter]
    [ValidateModel]
    [Authorize]
    public class CustomersV1Controller : BaseV1Controller
    {
        IAsyncRepository<Customer> _repo = new CustomerAsyncRepository();
        public CustomersV1Controller() : base()
        {
            _repo = new CustomerAsyncRepository();
        }

        public CustomersV1Controller(IAsyncRepository<Customer> repo, MyDBContext db) : base(db)
        {
            __loggingResourceName = "Customer";
            _repo = repo;
        }

       //All Actions implemented here

    }

Repository Interface and Class:
    public interface IAsyncRepository<T>
    {

        Task<T> Add(T type);
        Task<T> Get(int Id);
        Task Update(T type);
    }

public class CustomerAsyncRepository : IAsyncRepository<Customer>
    {
        //saves the customer view models
        private MyDBContext _db { get; }

        public CustomerAsyncRepository(MyDBContext db)
        {
            this._db = db;
        }

        public CustomerAsyncRepository()
        {
            _db = new MyDBContext ();
        }

        public async Task<Customer> Add(Customer model)
        {
            //Add method implmementation
            return model;
        }

        public async Task<Customer> Get(int id)
        {
           //Implementation to return customer model
        }

        public async Task Update(Customer model)
        {
           //Implementation to update customer model
        }

    }

I have the following clarification based on this

I think we should include _db.Dispose() in the dispose method of BaseV1Controller. Currently I can't implement DI pattern.  Please suggest?
In Repository IDisposable not implemented. Is this correct?
Any other improvements?
Comment: Use a **D**ependency **I**njection (DI) framework. My personal preference is AutoFac. These frameworks handle the creation of dependencies as well as the release of resources used by the created instances (ie. calling dispose or custom cleanup methods). This includes injecting a `DbContext` instance and calling Dispose on it at the end of the request.
Comment: thanks and accepted. But as of now i don't want to change all area to include DI. Gradually i will do that. But now i am looking to stabilize without not much change and it is not allowable now
Answer: Yes, you should dispose your DbContext in the base controller's Dipose method.  Otherwise, nothing knows that it needs disposing.  It may eventually be finalized sometime after the request is finished, but until that happens the underlying database connection will remain open and unavailable, which means you will exhaust your connection pool more quickly.
To ensure this happens, you probably don't want to have your _db property (which probably should be renamed to Db, or even better DataContext as property names in .Net don't normally start with an _) having a protected setter; a subclass could change the value of the property, and the original context which was there would be lost without being disposed.
Regarding the repository, the norm there is that if the class has a field which is an IDisposable, you should implement IDisposable in that class too.  What I'd probably do in this case is change your IAsyncRepository<T> to require implementing IDisposable as well.  Then your repository implementation should dispose the DbConext, and your controller would instead dispose the repository instance.  It would probably be best in that case as well to not have the controller keep any reference to the DbContext, and just expose the repo instance instead.
You can read more about how to correctly implement IDisposable here https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose?view=netframework-4.7.2
Comment: Thanks mate. ok i will dispose in BaseV1Controller. Yous second suggestion i can rename _db but if not any problem? I din't get your all points clearly here. Can you tell me that  i need to add IDisposable in Repository and override Dispose there also?
Comment: @Akhil Renaming the property is just a suggestion so that your code style matches what .Net developers will expect.  It was actually a bit confusing for me when I tried to read your code as you weren't following the conventions (and have double underscores for the field).
Comment: thanks. So overall suggestions should be to do 2 areas.  1) Need to dispose _db in the BaseV1Controller 2) Need to add IDisposable in repository interface and dispose Dbobject in each repository / generic repository also.

Disposing Objects in WebAPI


Why strings are not equal

Question: In my android app, I have a Play button. but after I clicked the button, nothing happend. Seems when comparing the text on the button, they are not equal. if I use indexOf(PLAY), it works. Cannot figure out why it behaves like this. I defined my string values in res/values/strings.xml  as
    <string name="play">Play</string>

    private final static String PLAY = "Play";

    //some code in between

    Button playButton = new Button(this);
    playButton.setText(R.string.play);
    playButton.setTextSize(BUTTON_FONT_SIZE);
    playButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
           Button b = (Button) v;
           if (b.getText().equals(PLAY)) {    //stuck here.
                 startPlay();
            } else {

                stopPlay();
            }
        }
    });

Thanks for the help.
Comment: add some logs and see if b.getText() is not returning null
Comment: on a side note, depending on your problem space it can be considered good practice to convert both strings to either lower or uppercase before comparing them. This can save time during later debugging
Comment: I do have debug output and visually they are the same. but when I try to use "string size=" + R.string.play.length, it gives error: int cannot be dereferenced.
Comment: Do you have the same problem if you use an intermediate variable? Like : `String buttonText = b.getText().toString();` `if(buttonText.equals(PLAY)....?`
Comment: @jbihan You got it. Thanks a bunch. I thought toString() is not needed.
Comment: You're welcome, let me add it as an answer then ;)
Comment: @jbihan why toString() is needed? see this post: http://stackoverflow.com/questions/4199320/android-how-to-get-listview-text?rq=1 . It works without toString(), but mine does not work. I know button.getText() returns CharSequence.
Comment: Honestly, I don't know, it was just a guess. I saw links like the one you gave me, I thought it didn't understand why it didn't work so I tried to find an alternative solution. But I agree with you, it's strange... I'll try to find out why! (and if you find out, let me know!)
Answer: You can use an intermediate variable, like this
String buttonText = b.getText().toString();
if (buttonText.equals(PLAY)) {
    .....

Or just
if (b.getText().toString().equals(PLAY)) {

Why strings are not equal


Clear Radio Button on ng-disabled

Question: Below is how I a implemented my code which I modified from Ng-repeat hiding radio button based on other radio answers selected. What I need help with is clearing the radio button when it is removed/disabled == true of that answer.
If the user starts with Q3 and selects answer31 then goes back to Q1 and selects answer11, the question.selectedAnswer  still shows up as answer31.
Any help is appreciated

var app = angular.module('plunker', []);

app.controller('MainCtrl', ['$scope',
  function($scope) {

    function getAnswer(qid, aid) {
        var qs = $scope.questions, q;
        for (var i = 0; i < qs.length; ++i) {
          if (qs[i].qid === qid) {
            q = qs[i];
            break;
          }
        }
        if (q) {
          var as = q.Answer;
          for (i = 0; as.length; ++i) {
            if (as[i].aId === aid) {
              return as[i];
            }
          }
        }
    }

    function doRemove(q, a) {
      if (a.removes && a.removes.length) {
        for (var i = 0; i < a.removes.length; ++i) {
          var r = a.removes[i],
              answer = getAnswer(r.qid, r.aId);
          if (answer) {
            answer.isDisabled = (q.selectedAnswer == a.answertxt);
          }
        }
      }
    }

    $scope.select = function (q, a) {
      var as = q.Answer;

      for (var i = 0; i < as.length; ++i) {
        var answer = as[i];
        doRemove(q, answer);
      }
    };

    $scope.questions = [{
        questiontxt: 'Please select your Age range',
        qid: 1234,
        Answer: [{
          answertxt: "answer11",
          aId: 83493,
          hides: [{
            qid: 5678,
            aId: 67107
          }],
          removes: [{
            qid: 4321,
            aId: 32342
          }]
        }, {
          answertxt: "answer12",
          aId: 1223,
        }, {
          answertxt: "answer13",
          aId: 1223
        }]
      },
      {
        questiontxt: 'Please select your favorite activity',
        qid: 5678,
        Answer: [{
          answertxt: "answer21",
          aId: 90886
        }, {
          answertxt: "answer22",
          aId: 67107
        }]
      },
      {
        questiontxt: 'Please select your favorite food',
        qid: 4321,
        Answer: [{
          answertxt: "answer31",
          aId: 32342
        }, {
          answertxt: "answer32",
          aId: 79130
        }]
      }
    ];
  }
]);
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />

Q{{$index+1}}. {{question.questiontxt}}

        <input type="radio"
          ng-change="select(question, answer)"
          ng-disabled="answer.isDisabled"
          ng-model="question.selectedAnswer"
          ng-value="answer.answertxt" />
          {{answer.answertxt}}

update
I want to make sure my intent is clear.
If the user starts on Q1 and selects "answer11" in Q1 you can see that in Q3 "answer31" disappears. Making it not possible for the user to select "answer31"
But if the user starts on Q3 and selects "answer31" in Q3, the answer is still selected even though the user selects "answer11" in Q1 (which makes the answer disappear). In the backend "answer31" is still selected.
Please let me know if this makes sense. Looking at the one of the answers received, the solution might be to hide Q3 until a selection is made in Q1. Which might be a different question.
Answer: I'm not sure if I understood your purpose exactly.
But I've made a fiddle that might be able to help you.
Check this fiddle
$scope.showQuestion = function(index, answer){
    $scope.answerArr.length = index;
    var questionNum = 0;    //  for innitializing radio after this question
    angular.forEach($scope.questions, function(question){
        if(index < questionNum){
            delete question.selectedAnswer;
        }
        questionNum++;
    });
    $scope.answerArr.push(answer);
};

Is this what you want to do?
If not, give me some feedback.
I hope I've understood what you want and this fiddle is near from perfect for your purpose. :)
.
.
.
UPDATED
First, sorry for my misunderstanding of your question.
I think maybe this time, the fiddle what I'll bring to you, is almost proper to your intent.
Updated fiddle
You can test check boxes of 'Q1' or 'Q2'.
But in this fiddle, the way handling $scope.questions is different from yours.
So it might be too hard to understanding my codes, even though I've added comment each lines.
Moreover, It's been a short time I've started programming, you might think this is a kind of 'hard coding'. :D
.
.
UPDATED2
This is finally well working fiddle
I just hope this can be a little helpful for you, or brought a good hint to you.
Comment: Hi thanks for the solution.  It didn't cross my mind to hide the question before showing the question but this might be a solution.  So based on what the user selects on Q1, I want on Q2 one of the answers to be removed so the user cannot select it.
Comment: Ah, you mean all questions should be shown and when user didn't select Q1, Q2 and Q3 have to be disabled, then user select Q1 and Q2, Q3 still have to be disabled, right?
Comment: And did you find solution of this?
Comment: No I haven't found a solution to this.  I think based on your response, I am going to create a new question, and have people respond to that. you have shown me a new way to approach the problem.   Yes, I was showing all the questions and answers at first.  If the user selected in Q1, answer11 then in Q3 answer31 would disappear, this worked only okay.   If the user decided to go out of order, and start with Q3 and selected answer31 and then select Q1 answer 11, Q3 answer31 would disappear but in the backend answer31 is still selected.
Comment: @user990951 Oh, I'v been misunderstanding until now.. I think I got it! From now on I'll try to find the right solution and if I get it, share it to you. :)
Comment: @user990951 oh.. wait a minute. This has some problems.. T.T I'm trying to fix them.
Comment: @user990951 I think this'll take times.. sorry for my wrong answer. ASAP I'll fix it.
Comment: @user990951 Finally, I've made fiddle which works good! Check fiddle below 'UPDATE2'.
Comment: @user990951 Thanks. But there's still errors. when you check 'Answer12' and 'Answer21', then 'Answer41' and 'Answer42' is disabled. but when you make disabling 'Answer21' by click 'Answer13', 'Answer41' still disabled.
Comment: @user990951 Oh, this was caused by order in 'selectAnswer' function. I've modified fiddle and this works well. It's all done. :)
Comment: well done. you still got me curious on hiding the question based on a user radio selection. I am trying to see if i can solve it on my own. Thanks again

Clear Radio Button on ng-disabled


How to Lay Concrete Slabs [900mm x 600mm x 50mm]

Question: I have a bunch of these concrete slabs to make a patio outside my garden house roughly 6ft width x 10ft length area. Can these be set on top of a sand screed [Slabs]
Also what gap in between is ideal in between slabs.
Can they also be doubled up on eachother to increase the height?
I have attached pictures
Answer: The smallest gap between each is preferrable - unless you want to be constantly clearing bigger gaps that weeds will grow from. So, butting them up to each other is good. You may want to sprinkle some cement down the edges as a barrier, too, brushing off to tidy up.
Putting layers of slabs seems a waste. Either spread more sand first to bring the level up, or just leave them at the level they finish at. It's well worth spotting each slab with concrete in 5 spots to make levelling easier, and using a big rubber mallet to get them level - or perhaps sloping a little away from the shed, so rainwater will drain away from the foundations.
Comment: Not sure this is good advice. My experience is that butting slabs makes them difficult to level and causes spalling (chips flaking off where the edges touch). A small gap filled with sand, rock dust or grout avoids this. Dabs of concrete cause the slabs to be poorly supported and liable to cracking. It also creates a space for ants or rain to excavate below the slabs, further destabilising them.
Answer: I'd lay them the same way you lay slate or bluestone.  Dig down, put some gravel down, put some sand on top of it, level it, then put the slabs down.
You will need at least a 1/4 inch gaps, both to make things level and for aesthetic purposes.  Put some rock dust between the slabs to keep the weeds down
Comment: +1 for gravel subbase with a layer of sand on top. Don't forget to put a border in place to contain the edges and stop the sand and gravel escaping.


add ng-dbclick for options of select in AngularJS

Question: i have a <select> tag and use ng-options to bind options of select.
my question is how to add ng-dbclick to each option of select
here is my code
<select  size="4"  ng-model="pattern" ng-options="p.name  for p in patterns | filter:obj">

</select>

Comment: ng-dbclick is an event that fires when you double click on an element

[ng-dbclick](http://docs.angularjs.org/api/ng.directive:ngDblclick)
Answer: I don't think that you can add an event handler to an option of a select box in js so this won't work in angular either.
What you can do is add the ng-dblclick to the select element and then get the selected option which will also be the doubleclicked one.
This would be the value of your pattern model.
<select  size="4"  ng-model="pattern" ng-dblclick="doYourStuff()" ng-options="p.name  for p in patterns | filter:obj">

</select>

Have a look at this plunker for a demo.


Is induction neccessary for proving that every injective mapping of a finite set into itself is a mapping onto itself?

Question: Upon reviewing the basic theorem that the number of elements in a fixed finite set is unique, I tried to determine what part of this proposition is in need of proof.  It seems axiomatic.  Nonetheless, BBFSK have a very long-winded, and seemingly convoluted discussion of this, and related ideas.
When I attempted to produce my own argument in support of the above proposition, the part which I am not able to state purely in the terminology of mappings (bijection, injection, etc) is that an injection of a finite set into itself is a mapping onto itself.  The proof BBFSK give uses induction.  After thinking about it for a while, that was the only approach I could come up with.
Is there a rigorous proof of the proposition that every injective mapping of a finite set into itself is a mapping of the set onto itself which does not involve induction?
Answer: Dedekind proposed to use this property as the definition of "finite set", so that's at least one alternative -- closely in line with your intuition of declaring it to be axiomatic. Unfortunately there are technical problems with that approach. In particular you then need the axiom of choice to prove that induction works for all "finite" cardinalities, which is untidy at the least.
(A set $X$ such that every injection $X\to X$ is a bijection is now called "Dedekind-finite").
In a standard development of set theory, on the other hand, you're out of luck. Here "finite" is defined as "has the same cardinality as an element of $\omega$", and $\omega$ is (essentially) defined to be the largest set that mathematical induction works for. So in order to prove anything about "finite" you need to have an induction somewhere, because that's the only way to connect to the definition. This induction can be hidden in the proof of another property that you depend on, but that is basically just kicking the buck around. Eventually it has to stop.

This comment by Daniel Schepler is also relevant (but see further discussion in the comment thread):

There's also the notion of Kuratowski finiteness, which is essentially equivalent to the condition that the power set of $$ is well-founded under the relation of "strict extension by one element". But then, of course, the natural way to prove nearly anything about Kuratowski finite sets is to use induction on the well-foundedness property...
Comment: @StevenHatton: That's the same definition as the one Henning provides, because in the "usual" construction of $\mathbb{N}$ as an inductive set, your $A_n$ is exactly equal to $n+1$ (modulo including $0$ in $\mathbb{N}$)...
Comment: Bu the way: @Arturo gives the usual textbook definition of $\mathbb N$ (a.k.a. $\omega$). My characterization as "the largest set induction works for" looks rather different at first, but is nevertheless what the textbook definition _achieves_. Because $\omega$ contains $0$ and all the $x^+$s, induction must fail in any _strictly larger_ set (as $\omega$ itself would be a counterexample) -- and being the "smallest set" that satisfies this exactly guarantees that induction _will_ work in $\omega$.
Comment: There's also the notion of Kuratowski finiteness, which is essentially equivalent to the condition that the power set of $X$ is well-founded under the relation of "strict extension by one element".  But then, of course, the natural way to prove nearly anything about Kuratowski finite sets is to use induction on the well-foundedness property...
Comment: The definition the authors give is that a finite set is one which can be put in one-to-one correspondence with a segment $A_n=\left\{x\in\mathbb{N}|1\ge x \le n\right\}.$  It appears that what we are saying amounts to "if you count a set of objects, rearrange them, then count them again, you'll get the same number".
Comment: @StevenHatton: To be more explicit; in the "usual" construction as an inductive set, we have $0=\varnothing$, $n^+ = n\cup\{n\}$ for any set $n$, and $\mathbb{N}$ is the smallest set that includes $0$ and such that if $x\in\mathbb{N}$ then $x^+\in\mathbb{N}$. Then $1=0^+$, $2=1^+$, etc., and in this construction, the set $n$ contains exactly $n$ elements, namely $0,1,2,\ldots,n-1$.
Comment: @Daniel: I always thought that Kuratowski finiteness is that a set $X$ is finite if and only if whenever $\varphi$ is a statement such that $\varphi(\varnothing)$ holds and $\forall A\forall x(\varphi(A)\to\varphi(A\cup\{x\})$, then $\varphi(X)$ holds. In other words, finite sets is the smallest class of sets containing the empty set, all the singletons, and closed under unions (of two sets). I'm not entirely sure where well-foundedness comes from. This seems more of a meta-mathematical definition. Tarski's finiteness is that $\mathcal P(X)$ is well-founded with respect to $\subsetneq$.
Comment: @DanielSchepler In the current context, the approach is similar to what you describe.  I'm reading the chapter on constructing the real numbers, where numbers are the primitive elements appearing in a succession,, as in Peano's axioms.  Only after 11 pages of terse presentation am I permitted to use numbers to actually count something.
Comment: OK, I guess I was missing that the well-foundedness in the sense I said would require something more like $\forall A, [(\forall x\in A, \phi(A \setminus \{x\})) \rightarrow \phi(A)]$.  Still, the fact remains that Kuratowski finiteness can be viewed as "it's valid to prove properties of subsets of $X$ by a certain induction-style principle".


Can the Kernel of the commutator of two matrices with empty Kernel sets be non-empty?

Question: The motivation for this question arises from the following: Is it possible, given two Quantum Mechanical observables $A$ and $B$ with associated operators $\hat{\mathbf{A}}$ and $\hat{\mathbf{B}}$ such that $[\hat{\mathbf{A}},\hat{\mathbf{B}}] \neq \mathbf{0}$, for $$[\hat{\mathbf{A}},\hat{\mathbf{B}}]\left|\phi\right\rangle=0 \qquad \exists \left|\phi\right\rangle \neq 0$$
We can reduce this to the following: $\exists \left|\phi\right\rangle \neq 0$ such that this is true, if and only iff $\left| \phi \right\rangle \in \operatorname{Ker}([\hat{\mathbf{A}},\hat{\mathbf{B}}])$. So my question is this:

Given two matrices $\mathbf{A}$ and $\mathbf{B}$ such that $\operatorname{Ker}(\mathbf{A}) = \{0\}$ and $\operatorname{Ker}(\mathbf{B}) = \{0\}$, is it possible for: $$\operatorname{Ker}([\mathbf{A},\mathbf{B}])\neq \{0\}$$
Answer: The kernel of a linear operator can never be $\varnothing$. The smallest possible kernel is $\{0\}$.
But assuming that is what you meant: Yes, that is easily possible. For example,
$$ \mathbf A=\begin{pmatrix}1&0&0\\0&0&1\\0&1&0\end{pmatrix}
\qquad
\mathbf B=\begin{pmatrix}1&0&0\\0&0&-1\\0&1&0\end{pmatrix} $$
gives
$$ [\mathbf A,\mathbf B]=\begin{pmatrix}0&0&0\\0&2&0\\0&0&-2\end{pmatrix} $$
which is nonzero but singular.
Comment: Yes, sorry, I meant $\{0\}$, but I meant for when the commutator is non-zero?
Comment: @Shaktal: Yes, I saw that afterwards, edited now.


Partitioning a new Dell XPS 15 L521X for Ubuntu

Question: I just brought home my brand new XPS 15 L521X.
I booted to Ubuntu 12.10 using a memory stick to check that the wifi and everything is working (it is).
I am wanting to wipe the drive and install Ubuntu, and I don't really care about secure boot.
The only description of the hard drive on the site was "Up to 750GB SATA hard drive (7200RPM)" so I was a little surprised with what is actually in there:

And now the good surprise... an SSD! The 8 gig partition is EFI.

My instinct is to get rid of all the crazy little partitions on /dev/sda and probably use it for my home folder. The SSD on /dev/sdb I was thinking I would use for / so the OS would boot quickly.
My questions:
Is there enough space on the ~29 Gig /dev/sdb drive for the OS?
Is deleting the EFI partition a mistake? Does it mess up firmware upgrades?
Is there any reason to keep any of those OEM partitions if I am never going to use Windows?
Answer: I don't know what you mean by /dev/sdb1 being "EFI." The Extensible Firmware Interface (EFI) is your firmware and is stored on an EEPROM on your motherboard, not on a disk (except for developer tools like DUET or the "firmware" used in virtual machines). The EFI does have an associated partition, the EFI System Partition (ESP), but it's a FAT32 partition that's normally 100-600MiB in size and that has a particular partition type code. Your /dev/sdb1 holds an unrecognized (that is, not FAT) filesystem, according to the GParted screen shot, and does not have the ESP type code, so it's not an ESP. Your /dev/sda1, OTOH, is an ESP; it's FAT32 and has its "boot flag" set (which is GParted's way of identifying the ESP type code).
To answer your bigger question, if you don't care about the Windows you've got on your computer or any of the other software or data that Dell has provided, you can delete all your partitions, on both /dev/sda and /dev/sdb, with the caveat that since I don't know what /dev/sdb1 is, I don't know if it might have some non-standard purpose for the firmware. (It's more likely that it's used by Windows, though.) When you install Ubuntu, it will create whatever partitions it requires, including a fresh ESP. (The existing ESP just holds the Windows boot loader and associated data, so deleting it shouldn't be a problem.) If you want to preserve your ability to install re-install Windows in the future, though, you should preserve /dev/sda6 and perhaps /dev/sda4. Alternatively, in the Windows 7 era, it was common for manufacturers to provide a utility to let you burn a set of DVD-Rs that would enable you to re-install Windows. You could look for such a tool in your current system and back up the relevant data in that way.
Answer: First: 20 GB should be enough for the root partition, at least if you put /tmp somewhere else and you don't intend to install large games system wide. 28-29 GB would be even better. /tmp is used for instance for temporary data when burning DVDs, so I recommend that one being bigger than 10 GB.
Second: The EFI partition does afaik only store data that has something to do with the installed operating systems, so if you want to get rid of Windows completely, it should be safe to remove it and (if you don't want to be forced to use BIOS emulation) to create a new one for Ubuntu (I'm not an EFI expert, so please don't blame me if this does not work - maybe you should make a backup of the whole SSD by dd'ing it to a file on an external HDD first?). According to the Ubuntu Wiki UEFI Guide, an EFI partition of 200 MB should be sufficient for Ubuntu, so by deleting the current one and creating a new one, you could get some more space for your root partition, yet it's not a necessary step, for Ubuntu can make use of a present Windows EFI partition as well. Afaik only Apple computers use the EFI partition for firmware updates (but as said I'm not an expert). One more thing: Some broken EFI firmwares don't allow you to install Ubuntu in EFI mode. If this applies to your notebook, you can simply use BIOS mode by booting the live DVD in BIOS mode.
On every computer I know, there exists no reason to keep any of the OEM partitions if one doesn't want to reinstall Windows without a Windows DVD.


How do I enable webgl in Firefox?

Question: I've got Firefox 5 installed on my Ubuntu 11.04 system. I would like to have webgl working, which is not right now: this website just gives me a grey page:
<code>http://webglsamples.googlecode.com/hg/aquarium/aquarium.html
</code>
I've got it working on google-chrome using the nvidia proprietary drivers, so there must be a way to get it to work on the same system in Firefox.
Answer: It is my understanding that it is already enabled. I have checked the aquarium out with Firefox 5 right now. Works perfect. It was in Firefox 4 that you needed a command to activate WebGL (Although the programs ran horribly). On Firefox 5 WebGL is much better. Not as good as Chrome of course but it is catching it up very fast.
If you are still having problems seeing that webpage it is because of a direct problem with your video card. Does your video card support opengl 2.0.
Here is a mini guid that points from what version the browsers support WebGL and what to do to make it work if it is in Alpha/Beta with the browser: http://www.khronos.org/webgl/wiki/Getting_a_WebGL_Implementation
In the Wikipedia: http://en.wikipedia.org/wiki/Firefox_4 you can see that in Firefox 4 it got some support for WebGL (But trust me, most WebGL examples from Chrome Labs tested horrible)
In the Wikipedia:http://en.wikipedia.org/wiki/History_of_Firefox#Version_5.0 you can see that Firefox 5 got more support for WebGL that now actually lets you play most WebGL apps. There are some even that are very tough to support and it supports them like http://www.ro.me/ "3 Dreams of Black" which is literally you flying inside a video thats playing cool music.
Comment: upon further investigation, it looks like Firefox is blocking my drivers: http://askubuntu.com/questions/53460/firefox-blocks-my-nvidia-drivers-moz-glx-ignore-blacklist
Answer: Indeed this seems to be an issue linked to Firefox blocking graphics card drivers:
I have Kubuntu 11.04 and Firefox 6 and Chromium 12.0.742.112 (90304) Ubuntu 11.04 and
in FF I get a grey page, in Chromium I get to see some fish. Performance is not very good, I get 16-22fps even with 1 fish.
UPDATE: actually the number of fish does not seem to link in any way with fps: 1000 fish and I still get 16-22fps. The same is true for any number of fish I set and any perspective.
Answer: It is the same in Chrome. It is a problem with the code, not your browser or WebGL.
Answer: This worked for me with Firefox 5 and Ubuntu 11.04, although the aquarium demonstration link you provided ran extremely slowly on my machine, which admittedly isn't set up for gaming or multimedia. YMMV.
Answer: check about:config webgl and change webgl.force-enabled to true. worked for me to enjoy using the webgl ;-)

How do I enable webgl in Firefox?


Speech to Text SWIFT

Question: I have the following code:
func createStringFromAudio () {
    SFSpeechRecognizer.requestAuthorization {_ in
        DispatchQueue.main.async {
            switch SFSpeechRecognizer.authorizationStatus() {
            case .authorized :
                let audioURL = Bundle.main.url(forResource: "ConversionTest", withExtension: "mp3")!
                let recognizer = SFSpeechRecognizer()
                let request = SFSpeechURLRecognitionRequest(url: audioURL)
                recognizer?.recognitionTask(with: request) { result, error in
                    guard error == nil else { print("Error"); return}
                    guard let result = result else {print("No result"); return}
                    print(result.bestTranscription.formattedString)
                }
                break
            default :
                break
            }
        }
    }
}

Here is my question:
1: How do I know when the file is done? Currently it continually updates the result print but doesn't notify me when the transcription is 100% completed. How do I know when the transcription is done and I can save the string for parsing?
2: It seems to cut off before finishing. Is there a time limit? Character limit?
Answer: You can save the task to check its status, even cancell it.
Actually, the transcribing process is not controlled by us and when the system think its finished, it's finished.
If you do need precise controls, use  a delegate:
func recognitionTask(with request: SFSpeechRecognitionRequest, delegate: SFSpeechRecognitionTaskDelegate) -> SFSpeechRecognitionTask
This may provide more informations during transcribing, at least it will let you know when it is finished.

Speech to Text SWIFT


How to derive this series

Question:
The function $\dfrac1{1-x}$, equal to $$1 + x + x^2 + x^3 + \cdots,$$ can also be developed according to the series $$1 + \frac{x}{1 + x} + \frac{1\cdot2\cdot x^2}{(1 + x)(1 + 2x)} + \frac{1\cdot2\cdot3\cdot x^3}{(1 + x)(1 + 2x)(1 + 3x)} + \cdots $$ when $x$ is positive and smaller than $1$.

I know the first series and it is easy to obtain it. But the second series is strange. It is not a power series, not a Taylor series. How does one obtain this series?
Comment: The boxed sum looks to be $$\sum_{n=0}^\infty\frac{n!\cdot x^n}{\prod\limits_{m=0}^n(1+mx)}.$$  Can you make use of this?
Answer: We can show the  identity
\begin{align*}
\sum_{n=0}^\infty  \frac{n!x^n}{\prod_{j=1}^n(1+jx)}=\frac{1}{1-x}\qquad\qquad0<x<1\tag{1}
\end{align*}
with the help of Gauss' summation formula.

We obtain
\begin{align*}
\color{blue}{\sum_{n=0}^\infty  \frac{n!x^n}{\prod_{j=1}^n(1+jx)}}
&=\sum_{n=0}^{\infty}\frac{n!}{\left(1+\frac{1}{x}\right)^{\overline{n}}}\tag{2}\\
&=\sum_{n=0}^{\infty}\frac{1^{\overline{n}}1^{\overline{n}}}{\left(1+\frac{1}{x}\right)^{\overline{n}}}\,\frac{1}{n!}\tag{3}\\
&={}_2F_1\left(1,1;1+\frac{1}{x};1\right)\tag{4}\\
&=\frac{\Gamma\left(\frac{1}{x}+1\right)\Gamma\left(\frac{1}{x}-1\right)}{\Gamma\left(\frac{1}{x}\right)\Gamma\left(\frac{1}{x}\right)}\tag{5}\\
&=\frac{\frac{1}{x}\Gamma\left(\frac{1}{x}\right)\Gamma\left(\frac{1}{x}-1\right)}
{\Gamma\left(\frac{1}{x}\right)\,\left(\frac{1}{x}-1\right)\Gamma\left(\frac{1}{x}-1\right)}\tag{6}\\
&=\frac{\frac{1}{x}}{\frac{1}{x}-1}\tag{7}\\
&\,\,\color{blue}{=\frac{1}{1-x}}
\end{align*}
and the claim (1) follows.
Comment:

In (2) we expand with $\frac{1}{x^n}$ and use the rising factorial notation $q^{\overline{n}}=q(q+1)\cdots (q+n-1)$.

In (3) we write $1^{\overline{n}}=n!$ and prepare the representation for use of hypergeometric series.

In (4) we use the hypergeometric series notation
\begin{align*}
{}_2F_1\left(a,b;c;z\right)=\sum_{n=0}^{\infty}\frac{a^{\overline{n}}b^{\overline{n}}}{c^{\overline{n}}}\,\frac{z^n}{n!}
\end{align*}
with $a=b=z=1$ and $c=1+\frac{1}{x}$.

In (5) we use Gauss' summation formula
\begin{align*}
{}_2F_1\left(a,b;c;1\right)=\frac{\Gamma(c)\Gamma(c-a-b)}{\Gamma(c-a)\Gamma(c-b)}
\end{align*}
with $a=b=1$ and $c=1+\frac{1}{x}$ valid for $\Re\left(\frac{1}{x}\right)>1$.

In (6) we use the identity $\Gamma(x+1)=x\Gamma(x)$ for all $x\in\mathbb{C}\setminus\{0,-1,-2,\ldots\}$.

In (7) we finally cancel terms.
Comment: I sent you an important email concerning a live Zoom meeting on Egorychev method. Please check your email.
Answer: The series you are asking about is
$$ S(x) \!:=\! 1 \!+\! \frac{x}{1\!+\!x} \!+\!
 \frac{1\cdot 2\cdot x^2}{(1\!+\!x)(1\!+\!2x)} \!+\!
 \frac{1\cdot 2\cdot 3\cdot x^3}{(1\!+\!x)(1\!+\!2x)(1\!+\!3x)}
 \!+\! \cdots. \tag{1} $$
One of the first things to do in such a series is to find the
ratio of consecutive terms which gives the sequence
$$ \frac{x}{1+x},\;\; \frac{2x}{1+2x},\;\; \frac{3x}{1+3x}\;\;
 \dots,\;\; \frac{nx}{1+nx},\;\; \dots $$
which is a rational function in $\,n\,$ and this is the
characteristic property of a Hypergeometric series.
Assuming $\,x\ne 0\,$, let $\, y := 1/x.\,$ Then
$$ S(x) \!=\! 1 \!+\! \frac{1!}{(1\!+\!y)} \!+\!
 \frac{2!}{(1\!+\!y)(2\!+\!y)} \!+\!
\frac{3!}{(1\!+\!y)(2\!+\!y)(3\!+\!y)} \!+\! \cdots. \tag{2} $$
This is a simple Hypergeometric series
$$ S(x) = {}_2F_1(1,1;1+1/x;1) = 1/(1-x) \tag{3} $$
where the left side series has a complicated domain of
convergence and the right side has a simple pole
at $\,x=1.\,$
Your question was

How does one obtain this series?

Quoting from the Wikipedia article:

Many of the common mathematical functions can be expressed in terms of the hypergeometric function, or as limiting cases of it.

In this particular case, assume the Ansatz
$$ f(x) \!:=\! a_0 \!+\! \frac{a_1\,x}{1\!+\!x} \!+\!
 \frac{a_2\,x^2}{(1\!+\!x)(1\!+\!2x)} \!+\!
 \frac{a_3\,x^3}{(1\!+\!x)(1\!+\!2x)(1\!+\!3x)}
 \!+\! \cdots. \tag{4} $$
Then by expanding into power series in $\,x\,$ we
have the result
$$ f(x) \!=\! a_0 \!+\! a_1\,x \!+\!
 (a_2\!-\!a_1)x^2 \!+\! (a_3\!-\!3a_2\!+\!a_1)x^3 \!+\!
 (a_4\!-\!6a_3\!+\!7a_2\!-\!a_1)x^4 \!+\! \cdots \tag{5} $$
which gets the power series coefficients of $\,f(x)\,$
from those of the series in equation $(4)$.
For this particular hypergeometric series, there is
another simple method to try. Define the partial sums
$$ S_n := \sum_{k=0}^n k!/(1+1/x)_k. \tag{6} $$
Then we can observe that
$$ S_n = P_n x^n/(1+1/x)_n \tag{7} $$
where $\,P_n\,$ is a polynomial of degree $\,n\,$
with positive integer coefficients appearing in
OEIS sequence A109822.
For example
$$ P_1\!=\! 1\!+\!2x, P_2\!=\! 1\!+\!4x\!+\!6x^2, P_3 = 1\!+\!7x\!+\!18x^2\!+\!24x^3. \tag{8} $$
But notice that the same coefficients appear in
OEIS sequence A096747
which has an extra $\,(n+1)!\,$ for each row. This
suggests looking at
 $$ 1/(1-x) - S_n = (n+1)!
\frac{x}{(1-x)(1+1/x)_{n+1}}. \tag{9} $$
This equality of two rational functions can be
proved by induction using telescoping sums.
Comment: You may have misread the series, unless you haven't.
Comment: @AndrewChin Oops! Fixed the denominators in (1).
Comment: @Somos May I ask how do you know it is a hypergeometric series in the first place? Is it a hunch or what?
Comment: @Somos How do you know the coefficients for $$ S(x) = {}_2F_1(\color{red}{1,1;1+1/x;1}) = 1/(1-x). \tag{3} $$

Is there a way to find the limiting function of this series?
Comment: @JamesWarthington If you are interested in that specific question, please submit it as another question because it has not a simple answer.
Comment: @Somos: If the LHS side of (3) has a complicated domain of convergence and the RHS is convergent for $|x|<1$, where is equality established?
Comment: @MarkusScheuer I don't know yet.
Comment: @Somos I already post the question here: https://math.stackexchange.com/questions/3497810/how-to-determine-the-coefficients-of-hypergeometric-functions
Comment: @JamesWarthington Thanks. I noticed.
Answer: Proof of the Formula
Below, we show inductively
$$
\frac1{1-x}=\sum_{k=0}^{n-1}\frac{k!\,x^k}{\prod_{j=1}^k(1+jx)}+\frac{n!\,x^n}{\prod_{j=1}^n(1+jx)}\frac{1+nx}{1-x}\tag1
$$
where the empty sum is $0$ and the empty product is $1$.
Gautschi's Inequality says that
$$
\begin{align}
\frac{n!\,x^n}{\prod_{j=1}^n(1+jx)}
&=\frac{\Gamma(n+1)\,\Gamma\!\left(1+\frac1x\right)}{\Gamma\!\left(n+1+\frac1x\right)}\\
&\sim\frac{\Gamma\!\left(1+\frac1x\right)}{(n+1)^{1/x}}\tag2
\end{align}
$$
Thus, for $0\lt x\lt1$, the series
$$
\sum_{k=0}^\infty\frac{k!\,x^k}{\prod_{j=1}^k(1+jx)}\tag3
$$
converges and the remainder term
$$
\frac{n!\,x^n}{\prod_{j=1}^n(1+jx)}\frac{1+nx}{1-x}\tag4
$$
vanishes as $n\to\infty$. Therefore, for $0\lt x\lt1$,
$$
\bbox[5px,border:2px solid #C0A000]{\sum_{k=0}^\infty\frac{k!\,x^k}{\prod_{j=1}^k(1+jx)}=\frac1{1-x}}\tag5
$$

Inductive Proof of $\bf{(1)}$
Trivially, we have that $(1)$ is true for $n=0$.
Suppose that we have $(1)$ for some $n$. Then
$$
\begin{align}
\frac1{1-x}
&=\sum_{k=0}^{n-1}\frac{k!\,x^k}{\prod_{j=1}^k(1+jx)}+\frac{n!\,x^n}{\prod_{j=0}^n(1+jx)}\frac{1+nx}{1-x}\\
&=\sum_{k=0}^{n-1}\frac{k!\,x^k}{\prod_{j=1}^k(1+jx)}+\frac{n!\,x^n}{\prod_{j=0}^n(1+jx)}\left(\color{#C00}{1}+\color{#090}{\frac{(n+1)x}{1-x}}\right)\\
&=\sum_{k=0}^{\color{#C00}{n}}\frac{k!\,x^k}{\prod_{j=1}^k(1+jx)}+\color{#090}{\frac{(n+1)!\,x^{n+1}}{\prod_{j=1}^{n+1}(1+jx)}\frac{1+(n+1)x}{1-x}}\tag6
\end{align}
$$
Thus, $(1)$ holds for $n+1$.
Answer: Using @Andrew Chin's comments, we face for the second series
$$S_\infty=\sum_{n=0}^\infty\frac{\Gamma(n+1)\, x^n}{\prod\limits_{m=0}^n(1+mx)}$$
Let $$a_n=\frac{\Gamma(n+1)\, x^n}{\prod\limits_{m=0}^n(1+mx)}=\frac{\Gamma (n+1)}{\left(1+\frac{1}{x}\right)_n}$$ where appear Pochhammer symbols. So
$$S_p=\sum_{n=0}^p a_n=\frac{\frac{\Gamma (p+2)\, \Gamma \left(\frac{1}{x}\right)}{\Gamma
   \left(p+1+\frac{1}{x}\right)}-1}{x-1}$$ and, assuming $0< x <1$
$$\lim_{p\to \infty } \, \frac{\Gamma (p+2) \Gamma \left(\frac{1}{x}\right)}{\Gamma
   \left(p+1+\frac{1}{x}\right)}=0$$ since, using expansion for large $p$
$$\frac{\Gamma (p+2) \Gamma \left(\frac{1}{x}\right)}{\Gamma
   \left(p+1+\frac{1}{x}\right)}=\Gamma \left(\frac{1}{x}\right) p^{1-\frac{1}{x}}\left(1+ \frac{(x-1) (2 x+1)}{2 x^2}\frac 1p+O\left(\frac{1}{p^2}\right)\right)$$

How to derive this series


AWS CodePipeline Notifications

Question: I am trying to add some notifications to my Pipeline in AWS.
I have a build stage where I use AWS CodeBuild and I want to receive an email whenever the build fails.
I have followed the tutorial that amazon offers and it works fine to notify me about the failure,  but I can't seem to find how to add the logs in the email.
I have created the following CloudWatch Event Rule, which monitors the execution of the entire Pipeline.
<code>{
  "source": [
  "aws.codepipeline"
  ],
  "detail-type": [
    "CodePipeline Pipeline Execution State Change"
  ],
  "detail": {
    "state": [
      "FAILED",
      "SUCCEEDED",
      "CANCELED"
    ],
    "pipeline": [
      "Pipeline_Trial"
    ]
  }
}
</code>
Can anyone help me figure how to add the logs to this rule ?
Comment: By logs do you mean eg. the CodeBuild build logs?
Comment: Exactly , @TimB
Answer: The event from CodePipeline does not contain the CodeBuild logs so you can't pass this through to your email without something in the middle.
A solution could be to have your CloudWatch event target a Lambda function which looks up the logs via the CodeBuild / CloudWatch logs API. It can then generate the email including the logs and send the notification via SNS.

AWS CodePipeline Notifications


Broken HTML tags - BeautifulSoup

Question: The below code perfectly scrapes the data from this website, except a few records which are contained in either broken HTML or are in different tags. Also, the initial letters for some of the names are not appearing, like for Cyclect Electrical Engineering Pte Ltd on this page  How can i fix this to have all the names appearing correctly :-
import requests
from bs4 import BeautifulSoup
import re

urls = []
for i in range(14,25):
    pages = "http://www.asmi.com/index.cfm?GPID={0}".format(i)
    urls.append(pages)
for info in urls:
    entry=[]
    page = requests.get(info)
    soup = BeautifulSoup(page.content, 'html5lib')
    text = [' '.join(items.split()) for items in soup(text =re.compile(r"Ltd$"))]
    print(text)

The output i am getting is
['ASL Shipyard Pte Ltd', 'Damen Shipyards Singapore Pte Ltd', 'DDW-PaxOcean Shipyard Pte Ltd', 'Dundee Marine & Industrial Services Pte Ltd', 'Dyna-Mac Engineering Services Pte Ltd', 'Five Aluminium Boat & Engineering Pte Ltd', 'Keppel FELS Ltd', 'Keppel Offshore & Marine Ltd', 'Keppel Shipyard Ltd', 'Keppel Singmarine Pte Ltd', 'Kim Heng Marine & Oilfield Pte Ltd', 'Kim Seah Boat Builders Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'Pandan Shipyard Pte Ltd', 'Penguin International Ltd', 'Sembcorp Marine Ltd', 'Sembcorp Marine Integrated Yard Pte Ltd', 'Sembcorp Marine Offshore Platforms Pte Ltd', 'Sembcorp Marine Repairs & Upgrades Pte Ltd', 'Sembcorp Marine Specialised Shipbuilding Pte Ltd', 'ST Engineering Marine Ltd', 'Strategic Marine (S) Pte Ltd', 'YTC Shipyard Pte Ltd']
['edge Technologies Pte Ltd', 'yclect Electrical Engineering Pte Ltd', 'Engie Axima Singapore Pte Ltd', '& Hopman Engineering Pte Ltd', 'OceanMaster Engineering Pte Ltd', 'Sindex Refrigeration Pte Ltd', 'Viking Engineering Pte Ltd']
[]
['Aedge Technologies Pte Ltd', 'Allbest Marine Engineering Pte Ltd', 'Atwin Marine Engineering Pte Ltd', 'Chugoku Marine Paints (S) Pte Ltd', 'Drew Ameriod (S) Pte Ltd', 'Hempel (Singapore) Pte Ltd', 'Hypex Engineering & Services Pte Ltd', 'ternational Paint Singapore Pte Ltd', 'LNT Coating Pte Ltd', 'PPG Coatings (Singapore) Pte Ltd', 'Viking Engineering Pte Ltd']
['edge Technologies Pte Ltd', 'Alphatron Marine Systems Pte Ltd', 'Codar (Pte) Ltd', 'Emerson Process Management Marine Solutions Singapore Pte Ltd', 'Furuno Singapore Pte Ltd', 'Jason Electronics (Pte) Ltd', 'Kongsberg Maritime Pte Ltd', 'Singapore Telecommunications Ltd', 'STSTC Pte Ltd', 'SWTS Pte Ltd']
['QA Systems Pte Ltd', 'Rigging & Marine Services Pte Ltd', 'Royscan Engineering Pte Ltd', 'Weldtech Inspection Services (S) Pte Ltd']
['ABB Pte Ltd', 'Aedge Technologies Pte Ltd', 'Alfa Laval Singapore Pte Ltd', 'Allbest Marine Engineering Pte Ltd', 'Alpine Engineering Services Pte Ltd', 'Apbco Offshore & Marine Pte Ltd', 'Atwin Marine Engineering Pte Ltd', 'Brightsun Marine Pte Ltd', 'Candid Marine Engineering Pte Ltd', 'Crestchic (Asia-Pacific) Pte Ltd', 'Cutech Solutions & Services Pte Ltd', 'Cyclect Electrical Engineering Pte Ltd', 'Devcon Enterprises Pte Ltd', 'yna-Mac Engineering Services Pte Ltd', 'EELAT Pte Ltd', 'Singapore Pte Ltd', 'Eng Soon Investment Pte Ltd', 'Five Aluminium Boat & Engineering Pte Ltd', 'Foo Ngan Marine Pte Ltd', 'Foster Asia Pacific Pte Ltd', 'obal Offshore & Marine Pte Ltd', 'Goltens Singapore Pte Ltd', 'Great Sun Offshore Pte Ltd', 'Heatec JieTong Pte Ltd', 'HongRong Engineering Pte Ltd', 'Hoo Huat Engineering Pte Ltd', 'Hup Hoe Engineering Pte Ltd', 'Hypex Engineering & Services Pte Ltd', 'Index-Cool Marine & Industry Pte Ltd', 'Jemix Engineering Pte Ltd', 'Johnson Controls (S) Pte Ltd', 'Keppel Sea Scan Pte Ltd', 'Kim Heng Marine & Oilfield Pte Ltd', 'Kim Seah Boat Builders Pte Ltd', 'Kok & Chan Marine Services Pte Ltd', 'K S Automation Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'Lam Heng Marine Pte Ltd', 'LPJ Marine Services Pte Ltd', 'Major Engineering and Technology Pte Ltd', 'Mantech Engineering Pte Ltd', 'Maritime Associates Pte Ltd', 'Mectrade Engineering Pte Ltd', 'Megawatts Engineering Services Pte Ltd', 'Mencast Holdings Ltd', 'Mentrade Marine Engineering Pte Ltd', 'New & Novel Engineering Pte Ltd', 'OceanMaster Engineering Pte Ltd', 'Onda Industries Engineering Marine Pte Ltd', 'QA Systems Pte Ltd', 'Rolls-Royce Singapore Pte Ltd', 'Royscan Engineering Pte Ltd', 'Seagull Pte Ltd', 'Seah Marine Engineering Pte Ltd', 'SeaTech Solutions International (S) Pte Ltd', 'Sentek Marine & Trading Pte Ltd', 'Siong Leng Engineering Pte Ltd', 'Sparrows Offshore Services (Singapore) Pte Ltd', 'SPCO Holdings Pte Ltd', 'Straits Innovation Pte Ltd', 'Star-Ray Pte Ltd', 'Ta-Ching Marine Technology Pte Ltd', 'Tech-Growth Engineering Pte Ltd', 'Tech Offshore Marine (S) Pte Ltd', 'Tru-Marine Pte Ltd', 'Viking Engineering Pte Ltd', 'Vita Enterprises Pte Ltd', 'Vosper Naval Systems Pte Ltd', 'Wah Soon Marine Pte Ltd', 'Yanmar Asia (S) Corporation Pte Ltd', 'Yong Cheong Marine & Engineering Pte Ltd']
['Caterpillar Marine Asia Pacific Pte Ltd', 'Chong Lee Leong Seng Co Ltd', 'Cinta Asia (Singapore) Pte Ltd', 'Cummins Sales and Service Singapore Pte Ltd', 'Daikai Engineering Pte Ltd', 'Harris Pye Singapore Pte Ltd', 'Junma Services Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'MAN Energy Solutions Singapore Pte Ltd', 'MTU Asia Pte Ltd', 'Power Diesel Engineering Pte Ltd', 'Rolls-Royce Singapore Pte Ltd', 'Stewart Engineering Works (S) Pte Ltd', 'Tractors Singapore Ltd', 'Tru-Marine Pte Ltd', 'Wartsila Singapore Pte Ltd', 'West Marine Engineering Pte Ltd', 'Xin Ming Hua Pte Ltd', 'Yanmar Asia (S) Corporation Pte Ltd']
['ABB Pte Ltd', 'Pte Ltd', 'Atlas Marine Services Pte Ltd', 'eng Hui Marine Electrical Pte Ltd', 'Best Technology Pte Ltd', 'hong Lee Leong Seng Co Ltd', 'Cinta Asia (Singapore) Pte Ltd', 'Daikai Engineering Pte Ltd', 'Drew Ameriod (S) Pte Ltd', 'Emerson Process Management Marine Solutions Singapore Pte Ltd', 'Engtek Pte Ltd', 'ERIKS Pte Ltd', 'ESAB Asia/Pacific Pte Ltd', 'Excel Marco Singapore Pte Ltd', 'Fassmer Singapore Pte Ltd', 'Finetek Pte Ltd', 'Flotech Controls Pte Ltd', 'Franklin Offshore International Pte Ltd', 'Global Marine Safety (Singapore) Pte Ltd', 'Griffin Group International Pte Ltd', 'Griffin Kinetic Pte Ltd', 'Harris Pye Singapore Pte Ltd', 'Hup Hoe Engineering Pte Ltd', 'HydroPro Pte Ltd', 'ICF International Pte Ltd', 'Industmarine Engineers Pte Ltd', 'Invertek Drives Far East Pte Ltd', 'Kelvin Hughes (Singapore) Pte Ltd', 'Keppel Sea Scan Pte Ltd', 'Kheng Cheong Co Pte Ltd', 'KM Kinley Marketing Pte Ltd', 'Kongsberg Maritime Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'acGregor Pte Ltd', 'Marinelec Technologies Asia Pte Ltd', 'Mencast Subsea Pte Ltd', 'MTU Asia Pte Ltd', 'Niigata Power Systems (Singapore) Pte Ltd', 'Nordic Flow Control Pte Ltd', 'OceanMaster Engineering Pte Ltd', 'Omega Pro Tech (1996) Pte Ltd', 'lfinger Asia Pacific Pte Ltd', 'Pamarine Pte Ltd', 'PH Hydraulics & Engineering Pte Ltd', 'Poclain Hydraulics Pte Ltd', 'K Instruments (S) Pte Ltd', 'Rapid Marine HVAC (Asia-Pacific) Pte Ltd', 'Reintjes Asia Pacific Pte Ltd', 'Robert Bosch (South East Asia) Pte Ltd', 'Scanjet Asia Pacific Pte Ltd', 'Scanvik Marine Services Pte Ltd', 'Schottel Far East (Pte) Ltd', 'Seaquest Enterprise Pte Ltd', 'Seng Heng Engineering Pte Ltd', 'SES Marine Services Pte Ltd', 'Singapore Cables Manufacturers Pte Ltd', 'SL Metals Pte Ltd', 'Sparrows Offshore Services (Singapore) Pte Ltd', 'Springer-EMS Pte Ltd', 'Teho International Inc Ltd', 'Tractors Singapore Ltd', 'Trans-Asiatic Trading Pte Ltd', 'Transvictory Winch System Pte Ltd', 'Turbo Solutions Pte Ltd', 'alves & Piping Asia Pte Ltd', 'Viking Engineering Pte Ltd', 'Wartsila Pumps Pte Ltd', 'Xin Ming Hua Pte Ltd', 'Z-Power Automation Pte Ltd', 'ZF Asia Pacific Pte Ltd']
['Aedge Technologies Pte Ltd', 'Any Mari Scaffolding Pte Ltd', 'HHE Scaffold Pte Ltd', 'Hoo Huat Engineering Pte Ltd', 'Multiheight Scaffolding Pte Ltd', 'Singa Marine Scaffolding Pte Ltd']
['Aedge Technologies Pte Ltd', 'Apbco Offshore & Marine Pte Ltd', 'ASL Solutions Pte Ltd', 'Astoria Solutions Pte Ltd', 'CESCO Environmental Technologies Pte Ltd', 'Cutech Solutions & Services Pte Ltd', 'Ecospec Global Technology Pte Ltd', 'Global Fire Solution Pte Ltd', 'Griffin Kinetic Pte Ltd', 'Kim Heng Marine & Oilfield Pte Ltd', 'M3 Marine Group Pte Ltd', 'Maritime Associates Pte Ltd', 'NSL OilChem Waste Management Pte Ltd', 'NYK ShipManagement Pte Ltd', 'ower Systech Pte Ltd', 'Rubicon Offshore International Pte Ltd', 'Seaquest Enterprise Pte Ltd', 'Sentek Marine & Trading Pte Ltd', 'The National Forwarder (S) Pte Ltd', 'Vision Global Engineering & Safety Services Pte Ltd']

Any input would be greatly appreciated !!
Comment: Hi renu, i think that I've solved that issue for you before ?
Comment: Hi Ahmed, no it was another one - https://stackoverflow.com/questions/59404674/beautifulsoup-not-fetching-the-data
Comment: so you want to take the `SHIPYARDS` company names for all pages?
Comment: The names for all companies are coming for all pages in the loop, except for some as i mentioned in the question
Comment: and for some records the initial alphabets are missing , but i am seeking to get all names with complete names for all the mentioned pages
Comment: that site is very interesting. let me see workaround
Comment: Sure !! Thank you so much for taking out time for this,
Comment: you welcome, Issue is fixed. check my answer below
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204713/discussion-between--c-and-renu).
Comment: i tried your suggestion and through your approach i could get the Zipcode, email, website, contact person , but couldn't extract the names properly & Address also, as i couldn't figure out the correct REGEX for Address line, Can you please help me on that
Comment: you should open a new question for that as it's different approach
Answer: import requests
from bs4 import BeautifulSoup
import re

for num in range(14, 25):
    r = requests.get(f"http://www.asmi.com/index.cfm?GPID={num}")
    soup = BeautifulSoup(r.text, 'html.parser')
    names = list(dict.fromkeys([' '.join(items.split())
                                for items in soup(text=re.compile(r'Ltd\s?$'))]))
    print(names)

Your assumption is wrong that each name ends with Ltd.
If you look at the source for page#14
You actually were missing 2 company names and sure for other pages as well:
Crestsa Marine & Offshore Pte Ltd
MMA Offshore Shipyard and Engineering Services Pte Ltd

If you did look at the source for the first company:
Crestsa Marine & Offshore Pte Ltd

  is non-breakable space ASCII 160
Thus the Ltd$ regex will not match, Because you have Ltd\xa0 at the end
So with r'Ltd\s?$' is now fixed.
Output:
['ASL Shipyard Pte Ltd', 'Crestsa Marine & Offshore Pte Ltd', 'Damen Shipyards Singapore Pte Ltd', 'DDW-PaxOcean Shipyard Pte Ltd', 'Dundee Marine & Industrial Services Pte Ltd', 'Dyna-Mac Engineering Services Pte Ltd', 'Five Aluminium Boat & Engineering Pte Ltd', 'Keppel FELS Ltd', 'Keppel Offshore & Marine Ltd', 'Keppel Shipyard Ltd', 'Keppel Singmarine Pte Ltd', 'Kim Heng Marine & Oilfield Pte Ltd', 'Kim Seah Boat Builders Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'MA Offshore Shipyard and Engineering Services Pte Ltd', 'Pandan Shipyard Pte Ltd', 'Penguin International Ltd', 'Sembcorp Marine Ltd', 'Sembcorp Marine Integrated Yard Pte Ltd', 'Sembcorp Marine Offshore Platforms Pte Ltd', 'Sembcorp Marine Repairs & Upgrades Pte Ltd', 'Sembcorp Marine Specialised Shipbuilding Pte Ltd', 'ST Engineering Marine Ltd', 'Strategic Marine (S) Pte Ltd', 'YTC Shipyard Pte Ltd']
['edge Technologies Pte Ltd', 'yclect Electrical Engineering Pte Ltd', 'Engie Axima
Singapore Pte Ltd', '& Hopman Engineering Pte Ltd', 'OceanMaster Engineering Pte Ltd', 'Sindex Refrigeration Pte Ltd', 'Viking Engineering Pte Ltd']
['Marine (Singapore) Pte Ltd', 'Singapore Pte Ltd', 'RINA Hong Kong Ltd']
['Aedge Technologies Pte Ltd', 'Allbest Marine Engineering Pte Ltd', 'Atwin Marine Engineering Pte Ltd', 'Chugoku Marine Paints (S) Pte Ltd', 'Drew Ameriod (S) Pte Ltd', 'Hempel (Singapore) Pte Ltd', 'Hypex Engineering & Services Pte Ltd', 'ternational Paint Singapore Pte Ltd', 'LNT Coating Pte Ltd', 'PPG Coatings (Singapore) Pte Ltd', 'Viking Engineering Pte Ltd']
['edge Technologies Pte Ltd', 'Alphatron Marine Systems Pte Ltd', 'Codar (Pte) Ltd', 'Emerson Process Management Marine Solutions Singapore Pte Ltd', 'Furuno Singapore
Pte Ltd', 'Jason Electronics (Pte) Ltd', 'Kongsberg Maritime Pte Ltd', 'Masstron Pte Ltd', 'Modern Automation & Engineering Pte Ltd', 'Singapore Telecommunications Ltd', 'STSTC Pte Ltd', 'SWTS Pte Ltd']
['QA Systems Pte Ltd', 'Rigging & Marine Services Pte Ltd', 'Royscan Engineering Pte Ltd', 'Weldtech Inspection Services (S) Pte Ltd']
['ABB Pte Ltd', 'Aedge Technologies Pte Ltd', 'Alfa Laval Singapore Pte Ltd', 'Allbest Marine Engineering Pte Ltd', 'Alpine Engineering Services Pte Ltd', 'Apbco Offshore & Marine Pte Ltd', 'Arc Marine Engineering Pte Ltd', 'Atwin Marine Engineering Pte Ltd', 'Brightsun Marine Pte Ltd', 'Candid Marine Engineering Pte Ltd', 'Crestchic
(Asia-Pacific) Pte Ltd', 'Cutech Solutions & Services Pte Ltd', 'Cyclect Electrical
Engineering Pte Ltd', 'Devcon Enterprises Pte Ltd', 'yna-Mac Engineering Services Pte Ltd', 'EELAT Pte Ltd', 'Singapore Pte Ltd', 'Eng Soon Investment Pte Ltd', 'Five Aluminium Boat & Engineering Pte Ltd', 'Foo Ngan Marine Pte Ltd', 'Foster Asia Pacific Pte Ltd', 'obal Offshore & Marine Pte Ltd', 'Goltens Singapore Pte Ltd', 'Great Sun Offshore Pte Ltd', 'Harris Pye Singapore Pte Ltd', 'Heatec JieTong Pte Ltd', 'HongRong Engineering Pte Ltd', 'Hoo Huat Engineering Pte Ltd', 'Hup Hoe Engineering Pte
Ltd', 'Hypex Engineering & Services Pte Ltd', 'Index-Cool Marine & Industry Pte Ltd', 'Japan Marine United Singapore Pte Ltd', 'Jemix Engineering Pte Ltd', 'Johnson Controls (S) Pte Ltd', 'Keppel Sea Scan Pte Ltd', 'Kim Heng Marine & Oilfield Pte Ltd', 'Kim Seah Boat Builders Pte Ltd', 'Kok & Chan Marine Services Pte Ltd', 'K S Automation Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'Lal Offshore Marine Pte Ltd', 'Lam Heng Marine Pte Ltd', 'LPJ Marine Services Pte Ltd', 'Major Engineering and Technology Pte Ltd', 'Mantech Engineering Pte Ltd', 'Maritime Associates Pte Ltd', 'Mectrade Engineering Pte Ltd', 'Megawatts Engineering Services Pte Ltd', 'Mencast Holdings Ltd', 'Mentrade Marine Engineering Pte Ltd', 'MR Marine Engineering Pte Ltd',
'MTQ Engineering Pte Ltd', 'New & Novel Engineering Pte Ltd', 'OceanMaster Engineering Pte Ltd', 'Onda Industries Engineering Marine Pte Ltd', 'Promor Pte Ltd', 'QA Systems Pte Ltd', 'Rolls-Royce Singapore Pte Ltd', 'Royscan Engineering Pte Ltd', 'Seagull Pte Ltd', 'Seah Marine Engineering Pte Ltd', 'SeaTech Solutions International (S) Pte Ltd', 'Sentek Marine & Trading Pte Ltd', 'Siemens Pte Ltd', 'Siong Leng Engineering Pte Ltd', 'SMIT Singapore Pte Ltd', 'Sparrows Offshore Services (Singapore) Pte Ltd', 'SPCO Holdings Pte Ltd', 'Straits Innovation Pte Ltd', 'Star-Ray Pte Ltd', 'SWTS Pte Ltd', 'Ta-Ching Marine Technology Pte Ltd', 'Tech-Growth Engineering Pte Ltd', 'Tech Offshore Marine (S) Pte Ltd', 'Tru-Marine Pte Ltd', 'Viking Engineering Pte Ltd', 'Vita Enterprises Pte Ltd', 'Vosper Naval Systems Pte Ltd', 'Wah Soon Marine Pte Ltd', 'Welmet Engineering Pte Ltd', 'Yanmar Asia (S) Corporation Pte Ltd', 'Yong Cheong Marine & Engineering Pte Ltd']
['Caterpillar Marine Asia Pacific Pte Ltd', 'Chong Lee Leong Seng Co Ltd', 'Cinta Asia (Singapore) Pte Ltd', 'Cummins Sales and Service Singapore Pte Ltd', 'Daikai Engineering Pte Ltd', 'Harris Pye Singapore Pte Ltd', 'Japan Marine United Singapore Pte Ltd', 'Junma Services Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'MAN Energy Solutions Singapore Pte Ltd', 'MTU Asia Pte Ltd', 'Power Diesel Engineering Pte Ltd', 'Rolls-Royce Singapore Pte Ltd', 'Stewart Engineering Works (S) Pte Ltd', 'Tractors Singapore Ltd', 'Tru-Marine Pte Ltd', 'Wartsila Singapore Pte Ltd', 'West Marine
Engineering Pte Ltd', 'Xin Ming Hua Pte Ltd', 'Yanmar Asia (S) Corporation Pte Ltd']
['ABB Pte Ltd', 'Aflex Ships Equipment Pte Ltd', 'Pte Ltd', 'Atlas Marine Services Pte Ltd', 'eng Hui Marine Electrical Pte Ltd', 'Best Technology Pte Ltd', 'Bloomfoss
Pte Ltd', 'hong Lee Leong Seng Co Ltd', 'Cinta Asia (Singapore) Pte Ltd', 'Crestsa Marine & Offshore Pte Ltd', 'Daikai Engineering Pte Ltd', 'Drew Ameriod (S) Pte Ltd', 'Emerson Process Management Marine Solutions Singapore Pte Ltd', 'Engtek Pte Ltd',
'ERIKS Pte Ltd', 'ESAB Asia/Pacific Pte Ltd', 'Excel Marco Singapore Pte Ltd', 'Fassmer Singapore Pte Ltd', 'Finetek Pte Ltd', 'Flotech Controls Pte Ltd', 'Franklin Offshore International Pte Ltd', 'Gardyon Pte Ltd', 'Global Marine Safety (Singapore) Pte Ltd', 'Griffin Group International Pte Ltd', 'Griffin Kinetic Pte Ltd', 'Harris Pye Singapore Pte Ltd', 'Hup Hoe Engineering Pte Ltd', 'HydroPro Pte Ltd', 'ICF International Pte Ltd', 'Industmarine Engineers Pte Ltd', 'Invertek Drives Far East Pte Ltd', 'Japan Marine United Singapore Pte Ltd', 'Kelvin Hughes (Singapore) Pte Ltd', 'Keppel Sea Scan Pte Ltd', 'Kheng Cheong Co Pte Ltd', 'KM Kinley Marketing Pte Ltd',
'Kongsberg Maritime Pte Ltd', 'KTL Offshore Pte Ltd', 'Kwong Soon Engineering Co. (Pte) Ltd', 'acGregor Pte Ltd', 'Marinelec Technologies Asia Pte Ltd', 'Mencast Subsea Pte Ltd', 'MEP Deck Solutions Pte Ltd', 'Mooreast Asia Pte Ltd', 'MTU Asia Pte Ltd', 'Niigata Power Systems (Singapore) Pte Ltd', 'Nordic Flow Control Pte Ltd', 'OceanMaster Engineering Pte Ltd', 'Omega Pro Tech (1996) Pte Ltd', 'lfinger Asia Pacific
Pte Ltd', 'Pamarine Pte Ltd', 'PH Hydraulics & Engineering Pte Ltd', 'Poclain Hydraulics Pte Ltd', 'K Instruments (S) Pte Ltd', 'Rapid Marine HVAC (Asia-Pacific) Pte Ltd', 'Reintjes Asia Pacific Pte Ltd', 'Robert Bosch (South East Asia) Pte Ltd', 'Scanjet Asia Pacific Pte Ltd', 'Scanvik Marine Services Pte Ltd', 'Schottel Far East (Pte) Ltd', 'Seaquest Enterprise Pte Ltd', 'Seng Heng Engineering Pte Ltd', 'Sensitron
Singapore (Sensing) Pte Ltd', 'SES Marine Services Pte Ltd', 'Singapore Cables Manufacturers Pte Ltd', 'SL Metals Pte Ltd', 'Sparrows Offshore Services (Singapore) Pte
Ltd', 'Springer-EMS Pte Ltd', 'Tat Wai Enterprise Pte Ltd', 'Teho International Inc
Ltd', 'Tractors Singapore Ltd', 'Trans-Asiatic Trading Pte Ltd', 'Transvictory Winch System Pte Ltd', 'Tri-Star Industries Pte Ltd', 'Turbo Solutions Pte Ltd', 'Uniclimb Services Pte Ltd', 'alves & Piping Asia Pte Ltd', 'Viking Engineering Pte Ltd', 'Wartsila Pumps Pte Ltd', 'Xin Ming Hua Pte Ltd', 'Z-Power Automation Pte Ltd', 'ZF Asia Pacific Pte Ltd']
['Aedge Technologies Pte Ltd', 'Any Mari Scaffolding Pte Ltd', 'HHE Scaffold Pte Ltd', 'Hoo Huat Engineering Pte Ltd', 'Multiheight Scaffolding Pte Ltd', 'Singa Marine
Scaffolding Pte Ltd']
['Aedge Technologies Pte Ltd', 'Apbco Offshore & Marine Pte Ltd', 'ASL Solutions Pte Ltd', 'Astoria Solutions Pte Ltd', 'CESCO Environmental Technologies Pte Ltd', 'Crestsa Marine & Offshore Pte Ltd', 'Cutech Solutions & Services Pte Ltd', 'Ecospec Global Technology Pte Ltd', 'Global Fire Solution Pte Ltd', 'Griffin Kinetic Pte Ltd',
'Kim Heng Marine & Oilfield Pte Ltd', 'M3 Marine Group Pte Ltd', 'Maritime Associates Pte Ltd', 'Mosestide Pte Ltd', 'NSL OilChem Waste Management Pte Ltd', 'NYK ShipManagement Pte Ltd', 'ower Systech Pte Ltd', 'Rubicon Offshore International Pte Ltd', 'Seaquest Enterprise Pte Ltd', 'Sentek Marine & Trading Pte Ltd', 'Sinwa (Singapore) Pte Ltd', 'Six Tee Engineering Groups Pte Ltd', 'The National Forwarder (S) Pte Ltd', 'Vision Global Engineering & Safety Services Pte Ltd']

Regarding your question about the name of Cyclect Electrical Engineering Pte Ltd
Actually the source include the following for it
yclect Electrical Engineering Pte Ltd
And regarding the letter C it's inside the following:

C

I've noticed that you only taken the companies which ending with Ltd but there's others as well. i do believe that you tried with that but actually the website is completely crab !
but you can use something like that to get the missed.
    other = list(dict.fromkeys([items.text
                                for items in soup.findAll("strong", text=True)]))
    print(names+other)

Broken HTML tags - BeautifulSoup


Arrays vs Generic in C#

Question: I have noticed that array, in c#, implements ICollection<T>. How can an array implement a generic container interface, yet not be generic itself? Is it possible for us to do the same?
Edit: I would also like to know how the array is not generic, yet it accepts any type and has type safety.
public class ListOfStrings : IList<string>
{
...
}

This is a great example that demonstrates that we can create non-generics from a generic (Thank you MarcinJuraszek!!). This collection would be stuck with strings. My guess is that it has nothing to do with the generic value type declaration of string and is some internal wiring that I am unfamiliar with.
Thank you again!
Comment: Arrays are already generic - `int[]` defines an array of type `int`. Since it's an in-built type, I would imagine there is some syntactical sugar to essentially be `Array` (Note, though, that `Array` is different from `[]` - it's just an example)
Comment: That makes complete sense and that will really help me think of this in the future! int[] ~ Array
Answer: Yes, it's totally possible. You can declare something like this:
public class MyListOfStrings : IList<string>
{
}

and as long as you implement all the properties/methods IList<string> requires you to everything will work just fine. As you can see MyListOfStrings is not generic.
You should also remember that Arrays are special types, and there is a bunch of stuff going on with them that's not happening with regular user-defined types. Some of it is described on MSDN, and the part that seem to be related to your questions is here:

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class. In addition, there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

As you can see Array implements IList<T>, ICollection<T> and IEnumerable<T> in a special way, and it's not something you can do with your own type.
Comment: I am unfamiliar with the etiquette here. I would like to clarify something in my question but I don't want it to to seem as if you didn't answer my question. Do I just make the edit or do I ask here? It is a question regarding the idea that an array accepts any type but your MyListOfStrings would only accept strings. How did they make the array non-generic but accept any type? Thanks for the edit, btw.
Comment: Feel free to update your question with that clarification.
Comment: @RyanWoods In general, if the edit invalidates existing answers, it's probably best to either clarify in the comments (assuming it's a minor change), or post a new question. Be aware though, that continually clarifying the question in comments is looked down upon - and at that point should probably be a new question.
Comment: Am I missing something, or does array not just implement the non-generic version or IList, ICollection, etc in 4.6.1? http://referencesource.microsoft.com/#mscorlib/system/array.cs
Comment: Thank you for the answer. I will take a look at the MSDN first next time. I will say that I would not have gleaned this information from the MSDN as well as you did. Your explanation gives it more sense. Between you, MarcinJuraszek, and Rob, I have a much better understanding of this topic. Thank you.
Comment: @SimonC Yes, `Array` (the class) only implements the non-generic version, but `int[]` implements `IList`
Comment: Hello Simon C,

I pasted the msdn class signature for an array. You are right!

`public abstract class Array : ICloneable, IList, ICollection,
 IEnumerable, IStructuralComparable, IStructuralEquatable`
Comment: @Rob, so that's what the `SZArrayHelper` does at runtime? Complex!

Arrays vs Generic in C#


Onsen UI postpop event is not firing

Question: I am trying to use onsen ui in Cordova development.

    <ons-navigator var="myNavigator" ng-controller="SubController" ons-prepush="onPopPost($event)" ons-postpop="onPopPost($event)">
        <ons-page>
            <ons-toolbar fixed-style>

            </ons-toolbar>
           <ons-tabbar position="top">
            <ons-tabbar-item active="true" page="latest.html" id="latestTab">

                <ons-toolbar-button class="tabmain" modifier="outline">   Latest  *</ons-button>

            </ons-tabbar-item>
    </ons-tabbar>
     </ons-page>
    </ons-navigator>

 <ons-template id="latest.html">
      <ons-page ng-controller="MainPageController" fixed-style>
 </ons-page>
  </ons-template>

In app.js I have
module.controller('AppController', function($scope,$timeout) {
$scope.onPopPost = function(event) {
        console.log("sad");
        console.log(event.enterPage);

      }

The event is not firing.
As per the documentation this is supported. But I could not see this event firing.
Is there any other settings I need to do?
Answer: Your navigator has the postpop handler but you are not pushing a page in the navigator. You are changing pages in the tabbar and those are different components. Use these events instead: http://onsen.io/reference/ons-tabbar.html#attributes
<ons-tabbar ng-controller="AppController" ons-postchange="onPopPost($event)" position="top">
   ...
</ons-tabbar>

Working here:
http://codepen.io/frankdiox/pen/NqOELO
Hope it helps!
Comment: `myNavigator.pushPage()` is working well. It is firing an event, I can see it on the console. However, you have a problem with Angular controllers in `launcher.html`. That page has no controller so when you call `closeLaunch()` nothing happens.
Comment: Thank you for the answer. I see the code is working in the codepen. But this is not firing in my project. I will create a minimal codepen code and send you the link. There is a ng-click I have added for the content inside one tab item. On Click of it I am using the code myNavigator.pushPage('launcher.html', { animation : 'lift' } ); there is a close button on the launcher.html. in that I am calling myNavigator.popPage('launcher.html'); none of these are firing any events
Comment: Fran Dios, added the code here. [http://codepen.io/kirant400/pen/jPeRNo](http://codepen.io/kirant400/pen/jPeRNo). if I add angular.module('app', ['onsen', 'ngSanitize']); code is not working. and tab events are working but not the push events

Onsen UI postpop event is not firing


use variable from another class

Question: I have two classes. I want to use english and french from the first class in the second class (class Question). Please help me to fix that code because it shows me an error.
Code Blocks :
package josephtraduire;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileParser implements IParser{

    @Override
    public void parseFile () throws IOException{
        String french="";
        String english="";

        try( BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\text.txt"))){
            String line;
            while ((line = br.readLine())!=null){
                    String[] pair = line.split(";");
                    french=(pair[0]);
                    english=(pair[1]);
            }
        }
    }

}

and
package josephtraduire;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Scanner;

public class Question extends FileParser {

String mot ;
String reponse ;
String name;
int nb;
int nbquest ;
String traduction;

Question (String name , int nb){
    this.name=name;
    this.nb=nb;
}

Question() throws IOException{

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(isr);
    {
        System.out.println("Entrer votre nom ");
        String nom = in.readLine();
        name=nom;
    }

    do {
        System.out.println("Rentrez le nombre de question :    ( max 20 )");
        Scanner nombrequest = new Scanner(System.in);
        nbquest = nombrequest.nextInt();
        nb=nbquest;
    }  while ( nbquest>20 ||nbquest<=0);

}

public void Play () throws IOException{

    int i=0;
    boolean bool=true;
    int score=0;
    String continuer;
    Date maDate = new Date();
    String a = maDate.toString() ;

    while (i<nbquest && bool) {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(isr);

        System.out.println("donner la traduction de "+french);
        String reponseee  = in.readLine();
        traduction=reponseee;

        if(bool=true ){
            if(traduction.equals(english)){
                score++;
                System.out.println("Bravo! Bonne reponse");
            }else{
                System.out.println("Mauvaise reponse");
            }
        }

Comment: Please format your code and post only relevant code snippet.
Comment: ... your ... your coding formatting ... the horror ....
Comment: Please format your code one more time and delete all unnecessary whitespaces, etc...
Comment: first of all format your code by using : ctrl+a and ctrl +shift+f (if you are using eclipse..)
Comment: You really need to pick up a beginner's book, or read a tutorial. Don't rush it.
Comment: You misspelled _french_ twice in your question, but not in your code. Did you write this?
Comment: *** is probably OPs attempt at bold text
Comment: My eyes are going to explode
Comment: @LukasWarsitz - format one more time???
Comment: What is `***french***=(pair[0]);` and `***english***=(pair[1]);`? Some kind of never seen Java pointers? O_O
Comment: R.I.P Indentation and formation :_____(
Comment: Besides the awful formatting of the question there is so much wrong with this "implementation" that I do not even know where to begin. General naming conventions also seem to be thrown out the window when there's something like `public void Play ()` Execution seems to be within a constructor and there is no main method or anything in sight.
Comment: Why is it still horrible after about 3 edits?
Comment: I don't believe any amount of edits will save this train-wreck
Comment: I'm struggling to get a full grasp of this, but 2 points. `English` and `French` are not instance members of the first class, they are just variables in a method. They are like mayflies, they live for but the scope of the method and then are gone. And what is `***french***=(pair[0]);`, I have never see the `***` operator before
Comment: @ all wannabe editors: if you're too lazy to do it properly, please leave it to others
Answer: I'm going to ignore the source code and answer this in general terms. You can access the instance variables of an object, either directly or using getters. I will use getters in this example.

Instance variables - live for as long as the class lives, they are
  declared within the body of the class but not within any method or
  constructor
Method variables - live for as long as the method and no longer, usually
  do some job and then are gone, they are declared within a
  method/constructor

public class ClassThatWantsFields {

    public String combineFields(ClassWithFields classWithFields){
        //if I have access to the object classWithFields then I have access to its
        //public methods (and possibly also protected and default access; but this is outside the scope of this question)
        return classWithFields.getEnglish()+classWithFields.getFrench();
    }

    public static void main(String[] args){
        ClassWithFields classWithFields=new ClassWithFields();
        ClassThatWantsFields classThatWantsFields=new ClassThatWantsFields();

        System.out.println(classThatWantsFields.combineFields(classWithFields));
    }

}

public class ClassWithFields {
    private String English; //these are instance variables, they live for as long as the object lives
    private String French;

    private String preservedMayFly;

    public ClassWithFields(){
        English="A language called English";
        French="A language called French";

        //mayfly is a method variable, it will be gone once the constructor
        //exits, anything you want to keep for the life of the object should
        //NOT be a method variable
        String mayfly="I won't live long";

        //preservedMayFly is an instance variable and will live as long as
        //the object
        preservedMayFly=mayfly+"but I can be used within the method"
    }

    public String getEnglish() {
        return English;
    }

    public String getFrench() {
        return French;
    }

}

use variable from another class