Debugging inconsistent results from C# WebMethod in IIS

Question: I have a simple webmethod that looks a bit like this:
[WebMethod]
public static object getData(string id, string type, string[] filters)
{
    //do some validation of inputs
    //execute a stored procedure and process with LINQ

    return new { Result = "OK", Records = results, TotalRecordCount = unpagedTotal };
}

When I run this in debug mode connected to my database it consistently returns the same data for the same inputs, as you would expect.
When this is run in production the Records and TotalRecordCount in my JSON is sometimes different for exactly the same inputs. There are
no determinable patterns that dictate when the numbers change - but frequently they do to all different values. The only observation
I can make about the values is that TotalRecordCount never exceeds the actual record count - when the value changes it's always to a lower number.
There are no INSERT statements in the stored procedures. This is for reading data only.
I have run SQL Server Profiler on the server and confirm that there are no queries running that could alter the count of the records. This is not a
transactional system, it's more of a read-only reporting database that gets rebuilt once a day.
I think I have isolated the issue to IIS, because all of the following tests pass:
Rule out SQL Server

Run the stored procedure 100 times in a loop and check outputs
Repeat above for 2 SSMS login sessions using the same SQL login

Rule out JavaScript / Front-end

In Chrome DevTools inspect: Network > Request > Headers. Check the Request Payload is correct.
In Chrome DevTools inspect: Network > Response - number of records displayed on page match (the erroneous) number of records in response

Rule out Application Layer / C#

Open solution in Visual Studio
Connect application to production DB
Run in debug mode - unable to replicate the error after many runs. TotalRecordCount is consistent.

Rule out Network

Check that the response coming back from server is a well-formed JSON object (stringified)
Compare Request Payload against @params in the stored procedure (using SQL Profiler)

What's left? IIS. I don't know much about IIS.
What I want to know is... is there some setting(s) in IIS that could manifest this bizarre behaviour? Have I missed anything? Does anyone have a clue what's going on?
I've just deployed this application and am having a brain meltdown after looking at this for several hours. All help appreciated!
SQL Code
As requested, the stored procedure looks a little like this:
ALTER PROCEDURE [SO].[getData]

 @ID bigint
 @Type string

WITH ENCRYPTION
AS
BEGIN

DECLARE @resultsTable
as table (
col1 nvarchar(100)
col2 nvarchar(100)
)

--Add test data
INSERT INTO @resultsTable
EXEC [SO].[someSP1] @ID @Type
INSERT INTO @resultsTable
EXEC [SO].[someSP2] @ID @Type
INSERT INTO @resultsTable
EXEC [SO].[someSP3] @ID @Type
INSERT INTO @resultsTable
EXEC [SO].[someSP4] @ID @Type

-- Returned combined dataset
SELECT * FROM @resultsTable

END

each of the someSP procedures have the same signature as this parent one. As mentioned above this works fine if I run it hundreds of times from 2 instances of SSMS connected using the same SQL Login to SQL server (e.g. emulating an application)
I cannot post someSP as they are huge and sensitive. The options I have are:
WITH ENCRYPTION
SET NOCOUNT ON;
Comment: One thing you can test to see if you can reproduce locally is pull up the site in 2 browsers and hit it at the same time. The reason it could be inconsistent in production is because it's a static method and multiple people are hitting it at the same time.
Comment: @Adam you need to show some sample data and the method call perhaps the WebService on the production box is pointing to an old version of the web service.. have you tried refreshing the web reference..?
Comment: Can we see some example output?
Comment: Can you share some procedure code? Are you using NOLOCK?
Comment: @Pseudonym Not easily. The data is of a sensitive nature. I don't think it's relevant. There's a line which says `unpagedTotal = results.Count()` and this inconsistently changes the `TotalRecordCount` in production only.
Comment: @MethodMan not sure if that's the case as this is being executed on the front-end by a javascript client (see: jtable.org) - the fault is intermittent and inconsistent. I will see what I can do about sample data but to be clear if I sit on a chrome web browser and load the page and use the same controls in the same order I get different results each time for the same query with the same inputs in a db which has no writes.
Comment: use the chrome debugger hitting `F12` perhaps you may be able to see what's going on that way as well
Comment: @MethodMan - I do appreciate all people's input and time on my question but I wonder if you actually bothered to read it before you posted comments? I described in detail the use of Chrome DevTools.
Comment: @StephenBrickner I had no idea that a static `WebMethod` had issues serving multiple users. Thank you very much. I will look at this. What is the impact of changing the method to non-static? I didn't write this code but I don't see why it needs to be static to be honest.
Comment: It depends on how it's called. If called through ajax I believe it has to be static so you could just use a lock to force one to wait for the other.
Answer: For a complete answer I'll add my comment from above:
One thing you can test to see if you can reproduce locally is pull up the site in 2 browsers and hit it at the same time. The reason it could be inconsistent in production is because it's a static method and multiple people are hitting it at the same time. I don't know for sure that this is your issue but it sounds like it. Try using a lock to force one request to wait for another.
[WebMethod]
public static object getData(string id, string type, string[] filters)
{
    //do some validation of inputs
    //execute a stored procedure and process with LINQ

    var _lock = new object();

    lock(_lock)
    {
        return new { Result = "OK", Records = results, TotalRecordCount = unpagedTotal };
    }
}

Comment: Thanks. I am looking down this avenue but it seems bizarre to me because: a) I thought all `WebMethod`s are static by nature as they are invoked by the client instead of in this application instance and b) It is totally normal for multiple clients of a web application to connect to the same webservice and get data from it. If this is all data-read and not write then what should it matter if two people make request at same time? Surely they'll both hit getData and whichever gets to execute the SQL sp first will get the data back first. Why would the data be different?
Comment: Here is a post by Marc Gravell that explains it pretty well: http://stackoverflow.com/questions/3037637/c-sharp-what-if-a-static-method-is-called-from-multiple-threads Again, I don't know if this is your issue but in the past I have come across what you are describing when static methods were sharing state.
Comment: Also, the lock would need to be wrapped around any code that could possibly share state not just what's returned.
Comment: This is invaluable information. Thank you very much. I'll confirm a fix before marking as right answer
Comment: Thanks, you saved my ass! For completeness I didn't use any locking in the end. The link you posted gave me the answer - static fields have shared-state. I refactored those out of the code and got the desired results - pure consistency!


Two switch with three black wires

Question: Hello I have a two switch with three black wires all connected on one side. The three black wires are all connected on the side with the three screws (two gold and one black). Pictures are below. I've seen two black wires on a single switch and a similar scenario (for an outside light) and understand why both the wires are black there, but this involves two separate lights. I haven't seen a switch quite like this either although I imagine it's an older version of a single pole? Any idea what's going on here?
Comment: What do the switches control? What are you trying to do with this switch?
Comment: Top turns on external sconces and bottom turns on a floodlight
Answer: Its just two separate switches in a single yoke.
Also, the supply wire is common to both switches, because the switch is configured that way.  The black screw is the common.
Note that there is another black screw on the other side of the switch... If for some reason you needed each switch to have a separate/different supply, the other black screw would come into play.  Right now both black screws are internally jumpered to each other, but that jumper could be removed if you needed each switch to have a separate supply.  So if you see anything weird on that switch that looks removable, don't remove it.   That's the jumper.
Comment: That's what I thought, but just wanted to make sure. Didn't seem that much else would make sense unless one of them was a wire to nowhere.
Comment: I see now that there's a black tab on the back that can be used to split the circuit

Two switch with three black wires


UK regulations concerning external staircases

Question: We're looking to buy a house which has a newly-built external triple garage, which has an external staircase to a storeroom above the garage.
Our plan is to turn this storeroom into an office.
What I'm curious about, though, is the staircase.  At the top of it it has a small landing area.  I've not taken measurements, but if, say, the staircase is 1m wide, instead of just having a 1m x 1m square at the top, there's actually something roughly like 2m x 1m.  You can either go up the stairs and turn left into the storeroom, or turn right onto a tiny balcony.
Would we be able to extend that balcony?  To make it (say) 3m x 3m instead, with space for a couple of chairs and a table?
As I understand it any decking etc that's more than 30cm off the ground requires planning permission.  I've looked at the planning permission for this garage, built a few years ago, and it doesn't show or mention the current balcony.
I'm not sure if the previous owner did something naughty by adding the extra 1m x 1m at the top of his stairs, or if there's actually a building reg that says you MUST have x amount of space at the top of a staircase, or what.
All of that aside, how hard do you think it'd be to get permission to extend the balcony, if we applied for planning permission?  The main house is 100 years old and isn't listed.  The garage is 4-5 years old.  It's not in a conservation area and no other houses overlook it.
Thanks!
Answer: In the U.S., our Codes require a "landing" at the top of stairs that are as wide as the stairs and extends the width of the stairs...so it's a landing that's as wide and as deep as the width of the stairs.
So, that's a minimum dimension required. If the previous owner enlarged it, you're lucky, especially if you're going to add a door that swings into that landing. Then minimum dimensions change, especially if it on a side next to the top step.


async operation is failing test cases in protractor jasmine framework

Question: I had code which was working absolutely fine without any issues. After opening the homepage, it was validating presence of elements on it but recently development team introduced new code which is doing async operation as soon as homepage opens and  protractor is unable to find the elements on the homepage after opening the homepage as it keeps waiting for that async operation to finish
Is there any way to ignore async operation and protractor runs test case execution smoothly or I saw ngzone concept but couldn't understand it.  Please help me in this case
I have started using and it made one tc passed but next tc failed
        browser.waitForAngularEnabled(false);
<code>    browser.waitForAngularEnabled(false); // introduced after async operation
    browser.get(homepage);
    browser.wait(EC.presenceOf(yourElement), 5000);
</code>
Comment: The question it too broad. In fact, you answered your own question right. Use `browser.waitForAngularEnabled(false);` to ignore async operations. What comes to your failures - you need to include your code, HTML, and error stack otherwise it's a shot in a dark
Answer: <code>it('',async() => {
    await browser.waitForAngularEnabled(false); // introduced after async operation
    await browser.get(homepage);
    await browser.wait(EC.presenceOf(yourElement), 5000);
});
</code>
Try the above one. Hope it helps you


Where can I find the source code of Ubuntu?

