How can I fix a squeaky hardwood floor in a small hallway?

Question: Trying to fix squeaky hardwood floor in small hallway, think joists run parallel to floorboards on sides, near or under the walls on either side, can't find any with stud finder that run at 90 degree angle to floor.
Any ideas what to do?
I know about those kits with the scored screws that snap off, but will they work if just screwed into subfloor?
Comment: The squeaking is wood rubbing during movement.  You have to identify what is moving and stop the movement.  Could be hardwood to hardwood, hardwood to subfloor, or subfloor to joist.  Either fasten what ever it is together or wedge it so it cannot move or both.  The hard part is access and identifying what actually is rubbing.  Good Luck.
Answer: I'm going to skip over the likelihood of this parallel joist situation actually being true (I have a deep mis-trust of stud finders), and attempt to just answer your question.
Answer part 1 - can any of this floor (+ subfloor) come up without causing damage/serious inconvenience to you or the property?  If so, then I would strongly suggest pulling up a couple of boards and having a look around.  I (unfortunately) had to do this in an old bathroom because we needed to move a sink, and after tearing up some plywood subfloor and 3 floorboards found a half-disintegrated joist holding up one end of the room.
I don't think your situation will be the same (water damage less likely in a hallway), but if it isn't obvious where to screw in to stop the squeaking this should help you out.
Answer part 2 - you aren't likely to get much long-term improvement from just screwing through to the subloor.  A long term fix will require knowing where those joists are (parallel or otherwise!)
Addendum
In an older property of mine, we regularly encountered the situation where a joist would be located directly underneath an internal wall, making affixing the boards to them pretty difficult.  If you can't find recognizable joists close to the walls - this could be why.  We solved that one by sistering another joist to it to give us something to screw into.
Answer: I haven't done this before, but I've seen it done in an my previous home and it worked for at least two years. Note this is not the best way to fix this, the right way is to lift all the boards. If this is an impossible hassle, likely to result in just more damaged areas.
identify the moving boards, using a very small bit (like 1/16) drill through the floor at ~ 45 degree angle just under the flooring's sound and/or moisture barrier. Using a syringe and 12-guage needle, inject glue to fill any gap that is causing squeaking. Glue serves as a means to fill the pockets causing the squeaking and also lock everything together. Now if this is laminate, laminate floods should be floating flanked by expansion gaps. using glue threatens the integrity of this expansion of the wood and could very potentially cause buckling later down the road.
Put some heavy weight onto the area being glues.
Answer: Stud finders are usually unable to find wood joists under thick wood floors. They are for drywall.
Friction noises depend where noise really comes from, not where you step.
In one house with plywood then oak hardwood, it was the  joist & X pieces . Polyurethane tube of sub-floor adhesive to an open basement ceiling joist edges applied like sealant fixed all those.
In my present house parquet oak 1x5" pieces glued to subfloor had spots that squeeked but we're caused by wall tightly touching floor. Anything to cut a gap under the wall moulding to floor in area near interfere noise fixed those.


How do I see my dota 2 MMR?

Question: Is there a way to see my MMR? The simpler, the better.
Answer: Yes, you can edit your profile, so that it is always shown, when you look at your profile.
When you click on "Edit Profile", there are two dropdown list, right next to the edit button.

(nevermind the fact, that I'm playing with the german client)
When there are no numbers, that means that you have not played enough games in either ranked solo or group (in my case, I did not play enough ranked solo, for my mmr to show up)
Answer: Here's how:

Open the new (Reborn) game client.
Click your name, top right.

Click Edit Profile, top right.

Choose the two MMR options:

Hit save!

There's now to boxes where you can showcase things, amongst which your solo and party mmr.
Comment: You can also see it in the "Play Dota" menu when selecting Ranked Game.
Answer: Another way is to click "Play Dota" then select the "Ranked Match" tab.  You don't have to actually play a game, but it should tell you your MMR there.
Answer: In the patch 7.07 "Dueling Fates", released on November 22, 2017, the rating system got reworked.
This means that you won't see your rating in your profile or at the Find Match tab anymore.
You can still find both your Solo and Party ratings by opening your ingame user profile, and selecting the "Stats" tab. Both ratings are listed on the upper right side.

How do I see my dota 2 MMR?


SQL monthly statement using recursive cte

Question: I am trying to create a monthly bank account statement from a transaction table which has all history records.
I would like have opening balance as the first row and then the current months transaction with the updated balance at that time using recursive cte.
I know this can be done by table update too but recursion is what i am looking for.
the table structure would be like:
declare @temp table (date datetime,tran_id int,cust_id int,tran_type char,amount int)
insert into @temp values('2017-06-06 22:05:10.703',1,1,'c',700),
('2017-06-12 22:05:10.703',2,1,'d',100),('2017-06-20 22:05:10.703',3,1,'c',200),
('2017-06-26 22:05:10.703',4,1,'d',450),(getdate()+1,5,1,'d',200),
(getdate()+2,6,1,'d',200),(getdate()+3,7,1,'c',500),
(getdate()+4,8,1,'d',300),(getdate()+5,9,1,'d',200),
('2017-06-18 22:05:10.703',12,1,'d',100)

So in here there is transaction for month 6 and 7.
The opening balance of current month would be sum of all transactions in June which will be used as anchor to get recursive balance.
Now i would like the select query to have date,tran_id,cust_id,credit,debit,balance as the result set.
So if table has data like:
date                   tran_id  cust_id tran_type   amount
2017-06-06 22:05:10.703 1   1   c   700
2017-06-12 22:05:10.703 2   1   d   100
2017-06-20 22:05:10.703 3   1   c   200
2017-06-26 22:05:10.703 4   1   d   450
2017-07-08 16:34:24.817 5   1   d   200
2017-07-09 16:34:24.817 6   1   d   200
2017-07-10 16:34:24.817 7   1   c   500
2017-07-11 16:34:24.817 8   1   d   300
2017-07-12 16:34:24.817 9   1   d   200
2017-06-18 22:05:10.703 12  1   d   100

The monthly statement for month 7 should be like:
opening balance of 250

date                     tran_id    cust_id credit  debit   balance
2017-07-08 16:40:56.810     5        1      NULL     200    50
2017-07-09 16:40:56.810     6        1      NULL     200    -150
2017-07-10 16:40:56.810     7        1      500      NULL   350
2017-07-11 16:40:56.810     8        1      NULL     300    -50
2017-07-12 16:40:56.810     9        1      NULL     200    -250

i have tried using recursive cte and sum windowed  function but it does not give continuous balance just a row by row balance.
Also using aggregate functions in a cte is a no no so stuck at that too.
;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
),

cte2 as
(
select * from cte
union all
select t.cust_id,amount+[opening balance] as 'balance1' from @temp t join
cte2 c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte2

OR
;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
union all
select t.cust_id,SUM(amount+[opening balance]) as 'balance1' from @temp t
join cte c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte
option (MAXRECURSION 1000)

what am i missing?
Comment: Can you add the expected result in table format
Comment: added the table with expected results
Comment: Which version of sql server you are using
Comment: SQL Server 2008
Answer: Just use a cumulative sum:
select t.*,
       sum(case when tran_type = 'c' then amount else - amount end) over
           (partition by cust_id order by date) as balance
from @temp t;

You can then select a range using a subquery or CTE:
select t.*
from (select t.*,
             sum(case when tran_type = 'c' then amount else - amount end) over
                 (partition by cust_id order by date) as balance
      from @temp t
     ) t
where . . .

You need a subquery for the where, so it doesn't affect the cumulative sum.
EDIT:
In SQL Server 2008, you can use cross apply:
select t.*,
       t2.balance
from @temp t cross apply
     (select sum(case when t2.tran_type = 'c' then t2.amount else - t2.amount end) as balance
      from @temp t2
      where t2.cust_id = t.cust_id and t2.date <= t.date
     ) t2;

Comment: this is helpful but i was looking for solutions in the case of SQL Server 2008
Answer: For older versions, you can use CROSS APPLY to calculate the running balance
;WITH opening_balance_cte
     AS (SELECT cust_id,
                Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS opening_balance
         FROM   Yourtable
         WHERE  [date] < '2017-07-01'
         GROUP  BY cust_id)
SELECT *,
       balance
FROM   Yourtable a
       JOIN opening_balance_cte ob
         ON ob.cust_id = a.cust_id
       CROSS apply (SELECT ob.opening_balance + Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS balance
                    FROM   Yourtable b
                    WHERE  a.cust_id = b.cust_id
                           AND a.tran_id >= b.tran_id
                           AND b.[date] >= '2017-07-01'
                           AND b.[date] < '2017-08-01') cs
WHERE  a.[date] >= '2017-07-01'
       AND a.[date] < '2017-08-01'

If you really want to know how to achieve this using Recursive CTE then
;WITH opening_balance_cte
     AS (SELECT cust_id,
                Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS opening_balance
         FROM   @temp
         WHERE  [date] < '2017-07-01'
         GROUP  BY cust_id),
     rec_cte
     AS (SELECT TOP 1 a.*,
                      opening_balance + CASE WHEN tran_type = 'c' THEN amount ELSE -amount END AS balance
         FROM   @temp a
                JOIN opening_balance_cte o
                  ON a.cust_id = o.cust_id
         WHERE  a.[date] >= '2017-07-01'
                AND a.[date] < '2017-08-01'
         ORDER  BY a.[date] ASC
         UNION ALL
         SELECT t.*,
                rc.balance + CASE WHEN t.tran_type = 'c' THEN t.amount ELSE -t.amount END
         FROM   rec_cte rc
                JOIN @temp t
                  ON t.cust_id = rc.cust_id
                     AND t.tran_id = rc.tran_id + 1)
SELECT *
FROM   rec_cte

Comment: yes..this works..correct me if i am wrong but there is no way this can be done using recursive cte right?because of the group by clause..
Comment: @AnisShaikh - We can do using `Recursive CTE` but this is a better way
Comment: @AnisShaikh - Updated with `Recursive CTE` answer
Comment: yes this is what i set out to do ...did use two ctes but used aggregate in second one too..perfect..Thanks for taking out the time..@prdp
Comment: @AnisShaikh - Glad it was helpful.. have fun ;)


I get the message "disconnected from server" after minutes away from the game. Did WoW reduce the AFK timeout?

Question: I've noticed this very recently and I don't recall reading something about in any of the recent patch notes.
I hop on a flying route and, as any normal human being, get bored of watching the bird flapping its wings all the way until I reach my destination 5 minutes later, so I alt-tab to go browse for something (mostly game-related research, such as finding a recipe/npc location -- nothing against game policy!).
Having spent barely 1-2 minutes out of the game, I alt-tab and find myself "disconnected from server".  And it's not just once or twice, it really happens a lot and is literally within a couple minutes.  Did they reduce the afk timeout or something?
Comment: I've gotten disconnected a couple times during cinematics. The one at the end of Vashj'ir disconnected me and when I got back in I was bugged. Probably just high server load mixed with a few bugs they haven't ironed out.
Comment: I've been seeing this in other games, too... although I think it may be my ISP.  Or its upstream provider (level 3).  In fact, it wouldn't surprise me if Level 3 is having all sorts of bandwidth issues due to its addition of Netflix traffic.
Comment: Have had SO many alt-tab disconnects lately...
Answer: The answer is no. They have not changed anything that effects AFK. Well, not in the sense that you are referring to. It is caused by high server loads for the most part. That and visiting other sites while logged in to the game.
I have the same issue. However, it only effects certain areas. Example, in Deepholm I was disconnected many times during the Stonehearth quest line. I was guarantee to be disconnected if I switch to surfing WoW Head, WoW forums, etc, etc, while logged in to World of Warcraft in the Stonehearth area and the area just to the north of it. That was because of the amount of data that was sent from the server. The server normally sends less than 2KB with few-second-spikes up to 30KB. This wasn't the case in this particular area. I continually had a 15 to 25KB streaming from the server while in this area of Deepholm. Again, it only happens in certain areas. I can be in Org during prime time with slight lag in comparison of my normal lag.
Other effected areas were two spots in Hyjal. One was the area that everyone is first ported to. The second effected area around the Circle of Cinders.
I found few short-term solutions on the official WoW forums from a Blizzard Blue. One is disable add-ons since of them uses bandwidth to talk to other players. An example would the GearScore add-on. Also, discontinuing surfing sites and limit what other system application that uses bandwidth while logged in to WoW. Here is another, which happen to surprise me, disable the your Combat Chat via removing the filters. Here is a link to the post I refer to.
Comment: This is about lag, not getting disconnected, isn't it? Or are they related?
Answer: If you're on a comcast server, they have started targetting wow users one at a time, claiming excessive bandwidth useage. They cap port 25, & chokehold your internet, then they claim you are a spammer & want to charge you in excess of $200+ bucks to remove the cap. Ironically they started doing this just efore the "net Nuetrallity" bill was signed in congress. Big surprise eh?
I haven't been able to log into wow since Dec 13th because of this comcast issue. I would switch providers in a heartbeat, that is if comcast hadn't already bought out all the tv, phone, & internet in my area.
Answer: I have found that if I change WoW to Windowed mode in the Video setting then I can Alt-Tab to other programs without the disconnection issue that started with the 4.0 patch for me. Also, I have noticed that if I'm in a party, it's less likely to disconnect me while Alt-Tabbed out. I think WoW is detecting being put into the background by Windows. Setting priority on the process might help, although I haven't tried that.
Comment: Same here - haven't had a problem with disco since I switched to Windowed Full Screen.  Also lets me browse the internet on one monitor while WoW remains visible on the other.
Answer: I'm going to throw out that Cataclysm came out a mere three days ago. It's a good bet that most, if not all, of Blizzard's hardware is taking unprecedented load, and will do so for quite some time.
Give it a few days, and see if the situation changes.
Comment: No no...  This has been happening since two weeks before Cata
Answer: Yes, they definitely have.  As of several months ago (well before the 4.* set of patches) Blizzard made some change that resulted in you getting disconnected if you're Alt-Tabbed out in a number of situations, specifically when you land after taking a flight path and also when you complete a "Loading..." display, whether that's on the initial log-in to a character, changing zones or Hearthstone-ing.  This happens every single time for me regardless of how long I last interacted with WoW before landing, so it's definitely not an AFK function.
Comment: Confirming that this is indeed true. If you are tasked out when landing using flight paths, or when the loading screen finishes, you _will_ be disced.
Comment: Alt-tabbing at the loading screen used to kick me off if I was zoning into Dalaran but not anywhere else.
Comment: @GreatBigFish - I tested this today and found an interesting fact.  Alt-Tabbing while logging into Exodar resulted in no disconnection.  Doing it while logging into Stormwind resulted in a disconnection.  So that part definitely seems related to activity in the area where you're logging into.


Date Range Filter Standard

Question: Has anyone encountered Date Range Filtering Standards in any business areas?
What is the best practice in Date Range Filtering, V1 or V2?
What could be some better options than this?
Answer: There can be some more approaches apart from the ones shown in the question. For e.g. the user should be shown a calendar indicator if they can pick from a calendar next to the input box. A detailed answer can be found here on UX.StackExchange: Better way for users to select a date range
Material Design Guidelines: https://material.io/components/date-pickers#desktop-pickers

Google Bookings
Answer: Depends on the audience and device (mobile/ desktop). From an Accessibility perspective V1 is better because it includes labels.
Comment: could you explain how the audience affects picking a particular filter?

Date Range Filter Standard


A better name for "Non Archived" entries

Question: My app shows a list of items that require the user's attention, and allows to "archive" some of them, and access the archived items later (like in Gmail)
I can't figure out a name for the "Non Archived" items (which are displayed by default). In gmail it is called "Inbox", but my app is not about emails.
Any ideas?
Comment: "Active" or "To be viewed" or "Received"
Comment: What's your app about then? Maybe there's an equivalent for inbox.
Comment: @PS86 No, it's not. The question is not about how to say something in English. It is on how to say something in a way that users will understand and not get confused. In other words - how to improve user experience.
Comment: "Current" ?....
Comment: "Fresh", "hot", "(a)live", "front …", "agenda", "work items", "popular", "stock"
Comment: This question is better suited to English language and usage site. http://english.stackexchange.com/
Comment: @Tzach I partially agree with you but I bet you would quickly get the answer you are looking for in there from the language experts...
Answer: If you have a common default state, then you don't have to mark that default state.  Instead you indicate when the state differs from the default.
The default state of an item is "unarchived", so you it would be strange to have to relate a default state to a non-default state.  It would be like marking files that haven't been deleted on your computer as "not deleted".  There is no need as everything is not-deleted unless it is deleted.
As long as you're clearly indicating the documents that are archived, I wouldn't call the other documents anything.
Comment: This makes sense. However in my app the archived items screen is visually replacing the default screen, and there must be a way to go back to the default screen, a link for example. In your files example, imagine that in any given time you can only view the recycle bin or the not-deleted files, how would you go back to the not-deleted?
Comment: @Tzach You don't have to name where you're going in that case, just name where you're leaving.  "Exit recycle bin" or "leave archives" are all more clear than trying to name the unnamed.
Answer: Don't name the unnamed. Instead reference only the named.

Leave Archive
Close Archive View

or something similar.
Answer: We have decided to go with "Need Attention" and "Archived". We tested it with our users and it works ok.
We also tried "Active" before, but it was confusing, because the items we display can be "Active" and "Closed" regardless on their location in my app.


winforms keeps freezing -endless loop? how do i un-freeze?