Question: I would like to know where to find the source code of Ubuntu.
I'd like to see how far it is "open source".
Comment: And it's completely open-source. No need to be skeptical about it...
Comment: All source is open for all of the source code files.
Comment: Despite being "open" there are things called binary blobs in the kernel as far as I'm aware. It's open, but not decipherable in some places.
Answer:
Linux Kernel Source Code:
apt-get source linux-source-3.2.0

Where can I find the source code for the Ubuntu Kernel?

Ubuntu Source Code:
Ubuntu archive

Specific Software Source Code:
sudo apt-get build-dep $package

where package is the program/package's source code you want to adopt.
Then type:
apt-get source $package

to get the source for that package.
For instance:
sudo apt-get build-dep abiword
apt-get source abiword

Answer: The source code for every package in the main and universe archives is in Launchpad, or you can get it by enabling Sources in the Software Properties dialog, and then doing apt-get source $packagename in a terminal, after refreshing the package information.
Source code for packages in the partner repositories is not generally available, as they are mostly not open source applications. This is true for some items available in the Software Center as well.
Answer: Software in linux distributions is organized into packages.  Each package either contains user facing software like Firefox, or libraries like libasound2 which is required by firefox.  If you install Firefox, the apt system will figure out what prerequisite packages exist, will download and install them.  Now, these packages are generally distributed as binary files that have already been compiled for a given processor architecture, but the exact source used to compile that version of a package is available via apt-get source firefox.
The vast majority of things in Ubuntu's repositories of packages are open source.  But Ubuntu does have a list of approved proprietary software.  While this software doesn't satisfy the freedom goals of Ubuntu, they are greatly desired by the community, and provide a lot of value.  Examples of this are Skype or Sun Java (now removed).  These packages are not listed on the Ubuntu packages site.
Comment: very good rundown of the sw context
Answer: You can download the complete source code ISOs from the Ubuntu download servers:

http://cdimage.ubuntu.com/releases/<version>/release/source/ for currently-supported releases. For example, http://cdimage.ubuntu.com/releases/12.04/release/source/ for 12.04.
http://old-releases.ubuntu.com/releases/<version>/release/source/ for obsolete/EOL releases. For example, http://old-releases.ubuntu.com/releases/12.10/source/ for 12.10. However, source ISOs seem to be available only for 12.10 onwards.
Answer: bzr
Get the latest version of package hello (includes next unreleased one):
bzr branch lp:ubuntu/hello

Get specific version:
bzr branch lp:ubuntu/trusty/hello

Now you can for instance to:
bzr log

to see the development history, or any similar SCM operation.
bzr is a good option as it maintains the actual input Ubuntu developers give to Ubuntu, so it is a more canonical (no pun intended) source.
Launchpad bzr browsing
You can also browse the repositories on the Launchpad.
For the hello package, visit: https://code.launchpad.net/ubuntu/+source/hello
Now choose the Ubuntu version that interests you, e.g.: https://code.launchpad.net/~ubuntu-branches/ubuntu/trusty/hello/trusty
Then if you click on "Browse the code" you will go to: https://bazaar.launchpad.net/~ubuntu-branches/ubuntu/trusty/hello/trusty/files where you can browse the files and commit history.
This is powered by Loggerhead.


Is it possible to avoid to load some assembly loading into the `AppDomain`?

Question: I need to load SomeMixedAssembly.dll into the additional domain (i.e. it is not the main domain) and unload that domain after finishing the task. Also the SomeMixedAssembly.dll loads the SomeMixedAssembly_2.dll which is necessary for its work. Both assemblies are mixed and written not by me. It is not a problem, but the problem is the SomeMixedAssembly.dll loads the SomeMixedAssembly_2.dll into the main domain also.
Is it possible to avoid to load some assembly loading into the main AppDomain?
Comment: I suppose the word "mixed" applies here.  AppDomains are a pure managed concept, they only isolate managed objects.  Any memory allocated by native code in a mixed-mode assembly is not isolated.  It can't be.  The isolation boundary for native code is a *process*.
Comment: You would need to create your own proxy that handles communication between the default domain and your created domain. That proxy is then loaded in its own domain and is a wrapper around the types defined in `SomeMixedAssembly`. Do not leak any of the types in `SomeMixedAssembly` directly through the proxy.  That should stop `SomeMixedAssembly` from being loaded in the default domain and also its dependencies.
Comment: To clarify Igors comment, the assembly is not loading itself into the main domain. *You* are by copying an object from the auxiliary domain to the main domain forcing the type to be loaded there.
Comment: I know about `AppDomain.AssemblyResolve` and I use a proxy.  The sample of my "HelloWorld" is here (git repository): https://bitbucket.org/Andrey-Bushman/acadcui/wiki/Home The `SomeMixedAssembly.dll` is `AcCUI.dll` and the `SomeMixedAssembly_2.dll` is `AcDbMgd.dll` in that example.
Comment: @HansPassant, does it mean that *any mixed* assemblies *always* will be loaded into the main `AppDomain` *also*?
Comment: Not the issue.  If I guessed right (why do I have to guess), this is about visibility of memory allocated by native code.  A global variable, so common in C code, is just as global to managed code that runs in another AppDomain.  It is process-global.
Answer: Yes, you can intervene in the process of assembly loading, using for instance, AppDomain.AssemblyResolve event handler. But assemblies usually load lazy on demand and you can not just not to load them and expect that your program will work. Assembly loaded in another AppDomain cannot automatically work as the original one by definition.
But such intervention can be useful if you want to load assembly from unusual place, check some prerequisites or for searching bugs.
Comment: I know about it and I use it, but it doesn't help me. You can see my "Hello World" with this problem here: https://bitbucket.org/Andrey-Bushman/acadcui/wiki/Home
Comment: The only possible reason I could see from your code: Assembly that contains Bushman.AcadCUI.Section class could have direct or chained reference to Acdbmgd.dll. Try to set breakpoint at "ISection section ="  line and check assemblies loaded. Then do step out and check again. If my guess is correct, unwanted assembly loaded in this step. Then, IlSpy or Reflector could help you.
Comment: It happens in the 83 row of the `Program.cs` file.
Comment: Really? At line 83 you call DoWork in taskDomain. Does it mean that at line 39 unwanted assembly is already loaded?
Comment: I didn't notice that Section class declared in you exe, so I correct my guess: the most interesting place is lines 61-68 of Section.cs. Maybe unwanted loading is a result of CustomizationSection constructor code.
Comment: Yes, at line 39 unwanted assembly is already loaded (I see it if I add the registration of the `AssemblyLoad` event of the main domain - it happens at the `83` row of the `Program.cs` file). I too think that the CustomizationSection constructor can be reason of this behaviour, but on the main domain I expected to get the proxy of that instance instead of really called constructor.
Comment: Well, what we have: your exe has no references to non-standard assemblies and it loads unwanted assembly even before it knows what to load (the assembly name is a string).

I see two possibilities: either .Net Runtime **predicts** its future execution (non-realistic assumption)  or the code that really rinning is different from the code you published. I see, that Output for the project is network share. Maybe deployment doesn't work or you have several different copies of you output files and some different assembly really loaded instead of proper one?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126829/discussion-between-olk-and-andrey-bushman).


Difference of setValue() & postValue() in MutableLiveData

Question: There are two ways that make change value of MutableLiveData. But what is difference between setValue() & postValue() in MutableLiveData.
I could not find documentation for same.
Here is class MutableLiveData of Android.
package android.arch.lifecycle;

/**
 * {@link LiveData} which publicly exposes {@link #setValue(T)} and {@link #postValue(T)} method.
 *
 * @param <T> The type of data hold by this instance
 */
@SuppressWarnings("WeakerAccess")
public class MutableLiveData<T> extends LiveData<T> {
    @Override
    public void postValue(T value) {
        super.postValue(value);
    }

    @Override
    public void setValue(T value) {
        super.setValue(value);
    }
}

Answer: Based on the documentation:
setValue():

Sets the value. If there are active observers, the value will be
  dispatched to them. This method must be called from the main thread.

postValue():

Posts a task to a main thread to set the given value. If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.

To summarize, the key difference would be:
setValue() method must be called from the main thread. But if you need set a value from a background thread, postValue() should be used.
Comment: IMPORTANT NOTE: I just noticed that if you're in main thread and use postValue it will take a few more millis compared to setValue to dispatch the data. I had this happen when I fill a layout manually, with setValue it was instant but not with post
Comment: "only the last value would be dispatched". I can't be sure about it by reading the code. So it seems like once the first thread about to hit the inner synchronised block inside postValue(),  the next CPU window can be potentially given to the thread 2 which is posting another value. Thread 2 can then complete the synchronised block and the scheduler gives the first thread a window to run itself. Now, it overrites what thread 2 has already written. Is this possible?
Answer: All of the above answers are correct. But one more important difference. If you call postValue() and after that you call getValue(), you may not receive the value that you set in postValue(). If the main thread had already set the value, then you will get the value that you posted, but if the main thread hadn't set the value yet, then you don't get the value that you posted. So be careful if you work in background threads.
Comment: Wish I could triple-upvote!  Based on this, it appears it's best to use `setValue()` if possible, and cautiously use 'postValue()', only when necessary.  Thanks
Comment: No, here isn't any "best" way. If you work with your LiveData from background thread you should to use postValue. Also in latest version of lifecycle components it fixed... probably.
Comment: I made some tests and seems that with last version of lib everything works as it should.
Comment: "Also in latest version of lifecycle components it fixed... probably." Do you have any more information on this?  Thanks
Comment: Could you show me the above concretely code?

If In ViewModel, I Implemented like `noObserveLiveData.postValue("sample")`,