Question: I have a program which displays an image to the windows form, and places a message within the image as it paints it (this works fine) i then have a method which reads the message back. However, doing this causes the winforms screen to freeze! i must be getting stuck in an endless loop. The method does work as i do get the message back.... can anyone help un-freeze my program?
Code below:
<code>    public partial class MyImages : Form
    {
        //I have variables related to encoding and decoding here(deleted)
        private const String MESSAGE = "2008-01-07";

        Bitmap firstLoaded;
        Bitmap theImage;
        Bitmap imageEmbedded;
        Boolean isGetMessage = false;
        Boolean isEmbedImage = false;
        Boolean isLoaded = false;
        Graphics graphicsWindow;   // reference to the graphic surface of this window
        Graphics graphicsImage;     // reference to in-memory surface
        BitArray bitsOfMessage = new BitArray(8);
        String bytesOfTheMessage = null;

        public MyImages()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
        }

        private void MyImages_Paint(object sender, PaintEventArgs e)
        {
            HandlePainting();
        }

        public void HandlePainting()
        {
            if (isLoaded == true)
            {
                theImage = new Bitmap(Width, Height);     // bitmap for window surface copy
                graphicsWindow = CreateGraphics();   // get our current window's surface
                graphicsImage = Graphics.FromImage(theImage);     // create surfaces from the bitmaps
                graphicsImage.DrawImage(firstLoaded, 0, 0, Width, Height);

                if (isEmbedImage == true)
                {
                    theImage = embedMessageInImage(theImage);
                }
                else if (isGetMessage == true)
                {
                    getEmbeddedMessage(imageEmbedded);
                }

                if (isGetMessage == false)
                {
                    graphicsWindow.DrawImage(theImage, 0, 0);
                }
                else if (isGetMessage == true)
                {
                    graphicsWindow.DrawImage(imageEmbedded, 0, 0);
                }
            }
        }

        private void toolStripMenuItemLoadImage_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Title = "Load Image";

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    firstLoaded = new Bitmap(ofd.FileName);
                    this.Invalidate();
                }
            }
            isLoaded = true;
        }

        private void toolStripMenuEmbedMessage_Click(object sender, EventArgs e)
        {
            isEmbedImage = true;
            isGetMessage = false;
            this.Invalidate();
        }

        private void toolStripMenuItemGetMessage_Click(object sender, EventArgs e)
        {
            isEmbedImage = false;
            isGetMessage = true;
            this.Invalidate();
        }

        public void convertToChar(int byteChar)
        {
            char val = Convert.ToChar(byteChar);
            String nextChar = val.ToString();
            bytesOfTheMessage += nextChar;

        }

        private Bitmap embedMessageInImage(Bitmap bmp)
        {
           //Embed message in this method (deleted)

                //unlock the bitmaps
                newBitmap.UnlockBits(newData);
                bmp.Save("tina.bmp");
                bmp.UnlockBits(originalData);
                newBitmap.Save("tina7.bmp");
                imageEmbedded = newBitmap;
                return newBitmap;
            }
        }

        private void getEmbeddedMessage(Bitmap bmp)
        {
            unsafe
            {
                //create an empty bitmap the same size as original
                Bitmap newBitmap = new Bitmap(bmp.Width, bmp.Height);

                //lock the original bitmap in memory
                System.Drawing.Imaging.BitmapData originalData = bmp.LockBits(
                   new Rectangle(0, 0, bmp.Width, bmp.Height),
                   System.Drawing.Imaging.ImageLockMode.ReadOnly,
                   System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                //lock the new bitmap in memory
                System.Drawing.Imaging.BitmapData newData = newBitmap.LockBits(
                   new Rectangle(0, 0, bmp.Width, bmp.Height),
                   System.Drawing.Imaging.ImageLockMode.WriteOnly,
                   System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                //set the number of bytes per pixel
                int pixelSize = 3;

                for (int y = 0; y < bmp.Height; y++)
                {
                    //get the data from the original image
                    byte* originalImageRow = (byte*)originalData.Scan0 + (y * originalData.Stride);

                    //get the data from the new image
                    byte* newImageRow = (byte*)newData.Scan0 + (y * newData.Stride);

                    for (int x = 0; x < bmp.Width; x++)
                    {

                        byte b = (byte)(originalImageRow[x * pixelSize + 0]); // B
                        getEachBitOfMessage(b, BLUE);

                        byte g = (byte)(originalImageRow[x * pixelSize + 1]); // G
                        getEachBitOfMessage(g, GREEN);

                        byte r = ((byte)(originalImageRow[x * pixelSize + 2])); //R
                        getEachBitOfMessage(r, RED);

                    }
                }

                //unlock the bitmaps
                newBitmap.UnlockBits(newData);
                bmp.UnlockBits(originalData);
            }
        }

        public byte changeEachBit(byte byteToManipulate, int colour, byte theMessage)
        {
            byte value = 0;
            byte returnByte = 0;

            if (colour == BLUE)
            {
               value= (byte)(theMessage & BValueMask);
               value = (byte)(value>>5);
               returnByte = (byte)(byteToManipulate & BlueMask);
               returnByte = (byte)(returnByte | value);

            }
            else if (colour == GREEN)
            {
                value = (byte)(theMessage & GValueMask);
                value = (byte)(value >> 3);
                returnByte = (byte)(byteToManipulate & GreenMask);
                returnByte = (byte)(returnByte | value);

            }
            else if (colour == RED)
            {
                value = (byte)(theMessage & RValueMask);
                returnByte = (byte)(byteToManipulate & RedMask);
                returnByte = (byte)(returnByte | value);
            }

            return returnByte;
        }

        public void getEachBitOfMessage(byte byteToManipulate, int colour)
        {
            //I Input bits into image here (deleted)

        }
    }
}
</code>
Comment: What have you tried? How do you know it's an infinite loop? Do you really expect someone to copy all of your code, debug it, then tell you what the problem was?
Comment: Implement some log4net logging.
Answer: Let it freeze and click the Pause button on the top toolbar.
This will cause the debugger to break wherever execution may be, and you can then easily identify where it got stuck, and try and find out why as well (don't forget to watch values using the watch window or hovering them).
Comment: Thanks, i didn't know you could do that!


Find a simple formula for f(n)

Question: Let $f_n$ be the number of ways to choose a permutation π of [n] and then a subset of the cycles of π. For instance, f(2) = 6 (check!). Find a simple formula for f(n)(not involving any sums!).
Would this be ${n \choose π} * {π \choose k}$?
Answer: For a permutation with $k$ cycles, the number of subsets is $2^k$.
The number of ways to choose a permutation and then a subset of its cycles is thus:
$$\sum_{k=0}^n |s(n,k)|2^k=(n+1)!$$
Where $s(n,k)$ are Stirling numbers of the first kind: $|s(n,k)|$ is the number of permutations of $\{1,\dots,n\}$ with $k$ cycles.

The preceding formula is a special case of:
$$x(x+1)\cdots(x+n-1)=\sum_{k=0}^n |s(n,k)|x^k$$
It's often used as a definition of (unsigned) Stirling numbers of the first kind. It can then be used to prove the recurrence relation on Stirling numbers, which in turn, is used to prove the relation with permutation cycles. See here (I'll add a summary later to the answer).
Comment: Where does the π factor into this? In place of k, do i just put π? Also, since the questions asks for formula not involving sum, the answer will just be (n+1)!.
Comment: @hilh Yes, the answer is $(n+1)!$, the sum is just the way to find this formula. Note that the sum runs on the number of cycles, and $|s(n,k)|$ is the number of permutations of $\{1...n\}$ with $k$ cycles. There is no $\pi$ involved. Anyway, you can't have $\pi$ in the closed-form formula: it's not a known constant of the problem, it would be, at best, an arbitrary permutation (possibly a sum index, but here it's not how it's computed).
Comment: Could you explain how you get (n+1)! again?

Find a simple formula for f(n)


Why can't I upgrade my Saka Horse Archers & Horsemen?

Question: I have Saka Horse Archers. I now have the Stirrups tech and have made a Knight. However I do not have the option to upgrade Saka Horse Archers or Horsemen to Knights.
Why not? Am I missing something?
They are light cavalry - but this is not in wikipedia. What am I missing?
Answer: Knights are not light cavalry they are heavy cavalry. Chariots or War carts can upgrade to Knights but Horsemen cannot.
Comment: thanks - is there a visual guide to all of this that you've seen? I think I may also need 2 sources of horses to do certain upgrades too (or an encampment)?
Comment: There's short descriptions of the units that do say light cavalry or heavy cavalry.  I think this description shows up when hovering over the unit in the build menu.
Answer: The next upgrade for horsemen is the cavalry from the industrial era.
Saka horse archers are actually classified as a ranged unit, not a cavalry unit at all. They also skip the upgrade to crossbowman and upgrade directly to field cannons, meaning they'll be pretty useless during the medieval/renaissance era.
You can check which class a unit belongs to and what it upgrades to on its civilopedia page.
Comment: thx - they weren't too bad as they were such veterans at that point they had 2 attacks & the Scythian heal after killing the opponent unique. I now have a lot of field cannons ;)


Determine the conditional probability mass function of the size of a randomly chosen family containing 2 girls.

Question: Suppose that 15 percent of the families in a certain community have no children, 20 percent have 1, 35 percent have 2, and 30 percent have 3 children; suppose further that each child is equally likely (and independently) to be a boy or a girl. If a family is chosen at random from this community, then B, the number of boys, and G, the number of girls, determine the conditional probability mass function of the size of a randomly chosen family containing 2 girls.
My attempt
There are exactly three ways this can happen:
1) family has exactly 2 girls
  2) family has 2 girls and 1 boy
  3) family has all 3 girls
The first one is pretty simple. Given that you are going to "select" exactly two children, find the probability that they are BOTH girls (it's a coin flip, so p = 50% = 0.5):
$0.5^2 = 0.25$
So the probability that the family has exactly 2 girls is the probability that the family has exactly two children times the probability that those two children will be girls:
$\frac{1}{4} \cdot 35\% = 8.75\%$
Now find the probability that, given the family has exactly 3 children, that exacly two are girls. Now you flip 3 times but only need to "win" twice-this is a binomial experiment.
There are 3 choose 2 = 3 ways to have exactly two girls: 1st, 2nd, or 3rd is a boy... interestingly the probability of having any particular permutation is just $0.5^3 = 1/8$ (because it's still $0.5 \times 0.5$ for two girls, then $0.5$ for one boy).
So the chance of exactly 2 girls is: $\frac{3}{8}$
Now find the probability for having exactly 3 girls... that's easy, there's only one way, you just have all 3 girls, probability is just $\frac{1}{8}$.
Now, add these up
$\frac{3}{8} + \frac{1}{8} = \frac{4}{8} = \frac{1}{2}$
So now use the percent of families with exactly 3 children to find this portion of the probability:
$\frac{1}{2} \cdot 30\%  = 15\%$
Hence, add the two probabilities... here is it in full detail
$$\begin{eqnarray}\mathbb{P}(\text{contains 2 girls}) &=& \mathbb{P}(\text{2 children}) \times \mathbb{P}(\text{2 girls, 2 children}) + \\ &\phantom{+=}& \mathbb{P}(\text{3 children}) \times \mathbb{P}(\text{2 or 3 girls, 3 children}) \end{eqnarray}$$
$\frac{1}{4} 35\%  + 30\% \times \left(\frac{3}{8} +\frac{ 1}{8}\right)$
$8.75\% + 15\% = 23.75\%$
Is my attempt correct?
Answer: It's correct as far as it goes, but it's incomplete. You've shown that $23.75$% of the families have at least two girls, but that doesn't answer the question. What you're to find is probability mass function of the family size given that the family has two girls. In other words, you want to calculate $$\Bbb P(B+G=x\mid G\ge 2)$$ for the various possible values of $x$.
This is very easy and obvious for $x=0$ and $x=1$, so I'll skip to $x=2$.
You calculated that $8.75$% of all the families have exactly two girls and no boys. What fraction of the families with at least two girls is this? It's $$\frac{8.75}{23.75}=\frac7{19}\;,$$ so the conditional probability that a randomly chosen family has exactly two children given that it has at least two girls is $7/19$: $\Bbb P(B+G=2\mid G\ge 2)=7/19$.
From here you should be able to finish it, I think.
Comment: @Daniela: It's part of the result. You still need to calculate $\Bbb P(B+G=x\mid G\ge 2)$ for $x=0,x=1$, and $x=3$.
Comment: So this is the result?
Comment: thanks very much.I understand
Answer: The problem statement is somewhat ambiguous. Either we want to find (i) the (conditional) probability distribution of the family size, given that there are at least $2$ girls, or (ii) the (conditional) probability distribution of the family size, given that there are exactly $2$ girls.  The phrase "containing $2$ girls" can be interpreted either way, with some tilting towards (i) as the more likely.
We calculate the probabilities for (i). The probability that there are at least $2$ girls is $(0.35)(1/2)^2 +(0.30)(1/2)$.  The second part of the sum is because if the family has $3$ children, the probability that girls will outnumber boys is, by symmetry, equal to $1/2$. You computed this probability correctly.
That is not what you are being asked to find, though it is a very useful part of the process. Given that there are at least $2$ girls, the family size is either $2$ or $3$. We want to find the conditional probability that the family size is $2$. (Then we will be able to find quickly the conditional probability that the family size is $3$.)
Let $G$ be the event "there are at least $2$ girls" and let $S_2$ be the event "the family size is $2$." We want $P(S_2|G)$.
By a formula that may be familiar, we have
$$P(S_2|G)P(G)=P(S_2\cap G)=P(G|S_2)P(S_2).$$
Now we are essentially finished. We know $P(G)$, because we computed it above. We know $P(G|S_2)$, it is $(1/2)^2$. And we know $P(S_2)$, we were told what it is in the statement of the problem.
To solve the problem under the assumption (ii), the procedure is almost the same, but the probabilities are different.  For example, the probability that a family has exactly $2$ girls is $(0.35)(1/2)^2+(0.30)(3/8)$.


How do you make a data frame with unequal row lengths?

Question: I have a large data frame, ExprsData, with several numeric and NA values. It looks something like this:

Patient
Gene_A
Gene_C
Gene_D

patient1
12
16
NA

patient2
15
NA
20

My data frame has 15 rows and 14 columns.
I have made a function that is meant to scale and center the values in my data frame:
MyScale <- function (x, scale, center){
  removena <- x[!is.na(x)] #remove the NA values
  meanofdata <- mean(removena) #calc the mean
  stdofdata <- sd(removena) #calc the std

if (scale==TRUE){ #if scale is true
  calcvec <- (removena - meanofdata)/stdofdata
  return(calcvec)
}else if (center ==TRUE){ #if vec is true
  centervec <- removena - meanofdata
  return(centervec)
}
}

I tested out my function by running a a single column of my data frame like this:
MyScale (ExprsData$Gene_C, scale = TRUE, center = TRUE)

It works great!
Next, I want to be able to apply my function to my entire data frame, have it output as a data frame, assign it to an object and then save as a csv.
To do this I tried this:
ExprsDataScaled <- as.data.frame(lapply(ExprsData, function(x) MyScale(x = x, scale = TRUE, center = TRUE)))
write.csv(ExprsDataScaled,"?path//filename.csv", row.names = TRUE)

However, when I try to apply my function to my entire data frame, I get the following error: Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  :
arguments imply differing number of rows: 14, 15
I understand that I am getting this error message because my columns differ in length. I know this is because in my function, I have it remove the NA values. I need to do this because otherwise I run into a lot of errors when I try to scale and center later in the function.
Is there a way to make a data frame with unequal columns? Is there a way to re-insert "NA" back into my data frame once it has been scaled and centered to avoid this error? Or a way to insert blank cells in some columns so they can all be the same length?
Comment: Actually, *arguments imply differing number of rows: 14, 15* means not that your rows differ in lengths, but that the **columns** differ in length (i.e. they have different number of rows)
Comment: What's wrong with the base function `scale`?
Comment: @dario typo. Original question has been edited.
Comment: @Limey I know this scale function exists. Just trying to make my own for practice
Comment: 1) Don't just remove NA values from your data, but handle them on a case-by-case basis (thats why R **has** NA as a symbol) 2) A data.frame **must** have equal length columns! Thats one of the guarantees you have when using a data.frame as opposed to a generic *list of lists*
Comment: @dario What does handling NA on a case-by-case basis mean?
Comment: Remove the NA **only** temporary for calculations (or rather *during* calculations). I'd strongly suggest getting more familiar with the basics before trying to implement functionality (otherwise you will be in for some nasty surprises ;)
Comment: @dario ohhhh i got it! I added na.rm=TRUE when scaling and centering instead of removing the NA values altogether and it worked. Thanks!
Answer: This is a better version of you function that does not remove any NA from your data:
(However, the function will still trip on non numeric values for x, or in cases where scale and center are both FALSE. But one could ask oneself why a scale function needs a scale yes or no parameter??)
MyScale <- function (x, scale, center){
  meanofdata <- mean(x, na.rm = TRUE)
  stdofdata <- sd(x, na.rm = TRUE)

  if (scale==TRUE){
    calcvec <- (x - meanofdata)/stdofdata
    return(calcvec)
  }else if (center ==TRUE){
    centervec <- x - meanofdata
    return(centervec)
  }
}


Get localized name other channel

Question: I get the version number of the firefox from the applications.ini.
Then I hardcoded that between date #### and #### v35 is release. So now based on this and the current date and version from applications.ini I figure out the channel of other builds.
But now I want to get the localized name of the channel.
So for example I'm using beta channel and from this build I want to get the localized name of "Nightly" in chineese, so it has the chineese characters, and word for nightly in chineese. Can this also be obtained from the applications.ini? Is [App] -> Name localized in applications.ini?
This is the applications.ini method: https://ask.mozilla.org/question/705/detect-if-auroranightlybetanormal-and-get-paths/ (credits to @paa)
EDIT
i discovered this file: OS.Path.join(Services.dirsvc.get('XREExeF', Ci.nsIFile).parent.path, 'defaults', 'pref', 'channel-prefs.js')
its contents is the following:
//@line 2 "c:\builds\moz2_slave\rel-m-beta-w32_bld-00000000000\build\browser\app\profile\channel-prefs.js"
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

pref("app.update.channel", "beta");

Is this a reliable check? Does this channel-prefs.js file exist for all builds as soon as they are installed?
Answer:
Is this a reliable check?

Not really. There used to be channel switcher add-ons, and in theory the user can change this pref (although at the moment this is not sufficient to really switch the channel I think).

Does this channel-prefs.js file exist for all builds as soon as they are installed?

Yes, for now. But this is an implementation detail. There is no guarantee that the file won't be moved or renamed later, or merged with another file.

Can this also be obtained from the applications.ini?

The localized name? I didn't even know there was one... I thought it was called e.g. "Nightly" in all locales like it was a (product) name. But yeah, it is theoretically possible to localize that string. It is not available from the ini file, though.
I wouldn't poke in application.ini anyway, and instead just use Services.appinfo.defaultUpdateChannel

But now I want to get the localized name of the channel.

Since you're in a running Firefox instance already (judging from your OS.File code), you should use the string bundle service to load chrome://branding/locale/brand.properties and get the brandShortName or brandFullName string from there.
Comment: Thanks @namaier, do you know since what FF version, the `channel-pref.js` file would get put there? Thanks for the brand.properties, is there any way from one build, to get the brandShortName for other channels, like from aurora channel to get the nightly/release/beta brandShortName? The biggest thing I'm trying to do is detect channel of another build based on it's build path which I have stored.

Get localized name other channel


Retrieving multiple values from the database using php unity3d

Question: I am making like RPG game where user can login and save and load the data. I can login and save. But, when I want to load the data, I am having a trouble to load that.
I will post the necessary code only (PHP code (Load.php)):
    <?PHP

    $Username = $_POST['Username'];
    $Location = $_POST['Location'];
    $Gold = $_POST['Gold'];
    $Level = $_POST['Level'];
    $Attack = $_POST['Attack'];
    $Defense = $_POST['Defense'];
    $MagicDefense = $_POST['MagicDefense'];
    $Evasion = $_POST['Evasion'];
    $Health = $_POST['Health'];
    $MaxHealth = $_POST['MaxHealth'];
    $Mana = $_POST['Mana'];
    $MaxMana = $_POST['MaxMana'];
    $Exp = $_POST['Exp'];
    $NextExp = $_POST['NextExp'];
    $AcceptedChiefQuest = $_POST['AcceptedChiefQuest'];
    $AddedChiefQuest = $_POST['AddedChiefQuest'];

    $con = mysql_connect("SERVER_NAME","DATABASE_NAME","PASSWORD") or ("Cannot connect!"  . mysql_error());

    if (!$con)
        die('Could not connect: ' . mysql_error());

    mysql_select_db("DATABASE_NAME" , $con) or die ("Could not load the database" . mysql_error());

    $check = mysql_query("SELECT * FROM Information WHERE `Username` = '".$Username."'");

    $numrows = mysql_num_rows($check);

    if ($numrows > 0)
    {
        while($row = mysql_fetch_assoc($check))
        {
            $Username = $row['Username'];
            $Location = $row['Location'];
            $Gold = $row['Gold'];
            $Level = $row['Level'];
            $Attack = $row['Attack'];
            $Defense = $row['Defense'];
            $MagicDefense = $row['MagicDefense'];
            $Evasion = $row['Evasion'];
            $Health = $row['Health'];
            $MaxHealth = $row['MaxHealth'];
            $Mana = $row['Mana'];
            $MaxMana = $row['MaxMana'];
            $Exp = $row['Exp'];
            $NextExp = $row['NextExp'];
            $AcceptedChiefQuest = $row['AcceptedChiefQuest'];
            $AddedChiefQuest = $row['AddedChiefQuest'];

            echo $Username;
            echo $Location;
        }

        die();
    }

    else
    {
        die ("Data does not exist!");
    }

    ?>

And here where I access it by script in Unity (necessary code where the problem is):
    IEnumerator LoadCoroutine(WWW _www)
        {
            yield return _www;

            if (_www.error == null)
            {
                message = _www.text;

                if (_www.text == "Data does not exist!")
                {
                    message = "Data does not exist";

                    clickedLoadGame = false;
                }

                else if (_www.text == "Saved data does not match!")
                {
                    message = "Saved data does not match";

                    clickedLoadGame = false;
                }

                else
                {
                    if (_www.text == "Village")
                    {
                        GameManager.CurrentLocation = "Village";

                        GameManager.Loader = 1;
                    }

                    else if (_www.text == "Yein Plain")
                    {
                        GameManager.CurrentLocation = "Yein Plain";

                        GameManager.Loader = 4;
                    }

                    message = "Successfully Loaded.";

                    mainMenu = false;

                    yield return new WaitForSeconds(3);

                    Reset();

                    GameManager.LoadLevel("Loading Scene");
                }
            }

            else
            {
                message = "Error while trying to connect to the server.\nMessage: " + _www.error;

                clickedLoadGame = false;
            }
        }

The script only return single value which is $Location based on PHP code, and when I want to retrieve the $Username for example, the _www.text will be VillageYunnan which is I dont want, I want only the single value will be printed on _www.text, like Village or Yunnan and not VillageYunnan and that is only for 2 values, if I want to retrieve all of the $ in PHP, it will be like VillageYunnan15101010100 and so on, which will be very hard to maintain.
My question is I only want the _www.text only print like a single value and not combined together like I mention before.
Any help?
Really appreciate your answer.
Thank you
EDITED: (Required Code)
GameManager.cs
public static void WebsiteConnect(string link)
{
    wwwForm = new WWWForm();

    wwwForm.AddField("Username", LoggedInUsername);
    wwwForm.AddField("Gold", UserInformation.CurrentGold);
    wwwForm.AddField("Level", Status.level);
    wwwForm.AddField("Attack", Status.attack);
    wwwForm.AddField("Defense", Status.defense);
    wwwForm.AddField("MagicDefense", Status.magicDefense);
    wwwForm.AddField("Evasion", Status.evasion);
    wwwForm.AddField("Health", Status.hp);
    wwwForm.AddField("MaxHealth", Status.maxHp);
    wwwForm.AddField("Mana", Status.mp);
    wwwForm.AddField("MaxMana", Status.maxMp);
    wwwForm.AddField("Exp", Status.CurrentExperience);
    wwwForm.AddField("NextExp", Status.NextLevelExperience);
    wwwForm.AddField("AcceptedChiefQuest", QuestManager._acceptedChiefQuest);
    wwwForm.AddField("AddedChiefQuest", QuestManager._addedChiefQuest);
    }

    www = new WWW(link, wwwForm);
}