In Activity, when I used getValue like
`viewModel.noObserveLiveData.getValue`
Do you mean Is  it not  the value that I set in postValue() ("sample")?
Comment: @w201 when you said *"with last version of lib everything works as it should"*, does it mean your answer is not valid anymore? ...So now we CAN get the value that we set in `postValue(...)` even if there are no observers? If that's the case, I think we should modify this answer so that people don't get confused.
Comment: Basically, to deviate people from messing up with volatile keyword, they do it for you using postValue + more sophistication added.
Answer: setValue() is called directly from caller thread, synchronously notifies observers and changes LiveData value immediately. It can be called only from MainThread.
postValue() uses inside something like this new Handler(Looper.mainLooper()).post(() -> setValue()), so it runs setValue via Handler in MainThread. It can be called from any thread.
Comment: Thanks for the nice answer. So, according to @w201's answer(if it's valid until now), the `Handler`'s `post` method doesn't get called if it's not the main thread and there is no observer?
Comment: post is always called and value is updated inside LiveData. But if there is no observers or they are not in started state they will not be notified.
Comment: The main issue is that post updates value asynchronously, so if you called getValue() you can get old one
Comment: So, if I call `getValue()`, I might get the old value, but maybe I can get the latest value, right? So w201 said in his/her answer that *"you don't receive the value that you set in postValue()"*, but maybe I can receive the value that I set?
Comment: @starriet yes, you can get value which was set by postValue(). It is all about concurrency. If main thread has enough time to execute update triggered by postValue() then getValue() will return posted one. If you call getValue() too soon after postValue() and main thread had no time to execute posted update, then getValue() will return old value.
Comment: So, if I understood correctly, setting the value has nothing to do with the existence of observers. Even if there is no observer, after the worker thread posted some value with `postValue()`, **if** the main thread executes setting the value, then we can get the value that we posted. Please let me know if I'm wrong. Thanks a lot :)
Answer: setValue()

Sets the value. If there are active observers, the value will be dispatched to them.
This method must be called from the main thread.

postValue

If you need set a value from a background thread, you can use postValue(Object)
Posts a task to a main thread to set the given value.
If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.
Answer: This is not a direct answer to the above problem. The answers from Sagar and w201 are awesome. But a simple rule of thumb I use in ViewModels for MutableLiveData is:
private boolean isMainThread() {
    return Looper.myLooper() == Looper.getMainLooper();
}

private MutableLiveData<Boolean> mutVal = new MutableLiveData<>(false);
public LiveData<Boolean> getMutVal() { return this.mutVal;  }
public void setMutVal(boolean val) {
    if (isMainThread()) mutVal.setValue(val);
    else mutVal.postValue(val);
}

Replace mutVal with your desired value.
Comment: Nice, I like this. In Kotlin I created an extension that encapsulates the smart update so the numerous value updates throughout my app are a single, consistent call.
Answer: setValue() method must be called from the main thread. If you need to set a value from a background thread, you can use postValue().
More here.
Answer: postValue - can be used from anywhere
setValue - only from main/UI thread
Basically, postValue should be used only from background thread as it might be slower compared to setValue, which reacts faster.
I've wrote a snippet that handles both case:
/**
 * Live data thread-safe set-value
 * Context: https://stackoverflow.com/a/52227632/6688493
*/
fun <T> MutableLiveData<T>.assignValue(newValue: T){

    if(Looper.myLooper() == Looper.getMainLooper()) {
        this.value = newValue
    }
    else {
        this.postValue(newValue)
    }
}

Comment: To handle null values

`fun  MutableLiveData.assignValue(newValue: T?){ ...`
Comment: Does the call to check the `Looper` negate some of the performance benefits of calling `setValue()`?
Answer: TL; DR

If you are working on the main thread, then both setValue and postValue will work in the same manner i.e. they will update the value and notify the observers.
If working in some background thread, then you can't use setValue. You have to use postValue here with some observer.
More here
Comment: Not exactly. If you are working on the main thread then setValue and postValue have a some difference: setValue will set the value and notify the observers instantly while postValue posts the task that will set the value and notify the observes later (usually in a couple of millis).
Answer: In our app, we had used single LiveData that contains data for multiple views in an activity/screen. Basically N no of datasets for N no of views. This troubled us a bit because the way postData is designed for. And we have state object in LD that conveys to view about which view needs to be updated.
so LD looks like this:
LD {
   state (view_1, view_2, view_3 …),
   model_that_contains_data_of_all_views
}

There are couple of views (view_1 and view_2) that had to be updated when one event occurs..mean they should get notified at the same time when event occurs. So, I called:
postData(LD(view_1, data))
postData(LD(view_2, data)

This would not work for reasons we know.
What I understood is that basically one LD should represent only one view. Then there is no chance that you would've to call postData() twice in a row. Even if you call, the way postData handles it for you is what you would also expect (showing latest data for you in view). Everything fall well in place.

One LD -> one View. PERFECT
One LD -> multiple views THERE MAY BE A WEIRD BEHAVIOR
Answer: If setting the value will take a long time (if you have to retrieve additional data from a remote source that could be slow to respond, for example), use postValue() so you don't lock up the main thread.
When setting the value is guaranteed to be fast (as it most often is), setValue() is simplest and best.


Problem when downloading a package using Ubuntu Software Center

Question: I am trying to download the package MATLAB from Ubuntu Software Center on Ubuntu 14.04 , but when it begins applying the changes it does not respond. I am stuck at this point, I can not stop the procedure and it does not finish. Forcing Ubuntu Software Center to close didn't benefit.
What is the reason for this problem? and what are the possible solutions?
I tried to write " sudo apt-get install matlab-support " in the terminal but it also wasn't helpful because it encountered errors.
Comment: "I  tried to write " sudo apt-get install matlab-support " in the terminal but it also wasn't helpful because it encountered errors." Would be really helpful if we could get those `exact` errors, no one can help you if you don't provide the relevant information.
Answer: You need to have MATLAB installed first. The package in Ubuntu software center is just the Matlab support tool. Follow this guide.
Comment: I know, I have installed MATLAB 2012. In fact, I have been using the same installation recently, but yesterday I did format and reinstalled it!
Comment: Please don't link other questions on the site as your answer, without any additional information, click the flag button under the question and flag as a duplicate, so the user can be redirected there.


fatal error LNK1106: invalid file or disk full: cannot seek to 0x5A57BEBC

Question: I got this error using Visual Studio 2008 and I found a solution on the web here and here. But I can't find out how to configure link.exe.
How can I set the /expectedoutputsize:600000000 option for linker.exe in VS2008? I searched in the project properties in the Linker section, but I can't find the place...I searched in the solution and in Visual Studio options. I found the linker.exe.config but I don't know the schema.
My problem is not the disk space, I have plenty of disk space. Any help?
Answer: The option must be added in the Project Settings->Librarian->Command Line->Additional options: text box.
Answer: Sorry to resurrect this old thread, but I had a similar problem yesterday, and my solution had nothing to do with anything I found online. This is the first SO post that comes up, so I figured I would contribute in case anyone as the same problem.
Here is how I ran into the problem:
I originally had a project that created an exe:

MyProject.vcxproj -> MyProject.exe

I then turned the original project in to a .lib project by splitting main.cpp out to a separate .exe project. I set the target name for the exe project to be the same as the lib, so that we wouldn't change our executable name. I also added a different .exe project that uses the library but has a slightly different main.cpp

MyProject.vcxproj -> MyProject.lib
MyProjectVariant1.vcxproj -> MyProject.exe
MyProjectVariant2.vcxproj -> MyProjectVariant2.exe

The way our solution is currently laid out, all of the projects dump their targets into the same output directory.
The problem was that both the .lib and first .exe share the same target name, so any secondary files (pdb files, iobj, ipdb, etc.) would get overwritten. MyProject.exe would literally overwrite these ancillary files before it could link in the MyProject.lib.
Conclusion:
I "fixed" the problem by using a unique target name for the first variant. We will also review our build strategy to see if we should be using different output directories for each project instead of slamming them all together in the same location. Seems more logical to give them different target directories.


android.os.TransactionTooLargeException on Nougat

Question: I updated Nexus 5X to Android N, and now when I install the app (debug or release) on it I am getting TransactionTooLargeException on every screen transition that has Bundle in extras. The app is working on all other devices. The old app that is on PlayStore and has mostly same code is working on Nexus 5X.
Is anyone having the same issue?
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 592196 bytes
   at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3752)
   at android.os.Handler.handleCallback(Handler.java:751)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6077)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.TransactionTooLargeException: data parcel size 592196 bytes
   at android.os.BinderProxy.transactNative(Native Method)
   at android.os.BinderProxy.transact(Binder.java:615)
   at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3606)
   at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3744)
   at android.os.Handler.handleCallback(Handler.java:751)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6077)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Comment: It has been reported as a bug, see https://code.google.com/p/android/issues/detail?id=212316
Comment: That is problem. in most cases I am sending just small parcelable object with few strings. I am getting this error on every activity transition.
On other devices it works without problems.
Comment: write class where with appear. it means you have a class with parces with a lot of data.
Comment: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception
Answer: Whenever you see TransactionTooLargeException happening when an Activity is in the process of stopping, that means that the Activity was trying to send its saved state Bundles to the system OS for safe keeping for restoration later (after a config change or process death) but that one or more of the Bundles it sent were too large. There is a maximum limit of about 1MB for all such transactions occurring at once and that limit can be reached even if no single Bundle exceeds that limit.
The main culprit here is generally saving too much data inside onSaveInstanceState of either the Activity or any Fragments hosted by the Activity. Typically this happens when saving something particularly large like a Bitmap but it can also happen when sending large quantities of smaller data, like lists of Parcelable objects. The Android team has made very clear on numerous occasions that only small amounts of view-related data should be saved in onSavedInstanceState. However, developers have often saved pages of network data in order to make configuration changes appear as smooth as possible by not having to refetch the same data again. As of Google I/O 2017, the Android team has made clear that the preferred architecture for an Android app saves networking data

in memory so it can be easily reused across configuration changes
to disk so that it can be easily restored after process death and app sessions

Their new ViewModel framework and Room persistence library are meant to help developers fit this pattern. If your problem is with saving too much data in onSaveInstanceState, updating to an architecture like this using those tools should fix your problem.
Personally, before updating to that new pattern I'd like to take my existing apps and just get around the TransactionTooLargeException in the meantime. I wrote a quick library to do just that: https://github.com/livefront/bridge . It uses the same general ideas of restoring state from memory across configuration changes and from disk after process death, rather than sending all that state to the OS via onSaveInstanceState, but requires very minimal changes to your existing code to use. Any strategy that fits those two goals should help you avoid the exception, though, without sacrificing your ability to save state.
On final note here : the only reason you see this on Nougat+ is that originally if the binder transaction limit was exceeded, the process to send the saved state to the OS would fail silently with only this error showing up in Logcat:
!!! FAILED BINDER TRANSACTION !!!
In Nougat, that silent failure was upgraded to a hard crash. To their credit, this is something the development team documented in the release notes for Nougat:

Many platform APIs have now started checking for large payloads being sent across Binder transactions, and the system now rethrows TransactionTooLargeExceptions as RuntimeExceptions, instead of silently logging or suppressing them. One common example is storing too much data in Activity.onSaveInstanceState(), which causes ActivityThread.StopInfo to throw a RuntimeException when your app targets Android 7.0.
Comment: If you weren't already using Icepick (or something like it), that's not enough. As mentioned in the documentation: "Bridge is intended as a simple wrapper for annotation-based state saving libraries like Icepick, Android-State, and Icekick." There are ways to get Bridge to work without using one of those, but it ends up being more work than it would to just updating your app to use one of those.
Comment: I tried implementing your library, but it didn't work. Still get the same crash.
Comment: I'd be curious to see your implementation. Feel free to leave details as an Issue on the library. I haven't had any reports of this when properly used.
Comment: I followed the instructions found on the libraries github page. Do I need to add anything else in the code?
Comment: That depends on how you were saving state previously. If you were using something like Icepick then there shouldn't be any extra steps. If you were not, though, there's likely some code reorganization you'll need to do to start using a library like that first. If you posted some more information with a code sample as a Issue on the Github project I could see if there's anything wrong with your setup.
Comment: I wasn't using anything. I just copied your code from gitlab and that's it.
Answer: In the end, my problem was with things that were being saved onSaveInstance, and not with things that were being sent to the next activity. I removed all saves where I can't control the size of objects (network responses), and now it's working.
Update 2:
Google now provides AndroidX ViewModel which is based on the same technology as retained Fragments but much easier to use. Now ViewModel is a preferred approach.
Update 1:
To preserve big chunks of data, Google is suggesting to do it with Fragment that retains instance. Idea is to create an empty Fragment without a view with all necessary fields, that would otherwise be saved in the Bundle. Add setRetainInstance(true); to Fragment's onCreate method.
And then save data in Fragment on Activity's onDestroy and load them onCreate.
Here is an example of Activity:
public class MyActivity extends Activity {

    private DataFragment dataFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // find the retained fragment on activity restarts
        FragmentManager fm = getFragmentManager();
        dataFragment = (DataFragment) fm.findFragmentByTag("data");

        // create the fragment and data the first time
        if (dataFragment == null) {
            // add the fragment
            dataFragment = new DataFragment();
            fm.beginTransaction().add(dataFragment, "data").commit();
            // load the data from the web
            dataFragment.setData(loadMyData());
        }

        // the data is available in dataFragment.getData()
        ...
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // store the data in the fragment
        dataFragment.setData(collectMyLoadedData());
    }
}

An example of Fragment:
public class DataFragment extends Fragment {

    // data object we want to retain
    private MyDataObject data;

    // this method is only called once for this fragment
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // retain this fragment
        setRetainInstance(true);
    }

    public void setData(MyDataObject data) {
        this.data = data;
    }

    public MyDataObject getData() {
        return data;
    }
}

More about it, you can read here.
Comment: That's right answer! Since targetSdkVersion 24+ this exception throws instead of "App sent too much data in instance state, so it was ignored." Some details for those who want to know more: https://code.google.com/p/android/issues/detail?id=212316
Comment: This doesn't help when the app is simply backgrounded and the ViewState causes this. Does anyone have any idea how to handle this?
Comment: Just curious, what if you hold a static reference to the data in question? My case is an arraylist of POJO objects.
Comment: @X09 Problem with that approach is that you should clear that memory when you go to another activity, and that can be tricky (you need to clean it onDestory, but not onDestroy when you rotate a screen). Otherwise, all your activities will have static vars with some objects that you don't need. This approach can work, but you will have a really messy app, so I would not recommend it.
Answer: Did a hit and trial, and finally this solved my issue.
Add this to your Activity
@Override
protected void onSaveInstanceState(Bundle oldInstanceState) {
    super.onSaveInstanceState(oldInstanceState);
    oldInstanceState.clear();
}

Comment: Thank you @Raj...you saved my time
Comment: You're not saving anything that way. Clearing any "progress" users made in your `Activity` is a bad practice.
Comment: If your instance is important and you want to store them then you can save it before clearing,

`//Create instance variable, Bundle oldInstance;

@Override
protected void onSaveInstanceState(Bundle oldInstanceState) {
    super.onSaveInstanceState(oldInstanceState);
    //save your instance here, here
    oldInstance = oldInstanceState

    oldInstanceState.clear();
}`
Comment: You saved my whole life brother. @RajYadav
Answer: The TransactionTooLargeException has been plaguing us for about 4 months now, and we've finally resolved the issue!
What was happening was we are using a FragmentStatePagerAdapter in a ViewPager. The user would page through and create 100+ fragments (its a reading application).
Although we manage the fragments properly in destroyItem(), in Androids
implementation of FragmentStatePagerAdapter there is a bug, where it kept a reference to the following list:
private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();

And when the Android's FragmentStatePagerAdapter attempts to save the state, it will call the function
@Override
public Parcelable saveState() {
    Bundle state = null;
    if (mSavedState.size() > 0) {
        state = new Bundle();
        Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
        mSavedState.toArray(fss);
        state.putParcelableArray("states", fss);
    }
    for (int i=0; i<mFragments.size(); i++) {
        Fragment f = mFragments.get(i);
        if (f != null && f.isAdded()) {
            if (state == null) {
                state = new Bundle();
            }
            String key = "f" + i;
            mFragmentManager.putFragment(state, key, f);
        }
    }
    return state;
}

As you can see, even if you properly manage the fragments in the FragmentStatePagerAdapter subclass, the base class will still store an Fragment.SavedState for every single fragment ever created. The TransactionTooLargeException would occur when that array was dumped to a parcelableArray and the OS wouldn't like it 100+ items.
Therefore the fix for us was to override the saveState() method and not store anything for "states".
@Override
public Parcelable saveState() {
    Bundle bundle = (Bundle) super.saveState();
    bundle.putParcelableArray("states", null); // Never maintain any states from the base class, just null it out
    return bundle;
}