And i called it like this:
private void OnGUI()
{
if (GUILayout.Button("Continue", customStartButton.customStyles[0]))
            {
                clickedLoadGame = true;

                audio.PlayOneShot(audioSEClip);

                Load();
            }
}

private void Load()
    {
        GameManager.WebsiteConnect("WEBSITE_ADDRESS/Load.php");
        StartCoroutine(LoadCoroutine(GameManager.www));
    }

IEnumerator LoadCoroutine(WWW _www)
    {
        yield return _www;

        if (_www.error == null)
        {
            message = _www.text;

            var jsonObject = JSON.Parse(_www.text);

            //string jsonString = jsonObject.ToString();

            Debug.Log(jsonObject);

            if (_www.text == "Data does not exist!")
            {
                message = "Saved data does not match!";

                mainMenu = false;

                fadeAudio = false;

                yield return new WaitForSeconds(3);

                clickedLoadGame = false;

                Reset();
            }

            else
            {
                if (_www.text == "Village")
                {
                    message = "Successfully Loaded.";

                    GameManager.CurrentLocation = "Village";

                    GameManager.Loader = 1;

                    mainMenu = false;

                    fadeAudio = true;

                    yield return new WaitForSeconds(3);

                    Reset();

                    GameManager.LoadLevel("Loading Scene");
                }

                else if (_www.text == "Yein Plain")
                {
                    message = "Successfully Loaded.";

                    GameManager.CurrentLocation = "Yein Plain";

                    GameManager.Loader = 4;

                    mainMenu = false;

                    fadeAudio = true;

                    yield return new WaitForSeconds(3);

                    Reset();

                    GameManager.LoadLevel("Loading Scene");
                }

                else
                {
                    message = "Data does not exist!";

                    mainMenu = false;

                    fadeAudio = false;

                    yield return new WaitForSeconds(3);

                    clickedLoadGame = false;

                    Reset();
                }
            }
        }

        else
        {
            message = "Error while trying to connect to the server.\nMessage: " + _www.error;

            clickedLoadGame = false;
        }
    }

And here is the PHP code (Load.php):
<?PHP

$Username = $_POST['Username'];
$Location = $_POST['Location'];
$Gold = $_POST['Gold'];
$Level = $_POST['Level'];
$Attack = $_POST['Attack'];
$Defense = $_POST['Defense'];
$MagicDefense = $_POST['MagicDefense'];
$Evasion = $_POST['Evasion'];
$Health = $_POST['Health'];
$MaxHealth = $_POST['MaxHealth'];
$Mana = $_POST['Mana'];
$MaxMana = $_POST['MaxMana'];
$Exp = $_POST['Exp'];
$NextExp = $_POST['NextExp'];
$AcceptedChiefQuest = $_POST['AcceptedChiefQuest'];
$AddedChiefQuest = $_POST['AddedChiefQuest'];

$con = mysql_connect("WEBSITE_ADDRESS","DATABASE_NAME","PASSWORD") or ("Cannot connect!"  . mysql_error());

if (!$con)
    die('Could not connect: ' . mysql_error());

mysql_select_db("DATABASE_NAME" , $con) or die ("Could not load the database" . mysql_error());

$check = mysql_query("SELECT * FROM Information WHERE `Username` = '".$Username."'");

$numrows = mysql_num_rows($check);

if ($numrows > 0)
{
    while($row = mysql_fetch_assoc($check))
    {
        if ($Username == $row['Username'])
        {
            $Username = $row['Username'];
            $Location = $row['Location'];
            $Gold = $row['Gold'];
            $Level = $row['Level'];
            $Attack = $row['Attack'];
            $Defense = $row['Defense'];
            $MagicDefense = $row['MagicDefense'];
            $Evasion = $row['Evasion'];
            $Health = $row['Health'];
            $MaxHealth = $row['MaxHealth'];
            $Mana = $row['Mana'];
            $MaxMana = $row['MaxMana'];
            $Exp = $row['Exp'];
            $NextExp = $row['NextExp'];
            $AcceptedChiefQuest = $row['AcceptedChiefQuest'];
            $AddedChiefQuest = $row['AddedChiefQuest'];

            json_encode($row);
        }

        else
        {
            die ("Saved data does not match!");
        }
    }

    die();
}

else
{
    die ("Data does not exist!");
}

?>

When I delete all the $Username and so on and replace it with json_encode($row) only and if the PHP code stays like above, the result still same, there is an error pointed at string jsonString = jsonObject.ToString(); and the var jsonObject = JSON.Parse(_www.text); is null.
Answer: You can use some common format (like xml or json) to share structured data between different applications.
In PHP code replace:
$Username = $row['Username'];
$Location = $row['Location'];
$Gold = $row['Gold'];
$Level = $row['Level'];
$Attack = $row['Attack'];
$Defense = $row['Defense'];
$MagicDefense = $row['MagicDefense'];
$Evasion = $row['Evasion'];
$Health = $row['Health'];
$MaxHealth = $row['MaxHealth'];
$Mana = $row['Mana'];
$MaxMana = $row['MaxMana'];
$Exp = $row['Exp'];
$NextExp = $row['NextExp'];
$AcceptedChiefQuest = $row['AcceptedChiefQuest'];
$AddedChiefQuest = $row['AddedChiefQuest'];

echo $Username;
echo $Location;

with:
echo json_encode($row);