Comment: in the saveState() the bundle can be null, so if (bundle != null) bundle.putParcelableArray("states", null);
Comment: @IKK828 Thanks a lot for your answer, you saved my day! Works like a charm :)
Answer: I face this issue as well on my Nougat devices. My app uses a fragment with a view pager which contains 4 fragments. I passed some large construction arguments to the 4 fragments which caused the problem.
I traced the size of Bundle causing this with the help of TooLargeTool.
Finally, I resolved it using putSerializable on a POJO object which implements Serializable instead of passing a large raw String using putString during fragment initialization. This reduced size of Bundle by half and does not throw the TransactionTooLargeException. Therefore, please make sure you do not pass huge size arguments to Fragment.
P.S. related issue in Google issue tracker: https://issuetracker.google.com/issues/37103380
Comment: Thanks David . This tool really helped me in finding the root cause of the issue. You rock :)
Comment: Welcome @NitinMesta, :)
Answer: I  face the similar issue. The issue and scenario are little different and  I fix it in the following way. Please check the scenario and solution.
Scenario:
I got a weird bug from the customer in the Google Nexus 6P device(7 OS) as my application will crash after 4 hours of working. Later I identify that it's throwing the similar (android.os.TransactionTooLargeException:) exception.
Solution:
The log was not pointing any particular class in the application and later I found that this is happening because of keeping the back stack of fragments. In my case, 4 fragments are added to the back stack repeatedly with the help of an auto screen movement animation. So I override the onBackstackChanged() as mention below.
 @Override
    public void onBackStackChanged() {
        try {
            int count = mFragmentMngr.getBackStackEntryCount();
            if (count > 0) {
                if (count > 30) {
                    mFragmentMngr.popBackStack(1, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    count = mFragmentMngr.getBackStackEntryCount();
                }
                FragmentManager.BackStackEntry entry = mFragmentMngr.getBackStackEntryAt(count - 1);
                mCurrentlyLoadedFragment = Integer.parseInt(entry.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

If the stack exceeds the limit, it will automatically pop to initial fragment. I hope somebody will help this answer because the exception and stack trace logs are same.  So whenever this issue happens, please check the back stack count, if you are using Fragments and back stack.
Comment: This solution seems to handle the TransactionTooLargeException and FAILED BINDER TRANSACTION exceptions I have. Would like to know what mCUrrentlyLoadedFragment is, and why we need to parse entry.getName() to it. Thanks.
Answer: In my case, I got that exception inside a fragment because one of its arguments was a very large string that I forgot to delete it (I only used that large string inside the onViewCreated() method). So, to solve this, i simply deleted that argument. In your case, you have to clear or nullify any suspicious field before call onPause().
Activity code
Fragment fragment = new Fragment();
Bundle args = new Bundle();
args.putString("extremely large string", data.getValue());
fragment.setArguments(args);

Fragment code
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    String largeString = arguments.get("extremely large string");
    //Do Something with the large string
    arguments.clear() //I forgot to execute this
}

Comment: Thanks a lot, worked for me, was looking for this problem since long, tried everything, and finally this worked.
Comment: Wouldn't the arguments clear after the fragment is removed??? Why isnt this part of the logic in fragments...
Answer: The problem in my app was that I was trying to save too much into the savedInstanceState, the solution was to identify exactly which data should be saved at the right time. Basically look carefully into your onSaveInstanceState to make sure you don't stretch it:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current state
    // Check carefully what you're adding into the savedInstanceState before saving it
    super.onSaveInstanceState(savedInstanceState);
}

Comment: I had the same problem and finally I got fixed it removing some data I was saving into the savedInstanceState. Be careful specially with outState.putParcelableArrayList(... or Parcelable objects that contains parcelable lists.
Answer: In my case, I used TooLargeTool to track where the issue was coming from and I found out the android:support:fragments key in the Bundle from my onSaveInstanceState used to reach almost 1mb when the app crashed. So the solution was like:
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.remove("android:support:fragments");
}

By doing that, I avoided to save all fragments' states and kept with other things that need to be saved.
Comment: Where did you add the above code snippet? In the parent activity or the fragment itself. Also, is the above solution working for you in order to eliminate the Transaction Too Large Exception?
Comment: @JatinJha I added that code in the activity and it prevented to have `TransactionTooLargeException`. If that didn't work for you, it's better you check what is doing by using https://github.com/guardian/toolargetool
Answer: I faced the same issue.
My workaround offloads savedInstanceState to files in cache dir.
I made the following utility class.
package net.cattaka.android.snippets.issue;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * To parry BUG of Android N. https://code.google.com/p/android/issues/detail?id=212316
 *

 * Created by cattaka on 2017/01/12.
 */
public class Issue212316Parrier {
    public static final String DEFAULT_NAME = "Issue212316Parrier";
    private static final String KEY_STORED_BUNDLE_ID = "net.cattaka.android.snippets.issue.Issue212316Parrier.KEY_STORED_BUNDLE_ID";

    private String mName;
    private Context mContext;
    private String mAppVersionName;
    private int mAppVersionCode;
    private SharedPreferences mPreferences;
    private File mDirForStoredBundle;

    public Issue212316Parrier(Context context, String appVersionName, int appVersionCode) {
        this(context, appVersionName, appVersionCode, DEFAULT_NAME);
    }

    public Issue212316Parrier(Context context, String appVersionName, int appVersionCode, String name) {
        mName = name;
        mContext = context;
        mAppVersionName = appVersionName;
        mAppVersionCode = appVersionCode;
    }

    public void initialize() {
        mPreferences = mContext.getSharedPreferences(mName, Context.MODE_PRIVATE);

        File cacheDir = mContext.getCacheDir();
        mDirForStoredBundle = new File(cacheDir, mName);
        if (!mDirForStoredBundle.exists()) {
            mDirForStoredBundle.mkdirs();
        }

        long lastStoredBundleId = 1;
        boolean needReset = true;
        String fingerPrint = (Build.FINGERPRINT != null) ? Build.FINGERPRINT : "";
        needReset = !fingerPrint.equals(mPreferences.getString("deviceFingerprint", null))
                || !mAppVersionName.equals(mPreferences.getString("appVersionName", null))
                || (mAppVersionCode != mPreferences.getInt("appVersionCode", 0));
        lastStoredBundleId = mPreferences.getLong("lastStoredBundleId", 1);

        if (needReset) {
            clearDirForStoredBundle();

            mPreferences.edit()
                    .putString("deviceFingerprint", Build.FINGERPRINT)
                    .putString("appVersionName", mAppVersionName)
                    .putInt("appVersionCode", mAppVersionCode)
                    .putLong("lastStoredBundleId", lastStoredBundleId)
                    .apply();
        }
    }

    /**
     * Call this from {@link android.app.Activity#onCreate(Bundle)}, {@link android.app.Activity#onRestoreInstanceState(Bundle)} or {@link android.app.Activity#onPostCreate(Bundle)}
     */
    public void restoreSaveInstanceState(@Nullable Bundle savedInstanceState, boolean deleteStoredBundle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (savedInstanceState != null && savedInstanceState.containsKey(KEY_STORED_BUNDLE_ID)) {
                long storedBundleId = savedInstanceState.getLong(KEY_STORED_BUNDLE_ID);
                File storedBundleFile = new File(mDirForStoredBundle, storedBundleId + ".bin");
                Bundle storedBundle = loadBundle(storedBundleFile);
                if (storedBundle != null) {
                    savedInstanceState.putAll(storedBundle);
                }
                if (deleteStoredBundle && storedBundleFile.exists()) {
                    storedBundleFile.delete();
                }
            }
        }
    }

    /**
     * Call this from {@link android.app.Activity#onSaveInstanceState(Bundle)}
     */
    public void saveInstanceState(Bundle outState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (outState != null) {
                long nextStoredBundleId = mPreferences.getLong("lastStoredBundleId", 1) + 1;
                mPreferences.edit().putLong("lastStoredBundleId", nextStoredBundleId).apply();
                File storedBundleFile = new File(mDirForStoredBundle, nextStoredBundleId + ".bin");
                saveBundle(outState, storedBundleFile);
                outState.clear();
                outState.putLong(KEY_STORED_BUNDLE_ID, nextStoredBundleId);
            }
        }
    }

    private void saveBundle(@NonNull Bundle bundle, @NonNull File storedBundleFile) {
        byte[] blob = marshall(bundle);
        OutputStream out = null;
        try {
            out = new GZIPOutputStream(new FileOutputStream(storedBundleFile));
            out.write(blob);
            out.flush();
            out.close();
        } catch (IOException e) {
            // ignore
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    @Nullable
    private Bundle loadBundle(File storedBundleFile) {
        byte[] blob = null;
        InputStream in = null;
        try {
            in = new GZIPInputStream(new FileInputStream(storedBundleFile));
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            int n;
            byte[] buffer = new byte[1024];
            while ((n = in.read(buffer)) > -1) {
                bout.write(buffer, 0, n);   // Don't allow any extra bytes to creep in, final write
            }
            bout.close();
            blob = bout.toByteArray();
        } catch (IOException e) {
            // ignore
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }

        try {
            return (blob != null) ? (Bundle) unmarshall(blob) : null;
        } catch (Exception e) {
            return null;
        }
    }

    private void clearDirForStoredBundle() {
        for (File file : mDirForStoredBundle.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".bin")) {
                file.delete();
            }
        }
    }

    @NonNull
    private static <T extends Parcelable> byte[] marshall(@NonNull final T object) {
        Parcel p1 = Parcel.obtain();
        p1.writeValue(object);

        byte[] data = p1.marshall();
        p1.recycle();
        return data;
    }

    @SuppressWarnings("unchecked")
    @NonNull
    private static <T extends Parcelable> T unmarshall(@NonNull byte[] bytes) {
        Parcel p2 = Parcel.obtain();
        p2.unmarshall(bytes, 0, bytes.length);
        p2.setDataPosition(0);
        T result = (T) p2.readValue(Issue212316Parrier.class.getClassLoader());
        p2.recycle();
        return result;
    }
}

Full codes: https://github.com/cattaka/AndroidSnippets/pull/37
I worry about that Parcel#marshall should not be used for persistent.
But, I don't have any other idea.
Comment: Your solution is looks good. But I think it cannot restore when process was killed by system. However it may not big problem because it is a edge case.
Comment: Can you please take a look at my updated answer. I accidentally found that solution. At first glance it looks strange, but it works really nice.
Answer: None of the above answers worked for me, the reason of the issue was quite simple as stated by some I was using FragmentStatePagerAdapter and its saveState method saves the state of the fragments, because one of my fragment was quite large , so saving of this fragment leads to this TransactionTooLargeExecption.
I tried overriding the saveState method in my implementation of pager as stated by @IK828, but this couldn't resolve the crash.
My fragment was having an EditText which used to hold very large text, which was the culprit of the issue in my case, so simply in onPause() of fragment, I set the edittext text to empty string.
ie:
@Override
    public void onPause() {
       edittext.setText("");
}

Now when FragmentStatePagerAdapter will try to saveState, this large chunk of text will not be there to consume bigger part of it, hence resolves the crash.
In your case you need to find whatever is the culprit, it could be an ImageView with some bitmap, a TextView with huge chunk of text or any other high memory consuming view, you need to free it's memory, you may set imageview.setImageResource(null) or similar in onPause() of your fragment.
update :  onSaveInstanceState is better place for the purpose before calling super like:
@Override
    public void onSaveInstanceState(Bundle outState) {
        edittext.setText("");
        super.onSaveInstanceState(outState);
    }

or as pointed by @Vladimir you can use android:saveEnabled="false" or view.setSaveEnabled(false); on the view or custom view and make sure to set the text back in onResume otherwise it will be empty when Activity resumes.
Comment: A better solution would be to use `android:saveEnabled="false"` on a particular View.
You can read more about it [here](https://developer.android.com/reference/android/view/View.html#setSaveEnabled(boolean)).
Answer: Just Override this method on your activity :
@Override
protected void onSaveInstanceState(Bundle outState) {
    // below line to be commented to prevent crash on nougat.
    // http://blog.sqisland.com/2016/09/transactiontoolargeexception-crashes-nougat.html
    //
    //super.onSaveInstanceState(outState);
}

Go to https://code.google.com/p/android/issues/detail?id=212316#makechanges for more info.
Comment: This answer alone is not helpful
Comment: it might help if you could add some more info that the users could see before they click the link
Comment: transactiontoolargeexception arise when saving large data into SaveInstanceState. By this code it will prevent saving  data.
Comment: It's not a good solution because you might need to store something from your activity
Answer: As the Android N change the behavior and throw TransactionTooLargeException instead of logging the error.
     try {
            if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Reporting activity stopped: " + activity);
            ActivityManagerNative.getDefault().activityStopped(
                activity.token, state, persistentState, description);
        } catch (RemoteException ex) {
            if (ex instanceof TransactionTooLargeException
                    && activity.packageInfo.getTargetSdkVersion() < Build.VERSION_CODES.N) {
                Log.e(TAG, "App sent too much data in instance state, so it was ignored", ex);
                return;
            }
            throw ex.rethrowFromSystemServer();
        }

my solution is to hook the ActivityMangerProxy instance and try catch the activityStopped method.
Here is the code:
private boolean hookActivityManagerNative() {
    try {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        Field singletonField = ReflectUtils.findField(loader.loadClass("android.app.ActivityManagerNative"), "gDefault");
        ReflectUtils.ReflectObject singletonObjWrap = ReflectUtils.wrap(singletonField.get(null));
        Object realActivityManager = singletonObjWrap.getChildField("mInstance").get();
        Object fakeActivityManager = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
                new Class[]{loader.loadClass("android.app.IActivityManager")}, new ActivityManagerHook(realActivityManager));
        singletonObjWrap.setChildField("mInstance", fakeActivityManager);
        return true;
    } catch (Throwable e) {
        AppHolder.getThirdPartUtils().markException(e);
        return false;
    }
}

private static class ActivityManagerHook implements InvocationHandler {

    private Object origin;

    ActivityManagerHook(Object origin) {
       this.origin = origin;
    }

    public Object getOrigin() {
        return origin;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        switch (method.getName()) {
            //ActivityManagerNative.getDefault().activityStopped(activity.token, state, persistentState, description);
            case "activityStopped": {
                try {
                    return method.invoke(getOrigin(), args);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        return method.invoke(getOrigin(), args);
    }
}

And the reflect helper class is
public class ReflectUtils {

private static final HashMap<String, Field> fieldCache = new HashMap<>();
private static final HashMap<String, Method> methodCache = new HashMap<>();

public static Field findField(Class<?> clazz, String fieldName) throws Throwable {
    String fullFieldName = clazz.getName() + '#' + fieldName;

    if (fieldCache.containsKey(fullFieldName)) {
        Field field = fieldCache.get(fullFieldName);
        if (field == null)
            throw new NoSuchFieldError(fullFieldName);
        return field;
    }

    try {
        Field field = findFieldRecursiveImpl(clazz, fieldName);
        field.setAccessible(true);
        fieldCache.put(fullFieldName, field);
        return field;
    } catch (NoSuchFieldException e) {
        fieldCache.put(fullFieldName, null);
        throw new NoSuchFieldError(fullFieldName);
    }
}

private static Field findFieldRecursiveImpl(Class<?> clazz, String fieldName) throws NoSuchFieldException {
    try {
        return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        while (true) {
            clazz = clazz.getSuperclass();
            if (clazz == null || clazz.equals(Object.class))
                break;

            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException ignored) {
            }
        }
        throw e;
    }
}

public static Method findMethodExact(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws Throwable {
    String fullMethodName = clazz.getName() + '#' + methodName + getParametersString(parameterTypes) + "#exact";

    if (methodCache.containsKey(fullMethodName)) {
        Method method = methodCache.get(fullMethodName);
        if (method == null)
            throw new NoSuchMethodError(fullMethodName);
        return method;
    }

    try {
        Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
        method.setAccessible(true);
        methodCache.put(fullMethodName, method);
        return method;
    } catch (NoSuchMethodException e) {
        methodCache.put(fullMethodName, null);
        throw new NoSuchMethodError(fullMethodName);
    }
}

/**
 * Returns an array of the given classes.
 */
public static Class<?>[] getClassesAsArray(Class<?>... clazzes) {
    return clazzes;
}

private static String getParametersString(Class<?>... clazzes) {
    StringBuilder sb = new StringBuilder("(");
    boolean first = true;
    for (Class<?> clazz : clazzes) {
        if (first)
            first = false;
        else
            sb.append(",");

        if (clazz != null)
            sb.append(clazz.getCanonicalName());
        else
            sb.append("null");
    }
    sb.append(")");
    return sb.toString();
}

/**
 * Retrieve classes from an array, where each element might either be a Class
 * already, or a String with the full class name.
 */
private static Class<?>[] getParameterClasses(ClassLoader classLoader, Object[] parameterTypes) throws ClassNotFoundException {
    Class<?>[] parameterClasses = null;
    for (int i = parameterTypes.length - 1; i >= 0; i--) {
        Object type = parameterTypes[i];
        if (type == null)
            throw new ClassNotFoundException("parameter type must not be null", null);

        if (parameterClasses == null)
            parameterClasses = new Class<?>[i + 1];

        if (type instanceof Class)
            parameterClasses[i] = (Class<?>) type;
        else if (type instanceof String)
            parameterClasses[i] = findClass((String) type, classLoader);
        else
            throw new ClassNotFoundException("parameter type must either be specified as Class or String", null);
    }

    // if there are no arguments for the method
    if (parameterClasses == null)
        parameterClasses = new Class<?>[0];

    return parameterClasses;
}

public static Class<?> findClass(String className, ClassLoader classLoader) throws ClassNotFoundException {
    if (classLoader == null)
        classLoader = ClassLoader.getSystemClassLoader();
    return classLoader.loadClass(className);
}

public static ReflectObject wrap(Object object) {
    return new ReflectObject(object);
}

public static class ReflectObject {

    private Object object;

    private ReflectObject(Object o) {
        this.object = o;
    }

    public ReflectObject getChildField(String fieldName) throws Throwable {
        Object child = ReflectUtils.findField(object.getClass(), fieldName).get(object);
        return ReflectUtils.wrap(child);
    }

    public void setChildField(String fieldName, Object o) throws Throwable {
        ReflectUtils.findField(object.getClass(), fieldName).set(object, o);
    }

    public ReflectObject callMethod(String methodName, Object... args) throws Throwable {
        Class<?>[] clazzs = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            clazzs[i] = args.getClass();
        }
        Method method = ReflectUtils.findMethodExact(object.getClass(), methodName, clazzs);
        return ReflectUtils.wrap(method.invoke(object, args));
    }

    public <T> T getAs(Class<T> clazz) {
        return (T) object;
    }

    public <T> T get() {
        return (T) object;
    }
}
}


Return data from Powershell jobs without the Job-Information

Question: i'm running a job which looks like this
$myjob =
{
  # regerate some $data
  return $data
}

I start and receive my job like this:
Start-Job -ScriptBlock $myjob -Name "job1"
Wait-Job -Name "job1"
$result = Receive-Job -Job "job1"

Now i want my $result to contain ONLY the $data which was returned. However, when inspecting $result besides of the $data i see much more information which I don't want to be included in my $data array. The messed-up data starts something like this:
(Returned Data:)
State         : Running
HasMoreData   : True
StatusMessage :
Location      : localhost
Command       :  # regerate some $data
                 return $data
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : f7c63b33-d270-4fa8-8042-111edf9d86a6
Id            : 270
Name          : job1
ChildJobs     : {Job271}
PSBeginTime   : 03.12.2012 14:06:26
PSEndTime     :
PSJobTypeName : BackgroundJob
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}

this repeats over and over again like 20 times. After that my real $data is listed. However: iterateing over the $result array is not possible that way. What can i do?
Answer: You are falling prey to a common misunderstanding about powershell: All uncaptured output in a script is returned to the caller, not just the arguments to "return." Example:
ps> $s = {
    1..3 # write 1,2,3 to output stream
    return 4 # write 4 to output stream, then exit scriptblock!
    5 # won't be output
    return 6 # won't be output either
}

ps> & $s
1
2
3
4

The return statement is used to exit a function early, and to optionally write one or more objects to the output stream (in addition to other outputs already emitted.)
If you don't want something to get output, then use one of the follow syntaxes:
$null = mycommand
mycommand > $null
[void] (mycommand)

The reason you're seeing two extra "job" objects in your output is that both start-job and wait-job return the job object created and waited for, respectively. The reason for this is to allow pipelining:
$results = start-job { ... } | wait-job | receive-job

What's happening here? Well, start-job creates a job and passes it to wait-job which waits until the job is complete, then passes the job to receive-job, which returns the results and is finally assigned to $results.
Following?
Comment: Well, this was enlightening and solved the problem! Thank you!
Answer: I had the same problem too. I kind of worked around it by not using the return keyword; instead of exiting with return $data try just using $data as the last statement in your remote job:
$myjob =
{
  # regerate some $data
  $data
}

I don't know why this seems to work though.
I'm invoking my remote jobs like this too:
$job = Invoke-Command -ComputerName $servers -FilePath $myRemoteScript -ArgumentList $myArgs -AsJob -JobName $jobName | Get-Job | Wait-Job
$data = Receive-Job -Job $job

Comment: Nearly perfect! but instead the details i posted in the **Returned-Data** Code-Block i still get two `System.Management.Automation.PSRemotingJob` entries returned (the types of those objects) before the actual $data. Any ideas?
Comment: The return keyword is not the only way to return things from scripts. See my answer above.
Answer: I also faced the same issue where I want to exclde comments.
So the easiest solution is to write your comments using:
Write-Host("Your comments ") -Fore Red


Determine convergence of $\sum_{n=1}^{\infty}a_n$

Question: Let $a_n=1-2^{\frac{-1}{n}}$, $b_n=\frac{1}{n^p}$.
Does $\sum_{n=1}^{\infty}a_n$ converge or diverge when compared to $\sum_{n=1}^{\infty}b_n$ if $p < 1$?
My answer to this is that it diverges, since $b_n$ diverges if $p<1$, and by a comparison test $a_n$ does as well.
Is this correct? Thank you.
Comment: Note that series for $a_n$ will diverge if the series of $b_n$ diverges, where $b_n$ is less than or equal to $a_n$.
Comment: $a_n\to 1$ so it diverges by the divergence test
Comment: Start by working with $a_n$ = $\:1-2^{-\frac{1}{n}}\:=\:1-\frac{1}{2^{\frac{1}{n}}} = \frac{2^{\frac{1}{n}}-1}{2^{\frac{1}{n}}}$.

Take the limit of this $a_n$.

$\lim _{n\to \infty }\:\frac{2^{\frac{1}{n}}-1}{2^{\frac{1}{n}}} = 0$

Divergence test doesn't apply then.
Comment: Presumably, you are asked to *perform* the comparison test. This is the intersting part of the question.
Answer: If $p = 1$, then $\sum_{n=1}^{\infty}b_n$ diverges. Then use the limit comparison test. The limit of the ratios of the terms is $$L = \lim_{n \to \infty } \frac{a_n}{b_n}=\lim_{x \to 0}\frac{1-2^{-x}}{x}$$
Can you finish from here?
Hint for evaluating that limit:

 Use L'hopital's rule (or the Maclaurin series expansion).
Comment: Or (to find $L$) that $e^x$ is its own derivative, and if $f(x)=2^{-x}=e^{-x\ln2}$ then $L=f'(0).$
Answer: If you think it diverges by comparison with $\sum_{n=1}^{\infty}b_n$ which diverges, use the limit comparison test to be sure.
The limit comparison test states
$L = \lim_{n \to \infty } \frac{a_n}{b_n}$
$=\lim_{n \to 0 }\frac{1-2^{-n}}{n}$
$=\frac{\lim _{n\to 0\:\:}\left(1-2^{-n}\right)}{\lim _{n\to 0\:\:}\left(n\right)}$
$=$undefined
And thus, by limit comparison test, both $a_n$ and $b_n$ diverge. Note that if you evaluate the limit for $n \to \infty$ instead of $n \to 0$ (common error), the limit will be $0$. And again, since $L=0$, diverges. For it to converge, $L$ must be greater than $0$ and less than $\infty$.
Hope this helps you out!
Answer: Comparing to $\sum_nb_n$ with $p<1$ is not useful. What you will find is that $a_n/b_n\to 0,$ but this is not sufficient to decide whether $\sum_na_n$ converges.
Comparing to $\sum_nb_n$ with $p>1$ is not useful either. What you will find is that $a_n/b_n\to \infty,$ but this is  not sufficient to decide whether $\sum_na_n$ converges.
For brevity let $s_n=\frac {\ln 2}{n}.$ When $n\in \Bbb N$ we have $1>s_n>0$ so $$2^{1/n}=\exp (s_n)=1+s_n/1!+s_n^2/2!+... >1+s_n>0.$$ So when $n\in \Bbb N$ we have $2^{-1/n}<1/(1+s_n)$ so $$1-2^{-1/n}>1-1/(1+s_n)=s_n/(1+s_n)>s_n/2=\frac {\ln 2}{2n}.$$ Compare this to $b_n$ with $p=1.$


JRadioButton in JPopupMenu does not close the menu after selecting

Question: With the above code i want to close the popup right after click on one of the radio buttons but the popup stays open.
Is there something build-in in swing or must i call actionPeformed and close the popup explicity ?
public class NewClass extends JFrame {

    NewClass() {
        setSize(100,100);

        JPopupMenu pop = new JPopupMenu();

        JRadioButton log1 = new JRadioButton("Level 1");
        pop.add(log1);

        JRadioButton log2 = new JRadioButton("Level 2");
        pop.add(log2);

        JPanel p = new JPanel();
        add(p);
        p.setComponentPopupMenu(pop);
    }

    public static void main(String[] args) {
        new NewClass().setVisible(true);
    }
}

Answer: look at JRadioButton#addItemListener() and check if ButtonGroup is usefull in your case
EDIT:
Is there something build-in in swing or must i call actionPeformed and
close the popup explicity ?

I don't know..., good question, but if you adds JRadioButton to the JMenuItem then is build-in look here
Comment: JRadioButtonMenuItem thats it ! Thank you
Answer: I would have added actionlisteners on the buttons so when you press a button you then use:
public void actionPerformed(ActionEvent e){
    pop.setVisible(false);
    pop.dispose();
}

Comment: Do you know how to use ActionListeners?


Mineral spirits not drying out of hardwood floor before finishing

Question: I just finished sanding and cleaning up the floors in my living room and dining room and the last step I did was to clean the whole floor with mineral spirits before applying the polyurethane.  I realized as I was using the mineral spirits that I accidentally bought the biodegradeable kind that is white in appearance.  It has been about 12 hours and most of the floor has dried out, but there are still patches where the mineral spirits is still leaving the wood looking wet.
Has any one else encountered this?  Can I apply the polyurethane now even though there are some spots where it hasn't completely dried yet?  Is this because it is the white biodegradable kind?
Any insights would be appreciated!
Comment: Have you put fans on those areas?  Is it very humid where you are?  I'm not sure whats in that "biodegradable" mineral spirits.
Comment: you may want to be more specific about the product you used.
Comment: Is the polyurethane compatible with the "mineral" spirits?
Answer: I would never put poly down on a surface that was uneven looking as this may magnify the uneven appearance. You may have saturated this area more than other areas, a fan might dry it out but remember the base of your floor is the starting point if it looks wrong now it will look worse with poly in my experiances, you want an even appearance for the entire floor, excess spirits may dilute the poly or cause it not to cure properly it sounds like you have done a good job with the prep work don't rush and you will have a better looking end product.
Comment: Thanks for all the answers.  I put a fan on and waited longer and it eventually dried out.  The product I used was Klean Strip Green Mineral Spirits.


Game updates while playing not working as expected

Question: I've set up Steam to stop downloading updates while I'm playing other games like this:

Anyway Steam doesn't seem to care and keeps updating games while I play.
How can I ensure that Steam is not continuing downloads in the background while I am playing games?
Comment: Whoops, I didn't notice there was a link to a picture.  Incidentally, it's possible to attach a picture directly to your question.
Comment: I've had this problem before, it got solved by restarting my PC when changing the settings didn't work. Have you tried rebooting your PC or your Steam client?
Comment: @RegularUser Yes I did both,but still not working
Comment: Is this happening regardless of which game you're playing?  There's both a steam-wide setting and a per-game setting.
Comment: @Powerlord Yes it happens with every game even though my settings for all games are like in the picture
Comment: Maybe a silly question, but is the game you are running a Steam game or added as non-steam game? If it's not either of these, Steam won't be able to say you are playing something, hence it won't stop downloading.
Comment: @Asunez it's a Steam game(Dota 2 in the example)
Comment: Looks to me like you've done everything correctly and Steam is just being buggy
Answer: I would suggest limiting your auto-update schedule to some time when you never use Steam, like when you're asleep or at work. That way, it shouldn't start updates while you're playing, and you should still be able to start them manually if you want to.


Using Zend_PDF and Zend Framework, Loading Libraries in PHP?

Question: I'm new to PHP, only having worked with a LAMP stack a little bit. I would like to use Zend_PDF to fill forms using PHP. I am having issues and believe I do not know how to properly load Zend Framework (or external libraries in general). Here is what I have currently:
<?php
include_path='.:/var/www/html/lib/';
require_once'.:/var/www/html/lib/Zend/Loader/ClassMapAutoloader.php';
$pdf = Zend_Pdf::load('.:/var/www/html/forms/test.pdf');

echo count($pdf->pages);
?>

I was using count(); as a test but I'm looking to use the setTextField(); functions. I do not have a "/Loader/Autoloader.php" as referenced in some guides.
How do I properly load the library so that I can use the setTextField(); function?
PHP 5.4.16,
Zend Framework 2.4.4,
CentOS7
Answer: There are a few issues with your question.
Firstly, the Zend_Pdf you mentioned above belongs to ZF1, not ZF2. If you really are talking about ZF2, then the class is called ZendPdf and can be used as a standalone component - you do not need to have a full copy of ZF2 available for the autloading (composer will generate an autoloader - you will just need to require that in your script). Last time I checked (which, admittedly, was a couple of years ago), the two versions were functionally equivalent, so you should probably just use the version that matches the version of Zend Framework that you're actually using.
Which brings me to the next issue. Because I wasn't completely sure which version you were referring to, I did a quick text search and discovered that the setTextField() method only exists in Zend_Pdf from ZF1, not the ZendPdf class that is related to ZF2, so I'm not sure why you mentioned ZF2 in your question. But anyway, I figured out how to get the ZF2 version working before I made that discovery, so I've included both methods below for completeness.
Also, you have an error in your require_once statement - it should not have the '.:' included at the start. Now on to my actual answer.
Loading Zend_Pdf from Zend Framework 1 Standalone
This should work:
set_include_path( '/path/to/zf1/library' . PATH_SEPARATOR . get_include_path());
require_once( '/path/to/zf1/library/Zend/Loader/Autoloader.php' );
Zend_Loader_Autoloader::getInstance();

$pdf = new Zend_Pdf();

$pdf->pages[0] = new Zend_Pdf_Page( Zend_Pdf_Page::SIZE_A4 );
$pdf->pages[0]->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 24 );

$pdf->pages[0]->drawText( "Hello world!", 240, 400 );

$pdf->save( 'example.pdf' );

You will obviously need to adjust the paths in the code above in order to make it work properly, but once you do that and run the script, you should end up with example.pdf being created.
Loading ZendPdf from Zend Framework 2 Standalone
Download the ZendPdf project from github (https://github.com/zendframework/ZendPdf) using the instructions on the project page or clone the repository directly using git if you prefer.
Change into the directory where ZendPdf has been placed and run composer install to download the supporting files.
In that same directory (ie. the project root of ZendPdf), create a file called test.php with the following contents:
require 'vendor/autoload.php';

use ZendPdf\PdfDocument;
use ZendPdf\Page;
use ZendPdf\Font;

$pdf = new PdfDocument();

$pdf->pages[0] = new Page( Page::SIZE_A4 );
$pdf->pages[0]->setFont( Font::fontWithName( Font::FONT_HELVETICA ), 24 );
$pdf->pages[0]->drawText( 'Hello world!', 240, 400 );

$pdf->save( 'example.pdf' );

Run php test.php and the example.pdf file should be created.
The magic in that second solution comes from composer, which creates the autoload.php file for you. There are many, many benefits to using this approach, one of which is that you don't have to have a full copy of Zend Framework 2 installed simply to get a working autoloader.
Comment: What an amazing answer, thank you so much. I was referring to ZF2 but did not realize Zend_Pdf was only in ZF1. After testing it out it looks like ZendPdf doesn't have the ability to edit text fields, only draw. I suppose I'll be playing with coordinates for a while. Thank you for the help!
Comment: You are welcome - glad I could help. Good luck with your coding!
Comment: I do have one more question, if you could still help me. '$filename = 'new.pdf';
$pdf->save( $filename );' works while '$filename = '/forms/new.pdf';
$pdf->save( $filename );' doesn't. how do I save/open in other directories?
Comment: What happens when you try to save to the /forms directory? Do you get a message saying "Can not open '/forms/new.pdf' for writing"? If so, it is most likely a problem with file permissions. You need to ensure that the directory you are trying to save the file to (A) exists and (B) is writable by the user (or group) that the script is running as.
Comment: Looks like that was it, along with changing it to 'forms/new.pdf'. Thanks!


remove/replace door hinge on wood door frame

Question: Can the screws be removed from the hinge and wood frame, the frame painted and the hinge reattached with the same screws and holes?
Answer: Yes the screws can be taken out and reused as long as you are careful and the holes and the heads of the screws are still in good shape.
If the holes are a little to large, the screws do not tighten down well,  you can jam a wooden toothpick or two into the holes and break them off flush, then install the screws for a tighter fit.


How to remove plastic expanding fasteners without damaging them?

Question: I have a lot of these plastic expanding fasteners that need to be removed to make some repairs behind the shower in my RV. They all out in the open and easily accessible, but require I remove the expanding pin in the center for the fastener to be removed.
My thoughts were to use super glue onto the pin and extract, then pull out the fastener, but I feel like that could cause trouble if the pin became glued to the fastener.
Is there an easier way to remove the fasteners without causing any damage?
Comment: Buying a new box of fasteners might be cheaper and easier than trying to preserve them.
Comment: Idea not worth a full answer - hot glue the head of a small nail to the fastener to pull out the plunger.  The hot glue should peel off once the fastener is out.  Easier than superglue, and more removable.
Comment: There's almost certainly a specialty prying tool to make it easy, (check an RV site if this is RV-specific stuff) but an appropriately small pry-bar or flat screwdriver should slip into the gap and pry up the ridge on the pin head.
Comment: This is n motor vehicle repair question and belongs in https://mechanics.stackexchange.com/
Comment: Next time, buy 'scrivets'. Same insert method, but they'll unscrew [sometimes]. My usual method for getting these off [I used to deal with a lot of them, you can almost never get them out whole & still look pretty] was have a sharpened pair of pincers that would just lop off the entire head in one go, push the rest inside, or remove them once you have the entire face off.
Answer: Punch the pin through and then pull the outer bit out - with luck you might find the pin.
Comment: One caveat: This tends to mash open the hole behind, so if it's soft (like drywall) the new fastener may not grab as well.
Answer: If you only had a couple of these to remove, I would try some of the suggestions to remove them non-destructively. But since you say you have a lot, I would just buy new ones and remove the old ones however it is fastest.
These clips are very inexpensive, and the replacement ones you can buy would actually be removable and reusable. Search for something like "plastic fender rivets white" on google/amazon/walmart, etc and you will find various sizes and styles.
Regarding the destructive removal of the existing ones if you were to follow my suggestion, it would probably be easiest and safest to drill out the pin. This should carry the least risk of damaging the wall material.
Answer: Non-destructive (or only slightly): Press the points of two knives under the pin head and pry it out.
Destructive: Slide a putty knife or chisel under the flange and pop it off. Push the remaining shaft through the wall surface.
Comment: Wonder if using a screw in the pin might be better than knives.
Comment: You wouldn't want to reuse the thing after poking a hole in it.
Comment: Just thinking knife points have a habit of snapping off, maybe into an eye(eye protection good) and probably want new ones anyway.


How to create an zip archive that MS Windows 10 can extract

Question: I'm trying to create a zip archive that a user on an MS Windows 10 laptop can extract. With only built-in MS Windows utilities.
But it is not clear to my how zip / unzip works on a MS Windows 10 machine. I only use Ubuntu. I tried already a couple of things

I created a zip archive on Ubuntu and found that the built-in MS Windows zip utility cannot extract it. It just reports that the archive is invalid. I can extract it using 7-zip but the users do not have 7-zip installed.
I created a zip archive on MS Windows using 7-zip and found that MS Windows also cannot extract it.
I tried to create a zip archive using right-click and then Send to and then Compressed ( zipped ) folder but this does not seem to do anything. I suppose this feature has not been implemented yet in MS Windows 10.

Is there another way to create a MS Windows 10 zip archive that MS Windows 10 can extract using only built-in MS Windows 10 utilities?
I sort of expected MS Windows 10 to support basic zip / unzip operations but this is not the case yet? Is it a requirement that we update user laptops with third party archive utility for example 7-zip to support basic zip / unzip?
Answer: I think your are doing it incorrectly mate.. as you mentioned "you created a zip archive
on MS Windows using 7-zip and found that MS Windows cannot extract it." it can't be, I have some files which are zipped on windows platform and I have my server running on Ubuntu machine I use those zip files for deployment.
Please check below things on your system, try it yourself.

Create a folder anywhere it could be on Desktop or in D Drive(example: Desktop/MyFolder)
Right click on MyFolder select->  7-Zip- -> select Add to archive.
you'll have new screen. now click on Archive format -> select zip.
You can configure rest of the option if you want like Compression level, Encryption etc.
Once you are done with configuration click Ok button.

Right on zip file which we just created and select 7-zip -> Extract to Myfolder/ Extract here.. you can select any of the option. it will also work on Ubuntu machine.
Hope this will work for you.
If this doesn't work the you can try WinRAR software available freely.
Cheers


Where should I tap in to the existing duct work?

Question: Bought a 1981 repo a year ago. The house measures around 900 SQFT. I enclosed the one car garage (10'x20') @ 200 SQFT to serve as an office. The front of the garage is insulated (10') along with the wall attached to the house (20'). I am planning on running 2 ducts off of the central air system into the room and insulating the ceiling of the garage. I do not have the cash right now to insulate the other 2 dry-walled walls with blown in insulation. One of the non-insulated walls (20') faces West and gets pretty hot in the late afternoon. The other 10' wall faces North and is shaded 24/7 by trees. I am located in Dallas so right now temps are running 95 to 105 degrees F.
I have a Goodman (Furnace: GMS80603AN/Outside Unit: VSX130361) central air 3.0 ton system (Cool is electric & Heat is natural gas) which, according to specs, does 60,000 BTU/h with a max CFM @ 0.5" ESP of 1200. The system is located in an interior closet and utilizes an up-flow method into the attic where the ducts attach. From my measurements, it appears that the ducts coming off of the supply duct measure between 8-10". One side of the supply duct is free for new ducts.
I have a few possible options that I have been kicking back and forth in my mind:
1) Take a new duct off of the supply duct to the office. A new duct run would be about 30-35' long.
I have 2 bags of 25' 12" duct that a friend gave me. Should I use this duct considering its size? Will this cause an airflow problem to the smaller ducts? I plan to divide the duct in the office into two air ducts into the room. If that size supply is safe, what size would I use for each of the two office vents?
2) I have two ducts from the supply duct that run to the kitchen and living room. They split off into two 8" ducts for each room. I could tap into one of these to run both office ducts or tap into each duct run for a single duct run into the office. The run would be about 5' long.
I hope I didn't leave any important info out. What is your opinion?
Additional Measurements:
The Supply Duct measures 15" x 20"
The diameter of the Kitchen and Living Room vents (2 each) measure 7". I believe but have not measured the duct before the split for each room to be either 8" or 10". I am guessing 8".
Answer: Basically you are trying to balance your new ducts with respect to your old ducts by sizing the new ducts. If you make a mistake or if your relative cooling loads (office vs rest of the house) ever changes, your only recourse would be to replace the ducts.
My preference is to size the ducts as large as reasonable possible (without increasing cost too much) and use a damper to tune the airflow ratios. Since you have 12" duct and a place to attach them, just get a damper like this:
http://www.grainger.com/Grainger/DAYTON-Round-Balancing-Damper-2TFY1?Pid=search
An uninsulated unshaded west wall in Texas can probably generate a very high cooling load in the afternoon.


How to Load a JavaScript Array Items To MySQL Database Using jQuery Ajax

Question: I Have a simple array which looks like
var arr = ["foo", "2015/11/04", "Jill", "Smith", "60"]
var serializedArr = JSON.stringify( arr );

now can you please let me know how I can load the serializedArr into the data in following ajax request?
var upload = $.ajax({
    type: "POST",
    url: "assets/.../loader.php",
    data: data,
    cache: false,
    beforeSend: function() {
    }
});

and also how to read the data on server side PHP file? Thanks
Comment: Possible duplicate of [Passing JavaScript Array To PHP Through JQuery $.ajax](http://stackoverflow.com/questions/2013728/passing-javascript-array-to-php-through-jquery-ajax)
Answer: var upload = $.ajax({
    type: "POST",
    url: "assets/.../loader.php",
    data: {array:serializedArr},// pass here{key:value,key:value,...}
    cache: false,
    beforeSend: function() {
    }
});

In php
$array = json_decode($_POST['array']);
print_r($array);// this will get back the array which was encoded.

You have to decode the array because, array is encoded(JSON.stringify(arr))
Comment: Thanks Niranjan, just on PHP side can you please let me know incase of having a variable like `$foo`  how can I get it's value from the `$array` I mean the first item in the `arr`
Comment: use `foreach()` on `$array`, and get the values .
Comment: why `foreach()`? I just need the first element? in a only one set of array
Comment: `echo $array[0];`. But this is simply spoon feeding nothing else
Comment: if you want only 1 element, then dont encode r aont use array. just send as normal variable.


Android arraylist reset index

Question: I am trying to create an ArrayList using the z-axis from the accelerometer with a limit of four elements.
When the fourth element is recorded, it will reset the index of the array to zero and continue the array.
Example: Array = 1 , 2 , 3 , 4
then a new value comes in which is 5
then Array = 5 , 1 , 2 , 3
ArrayList<Float> z = new ArrayList<>();

@Override
public void onSensorChanged(SensorEvent Event) {
    z.add(Event.values[2]);

    if (z.size() > 3) {
        z.remove(3);
        z.add( 0, Event.values[2] );
    }
}

Comment: Maybe you should use fixed size array instead and just write the logic in the paper first if figuring it out in the code is giving you a headache. This smells like homework...
Answer: If you only want 4 values just use an array.
Also keep the index that's added to and use modulo to reset it
float[] events = new float[4];
int eventIndex;

@Override
public void onSensorChanged(SensorEvent Event) {
   events[ (++eventIndex) % events.length ] = Event.values[2];
}

Or if you want to create a "stack" (or actually, a queue) that pushes out the end, then you probably should limit where you add the data based on the size, and not add the element twice when you do reach that size.
@Override
public void onSensorChanged(SensorEvent Event) {
    float value = Event.values[2];
    if (z.size() <= 3) {
        z.add(value);
    } else {
        z.add(0, value);
        z.remove(z.size() - 1);
    }
}

Comment: thanks for your help but it did not work, i need it so when the event happens then the data is stored in index zero and the rest of the data is shifted right.
Comment: thanks for your help, I voted for your answer although i am not sure if it registered because i recently joined.
Comment: You can't upvote with less than 10 rep. If the answer solved your problem, you can use the checkmark, otherwise, you can comment to say that is still isn't what you wanted.
Answer: I have written a method to achieve the input as per your requirement.
public static void addToList(String s){
     if(list.size()>=5){
         list.add(0,s);
         for (int i = list.size() - 1; i > 4; i--) {
            list.remove(i);
         }  }
    else if(list.size()<=4){
       list.add(s);
     }
  }

Android arraylist reset index