In C# code use some JSON library (like SimpleJSON) to parse JSON string and retreive encoded data.
Comment: do you mean by replace the code is I should remove just the `echo $Username` and so on, or I should remove both the `$Username = $row['Username']` and `echo $Username` and replace it with `json_encode($row)`? Thanks
Comment: if you want to export whole object (i.e. all fields from selected table row) - then yes. If not, than you can create new associative array and json_encode it.
Comment: Hi @rtf_leg, I already tried the SimpleJSON, and replace the PHP code above with `json_encode($row)` and upload it to the server, and in C# I do it like this: `var jsonObject = JSON.Parse(_www.text);

            string jsonString = jsonObject.ToString();

            Debug.Log(jsonString);`

But when I run, it gives me an error of `NullReferenceException: Object reference not set to an instance of an object`. What could be wrong? Thank you
Comment: This means that you try to call instance method without instance. What line throws exception?
Comment: the error pointed at this code: `string jsonString = jsonObject.ToString();`
Comment: Ok, jsonObject is null and you try to call ToString() on it - NullReferenceException.
Comment: SimpleJSON as you suggested sir @rtf_leg. And in C#, I import it like `using SimpleJSON;` and yes sir, I just comment out the `string jsonString = jsonObject.ToString();` and Debug the `jsonObject`, the result was `null`.
Comment: Ok, it seems like JSON.Parse(_www.text) returns null. Can you show me contents of _www.text? SimpleJSON returns null for empty strings.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/72761/discussion-between-yunnan-and-rtf-leg).
Comment: @rtf_leg could you please edit the answer to include what you did in chat/comments to finish answering the question?
Answer: I'm not 100% sure I get the question but I think this is the cause of your problems:
        echo $Username;
        echo $Location;

This would output YunnanVillage which is bad. Replace it with:
        echo '[' . $Username . ',' . $Location . ']';

This will output [Yunnan, Village]. You can now parse this string much more easily (it's a JSON format). Note that this is an extremely simple example, there are much better ways to output an array in PHP, for example:
json_encode(array('Username' => $Username, 'Location' => $Location));

I'm here due to c# tag but know PHP enough to see the error in your code. Hope this helps.
Comment: What i mean is, I want the output to be whether `Village` or `Yunnan` which from the PHP, i set echo `$Location` and `$Username`. But the problem is, when I set the echo like that, the result of `_www.text` is `VillageYunnan`. I apologize if my question did not clear enough. I will try your code and let you know @bokibeg. Thank you anyway for replying the question. And, if I already put `json_encode(array(blablabla));` in the PHP code, what can I retrieve the result in C#? is `_www.text` still do it?
Comment: You can parse the resulting _www.text via some JSON library in C# like rtf_leg suggested. Problem is that you aren't using the echo syntax correctly, check [this reference](http://php.net/manual/en/function.echo.php) if you're still confused about how to get the proper output.
Comment: Hi @bokibeg, I already tried the SimpleJSON, and replace the PHP code with `json_encode($row)` and upload it to the server, and in C# I do it like this: `var jsonObject = JSON.Parse(_www.text); string jsonString = jsonObject.ToString(); Debug.Log(jsonString);` But when I run, it gives me an error of `NullReferenceException: Object reference not set to an instance of an object`. What could be wrong? Thank you


Session.request and 'Decimal' is not JSON serializable

Question: I try to improve my Django knowledge (I'm a beginner) by developing a Django ecommerce website.
I'd like to have two types of cart, one named cart and this other one named composed_cart.
I have an error with the composed_cart.
I came accross the following error when I try to display the cart: Object of type 'Decimal' is not JSON serializable
For my add to composed_cart class, I use the following code:
composed_cart.py:
class ComposedCart(object):
def __init__(self, request):
    self.session = request.session
    composed_cart = self.session.get('composed_cart')

    if not composed_cart:
        composed_cart = self.session['composed_cart'] = {}
    self.composed_cart = composed_cart

def add_composed(self, product, quantity=1):
    product_id = str(product.id)

    if product_id not in self.composed_cart:
        self.composed_cart[product_id] = {'quantity': 1,'price': str(product.prix_unitaire), 'tva': str(product.taux_TVA.taux_applicable)}

    else:
        self.composed_cart[product_id]['quantity'] += quantity #Ajoute +1 à la quantité et met à jour le dictionnaire contenant la quantité. += signifie ajoute à la valeur initiale de quantité.

    self.save()

def save(self):
    self.session['composed_cart'] = self.composed_cart
    self.session.modified = True

def remove(self, product): #Supprimer le produit, quelque soit la quantité.
    product_id = str(product.id)

    if product_id in self.composed_cart:
        del self.composed_cart[product_id]
    self.save()

def remove_one(self, product, quantity=1): #Méthode permettant de supprimer une unité du produit.
    product_id = str(product.id)

    if product_id in self.composed_cart: #Si le produit est dans le panier
        if self.composed_cart[product_id]['quantity'] > 1: #Et si la quantité de ce produit est supérieure à 1
            self.composed_cart[product_id]['quantity'] -= quantity #On enlève la quantité par défaut, d'est à dire 1.
        else:
            del self.composed_cart[product_id] #Si la quantité du produit est égale à 1 alors et que l'on veut enlever une unité, cela veut dire que l'on supprimer le produit.
    self.save()

def __iter__(self):

    product_ids = self.composed_cart.keys() #Sélectionne les différentes clés du dictionnaires, dans notre cas l'id du produit, la quantité, le prix.

    products = Article.objects.filter(id__in=product_ids) #On filtre sur les IDs présents dans le dictionnaire du panier.

    for product in products:
        self.composed_cart[str(product.id)]['product'] = product

    for item in self.composed_cart.values():
        item['price'] = Decimal(item['price'])
        item['tva'] = Decimal(item['tva'])
        item['total_price'] = item['price'] * item['quantity']
        item['total_item_tva'] = item['total_price'] - item['total_price'] / item['tva'] #Calcul du total de TVA par article.
        yield item

def __len__(self):
    return sum(item['quantity'] for item in self.composed_cart.values())

def get_total_price(self):
    return sum(Decimal(item['price']) * item['quantity'] for item in self.composed_cart.values())

def get_total_tva(self):
    return sum(round(Decimal(item['total_item_tva']),2) for item in self.composed_cart.values()) #Calcul de la TVA, round(X,2), permet d'arrondir à 2 décimales après la virgule le montant de la TVA

def get_sub_total_price(self):
    return sum(Decimal(item['price']) * item['quantity'] for item in self.composed_cart.values()) - sum(round(Decimal(item['total_item_tva']),2) for item in self.composed_cart.values())

def clear(self):
    del self.session['composed_cart']
    self.session.modified = True

My cart.py:
class Cart(object):
    def __init__(self, request):
        self.session = request.session
        cart = self.session.get('cart')

        if not cart:
            cart = self.session['cart'] = {}
        self.cart = cart

    def add(self, product, quantity=1):
        product_id = str(product.id)

        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 1,'price': str(product.prix_unitaire), 'tva': str(product.taux_TVA.taux_applicable)}

        else:
            self.cart[product_id]['quantity'] += quantity #Ajoute +1 à la quantité et met à jour le dictionnaire contenant la quantité. += signifie ajoute à la valeur initiale de quantité.

        self.save()

    def save(self):
        self.session['cart'] = self.cart
        self.session.modified = True

    def remove(self, product): #Supprimer le produit, quelque soit la quantité.
        product_id = str(product.id)

        if product_id in self.cart:
            del self.cart[product_id]
        self.save()

    def remove_one(self, product, quantity=1): #Méthode permettant de supprimer une unité du produit.
        product_id = str(product.id)

        if product_id in self.cart: #Si le produit est dans le panier
            if self.cart[product_id]['quantity'] > 1: #Et si la quantité de ce produit est supérieure à 1
                self.cart[product_id]['quantity'] -= quantity #On enlève la quantité par défaut, d'est à dire 1.
            else:
                del self.cart[product_id] #Si la quantité du produit est égale à 1 alors et que l'on veut enlever une unité, cela veut dire que l'on supprimer le produit.
        self.save()

    def __iter__(self):

        product_ids = self.cart.keys() #Sélectionne les différentes clés du dictionnaires, dans notre cas l'id du produit, la quantité, le prix.

        products = Article.objects.filter(id__in=product_ids) #On filtre sur les IDs présents dans le dictionnaire du panier.

        for product in products:
            self.cart[str(product.id)]['product'] = product

        for item in self.cart.values():
            item['price'] = Decimal(item['price'])
            item['tva'] = Decimal(item['tva'])
            item['total_price'] = item['price'] * item['quantity']
            item['total_item_tva'] = item['total_price'] - item['total_price'] / item['tva'] #Calcul du total de TVA par article.
            yield item

    def __len__(self):
        return sum(item['quantity'] for item in self.cart.values())

    def get_total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

    def get_total_tva(self):
        return sum(round(Decimal(item['total_item_tva']),2) for item in self.cart.values()) #Calcul de la TVA, round(X,2), permet d'arrondir à 2 décimales après la virgule le montant de la TVA

    def get_sub_total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) - sum(round(Decimal(item['total_item_tva']),2) for item in self.cart.values())

    def clear(self):
        del self.session['cart']
        self.session.modified = True

My view is this one for adding product:
@require_POST
def cart_add(request, product_id):
    product = get_object_or_404(Article, id=product_id)
    #Si le produit ajouté au panier est un article simple sans composition, alors on l'ajoute directement au panier.
    if product.article_composer == False:
        cart = Cart(request)
        form = CartAddProductForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            next = cd['next'] # Permet d'enregistrer la page précédente et d'y retourner une fois la quantité ajoutée dans le panier.
            cart.add(product=product, quantity=cd['quantity'])
        return HttpResponseRedirect(next) # Redirection vers la page d'où le produit a été ajouté.

    #Si l'article que l'on ajoute au panier sert à composer alors on utilise la méthode permettant de composer un article.
    else:
        composed_cart = ComposedCart(request)
        form = ComposedCartForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            next = cd['next'] # Permet d'enregistrer la page précédente et d'y retourner une fois la quantité ajoutée dans le panier.
            composed_cart.add_composed(product=product, quantity=cd['quantity'])
        return HttpResponseRedirect(next)

And for displaying my cart:
def cart_detail(request):
    cart = Cart(request)
    composed_cart = ComposedCart(request)
    cart_product_form = CartAddProductForm()
    return render(request, 'panier/panier.html', locals())

I don't undestand why i get a TypeError. Do you have any ideas? How can i improve my code to get rid off this error?
Thanks in advance
Singertwist
Answer: I think the problem is locals() that you are sending over to the paneer.html.
locals() is a dictionary of everything in your current namespace which includes complex objects that cannot be serialized (i.e. converted into simple objects such as integer or string).
In order to fix this, try to change it to something simple:
return render(request, 'panier/panier.html', {'test': 'value'})

If it works, or gives another error, change it to what you need.
The error says that some of the fields are not JSON serializable. The simplest solution would be something like this:
cart = {
    'product_id': cart.product_id,
    ...
}

composed_cart = {
    'id': composed_cart.id,
    ...
}

return render(request, 'panier/panier.html', {'cart': cart, 'composed_cart': composed_cart})

That is, manually serialize your objects and choosing the fields that you need in the template.
Hope it helps.
Comment: Thank for your answer,
But I get the same error with the following code:
return render(request, 'panier/panier.html', {'cart': cart, 'composed_cart':composed_cart})
Comment: @singertwist can you try with just `{'test': 'value'}`?
Comment: i tried {'test': 'value'}, i don't have any error. I can display the page (without any data).
I did several other tests for trying to understand the problem.
As I mentioned above, I have two carts, Cart and Composed_Cart
These carts use the same code, except the session request which are:
- for the composed_cart: composed_cart = self.session['composed_cart']
- for the cart:  cart = self.session['cart']
When I add a product to the cart.py, and then a different product to a composed_cart it works.
But when, i only add a product to my composed_cart, it doesn't work (Type error).


I want to use Xmodmap along with multiple layouts

Question: I usually use 3 keyboard layouts: US, BG, DE. As I need the DE layout only for Umlaute, I found the solution with modifying the keys in ~/.Xmodmap. The command xmodmap ~/.Xmodmap changes my US layout in the desired way. But it has a side effect, it also changes my BG layout - the Euro sign is the default sigh for the key e. How can I apply the command only for the US layout?
Comment: has nobody seen this problem?
Comment: I have a similar problem. I use four layouts and my xmodmap mapping changes work on the DE and GB layout, but not on the JP and PL layout. Maybe a better question would be how xmodmap and the inbuilt GUI keyboard-layout settings work together. Also related:[Remap keyboard using xmodmap with layouts](http://askubuntu.com/q/417706/231418)
Comment: How has no-one answered this question in 8 years, I have this exact same problem, I think I'll make a new question if someone that knows a solution might find it.
Answer: I had a similar problem but where I needed to map a certain key to "n" in my English layout and "ν" (the Greek letter for "n") in my Greek layout.  I was using xmodmap -e "keycode 24 = n" to remap the English key, but then the "q" key (key code 24) did nothing in my Greek layout rather than printing "ν" as desired.
Eventually, I found out that you can map the same key code to multiple keysym values like this: xmodmap -e "keycode 24 = n N Greek_nu Greek_NU".  The first one is the the default value, the second is when "shift" is applied, the third is the default for my secondary layout, and the fourth is for when "shift" is applies to my secondary layout.
In order to find the correct order and keysym name, you can enter xmodmap -pk in the terminal to print a table with your present key map.  The names for each key code will be in parenthesis and in the order that they will need to appear in your xmodmap -e command.  For example, my table for the original "n" key (which is broken) is
57       0x006e (n)  0x004e (N)  0x07ed (Greek_nu)   0x07cd (Greek_NU)
which is how I knew to have "n N Greek_nu Greek_NU" in that order.
For your case, I'd imagine that all you'd have to do is set the first two values to be what you want for your English layout, and then the next four (since you have three layouts) to be their original values.


Treatment of large size packets at Twisted

Question: I am currently building a TCP server (the server is going to be used by my company so it must be at a high production level)
My requirements are:

The server will be fast (it can handle a large number of requests simultaneously because our clients send large files regularly and this will create Bottleneck).
The server will be easy to maintain.
Support as many users as possible at the same time.
That the server will be a TCP server because it receives protocol messages that our company has developed and I need to parse it myself.

After checking the options, I chose Python Twisted because he seems to be meeting the first requirement (and since he is in Python then the second demand is solved by itself).
After reading Twisted's documentation I thought of a problem I had not yet found an elegant answer , my clients send me pretty large packets and I make decisions based sub sequence within these packets.
Let's say if I got 1000 first bytes that are all zeros and then another 5,000 bytes that all of them 0x10, I will send back "Hello world" and if I get instead 2000 bytes that all of them 0x50 I will answer "Hello everyone".
My problem with Twisted is that the data eventually comes to "protocol.Protocol" and they are treated with the "dataReceived (self, data)" function, and this instant is a one-time instant, which means that if I only get some of the bytes for the first time and I'm going to get the rest of the bytes at the second time I do not have how to save the data from the first time...
I can not save the data in the protocol.Factory because I will talk with multiple clients simultaneously and then one will use the data of the other, for the same reason I can not use the Globals.
I'm pretty sure I'm not the first to come across this problem, I've seen several online solutions that included re-implementation of "protocol.Protocol" and they really were not elegant ..
Is there a simple and elegant way to solve this problem?
(The solution must be elegant because I add multi-threading over it since the things I give back to the client are much more than "Hello World" and I do not want to block the server)
By the way, if someone with experience can recommend for me on a better solution than Twisted I am more than happy.
Thank you
yoko
Answer: It sounds like you need to maintain some per connection state. That's the minimum amount you can store and still employ such a protocol. Your protocol class should be instantiated once per connection, so you should be able to use properties on that class to store things like zeros_received and twos_received.
def dataReceived(self, data):
    if self.zeros_received != 1000:
        for x, b in enumerate(data):
            if b != 0x00:
                # Handle unexpected byte error
            self.zeros_received += 1

            if self.zeros_received == 1000:
                break

    if self.twos_received != 5000:
        for b in data[x+1:]:
            if b != 0x10:
                # handle unexpected byte error
            self.twos_received += 1

            if self.twos_received == 5000:
                break

   # send hello...

An easier solution would be to buffer the data from the client and then block (with a timeout on the connection) until you've received the first 6k bytes. I'd be careful about prematurely optimizing. You assume now this will be your bottleneck, but often your assumptions may be wrong. Implement a naive solution first (using a buffered reader) and then benchmark speed/memory usage and see what actually needs improving.
def dataReceived(self, data):
    self.data += data

    if len(self.data) >= 6000:
        assert all(lambda b: b == 0x00, self.data[:1000]), 'expected 0x00'
        assert all(lambda b: b == 0x10, self.data[1000:6000]), 'expected 0x10'

        # send hello

Comment: Thank you for your response.
I apologize if I did not explain myself correctly, I am looking for a generic solution to the problem of maintaining per connection state and not a specific solution for the example I brought (I brought it as an example only is not really my protocol) . I can not use the solution you suggested in case I have a state machine that is based on the first 100K bytes, because if I implement it I will completely block my server and lose the ability to handle multiple clients simultaneously.
Comment: There are no generic solutions to this. I was trying to illustrate that you can store the state for a protocol without having to store the first 6k bytes. My first example is a FSM that handles such a protocol with only needing to store 2 numbers. You can't get away with storing no state in all. But it sounds like you may have a misunderstanding about how twisted works. Twisted uses an event loop. It handles multiple connections at once. One connection will not hold up another because there are no blocking reads due to how `dataReceived` is invoked.
Comment: "Put stuff on self" is exactly the generic solution to the problem of maintaining per connection state.  If your protocol isn't as described in the question, that just means you'll do different stuff with `data` and put different "stuff" on self.


Selenium 2 WebDriver NoClassDefFoundErrorS

Question: I'm working with Selenium 2 WebDriver in Eclipse and everything works fine.
But when I want to test my WebDriver Testcases without Eclipse many missing classes occur.
First it startet with :
NoClassDefFoundError com/google/common/collect/Maps

so I downloaded the guava.jar and set the classpath to it.
But now the next NoClassDefFoundError occured:
java.lang.NoClassDefFoundError: org/json/JSONException

The errors always occur on createDriver();
I run the Selenium with JUnit in Java.
"JUnit only"-testcases work fine (set the classpath to junit.jar & selenium-java.jar)
Do you know which jars I have to bind in that eclipse already has bound in as default for the selenium testcases?
Answer: Are you using a standalone server download?
If you download the selenium server package  you'll get about 47 jars with it. I believe you need all of those jars in your classpath in order to execute.  That package can be downloaded from here
Or the standalone package can be downloaded from http://code.google.com/p/selenium/downloads/detail?name=selenium-server-standalone-2.20.0.jar
If you're not using it right now, the easiest solution might be to switch to the standalone version; otherwise download the full server & add all the jars to your classpath.
Comment: Yeah thanks, I just wanted to post the same answer too, found it on the selenium page. Working now!


Can I safely bypass the door switch on my dryer?

Question: The door switch on my dryer is broken (the rocker part of the switch just hangs loose) and the dryer won't start.  I have the part number, but I won't be able to get one for several days.  Is this switch really just a switch?  Or does it serve some other function.  I'm wondering if it's relatively safe to just cut off the switch and short the wires together behind the molex connector for the next couple days until I can get the part.
Whirlpool dryer: part 3406104
Answer: It is a safety switch designed to prevent the drum from turning while the door is open. If the switch were removed and the circuit closed by connecting the wires the drum will turn and the dryer will work. Can you get someone to tell you it is an okay thing to do, not likely.


What href to set for routeProvider in Angular JS?

Question: I have page with ng-view. This page is generated by php following URL: www.sbt.com/profile
What url I need to set in href attribute, that will work Angular JS by url:
www.sbt.com/profile/privacy/1
I tried:
.when('/profile/:page/:type', {}

And link like as:
Go

But it does reload page at url when I click to link in page /profle:
www.sbt.com/#/profile/personal/1

Full code is:
.config(function ($locationProvider, $routeProvider) {
            $routeProvider

                .when('/profile/:page/:account', {
                    templateUrl: function(params) {
                        return '/public/html/personal.html';
                    },
                    controller: 'EditProfileController'
                })

                /* Chat */
                .when('/chat/dialog/:id', {
                    controller: 'ChatController'
                });
        })

Answer: If your angular application is served from the page with base URL like /profile then links should look like:
Go

and route configuration should be
.when('/:page/:account', {
    templateUrl: function(params) {
        return '/public/html/personal.html';
    },
    controller: 'EditProfileController'
});

Also make sure you define base href (although it should work without it too in your case). Put this script in the  of the page:

Comment: When I am on page `/profile` and tried click link the page reloads on url: `www.srt.com/#/personal/1`
Comment: It means that link href is something like `/#/personal/1` I guess. It should be `#/personal/1`. Then page can't reload.
Comment: Does work Angular JS with href "/chat/test" without hash `#`?
Comment: Without hash it will reload the page because `/chat/test` is different resource. So you either use `#/chat/test` or you need to configure html5 mode, in this case server support is necessary too.
Comment: Thanks. Can you notice attention on question: http://stackoverflow.com/questions/30298550/why-does-not-reset-bind-unsafe-html-after-new-content please


What should I do before re-painting my skirting boards?

Question: I'll be painting the skirting boards in my room as they are in bad condition. The paint is cracked and the surface uneven and blotchy. What I would like to know is how should I treat the skirting boards before painting them. From some googling I've got a rough idea of what I should be doing:

Strip the previous layers of paint using a paint stripper or heat gun, then apply a primer and then paint over this
Sand down the skirting board, apply a primer and then paint over this

The first seems quite a laborious task and i'm wondering if the returns are worth it.
Which of the above methods is better? Are there any other methods that are better?
The second seems more manageable however I'm wondering what kind of sand paper I should use? I'm aware that there are different grades, which grade of sanding paper is appropriate for sanding down paint on skirting boards so as to get the surface ready for a primer? Also is it even necessary to apply a primer to a wooden surface that has already been painted?
The paint I will be applying to the surface is of an eggshell finish.
What else can I do to ensure I end up with a good result?
Thank you.
Answer: If you want the boards to look brand spanking new again, you will want to go with method one. I'd use a heat gun to do it, and not the harsh chemical strippers. Either method takes about as long as the other and the heat gun method is less toxic, and, you either already have a heat gun and don't need to spend money, or you'll buy one and have it for a long time - they come in handy. You'll want a good organic vapor respirator for either method still, and a variety of scraping tools.
Method two sounds more appropriate if perfection is not important. Going this route, you'll want to start with various putty knives and scrapers and knock off any obviously loose and flaky paint, and then use 120 grit sand paper not to remove all the paint, but only to rough up the surface of any remaining paint that is sound and knock down any really high spots. This will leave you with patches of bare wood, and patches of sound, old paint. I don't recommend trying to sand off all of the old paint. If this is your goal, then go with method one. Also - buy expensive sand paper. Cheap sandpaper is a false economy as you'll burn through it so much faster than the good stuff.
Either way, you should use primer whenever painting bare wood, or a combination of bare wood and sound paint. You don't need primer when only painting over sound old paint.