How do I fix a wooden retaining wall?

Question: I need suggestions on how to fix my retaining wall.
Is there a quick and cheap way to fix it? Unfortunately, I don't have the money right now to spend on replacing everything.
You will notice that there is rot and a hole in the lumber:

You will see that above my retaining wall is our fence:
Comment: I hope I can buy something in hope depot that can fix this (even if its temporary)
Comment: You should [take our tour](https://diy.stackexchange.com/tour) so you know how the site operates with upvotes for helpful information and checks for accepted answers.
Answer: Although it looks to be functional at this point eventually the bottom tier will rot away causing the retaining wall to fail. You have a legitimate concern. There is no simple answer to this because the right answer is to rebuild the wall. I'm assuming here that the wall has compacted soil on the other side. Since the bottom tier is rotting, and if you're willing to invest some sweat equity in this project, one less expensive option might be to cut out the bottom landscape log with a wedge and sledge or axe. This will be labor intensive but not expensive. Remove one section of the log at a time, removing soil by hand and shoring each section up with pavers/landscaping blocks of the same height as the log. Work along the entire length until you have replaced the entire log with landscaping blocks.
You will mostly have vertical pressure on the bottom log from the weight of the retaining logs above it and whatever structural material is above the logs. The bottom log will not have a lot of lateral pressure from the soil behind it. The main thing you need to do is make sure that as you remove small sections (a foot or two at a time) that the pavers you put in its place fit securely and are on a solid base so as you transfer the load to the pavers there is no compression of the course of pavers. If you do that you'll be fine.
Any soil under that bottom log should be well compacted but you could put a layer of pea gravel under the pavers before you insert them. If you tap them in with a hammer be sure to hold a wooden block over the side of the paver as you tap it in so you don't crack the paver.
The blocks don't have to be flush with the logs above. It will appear to be a base for the wall.
Comment: Yup - replace with stone/concrete products. Any replacement wood will eventually have to be replaced again.
Comment: If it not expensive I have no problem on that. Thanks for giving me some option on how I can temporary fix it. Appreciate it.
Comment: question though, if I cut the  portion would break the whole retaining wall and cause accident? or cutting a small portion is safe to do. Sorry for too many question I am not used to doing this kind of stuff
Comment: I responded as an edit to the answer.

How do I fix a wooden retaining wall?


There was an error parsing the JSON document

Question: Currently I'm working on calling a JSON feed (from an URL) from within an Android application. Calling this URL is no problem, but I'm having a really annoying issue with my JSON output. Yesterday my JSON was working fine, but when I made a call to it today I'm getting an error that my string cannot be converted to a JSON object.
I printed the result to the console and the JSON string looked just fine.
{"message":{"success":false,"error":22}}

However, using the substring() method to obtain only the first character of the string, the output was:
·

I'm assuming this is an encoding issue, but I'm giving the following headers to my JSON feed:
content-type: application/json; charset=utf-8

I'm using the Yii-framework method CJSON::encode() to encode the data to JSON. It has always worked on me, until this morning. I set all my encoding to utf-8, but with no avail.
I also called to the JSON-feed from my browser, copied the JSON and used an online JSON validator, which gave me an 'Invalid JSON' result on the first line which is the '{' bracket. I removed the bracket and manually added it, validated the JSON again and the validator gave a 'Valid JSON' result.
Comment: And what happened this morning, when it stopped working?
Comment: Have you checked the string in a hex editor to get the hex value of each character? Could be that you've got some strange whitespace character in front of your opening "{" that is not visible on the screen.
Comment: The `--` parts are a placeholder for a specific character, likely in the control character range. The value of these characters are *masked*, you don't see their real value but a placeholder (mask) instead, the `--` string. Copying over from the browser and pasting into your hexeditor might create that, however, if you want to fully analyze what is going on, you need to get the real values of these characters. I'm not fluent with your IDE, however, you should log the real hex values of that json response and then copy that log output instead of the browser output.
Comment: It started to give the weird character infront of the JSON string, which is not visible from the browser. When looking at the feed from the browser, the page outputs: `There was an error parsing the JSON document. The document may not be well-formed.`
Comment: @GarethL I think I indeed have some strage whitespace in front of my opening {, as looking at the string with the hex editor returned:
`00000000: -- -- -- -- 7B 22 75 73  65 72 22 3A -- -- 7B 22
00000010: 6D 65 73 73 61 67 65 22  3A 7B 22 73 75 63 63 65
00000020: 73 73 22 3A 66 61 6C 73  65 2C 22 65 72 72 6F 72
00000030: 22 3A 32 32 7D 7D`
Comment: `--` is not a hexcode. This is especially sad because I'd say these masked parts are the most interesting. Please remove the masking and show the real values.
Comment: What do you mean remove the masking? I literally copied the JSON feed from the browser to my hex-editor and it showed -- -- infront of 7B, which refers to the opening "{".
Comment: As far as PHP is concerned with this, you might find this question useful to create a hex dump of a PHP string: [How can I get a hex dump of a string in PHP?](http://stackoverflow.com/q/1057572/367456).
Comment: Thanks hakre, using that function returned `7b226d657373616765223a7b2273756363657373223a66616c73652c226572726f72223a32327d7d`
Answer: Are you using PHP end tag ?> on all your custom PHP files?
if so, remove the end tag. It is optional in PHP. And make sure that PHP open tag <?php always start at top of the file without any spaces in your classes/models/controllers.
They create this kind of special characters, because after the end tag whatever you put will be a output to the client. NOT all PHP editors show special characters they may just display some blank space.
<?php
    echo "Hello, World,";

?>
__//Here is a special character, but editor unable to display it.

one way to debug is ... use ob_start()  ob_end_clean()

simply add ob_start()  on top of the front script  ...  i.e. add it in index.php
and before your CJSON::encode()  clean the buffer using ob_end_clean()
Comment: This fixed it. It seemed that I had a strange character in front of the opening `<?php` tag, but this wasn't visible in my IDE at first. Thank you!


EXCEL SUMIFS to nth value and return position

Question: I have a large spreadsheet with incoming quantities on it that i need to extract data from.
On the Y axis is our item SKU, and on the X is the Purchase Order in which the item came in on. I want to be able to take my current quantity and count from either left or right (right preferred) and return the current purchase orders my quantities are from.
Example: If i have 122 of one item, and we've brought in 352 over the last 7 orders, i would like to return which previous orders my remaining product is from.
Once i am able to return the orders in which my remaining quantities are from, i can index match the corresponding cost on the COST tab (which is laid out the same way) and calculate my FIFO (first in, first out) costing.

Also, i really dont know how to add any other information in to help you guys with what im working with.
Thank you.
EDIT: Here is the added picture. The red arrow is the part i would like automated. It returns the current Purchase order in which a pulled item would originate from.
basically just count from the right and stop once the SUM is within the range of the current quantity.
Comment: Please provide an example output for one set of inputs based on the provided sample data.
Comment: Show us what you have done to try to solve your problem, and specifically where you have gotten error messages or incorrect answers.
Comment: Does the field name have a date or some way to identify the order?
Comment: I added in what i wanted. I havent found any formulas that remotely work and just give a #value error, otherwise i could share were i started. And the order is preset at the time of purchase. I have a macro that builds this database.
Answer: I have created a Function that would work if this is always going to be the format of your table:
<code>Function GetInventoryPO(Current_Quantity As Long, Inventory_List As Variant) As String

    Dim i As Long, x As Long, InvtyArr As Variant

    InvtyArr = Inventory_List
    For x = UBound(InvtyArr, 2) To 1 Step -1
        If InvtyArr(1, x) <> Empty Then i = i + InvtyArr(1, x)
        If Current_Quantity < i Then Exit For
    Next x

    GetInventoryPO = Cells(1, x + 1).Value

End Function
</code>
It should look like this in Excel:

However, feel free to just integrate the code to your existing macros.
Comment: I'm trying this now. It's giving me the #NAME? error
Comment: I got the function to work, but it's inconsistent. It's not returning the correct purchase order for about 30% of the lines.


.htaccess RewriteRule apache: how to rewrite based on URL parameter?

Question: I have URLs with lots of parameters, here is an example that looks like this:

http://www.mysite.com/profile?reset=1&force=1&gid=9&custom_18=BS+Forestry%2C+University+of+Kentucky

I would like to do a RewriteRule that redirects any request containing the string:

&custom

To a static HTML page such as:
http://www.mysite.com/foo.html
Can someone tell me if/how this is possible?
Thanks a lot!
Comment: You should re-think your parameter scheme altogether, if you want decent page rank from search engines.
Comment: awesome idea, but it's not my software so i can't.  i just need to do a redirect.
Answer: This should do the trick:
RewriteCond %{QUERY_STRING}  (^|&)custom(&|$)
RewriteRule ^(.*)$ http://www.mysite.com/foo.html [R]

Comment: The `(^|&)` and `(&|$)` parts are to allow for cases like `?custom` and `&gid=1&custom`--- while not matching `?**customfield**=irrelevant`
Comment: gracias
you are a kind person
Comment: QUESTION: this doesn't appear to work.  I copied your info verbatim, changing only my domain.  Nothing changed.  I put the code near the top of the .htaccess file above all other ReWriteRules??
Comment: Add the `L` modifier, so the end looks like this: [R,L]. That'll fix the problem. (The L modifier will tell Apache to ignore the rules that you have below.)


Set Visual Studio's environment variables for debugging a project

Question: I'm creating an extension for visual studio and one of the requested feature is that it is able to change an environment variable to one of several options, which will then be inherited by the application being developed once it is debugged.
I have tried the following
Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Machine);

but while that persists the variable, it does not seem to pass it on to the program once I hit run.
I'm looking for other ways of doing this to try, and I don't mind if they're hacky.
Edit: For clarification, this process should be transparent to the (arbitrary) program being debugged.  It must also be a programmatic solution
Answer: You can use compilation constants. Define a class that is responsible to retrieve your variables:
public class MyEnvironment {

    public string SomeVariable{
        get{

#if DEBUG
           return "bar";
#else
           return Environment.GetEnvironmentVariable("foo");
#endif

        }
    }
}

You may also use some kind of IOC to inject a variable provider instance. Either a "production" version that reads the environment, or a debug version with hard coded values.
Answer: I have a guess why the program you are debugging doesn't get your environment variables. A process reads the environment variables at process startup. And if you are developing a .NET application Visual Studio create a *.vshost.exe process in order to speed up the debugging startup. So Visual Studio does not create start a new process when you start debugging - with the result that your environment variables are not read.
In stead you could use a memory mapped file to do the required IPC.
Comment: You can disable the *.vshost.exe stuff - in the project property under the debug section.
Comment: Killing the .vshost.exe process works.  Thanks for the inspiration
Answer: I don't know if the settings can be changed programattically, but I would take a look at this question: How do I set specific environment variables when debugging in Visual Studio?
If you are starting the process yourself, the StartInfo object that gets passed to Process.Start() has an EnvironmentVariables property that you could look into using as well.


Scope $watch between controller and directive not working only after minification

Question: I have a controller/view with a directive in it. That directive changes a variable that the controller scope is watching. This works perfectly until I minify everything. Once minified, there's no error but the watch handler doesn't fire any more.
My app is compiled by grunt using yeoman angular generator. After a lot of work it's building everything correctly (via grunt serve:dist). Apart from the fact the watch function handler isn't working, the rest of the app is fine. During development, everything works perfectly.
I've pretty sure all my dependancies are declared to avoid any minification problems. I'm also using ngAnnotate to clean up any I've missed. What could be the problem?
Here's a simplified example:
Controller:
(function(){
    'use strict';

    angular
        .module('app')
        .controller('MyCtrl', MyCtrl);

    MyCtrl.$inject = ['$scope', ...];

    function MyCtrl($scope, ...) {
        $scope.color = null;

        $scope.$watch('color', function(newVal, oldVal) {
            console.log('Color changed');
        });
    };
})();

View:
<mydirective color="color"></mydirective>

Directive:
(function(){
    'use strict';

    angular
        .module('app')
        .directive('mydirective', mydirective);

    function mydirective() {
        return {
            restrict: 'E',
            scope: {
                color: '=color'
            },
            templateUrl: 'directive.html',
            link: function($scope, element, attrs, form) {
                $scope.clickHandler = function(val) {
                    $scope.color = val;
                };
            }
        };
    }
})();

Directive template:
<button ng-click="clickHandler('blue')"></button>

Comment: This is a shot in the dark but can you try changing $scope to scope in the directive. I read somewhere that in the directive you should use scope instead of $scope because it is not a dependancy injection.
Comment: Good suggestion actually, but unfortunately it doesn't make a difference. Having turned off `uglify` the problem persists, so it seems it's actually a general build problem. I have a feeling it might be to do with the template cache. I'll have to do more investigation
Answer: After much trial and error, this ended up being an issue with the minification of my third-party bower components (in particular I think it was jquery-ui and ui-date). Nothing to do with what I originally thought but someone might end up here with the same symptoms. I ended up having to go back through each step of my grunt file manually until it worked (which was when I removed the extra unused dependancies in vendor.js)
Comment: I have the same problem, but is there any easy to to find  extra unused dependencies?


Flash projects with flash player above 7 don't work since CS5

Question: I have somewhat simple problem with my Flash projects. I've installed Flash CS5, created new project (AS2), made a simple button which on(release) is gotoAndPlay(2), published and... It doesn't work! After some research I noticed that none action scipt works when i choose to publish my project with flash player 8,9,10. This is really strange for me.I don't want to stick with FP7. Does anybody know why is this happening?
Answer: It turned out that Flash Players above 7 DO NOT support Actionscript 2 which is really strange for me. I had to change code to AS3 and it works fine now.


How to call SQL dateAdd method using JPA @Query

Question: I have to search for row, which is older than 6 months. I have insert time(datetime) as one of the column in my table.
if it would have been a sql query, it is straight forward like this :-
select * from myTable where insertTime<=dateadd(month, -6, getDate());

But I am using JPA, so I had to write something like this :-
select * from myTable where insertTime<=function('DATEADD',month, -6, function('getDate'));

I am not sure how to put month paramater in above query.
I am getting following error on above query

Error creating bean with name 'myRepository': Invocation of init
  method failed; nested exception is java.lang.IllegalArgumentException:
  Validation failed for query ....

How should I put month field in above query? Is it possible through JPA?
Thanks in advance.
Answer: Thanks to SPeL support you can try to use the following trick:
public interface MyEntityRepo extends JpaRepository<MyEntity, Integer> {

    @Query("select e from MyEntity e where e.createdAt <= ?#{@myEntityRepo.sixMonthsBefore()}")
    List<MyEntity> getAllSixMonthsOld();

    default Instant sixMonthsBefore() {
        return Instant.now().minus(6, ChronoUnit.MONTHS);
    }
}

Comment: My man you are a genius. I really really needed this in my life.


Creating Visual Studio 2017 Community Edition ISO

Question: i want to create offline installer (an ISO file) of visual studio 2017 community edition, but i dont want to download FULL features of it, i only want to install :
1. Universal Windows Platform Development
2. Desktop development with C++
3. .NET desktop development
4. Mobile development with .NET (XAMARIN)

i downloaded offline web installer from : ms.web but i don't know what to add on command prompt so i can download 4 components that i said before. Please tell me the command to add on command prompt so i can get those component only.
Answer: You can simply write the below command in CMD after opening it in the same folder where you downloaded the web installer (vs_Community.exe)
vs_community.exe --layout d:\vs2017offline --lang en-US
But take my word, there's no need to do that at all, I tried it today, and the ISO file reached 21.5GB so I stopped it.
Also, you can refer to Microsoft official blog for more details:
https://www.hanselman.com/blog/HowToMakeAnOfflineInstallerForVS2017.aspx


Installing TS3 Client returns "cannot execute binary file: Exec format error"

Question: I will start with saying I am new to Linux, so please be very detailed.
I just installed Ubuntu Mate 15.04 on my Raspberry Pi 2 (I also had the same issue with Ubuntu 14.04). From other posts I have read it has to do with 64/32 bit, but I have downloaded the 32 bit version of Teamspeak from here.
I ran the .run file and it produced a folder, in which it contained a .sh file. When that file is run by double clicking, nothing happens (no error or anything), when it is run from terminal it says cannot execute binary file: Exec format error.
Is this an issue with my operating system, hardware, or Teamspeak?
How could I go about getting the ts3 client working?
Comment: The Pi uses ARM CPUs, not Intel or AMD, so you need a version that's built for ARM CPUs.
Answer: Raspberry Pi is based on an ARM computing architecture, but Teamspeak
is available only for x86 ("32-bit") and AMD64 ("64-bit") architecture. Each binary executable file has a flag, that describes its format and target architecture. If they mismatch the host (the machine supposed to run the executable) architecture, Linux platforms will (typically) print the error mentioned in your question.
Conclusion: You cannot install Teamspeak (Client or Server) on a Raspberry Pi or other ARM-based computers.


Full Garbage Collection vs. Major Garbage Collection

Question: so Im going over the oracle garbage collection documentation and im a little confused about a this specific passage

Classes may get collected (unloaded) if the JVM finds they are no
  longer needed and space may be needed for other classes. The permanent
  generation is included in a full garbage collection.

Particularly that last sentence where it says that permGen is included in a "full garbage collection" because up until this point there has been no mention of a "full G.C." just minor and major G.C.
So is full g.c. another garbage collector or are they just using the word "full" interchangeably with "major" ? I tried looking at other resources but some say that full is another garbage collection separate from major G.C. and other resources dont mention it at all.
I would also like to know if it is the case that full g.c. is its own separate collector did the oracle documentation actually mean to use full gc or did they actually mean major gc ?
Thanks
Answer: Major GC is just cleaning the tenured space. On the other hand, Full GC cleans both young and tenured spaces (whole heap in this case).
I think this article explains the differences among them perfectly.
Comment: Yes I saw that page before asking this question , the problem for me is that in the page the author says " there is no formal definitions present for those terms." and that fine I get what the author is explaining and I understand the difference  ... what im more interested in is ,there is a formal definition for major g.c. but I havnt found one for full g.c. so is full g.c. just a concept thats encapsulated by major g.c. or is it actually its own collector ?
Comment: got it @BrixtonWeiss. I just found this, but nothing official:

A Full GC will be triggered whenever the heap fills up. In such a case the
young generation is collected first followed by the old generation. If the
old generation is too full to accept the content of the young generation,
the young generation GC is omitted and the old generation GC is used to
collect the full heap, either in parallel or serial. Either way the whole
heap is collected with a stop-the-world event.


Error while navigation

Question: When I navigate to another view controller with y=this two lines it works ok.
<code>  Inventory *obj = [[Inventory alloc] initWithNibName:@"Inventory" bundle:nil];
  [self.navigationController pushViewController:obj animated:YES];
</code>
But if i write this line [Which we must write]
<code>[obj release];
</code>
It gives me bad access error.
Pls help.
Thanks
Comment: Agreed. If you put `[obj release]` right after the `pushViewController`, then the object will have a +1 `retainCount` (because the `pushViewController` will retain it for you) and when you later `popViewController`, it will be appropriately be cleaned up for you.
Comment: The "Use ARC" counsel was undoubtedly just a side comment, not meant to be done in conjunction with the `release` code which is obviously unneeded with ARC, because you'll have a lot less of these routine memory management problems resulting from putting your `release` statements in the wrong place. You might, esp given that you're not using ARC, though, use Xcode's static analyzer ("Product" - "Analyze" or shift+command+B), which will highlight many routine memory management problems in your non-ARC code.
Comment: 1)Use Arc

2)Where are you writing the `[obj release];` ?
Comment: You mean auto release? I m not useing ARC.
Comment: same question here where are you release? before inserting nav controller or after?
Comment: `release` immediately after the `pushViewController`.
Comment: Inventory *obj = [[Inventory alloc] initWithNibName:@"Inventory" bundle:nil];
  [self.navigationController pushViewController:obj animated:YES];[obj release];
Comment: @Rob is perfectly correct !!!
Answer: your object of class was Released then it access again that object who already released so you got this bad access error.
please read this following link Article for Understanding EXC_BAD_ACCESS
Answer: <code>Inventory *obj = [[[Inventory alloc] initWithNibName:@"Inventory" bundle:nil] autorelease]
</code>

Error while navigation


Difference between writing ++i in the condition of a while loop and incrementing i inside the while loop

Question: I am writing the code as shown at the bottom of this question.
For the while loop part, I thought the following two codes are just the same
first one
                while (lIndex < rIndex && height[++lIndex] <= left) {
                    ans += (left - height[lIndex]);
                }

second one
                while (lIndex < rIndex && height[lIndex + 1] <= left) {
                    ans += (left - height[lIndex + 1]);
                    lIndex++;
                }

However, when I run the second one on system,
There is an error of Time Limit Exceeding.
Could someone explain the reason of this problem?
Thanks for reading my question.
Original code:
    public int trap(int[] height) {
        if (height.length < 3) return 0;
        int ans = 0;
        int lIndex = 0;
        int rIndex = height.length - 1;

        // Find the first wall on each side
        while (lIndex < rIndex && height[lIndex] <= height[lIndex + 1]) lIndex++;
        while (lIndex < rIndex && height[rIndex] <= height[rIndex - 1]) rIndex--;

        while (lIndex < rIndex) {
            int left = height[lIndex];
            int right = height[rIndex];
            if (left <= right) {
                while (lIndex < rIndex && height[++lIndex] <= left) {
                    ans += (left - height[lIndex]);
                }
            }
            else {
                while (lIndex < rIndex && height[--rIndex] <= right) {
                    ans += right - height[rIndex];
                }
            }

        }
        return ans;
    }

Answer: In the first example, lIndex is incremented even when evaluation of the condition ends up with it being false. In other words, if the while loop body is executed n times, lIndex will be incremented n + 1 times.
In the second example, lIndex is only incremented with the rest of the body. So if the while loop body is executed n times, lIndex will be incremented n times.
Here's a very simple example of both, showing the difference:
public class Test {
    public static void main(String[] args) {
        int i = 0;
        while (++i < 3) {
            System.out.println("First loop iteration");
        }
        System.out.println("Value of i afterwards: " + i);

        int j = 0;
        while (j + 1 < 3) {
            System.out.println("Second loop iteration");
            j++;
        }
        System.out.println("Value of j afterwards: " + j);
    }
}

Output:
First loop iteration
First loop iteration
Value of i afterwards: 3
Second loop iteration
Second loop iteration
Value of j afterwards: 2

So both loops execute the body twice, but they end up with different counter values.
Comment: Thank you for the explanation! That's very clear and solved my problem.


SQLite. Cordova. Can't insert more than 995 rows

Question: I'm using:

iPhone 5S, iOS 8.1.3
or any iOS Simulator
Cordova 4.0.0, Ionic v1.0.0-beta.14
Cordova/PhoneGap SQLitePlugin

I use SQLite plugin with Angular wrapper. Function self.insert() inserts a row in table "stores". Function self.query() handles all queries and possible errors.
Function $scope.init() in controller is used to insert 20000 rows in table "stores".
The problem:
Only first 996 rows are inserted. No errors. Sometimes 995 or 997 rows.
Note:
Everything works in WebSQL (Chrome). All 20000 rows are inserted.
Thank you in advance!
Factory 1:
self.query = function(query, parameters) {
    return $cordovaSQLite.execute(db, query, parameters).then(function(result) {
       //console.log(result);
        return result;
    }, function (error) {
        console.log(error);
        return error;
    });
};

Factory 2:
self.insert = function(shop) {
    var parameters = [shop.storeId, shop.storeName, shop.address, shop.post, shop.city, shop.lat, shop.lng, shop.open, shop.favorites];
    return DB.query("INSERT INTO stores (storeId, storeName, address, post, city, lat, lng, open, favorites) VALUES (?,?,?,?,?,?,?,?,?)", parameters);
};

Code in controller:
    $scope.init = function(){
        DB.query("DROP TABLE IF EXISTS stores");
        DB.query("CREATE TABLE IF NOT EXISTS stores (storeId integer,storeName text, address text, post text, city text, lat integer, lng integer, open text, favorites integer)");
        json_service.getJson().then(function(data){
            for (var i = 0; i < data.length; i++){
                for (var j = 0; j < data[i].data.shops.length; j++) {
                    var coordinates = data[i].data.shops[j].g.split(",");
                    var oneStore = {
                        storeId: i + 1,
                        storeName: data[i].data.title,
                        address: data[i].data.shops[j].a,
                        post: data[i].data.shops[j].p,
                        city: data[i].data.shops[j].s,
                        lat: coordinates[0],
                        lng: coordinates[1],
                        open: data[i].data.shops[j].t[0],
                        favorites: 0
                    };
                    stores_service.insert(oneStore);
                }
            }
        });
    };

Comment: What size are you setting for your DB? Seems like you are hitting a quota cap right around 995 records but sometimes get a bit more or less because the size of each record varies between each test.

[Determining HTML5 database memory usage](http://stackoverflow.com/questions/3899983/determining-html5-database-memory-usage)
Comment: I'm using SQLite database, not HTML5.
Comment: Ahh right. I am in the process of looking into SQLite and researching it. I am bluring the lines I guess between the two.
Answer: Looks like Cordova-sqlite-storage bug #190, which was observed on older versions of cordova-ios already solved on Cordova-iOS 3.8.0.


how to access shared resource between 2 threads?

Question: In one of Outlook add in, I have a worker thread that does some processing and then updates a boolean flag. Main thread checks this flag and if this is false , it just process a while loop and does nothing.

//worker thread
void DoSoneThing()
{
Outlook.Recipients recps = mail.Recipients.
foreach(Outlook.Recipient recp in recps)
{
//Save each recipients in a colection
}
isDone=true;
}

//Main thread
while(!isDone)
{
//read the collection where recipients name have been stored.
}``

if the Main thread comes to this piece of code before the worker thread has set the flag to true, main thread keeps on processing the loop and secondry thread is just kind of paused. and since the isDone flag is never set to true, main thread doesn't do any thing.
When I put a lock in the DoSomeThing method and used the same lock in mian thread, this issue is resolved.

myClass
{
public static object _syncRoot = new Object();
void DoSoneThing()
{
lock(_syncRoot)
{
//process
isDone=true;
}
}
}

myOtherClass
{
    lock(myClass._syncRoot)
{
//process
}
}

My understanding was that lock is used to restrict the entry to same piece of code by more than one thread. But don't understand why worker thread doesn't do any thing when shared resource is accessed by main thread.
Comment: You skipped all the logic that matters.  Please post the implementation of Main and DoSomething.
Answer: I think there is likely to be a slight conceptual problem here.
Firstly can I suggest that the
<code>while(!isDone)
</code>
is not a great way of waiting - It's known as 'spinning' and allows the thread to use processor time when it's not doing anything, which is not efficient. (Spinning on a lock can be ok in some specific circumstances, but in a user app is generally not a good plan.)
The lock, making one thread wait while the other processes is much better.
Now, as to your specific problem. It's possible that the isDone flag read in the while test has been optimised out (i.e. the compiler 'knows' that it isn't going to change, so it doesn't put in any code to get it from memory again - it just tests the same CPU register.) You can overcome this by using the 'volatile' modifier to tell the compiler it must re-get the value from memory.
It's also possible that the main thread, spinning, is starving the other thread so it never gets a chance to set the flag (although one would hope it would eventually, in a 'fair' system.)
Regardless of the latter, having a thread spin while waiting for another thread to finish proccessing is to be avoided, unless having checked the flag, it goes off to do something useful (such as updating the GUI) instead.
You need to be very careful with multi-threaded designs - they're intricate and can have obscure and hard-to-predict behaviour (but are well worth doing for the right circumstances.)
Comment: Thanks Ragster. I understand that it is not a good design , i'll work on that. I agree with your first reason, and i'm gonna check with  volatile. but with the latter reason, if mail thread starve the other thread, then how come it started working when I used lock instead of spinning over loop?
Comment: Hi Kapilg. When you use Lock, you're letting the OS know that the thread which doesn't have access should wait for access - that is the thread becomes non-schedulable, and Windows won't allocate it any processor time. In that instance it wouldn't starve the other thread because it is suspended. Does that make sense?


Not sending Serial data in C# application

Question: I have two Arduinos that allow  messages exchange via Serial Port using Serial Monitor.
If I use Serial Monitor in both sides everything works fine. If I use my C# application nothing happens. I tried to send from Serial Monitor for C# App and it works but not the reverse.
// ...
comPort1.Open();
// ...
private void comPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    this.Invoke(new EventHandler(processData));
}
private void processData(object sender, EventArgs e)
{
    string inData = comPort1.ReadExisting();
    msgBoxLog.AppendText(inData);
}
// ...
private void sendButton_Click(object sender, EventArgs e)
{
    string my_str = "my string";
    msgBoxLog.AppendText(msgBox.Text + my_str);
    comPort1.Write(msgBox.Text);
}

RtsEnable and DtrEnable are both Enabled
Comment: I've had bad luck using the DataReceived event in the built-in serial port libraries.  It seems to be buggy and miss data fairly frequently.  I've always had to resort to either using a polling approach (using a Timer or a tight while loop in a separate thread), or 3rd party libraries.
Comment: Why you are using an EventHandler? why you are not directly write string inData = comPort1.ReadExisting();
    msgBoxLog.AppendText(inData);  Inside comPort1_DataReceived()
Comment: @MehrdadKamelzadeh This will not work. I need to Make Thread-Safe Calls to Windows Forms Controls or I will get an `InvalidOperationException`
Comment: @mafap put a breakpoint there to see if it fires or not when new data is coming I mean inside comPort1_DataReceived()
Comment: @MehrdadKamelzadeh I tried that but didn't find what's wrong. The problem is when I send from my application. When I send from SerialMonitor to my application it works, so it is receiving
Comment: Are you using  `string my_str = "my string";
    msgBoxLog.AppendText(my_str);
    comPort1.Write(my_str);` to send data? if yes try using `comPort1.Writeline("my string")` instead and check if it works.
Comment: @MehrdadKamelzadeh yes, it sends the string to my editBox (msgBoxLog) and to Serial Port. I tried before and didn't work :/
Comment: When I send something in SerialMonitor, Arduino receives and sends the data. When I send from my application, Arduino just receives the data.
Comment: I tried all [this solutions](http://social.msdn.microsoft.com/Search/en-US?query=serial%20data%20send%20c%23&emptyWatermark=true∾=5) and can't get this working :@
Comment: @DaxFohl can you tell me what kind of solutions did you use?
Comment: Reading your question a bit more carefully, it looks like you've had trouble with the C# Send, but the C# Receive is working fine.  Is that correct?  I've never had problems with the Send functionality before, so I'm not sure I can be much help.
Comment: (Just as a sanity check, the `sendButton_Click` *is* getting called when you click the button, right?  You're seeing it append on the msgBoxLog?)
Comment: @DaxFohl That's correct and yes, `sendButton_Click` is getting called. `my_str` is appended but not sent to serial port (Arduino lights de Rx LED but not the Tx).
Comment: Why would you expect the Tx LED to light up if it's just receiving something from the PC?  What are you expecting to happen?
Comment: @DaxFohl The usual process when I use SerialMonitor is: PC (COM1) > Arduino > Arduino receives (Rx ligh up) > Arduino send (Tx) > PC (COM2). And this is not happening with my application.
Comment: Okay, sounds like something Arduino-specific, like it's expecting some of the Enable pins to be set/unset before sending a response.  I haven't messed with Arduino or needed to manage any of these pins before in my applications, so I'm not sure I can help.  It sounds like you're transmitting the data from C# to the Arduino just fine though; the issue is figuring out what you have to do to allow the Arduino to respond.  Read the documentation thoroughly and it should be in there somewhere.
Comment: @DaxFohl I don't know because using the Serial Monitor [from Arduino IDE] everything works fine :/
Answer: Well, with Console.Write(msgBox.Text); I realized it was just a silly problem, I was not sending msgBox.Text as I wanted. It should be:
private void sendButton_Click(object sender, EventArgs e)
{
    string my_str = "my string";
    comPort1.Write(msgBox.Text); //Console.Write(msgBox.Text);
    msgBoxLog.AppendText(msgBox.Text + my_str);
}


How do I get these toilet shut off valve out?

Question: As title says I am trying to figure out how to remove the old shut off valve from the pipe. I've been watching lot of videos, reading up on articles and all seem to deal with compression fit type but what I have at work (1st photo) and home (2nd photo) seem different from what I am dealing with. (Top photo is just a reference)

It doesn't look like it is soldered on either (at least that's what I think)
Comment: Thank you Niall C. for pasting photos directly from the link :) Cheers!
Comment: You're welcome, and welcome to the site.
Answer: Typically, the valve solders to the 1/2 inch water source pipe. the outlet is a pretty standard 3/8" compression fitting.  It is a little hard to tell from your pics, but it is rare that the valve would be a threaded fitting to the water source, but not unheard of. The differences between the valves pictured are that the top pic is a 90 degree 1/4 turn valve and the bottom pic is a straight multi-turn valve. If you are going to replace them, do yourself a favor and use nothing less than a  1/4 turn stainless steel ball valve. They are available in both straight and 90 degree styles.
Assuming they are solder on, you must heat them to melt the solder and remove them, or cut them free with a tubing cutter as close to the existing valve as possible.  If you unsolder them, take great care to remove all the old solder and clean/smooth the pipe end well before attempting to solder a new valve on. A basic knowledge of sweating pipes is needed for this project as well as basic plumbing tools like a tubing cutter, torch, abrasive cloth, flux and solder.
Comment: Take it from an idiot, soldering valves to pipes is not idiot proof. There's a good chance you'll either have a cold soldered joint (leak) or ruin the valve seals, or both, unless you're experienced in this stuff. You're better off soldering a pipe thread adapter on and using a PTxComp ball valve. And remove as much water as you can from the pipe or it will never get hot enough.
Comment: As the first reply suggest, I think it will make it easier for me if I just cut the pipe instead of trying to heat it and remove it. Trust me you dont want to see me with a torch lol
Answer: It looks like it is soldered.  You can either resolder on another valve or use a compression valve.  I use compression valves for shut-offs and just installed this one.
If it isn't soldered then then the nut closest to the wall turns out and there is a pin under it.  You have to take the pin out to release the compression valve - if it were a sharkbite or similar you would need to buy a little horseshoe device to release it.  With the water off.
Example of compression valve - every store has there own brands for these.  Also in most stores they are not with plumbing they are with toilet parts.
Make sure you get the right size.  Looks like yours is 1/2 to 3/8.
This is a 10 minute job!
To install -
- shut off water
- cut copper as close to current shut-off as possible.
- clean inside and outside of copper
- slide compression fitting on
- connect toilet
- turn on water
- turn valve on and off to make sure there are no leaks
Tools needed

Pipe cleaning brush
Tube Cutter
Comment: Compression fittings are measured in OD, so you need a 5/8" OD compression fitting for a 1/2" pipe
Comment: I am not a plumber but just a DIYer with a lot of plumbing experience.  I have installed at least 30-40 shut-off valves over the past few years.  If I had 1/2 inch copper I always got what was labeled as a 1/2 compression fitting - either the one at lowes in my answer or a similar manufacturer (yellow and blue box) from HD.  Most toilets I have done had 1/4 inch going in though but this looks like 3/8.
Comment: weird I wonder if there is something regional about it or maybe just how they label them.  the first time I went looking for them I couldn't figure out why I couldn't find any 1/2" ones at HD - labeled as 5/8 instead
Comment: Hmm thanks for your input. The funny thing is I dont know whether the white crusted stuff on the pipe is mineral deposit because it doesnt look like copper lol. It is indeed 1/2 inch to 3/8.
Comment: Looks like copper to me.  Scrub it with a steel/wool brush for a minute and you should see some copper.
Comment: Cool thanks. I feel lazy though cause jobs complete (well almost cause I want to change the valve too)
Comment: No plumbing job is a 10 minute job. :) (Or I just suck at plumbing.)
Comment: This is a true 10 min job - given that you have tube cutter, brush, and the right valve.  Those are big givens though!  And if you have done it before it is a 4-5 min job.  Also with compression make sure that you have at least 1.5 inches clearance from the wall and if you lose a half inch from cutting out the soldered connection that your toilet line still will make it (usually not an issue).
Answer: It looks like both ends just screw on.
Turn off the house water, unscrew both ends, take it with you to get the replacement (or make several trips like me).
Comment: Very unlikely.  99% it is soldered. If it were threaded, you would expect the valve to have flat sides so you could use a wrench
Comment: Are you talking about the flexible hose?
Answer: Thank you so much for your input guys!
While waiting for replies I did further digging and eventually figured out that it was soldered on.
So I decided to bypass changing the shut off valve since it still works even though it looks like crap and I needed a new toilet lol. Perhaps I will tackle it very soon :) I think I will end up cutting it to put new compression type shut off valve. Sharkbite ball valve looks nice and simple enough.
Took me roughly 2 hours to complete the job including a trip to hardware store to get one more wax ring to stack it to make tight contact. First time and bit nervous but all in all wasnt difficult. Wish the bowl was lighter though haha.
Gonna do one more toilet tomorrow and next project is bathroom sink!
Cheers,
Charles


A simple explanation to this asymmetry?

Question: Let $S_k^\delta=\{a+b\le k\mid(a,b)\in\mathbb N_+^2\wedge a^2+b^2\in\mathbb P\wedge a^2+b^2+\delta\in\mathbb P\}$, where $\mathbb P$ is the set of primes.
If $\delta=2$ then the condition on $a^2+b^2$ is to be the lower of a twin prime, while if $\delta=-2$ the condition on $a^2+b^2$ is to be the higher of a twin prime. Only primes of form $4n+1$ is a sum of two squares but since the distribution of those as high/low twin prime is approximately uniform, I didn't expect any asymmetries among these two cases.
Reformulation:

But $S_{50,000}^2$ contain all odd integers $x$ such that $1375<x\leq 50,000$, while
  no odd integer of form $6n+27\;(n\in\mathbb N_+)\;$ is a member of
  $S_{50,000}^{-2}$.

Can anyone explain this asymmetry?
Answer: If $a^2+b^2-2$ and $a^2+b^2$ are prime, then $a^2+b^2\equiv 1\pmod 4$ and $a^2+b^2-1$ is a multiple of $6$ (with the exception $\{a,b\}=\{1,2\}$). Then $a^2+b^2\equiv 1\pmod{12}$. This implies that $a$ and $b$ are of opposite parity.
Assume WLOG that $a$ is odd. Then $a\equiv 3,9\pmod{12}$ and $b\equiv 2,4,8,10\pmod{12}$; or $a\equiv 1,5,7,11\pmod {12}$ and $b\equiv 0,6\pmod {12}$.
Thus, $a+b\equiv 1,5,7,11\pmod {12}$.

A simple explanation to this asymmetry?


Dequeue from a Azure Storage queue very often without running multiple instances of cron job?

Question: I have a pretty typical challenge: I have an application where I want to send emails/SMS messages. I use third party API's for that (Mandrill and GatewayAPI). This is usually fast, but some of my messages are big and will take a while to send. That is why I want to move it to a different system.
My plan was to make a simple Azure Web Job reading from an Azure message queue that runs very often (ie 15 seconds), to make sure all new communication are sent quite fast.
My question is: is it a problem if my job sometimes takes longer than the interval? And if so, is there something obvious about my design that is flawed (ie using a message queue together with a web job with a low interval)?
(I hope this is not seen as an opinion based question - it's really not - I have an actual problem with how to program this setup)
Answer: What you need to do is to subscribe to a trigger to a specific queue.
This is really simple. When you create a new Azure web job based on the standard template, you get the following function inside Functions.cs which is added by default:
    // This function will get triggered/executed when a new message is written
    // on an Azure Queue called queue.
    public static void ProcessQueueMessage([QueueTrigger("QUEUENAME")] string message, TextWriter log)
    {
       // your code
    }

By then moving the code in here you don't have the problem with intervals because it's processed right away by the trigger.


Check for an array's key existing as a another arrays value

Question: I have a array called $menu_array; and currently looks like this
   [0] => Array
    (
        [id_parent_menu] => 4
        [parent_info] => test
        [children_menu] => Array
            (
                [0] => Array
                    (
                        [id_child_menu] => 21
                        [children_info] => test
                    )

                [1] => Array
                    (
                        [id_child_menu] => 22
                        [children_info] => test2.
                    )

            )

    )

and so on.
I also have another array $access that looks like this:
     array(
          [4]='true'
          [22]='true'
     )

What I'm trying to do is check to see if the key for the $access array exists as a id_parent_menu, and then put a key and value of
$menu_array[can_view]='true';

Then, also check if inside the $children_menu array inside of the $menu_array if the a $access key exists as a id_child_menu and set a value of can_view = true in there too.
$menu_array['children_menu'][1]['can_view']='true';

Answer: foreach ($menu_array as $key => $value){
  if(isset($access[$value['id_parent_menu']]) && $access[$value['id_parent_menu']])
  {
    $menu_array[$key]['can_view']=true;

    foreach($value['children_menu']  as $key2 => $value2)
      if(isset($access[$value2['id_child_menu']]) && $access[$value2['id_child_menu']])
         $menu_array[$key]['children_menu'][$key2]['can_view']=true;
  }

}

(A child item can be visible only if the parent item is visible.)


EOFError: EOF when reading a line. What is this Error and why is it occuring?

Question: I wanted to write a function that prints True if the pin the user inputted was 4 or 6 in length. I wrote the function, but when I run it outputs this error. How do I fix this error and what is wrong with it in the first place?
pin = raw_input("Please enter your four or six digit pins")

def validate_pin(pin):
    if len(pen) == 4 or 6:
        purp =  True
    else:
        purp = False
    return(purp)
    print purp

validate_pin(pin)

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from solution import *
  File "/home/codewarrior/solution.py", line 1, in <module>
    pin = input("Please enter your four or six digit pins")
EOFError: EOF when reading a line

Comment: you may need to change your if condition, by `if len(pin) == 4 or len(pin) == 6:` cuz this way 6 is always true, so the condition will always be verified `if 6:` is equivalent to `if True:`.
Comment: runs fine for me except for that pen typo. Could be an IDE problem; what IDE are you using
Comment: also, the print statement after return will never get executed.
Comment: you seem to be using interpreter from an editor that does not support raw_input or input, compile the file using a terminal and it'll be fine
Answer: There are several errors in your code, however, I was unable to create your specific error message. Most likely your raw_input failed.
Here is your fixed code:
pin = raw_input("Please enter your four or six digit pins")

def validate_pin(pin):
    if len(pin) in [4, 6]:
        # your old code results in two boolean statements
        # 1) len(pin) == 4, this correctly checks for a length of 4
        # 2) or 6, this is always true, result in your if statement
        #    always being true
        purp =  True
    else:
        purp = False
    print purp
    # if your print statement comes after a return statement,
    # it is never executed
    return(purp)

validate_pin(pin)

Comment: I understand know thanks to you. I appreciate your help.


Cookie dynamic redirect

Question: I have a landing page, that sets a cookie whenever a user enters the page. If this cookie is set, it redirects the user to my homepage. The problem is that if my user wants to enter the landing page again and they already have this cookie set, it will automatically redirect them to the homepage. My domain will be set on the landing page, meaning that every time a user enters my site they will see this page.
Is there a way to dynamically allow access to the landing page with the cookie? My users should be able to enter the landing page at will; however I also want the users to be directed to my homepage if they are directly entering my website.
Here's my code:
PHP:
<?php
    $time = time() + (60 * 60 * 24);

    if (isset($_COOKIE['landing'])) {
        header('Location: home.php');
    } else {
        setcookie("landing", true, $time);
    }
?>

Answer: Well, you could use a query parameter, eg. index.php?noredirect=1, and in your script:
if(isset($_COOKIE['landing']) && $_GET['noredirect'] != 1) {
    header('Location: home.php');
} else if(!isset($_COOKIE['landing'])) {
    setcookie('landing', true, $time);
}

Now if you append ?noredirect=1 to the url, the user will not be redirected, but by default they will (if the cookie is set).
Answer: You need to know if the user wants to stay or not. So you will have to set a variable or something like this.
if ( isset( $_COOKIE['landing'] ) && !$user_wants_to_stay ) {
    header( "Location: home.php" );
} else {
    ...
}

You could use the session or a second cookie which will be set via javascript or simply a get variable in the URL

Cookie dynamic redirect


Proving that for projection $E:V \rightarrow V$, $V=Im(E)\oplus Ker(E)$

Question: I am trying to prove for projection $E:V \rightarrow  V$, $V=Im(E)\oplus Ker(E).$
Started by taking a base for $Im(E): B_{1}=(v_1,...,v_n)$.
Then extended it to the base of $V:B=(v_1,..,v_n,...,v_k)$.
I took $v\in V$ and showed it as a linear combination of $B$, then operated $E$ on $v$.
What I got was $E(v_1)+...+E(v_k)=v$ I know that $E(v)\in Im(E)$ so I am guessing that all vectors that dont belong to $B_1$ should be $0$. How can I prove this? And so far, is this proof valid?
Comment: Stating that $E$ is a projection, do you mean that there exists a basis $\{u_1,...,u_n\}$ and an integer $m$ such that $E(\sum_i\lambda_iu_i)=\sum_{i\leq m}\lambda_iu_i$? Notice that if this is not the case then it is false: consider $V=\mathbb{R}^2$ and $E:(1,0)\mapsto(0,0),(0,1)\mapsto(1,0)$.
Comment: By projection I mean that $E:V\rightarrow V$ and that $E=E^2$
Answer: First
$$\forall\,v\in V\;,\;\;v=Ev+(v-Ev)\implies V=\text{Im}\,E+\ker E\;\;\;(\text{why?})$$
Also
$$x\in\text{Im}\,E\cap\ker E\implies\begin{cases}\exists\,v\in V\;\;s.t.\;\;x=Ev\\{}\\Ex=0\end{cases}\;\;\;\;\implies$$
$$\implies\;\; 0=Ex=E(Ev)=E^2v=Ev=x$$
End the argument now.
Comment: The last part is clear but I cant understand the first part. Of course $v=Ev+(v-Ev)$ but why does that mean that $V=ImE+KerE$?
Comment: @YinonEliraz It is clear that $\;Ev\in\text{Im}\,E\;$ , right? Then ...?
Comment: I cant continue this claim. I understand that $Ev \in ImE$ but what does this give?
Comment: @YinonEliraz Haven't you checked **where** is $\;v-Ev\;$ ??
Comment: My innitial thought was to operate $E$ on both sides, but that didnt get me very far.
Comment: @YinonEliraz What both sides? $$E(v-Ev)=Ev-E^2v=0$$ Can you see it?
Comment: Yes, I see it. But what it implies? How does it imply that $V=KerE+ImE$?
Comment: Well, it's hard for me how to lead you anymore without telling you completely the whole solution....and it is right in front of you. Anyway, as you already accepted the other solution (and, apparently, already understood that)  you can do it that way.
Comment: @Timbuc, I am here to understand better, not to solve my homework, If you can kindly explain your way of thinking I would appreciate it.
Answer: Bear in mind that $v\in Im(E)$ if and only if $E(v)=v.$ Can you prove this?
Also, you might have an easier time if you show that $V=Im(E)+Ker(E)$ and that $Im(E)\cap Ker(E)$ contains only the zero vector.
Comment: So if I say that $ImE\subseteq V$ and that $dim ImE=dimV$ this is all I need. proving that $ImE\cap KerE={0}$ is simple. Thank you.
Comment: @YinonEliraz What you wrote is very wrong! $\;\dim\,\text{Im}\,E=\dim V\implies E(V)=V\implies E\;$ is surjective $\;\implies \ker E=\{0\}\;$ , which is completely false in in the general case
Comment: In general, we will *not* have $\dim Im(E)=\dim E.$ You will need to show that $V$ is the sum of the image and kernel of $E$. Timbuc's answer gives a nice way to do so.
Comment: @CameronBuie I think you meant to write that we won't have $\;\dim\text{Im}\,E=\dim\color{red}V\;$ . Apparently you also get confused by the use of $\;E\;$ instead of $\;T\;$ ...jeje. Well, I know at least I do.
Comment: @Timbuc: Yep! Too used to $E$ being a set. :-\


Outswing French doors: are they doable without a porch roof?

Question: We'd like to install outswing French doors leading out to our patio. Does anyone have comments about the practicality of this if the patio does not have any covering/roof over it?  It is a patio, not a porch.
We've been thinking we won't open the French doors when it is raining.
Also we won't open them when it is windy, to avoid the door being snagged by the wind and yanked out of our hands.
Good enough?  Other problems we aren't forseeing?
We would have the install done by a contractor we've used before, and we would specify that he use flashing not just caulk, a good practice in general.
Our concern is really just the issue of the doors opening outwards onto a patio that does not have a roof.  Our house's roof overhang over where the the new door would be is about 24".
Comment: Don't all french doors open this way?  Isn't it the definition of french doors to do this?
Answer: Many doors open outwards into spaces without a roof over them. More of them are commercial than residential, but that has more to do with "common choices in residential doors" and "commercial egress door codes" than any inherent problem with it.
Unless there's a snowdrift against it, not generally a problem.
Comment: When isn't there a snowdrift against a door.  Doors are snowdrift magnets.


Get button content in event

Question: I have the code in XAML:
<Button Grid.Column="0" Grid.Row="1" x:Name="btnSete" Click="btn_Click">
    <ContentControl.Content>
        <Viewbox Margin="3">
            <TextBlock Text="7"/>
        </Viewbox>
     </ContentControl.Content>
</Button>

And code behind:
private void btn_Click(object sender, RoutedEventArgs e)
{
   Button btn = (Button)e.Source;

   txbDisplay.Text = btn.Content.ToString();
}

how do I get the value of <TextBlock Text="7"/> in btn_Click?
Comment: check this http://stackoverflow.com/a/11405038/2907017
Comment: possible duplicate of [get clicked button content from button styled listbox binded to xml](http://stackoverflow.com/questions/11404918/get-clicked-button-content-from-button-styled-listbox-binded-to-xml)
Comment: Though, while I think this question is a duplicate if you really want to retrieve the *content* of the button, in this case (with the value you are looking for being constant), the clean way to do things would probably be to simply subclass `Button` and provide it with an additional property that allows you to distinguish your buttons.
Answer: Based on your XAML, btn.Content should be the instance of the Viewbox. Then the Child property of the Viewbox should be your TextBlock.
So you should be able to do this (inside your button click event handler):
var viewBox = (Viewbox)btn.Content;
var textBlock = (TextBlock)viewBox.Child;
var text = textBlock.Text; //  This is the value you were looking for

txbDisplay.Text = text;

Also, just as a helpful note, the <ContentControl.Content> ... </ContentControl.Content> part of your XAML is superfluous. That block could just be written as:
<Button Grid.Column="0" Grid.Row="1" x:Name="btnSete" Click="btn_Click">
    <Viewbox Margin="3">
        <TextBlock Text="7"/>
    </Viewbox>
</Button>

See the "XAML Content Properties" section on this page for more information why that is if you're not sure.

Get button content in event


What is a good home station for mining low temp diamonds?

Question: I want to make some money by mining low temp diamonds but I want to know what a good home station would be for doing this.
It should preferably not be too far away from anything and not too hard to get to.
Answer: Setting up a long-term base of operations for mining isn't really that good of an idea. Mining hotspots become depleted the more they get mined out, so your yields will decline over time. Additionally, the selling price of the material you're mining will go down as the station that is buying receives its demand. What I recommend instead is looking for a medium term base of operations, which will shift pretty regularly.
/r/EliteMiners has a good tool to help find good hotspots with good prices here, which I used to get my Elite trade rank.
At the moment, the tool indicates that there is a good spot to mine Low Temperature Diamonds in Borann A2 ring B 123.06 LY from Sol, and a good spot to sell at Noon Orbital in Goibniugo 46.59 LY from Borann, however, this information will shift based on the depletion of the hotspots and the sale price at Noon Orbital.
Be advised though: player pirates will also use this information to plan interdictions. Fly safe.
Comment: Actually, the reason Borann is such a good place is that it has three overlapping Low Temperature Diamond hotspots (that will change in the next content update for a technical reason). I wouldn't hesitate to simply always mine for Borann until the hotspots are reshuffled.
Comment: However, where to sell the diamonds is certainly a question where the answer will change almost every day. Inara (https://inara.cz/galaxy-commodity/144/) is a good way to gauge where the highest sell prices are, but be aware of the QTY listed. This represents the amount of demand, and if the amount of diamonds you're carrying in your hold is an appreciable percentage of demand, the amount you sell each diamond for will decrease, sometimes dramatically if the demand is low.
Comment: I still havent picked a home station yet so should I pick one near there or just in the middle of things.?
Comment: @Addy Typically I like to dock where I plan to sell, so Noon Orbital would be where I would go.
Comment: so would i set that as my home station or just use it as a place to work from?
Comment: @Addy Having a "home station" doesn't really matter unless you have multiple ships. That being said, any system around Sol with a starport close to the entry star is a decent choice if you have a fleet to store. (for instance, my fleet is docked in Fuelum, and I leave it there to take my mining ship wherever the EliteMiners tool tells me)


Not able to create SSIS DB Catlog in linux RHEL 7

Question: I am not able to create SSIS DB Catalog on my MS SQL Server which is installed on Linux RHEL 7 Server. Though I have installed SSIS on Linux RHEL 7.
Whenever I am trying to create SSIS DB Catalog i am getting this error.

TITLE: Microsoft SQL Server Management Studio
The path to the catalog backup file could not be determined. Integration Services might not be installed on this server, or the user may not have the appropriate access permissions. (Microsoft.SqlServer.IntegrationServices.Common.ObjectModel)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProductVersion=15.0.900.30+((SQL_Main).180917-0221)&LinkId=20476
Answer: To quote the documentation: Extract, transform, and load data on Linux with SSIS - Deploy Packages

You can only store packages in the file system on Linux in this
  release. The SSIS Catalog database and the legacy SSIS service are not
  available on Linux for package deployment and storage.

Currently (at the time of writing this post), if you want to run an SSIS package on SQL Server on Linux you must use the file system deployment method, no other methods are supported.
If you are planning to use SSIS on SQL Server on Linux, I suggest having a read of Limitations and known issues for SSIS on Linux. The list is quite extensive.


Adding values to list using vlookup

Question: I have a big list like:
Actual:(sheet "A")          Expected:(Sheet "B")

A  Values                    A     Values
1    5                       1      5
3    12                      2      0
5    11                      3      12
                             4      0
                             5      11

I used formula =vlookup(A2, A!A2:A!B3, 2, FALSE) in B2 of sheet B and it returns "#N/A"
Comment: `A!A2:A!B3` remove the second `A!`? Edit: you might want to use `$` before the cells like `$A$2:$B$3`
Comment: Yup, got it. Thanks :)
Answer: In Sheet B, A2, use this: =IfError(vlookup(A2,A!$A:$B,2,0),"No Match")
Comment: Unless they are stuck in pre 2007 excel then use `=if(isna(vlookup(A2,A!$A:$B,2,0),"No Match",vlookup(A2,A!$A:$B,2,0))`
Comment: Yup, got it. Thanks :)

Adding values to list using vlookup


SQL query to insert default values

Question: I need to write a SQL query that would INSERT INTO CarSettings (fuelType='gasoline', doorCount=4) WHERE Cars.id does not exist as foreign key in CarSettings.carId.
Right now I have those default field values (fuelType='gasoline', doorCount=4) hardcoded in the codebase and if there is no entry for that carId in CarSettings table I use those hardcoded values. But this was obviously not a good idea, so now I need a query that would set those default settings values to all cars and insert them to CarSettings table.
Tables and structure:
Table Cars
id, name, description

Table CarSettings (one-to-one)
id, carId (FK Cars.id), fuelType, doorCount

Comment: Sample data and desird results would help.
Answer: You can use INSERT with NOT EXISTS:
INSERT INTO CarSettings (carid, fuelType, doorCount)
    SELECT c.id, 'gasoline', 4
    FROM cars c
    WHERE NOT EXISTS (SELECT 1 FROM CarSetting cs WHERE c.id = cs.carId);

Comment: Hey, you solution works perfectly, thank you. I apologize for not including sample data and desired results, but it would seem you were able to decipher the desired result. Again thank you very much! Cheers!

SQL query to insert default values


WhyJava Bean Pattern is not threadsafe

Question: Joshua Bloch states in Effective Java, 2nd Edition:
One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
My Question:-
Is above code not thread safe? Am I missing any basic thing?
Thanks in Advance,
Surya
Comment: Yes, your missing the basic of Java!!! Every new instance of Pizza is called will create a new instance. So NO sharing through multiple threads. Why do you think the above code is not thread-safe?
Comment: my understanding is, we will be creating new instance inside a method(say method createPizza()). When multiple threads calls createPizza() method, they have their own Pizza instance and it is threadsafe. Isn't it?
Comment: Yes, your understanding is correct!!
Comment: then, my statement is contradicting from what is there in book, right?
Comment: What does it say? Maybe you mis-interpreted?
Comment: Since you are reading Effective Java, you will find that the answer to your question is nicely presented in the chapter "Concurrency."
Comment: Sure, I will go through it. Thanks everyone who helped me to understand this
Answer: The code that you have shown us involves only one thread, so thread-safety of this code is moot.
If multiple threads could see the Pizza instance, then there are a couple of things to worry about:

Can another thread see the Pizza instance before you have finished initializing it?
When the other thread sees the instance, will it observe the correct values for the attributes?

The first concern is addressed by not "publishing" the references to another thread until you have finished initializing it.
The second one can be addressed by using an appropriate synchronization mechanism to ensure that the changes are visible.  This could be done in a number of ways.  For example:

You could declare the getters and setters as synchronized methods.
You could declare the (private) variables that hold the attribute values as volatile.

Note that the JavaBean pattern doesn't prescribe how beans are constructed.  In your example, you use a no-args constructor and then set fields using setters.  You could also implement a constructor which allows you to pass arguments giving (non-default) initial values for properties.

This also requires a lot of extra effort to ensure thread safety

Not really.  In this context, it is a small change to make the getters and setters thread-safe.  For example:
public class Pizza {
     private boolean cheese;

     public synchronized /* added */ void setCheese(boolean cheese) {
         this.cheese = cheese;
     }

     public synchronized /* added */ boolean isCheese() {
         return cheese;
     }
}

Comment: Can you add an example for making the setters / getters threadsafe? It's simple to add the `synchronized` keyword to them, but if you consider all setters part of initialization, you'd need to make sure none of the setters is called while any other Setter is called.
Comment: I don't understand your point.  Adding `synchronized` will do that.
Answer: The author says textually :

JavaBeans pattern precludes the possibility of making a class immutable and  requires a added effort on the part of the programmer
  to ensure thread safety.

I think that the author stresses on the fact that it makes no sense to provide methods that prevent the object immutability and may create consistency issues between threads if you object is designed to be immutable : that is it never needs to change once created.
Your question :

Why Java Bean Pattern is not threadsafe ?

Any class that provides a way to mutate a field is not thread safe.
It is true for JavaBeans methods (that generally don't use defensive copy) but it is also true for any mutable class.
Manipulating a no thread safe class is not necessary a problem if you use it in a context where you have no race conditions between threads.
For example this code is thread safe :
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

because the Pizza instance is not declared as a variable that is shared (instance or static field) but it is declared and used in a more restricted scope (probably a method but it could be also a initializer block).
The builder pattern provides a way to build an immutable and so by definition a thread safe object.
For example by using a builder to create a Pizza :
Pizza pizza = new Pizza.Builder().cheese(true).pepperoni(true).bacon(true).build();

Only the call to build() creates and returns the Pizza object.
Previous calls manipulate a Builder object and return a Builder.
So, if the object is immutable, you don't need to worry about synchronizing these calls :
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

as these method don't need to be provided. So they cannot be called.

About how to have thread safe JavaBeans
If you are in a context where the Pizza instance could be shared among multiple threads, these calls should be done in a synchronized way  :
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

These could be declared as synchronized method and or Pizza fields could be volatile but these could not be enough.
Indeed, if a Pizza should change its state according to its own state or even according to another object, we should also synchronize the whole logic : do the checks until the state modification of the Pizza.
For example suppose the Pizza has to add some units of Pepperoni only one time :
The code could be :
  if (pizza.isWaitForPepperoni()){
      pizza.addPepperoni(5);
  }

These statements are not atomic and so no thread safe.
pizza.addPepperoni(5); could be called by two concurrent threads even if the one of the threads already invoked pizza.addPepperoni(5);.
So we should ensure that no other thread calls pizza.addPepperoni(5) while it should not (The pizza will have too much Pepperoni) .
For example by doing a synchronized statement on the Pizza instance :
   synchronized(pizza){
      if (pizza.isWaitForPepperoni()){
          pizza.addPepperoni(5);
      }
   }

Comment: I don't think that is what he is asking. He is not asking how to make the code above thread-safe.
Comment: @Minh Kieu You are right. I edited to set the context.
Comment: "Pizza pizza = new Pizza.Builder().cheese(true).pepperoni(true).bacon(true).build();
" This is not one call. This are 5 calls.
Comment: @Angel O'Sphere only the call to `build()` creates and returns the Pizza object. Previous calls manipulate only a Builder object and return a Builder.

WhyJava Bean Pattern is not threadsafe


When switching fragments, does fragments go onPause()?

Question: Hello everyone i have a simple question:
(In Sliding menu) when we switch between fragments, does fragments go onPause?? or what?
Thanks
Also tried that:
<code>@Override
public void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    Log.d("onpause", "sorna bel on pause");
}
</code>
logcat shows nothing.
Comment: To find out stuff like this => Set a breakpoint in the fragment's `onPause()` method, then start your app with debugging. Thereafter trigger the sliding menu and see if your breakpoint is triggered. Simpler than waiting for a response here on SO.
Comment: If it doesn't show anything then the method isn't called.
Answer: yes...the onPause() method will be called, when you switch to another fragment. In the future please test it by your self. Implement the onPause() and put a Toast or a Log.d into it.
Comment: Yeap did it! I got no toast. i even tried System.out.println("going on pause"); and the logcat showed nothing.
Comment: You will have to Log it to see it in logcat aka Log.d("TAG", "going on pause");
Comment: Hmm...strange. If it's important for you, please post more code.
Comment: I think they go 'onDestroy()'. You might want to try that.


How can I save an image to my app's tmp dir?

Question: Why is that if I use NSTemporaryDirectory to save my image, the image is saved into

/var/folders/oG/oGrLHcAUEQubd3CBTs-1zU+++TI/-Tmp-/

and not into

/Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF/tmp

Here is my code:
-(NSString *)tempPath
{
    return NSTemporaryDirectory();
}

-(void) saveMyFoto
{
    NSString *urlNahledu = [NSString stringWithFormat:@"%@%@%@",@"http://www.czechmat.cz", urlFotky,@"_100x100.jpg"];
    NSLog(@"%@", urlNahledu);

    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlNahledu]]];

    NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.8f)];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSLog(@"%@    %@", paths, [self tempPath]);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"];

    [data writeToFile:localFilePath atomically:YES];
}

Comment: This post explain all directories of iOS application, save, delete http://kmithi.blogspot.in/2012/08/ios-application-directory-structure.html
Comment: `UIImageJPEGRepresentation()` already returns `NSData *` - why did you pass it to `dataWithData:` before using it? I'm wondering if you know something that I don't...
Answer: This is the preferred method which uses URL's to get a link directly to the tmp directory and then returns a file URL (pkm.jpg) for that directory:
Swift 5+
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    .appendingPathComponent("pkm", isDirectory: false)
    .appendingPathExtension("jpg")

// Then write to disk, here 0.8 is chosen for the compression quality
if let data = image.jpegData(compressionQuality: 0.8) {
    do {
        try data.write(to: url)
    } catch {
        print("Handle the error, i.e. disk can be full")
    }
}

Swift 4.1
let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
    .appendingPathComponent("pkm", isDirectory: false)
    .appendingPathExtension("jpg")

// Then write to disk, here 0.8 is chosen for the quality
if let data = UIImageJPEGRepresentation(image, 0.8) {
    do {
        try data.write(to: url)
    } catch {
        print("Handle the error, i.e. disk can be full")
    }
}

Swift 3.1
let tmpURL = try! URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
                    .appendingPathComponent("pkm")
                    .appendingPathExtension("jpg")
print("Filepath: \(tmpURL)")

Note that a possible error is not handled!
Swift 2.0
let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let fileURL = tmpDirURL.URLByAppendingPathComponent("pkm").URLByAppendingPathExtension("jpg")
print("FilePath: \(fileURL.path)")

Objective-C
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"pkm"] URLByAppendingPathExtension:@"jpg"];
NSLog(@"fileURL: %@", [fileURL path]);

Note that some methods still request a path as string, then use the [fileURL path] to return the path as string (as shown above in the NSLog).
When upgrading a current App all files in the folders:
<Application_Home>/Documents/
<Application_Home>/Library/

are guaranteed to be preserved from the old version (excluding the <Application_Home>/Library/Caches subdirectory). Use the Documents folder for files you may want the user to have access to and the Library folder for files that the App uses and the User should not see.

Another longer way might be to get an url to the tmp directory, by first getting the Document directory and stripping the last path component and then adding the tmp folder:
NSURL *documentDir = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSURL *tmpDir = [[documentDir URLByDeletingLastPathComponent] URLByAppendingPathComponent:@"tmp" isDirectory:YES];
NSLog(@"tmpDir: %@", [tmpDir path]);

Then we can address a file there, i.e. pkm.jpg as shown here:
NSString *fileName = @"pkm";
NSURL *fileURL = [tmpDir URLByAppendingPathComponent:fileName isDirectory:NO];
fileURL = [fileURL URLByAppendingPathExtension:@"jpg"];

The same may be accomplished with strings, which was used by the way on older iOS systems, but the first URL method above is the recommended one now (unless you are writing to older systems: iPhone OS 2 or 3):
NSString *tmpDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
tmpDir = [[tmpDir stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"tmp"];
NSString *filePath = [[tmpDir stringByAppendingPathComponent:@"pkm"] stringByAppendingPathExtension:@"jpg"];

Comment: I cant get files from `NSTemporaryDirectory ()` when is a video file .mp4. Works perfect for audio and image. Help
Comment: @jose920405 I don't really understand your problem, but it may have to do with whether the file is supported by iOS.
Comment: `isDirectory` is important
Answer: Because apps running in the simulator are not really sandboxed like in iOS devices. On the simulator a temporary directory from Mac OS is returned in NSTemporaryDirectory() - on an iOS device the temporary directory is really within the sandbox.
That difference shouldn't concern you as an app developer.
Answer: Swift 5 version of Sverrisson 's answer.
    let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
        .appendingPathComponent("pkm", isDirectory: false)
        .appendingPathExtension("jpg")

    // Then write to disk
    if let data = image.jpegData(compressionQuality: 0.8) {
        do {
            try data.write(to: url)
        } catch {
            print("Handle the error, i.e. disk can be full")
        }
    }

Answer: If you want to store your images in /Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF/tmp
then use nshomedirectory() which give you location upto /Users/MyMac/Library/Application Support/iPhone Simulator/4.3.2/Applications/A685734E-36E9-45DD-BBE7-0A46F8F91DAF then you just put /tmp and store your images.
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString* docDir = [paths objectAtIndex:0];
NSString* file = [docDir stringByAppendingString:@"/tmp"];

Comment: This does not work and the text talks of NSHomeDirectory() and the code uses NSDocumentDirectory thus, the /tmp directory will be part of Documents directory which is wrong.


Performance loss from 15" to 21" using the same resolution?

Question: Why do I have a huge performance loss when I changed my monitor from 15" to 21"?
For example, Dirt 2 used to run with ultra settings, 4xMSAA, 1024x768 and 30 FPS. Now it only runs 25 FPS with very low settings, no AA and 1024x768. What's wrong?
My specs: Core2Duo E4600 2,4ghz, 2GB DDR 800mhz, Geforce 9800GT 512mb 256-bit, Windows XP SP3.
Comment: Are you sure you're running the same resolution? 1024x768 is not a common native resolution for 21" screens.
Comment: To elaborate on what Fabian said, I would expect a 21" display these days to be 16:9, and so 1280x720 minimum. If the game is fill-rate bound, (1024 * 768) / (1280 * 720) is very close to (1000 / 30) / (1000 / 25), the speed drop you are seeing.
Answer: The only aspect of the display that influences performance in 3D games is the resolution. The higher the resolution that needs to be displayed, the greater the number of pixels the graphics card has to calculate and the lower the performance.
If the resolution stays the same, changing displays can not influence performance. My guess is that you're running your new display at a higher resolution than the old one, which will reduce performance. You're stating that you're using the same resolution, but if that is true there should be absolutely no difference in performance.


coin problem with two coins, inductive proof

Question: Adjustment This proof is flawed.
I want to ask something about the coin problem with two coins. Let $a,b$ be to numbers in $\mathbb{N} \setminus \{0\}$ (elsewhere I include zero) which have no prime factors in common. I will write
$$
S_{a,b} \quad = \quad a \mathbb{N} + b \mathbb{N}
$$
Now we look for the greatest number $M \in \mathbb{Z}$ that doesn't belong to $S_{a,b}$.
It seems that someone has shown that that $M = ab -a-b$. I didn't know how the proof worked but I wondered if this could be shown by reasoning inductively to product of primes which gives $a$ and $b$. Here below you will find what I tried, I hope that you can help me to finish it.

My attempts
The statement holds if both $a$ and $b$ are empty products, in this case $a=b=1$, so $ab-a-b = -1 $, and every $n \in \mathbb{N}$ can be reached so the equality is true.
Now, if there are are two coprime natural numbers $a,b$ such that
$$
\max (\mathbb{N} \setminus S_{a,b}) \quad = \quad ab-a-b
$$
Then we add a prime factor. Without loss of generality, we can multiply $a$ by a prime number that does not divide $b$. Now we should ask ourselves the following.
$$
\max (\mathbb{N} \setminus S_{pa,b}) \quad \stackrel{?}{=}  \quad pab-pa-b
$$
This equality can be split up in the following statements:

$\forall n,m \in \mathbb{N}, \quad pab-pa -b \ \neq \ npa +mb$
If $ \ k > pab-pa-b \ $ it follows that $k \ = \ n_k a + m_kb$ for some $n_k,m_k \in \mathbb{N }$

To establish the first statement, I remembered that for every combination $n,m \in \mathbb{N}$, we have that $ab-a-b \neq na+mb$. If we multiply by $p$ and add $b(p-1)$ on both sides, we get the $pab-pa-b \ \neq \  mpa + b(na+p-1)$. But I am afraid that this proves anything because the map $n \ \mapsto \  na+p-1$ is doesn't reach every natural number.
For the second one, I tried to solve $k = mpa + nb$ for $m,n \in \mathbb{N}$. To do this I rewrote
$$
k - m(p-1)a \quad = \quad ma+nb
$$
This would be solvable by the assumption of the induction if the left side is bigger then $ab-a-b$.
We aldready know that $ k > pab -pa -b$. Hence we know
$$
k-m(p-1)a \ > \ pab -pa -b -m(p-1)a \ = \ p(ab-a-ma) + ma -b \ \geq ab-a-b\
$$
as we wished.

I would like to read

If you know how I could end my proof of the first statement
If I didn't make any mistakes in the proof of the other one.
Comment: The $ab-a-b$ thing was shown by J.J. Sylvester in 1884.  ([Coin problem](http://en.wikipedia.org/wiki/Coin_problem))
Comment: If you want somebody to discuss your proof it would be easier if you number your equation/inequations. I think you made a mistake, you cannot get  $pab-pa-b \ \neq \  mpa + b(na+p-1)$ from the former equation. it should be $pab-pa-b \ \neq \  npa + b(mp+p-1)$ Also you should make your naming of variables consistent In the first part you use $n$ for the multiplier of $a$ int he second part you use $m$. This makes it more difficult to read the proof.
Answer: For the first step: I think it is easier to see what you are doing when we proceed in the other direction. By that I mean, suppose we have $pab - pa - b = npa + mb$ for some $n, m \in \Bbb N$. We want to show that we can then find $n', m' \in \Bbb N$ such that $ab - a - b = n'a + m'b$. You reached the first equation from the second one by scaling by $p$ and translating. Lets try to do that in the other direction:
Take $pab - pa - b = npa + mb$. This is clearly equivalent to $pab - pa - (m + 1) b = npa$. Since $p$ does not divide $b$ but it certainly divides $(m-1)b$, we conclude that it divides $m - 1$. Thus, we have $m - 1 = kp$ for some $k \in \Bbb N$. Dividing our equation by $p$ yields $ab - a - kb = na$. But clearly we can add $(k-1)b$ to get $ab - a - b = na + (k - 1)b$, which gives the desired contradiction (one detail is that since $m + 1$ is positive, we know that $k$ is positive, hence $k - 1$ is non-negative).
I think what I did is similar to your idea, just that in this direction it is easier to see why it works. Your concern about your proof is correct and I don't see how to fix it (without taking the backwards route described above).
For the second step, you probably mean $k > pab - pa - b$ (instead of "$\ge$"). In your proof I don't understand the step "$p(ab−a−ma)+ma−b \ge ab - a - b$. This is definitely not true for all $m$, so how do you choose $m$? Another problem is that in $k−m(p−1)a=ma+nb$ you have the same $m$ on both sides. On the other hand, your proof might give you a different $m$ on the right.
I don't see how to fix you proof (if I find something I will add it here), but I can give another proof for the second part that does not even rely on induction:
Given $k > ab - a - b$, lets try to solve $k = na + mb$. Consider this equation modulo $b$. Since $a$ and $b$ are coprime, we can solve $na \equiv k \bmod{b}$ (this is an elementary but quite important result in number theory). We can further choose $n$ among the residues $\{0, 1, \dots, b - 1\}$.
Then, the congruence tells us that $b \ | \ na - k$, so $na - k = mb$ for some integer $m$. Thus, $na - mb = k$. It suffices to show that $m$ is not positive (then $(n, -m)$ satisfies the desired property). This is clearly the case if $na \le k$.
We see that since $n \le b - 1$, we have $na \le (b-1) a = ab - a < k + b$. We get a problem if $na > k$, hence when $0 < na - k < b$. However, this cannot happen since this would contradict $na \equiv k \bmod{b}$!
So we are done. Please write in the comments if you want some explanations and also if there is an error in what I wrote (I had to figure the proof out myself, so it is definitely possible that something is wrong).
Comment: Thank you. I don't understand what $ab−a−b=na+(k−1)b$ contradicts. Could you tell me more about that?
Comment: It contradicts the induction hypothesis. For $n' := n$ and $m' := k - 1$ we have $ab - a - b = n'a + m'b$. Further $n', m' \in \Bbb N$.
Comment: About "$na>k$ , hence when $0 ab - a - b$.
Answer: So, after finishing the proof of the first part I noticed I forgot about the inductive hypothesis. I'm posting it anyway because there's no rule that says you can't use a non-inductive proof to show the inductive step.
Pretend $a,b \in \mathbb{N}$ are coprime, and suppose $ab - a - b = ma + nb$ for some $m,n \in \mathbb{N}\cup\{0\}$
then we can say $ab = ma + nb$ for $m,n>0$ (new $m$ and $n$ are the old ones plus 1)
then $a(b-m) = ab - ma = nb$
Here we see that both $a$ and $b$ are factors of something strictly less than $ab$, which if they had been coprime, would have been their LCM.
So if $ab - a - b \in S_{a,b}$, $a$ and $b$ aren't coprime.
So by the contrapositive if they are coprime $ab-a-b$ isn't in $S_{a,b}$
and we're done.


Existence of periodic orthogonal basis in $L^2([0,1])$ which is not trigonometric?

Question: Let
$$
\psi(x) := \sin(\pi x).
$$
It is well-known that system $\{ \psi(n x) \}_{n \in \mathbb{N}}$ forms an orthogonal basis in $L^2([0,1])$.
My question is the following:
Are there other examples of function $\psi(x)$, such that $\{ \psi(n x) \}_{n \in \mathbb{N}}$ forms an orthogonal basis in $L^2([0,1])$ or, at least, orthogonal and complete system in $L^2([0,1])$?
It is known, for instance, that square-wave functions of the form $\mbox{sign}(\sin(n \pi x))$ is complete system in $L^2([0,1])$, however, it is not orthogonal. Of course, one can orthogonalize this system, but the result will be "non-periodic" in the sense that the elements of the orthogonalized set cannot be constructed by replications of the initial function $\mbox{sign}(\sin(\pi x))$.
By the similar reasons Haar system, Legendre polynomials, etc. are not candidates, too.
It seems to me that the question is rather natural and it should be some results on this. However, I cannot find anything. Need your advice!
Comment: The Rademacher functions, if you are willing to accept $\{ r(2^nx)\}$ instead of $\{ r(nx)\}$.
Comment: @DanielFischer Agree. But for me it is necessary to assume $(nx)$.
Comment: @DanielFischer Moreover, I realized that Rademacher system is even not complete.
Comment: It isn't? What is orthogonal to all of them (of course one has to include $r_0$ which is $1$ on $[0,1]$ and $-1$ on $[1,2]$)?
Comment: @DanielFischer To be honest, I didn't study this question. But I believe some textbooks, which I met while searching the answer to the main problem.
Comment: A little bit of thinking about it reveals that for example $\chi_{[0,1/4)}$ is not in the (closure of the) span. Now the difficult question becomes why I thought it was complete ;)
Answer: It seems that I have found the answer in this article.
The main result (restricted to the interval $(0, 1)$) is that only
$$
\{\sin(n \pi x)\}_{n \in \mathbb{N}} \quad \mbox{or} \quad  \{1, \cos(n \pi x)\}_{n \in \mathbb{N}}
$$
forms a periodic orthogonal basis in $L^2(0, 1)$.
I'll leave this answer here for better search on this question.


Calendar allways returns the same date

Question: I'm trying to get the current day of the week and week of the year like this:
Declaring my variable like this:
Calendar calWeek;
Calendar calDay;

Setting the values like this:
calWeek = Calendar.getInstance();
calWeek.setFirstDayOfWeek(Calendar.MONDAY);
calWeek.set(Calendar.WEEK_OF_YEAR, Calendar.MONDAY);

calDay = Calendar.getInstance();
calDay.setFirstDayOfWeek(Calendar.MONDAY);
calDay.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

int currentWeek = calWeek.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calDay.get(Calendar.DAY_OF_WEEK);

currentWeek returns 2 and dayInWeek returns 2. The current week is 1 and it's Wednesday. (3rd day of the week)
Even if i change the date on my device, the output is the same, currentWeek returns 2 and dayInWeek returns 2.
Why does it always return the same date?
Best regards,
Dridia
Comment: They're both returning `2` because you're setting both to `Calendar.MONDAY`, which has a value of `2`. The `Calendar.getInstance()` method returns a `Calendar` object with the current date already set, so just remove both `set()` calls.
Comment: what do you expect `calWeek.set(Calendar.WEEK_OF_YEAR, Calendar.MONDAY);` to do?
Comment: @njzk2 I have no idea... It's completely useless for this kind of purpose. Removing both `set()` calls fixed the problem. Thank you so much!
Answer: As mentioned in Mike M's comment: you set both values to Calendar.MONDAY which is equals to 2.
Calendar.getInstance() returns an instance with the current date but if you call calendarInstance.get(Calendar.WEEK_OF_YEAR) you still get 2 because according to the docs:

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least  getMinimalDaysInFirstWeek() days of that month or year....

I just tried it and getMinimalDaysInFirstWeek()returns 1 by default. So you should set this to 7 days. So the first Week will begin on Monday as you expect.
One instance of Calendar is sufficient and your code should look like this:
Calendar calendarInstance = Calendar.getInstance();
calendarInstance.setFirstDayOfWeek(Calendar.MONDAY);
calendarInstance.setMinimalDaysInFirstWeek(7);
int currentWeek = calendarInstance.get(Calendar.WEEK_OF_YEAR);
int dayInWeek = calendarInstance.get(Calendar.DAY_OF_WEEK);
System.out.println("week = " + currentWeek);
System.out.println("day of week = " + dayInWeek);

prints:
week = 1
day of week = 4

P.S. 4 means Wednesday

Calendar allways returns the same date


Why is my Question still on hold after editing it extensively?

Question: I have asked the following question : How to redirect a User to a predefined URL next to a VBO (Views Bulk Operation) Operation?
... and was put on hold on nov.13 by kiamlaluno.
I have extensively reedited my question, several times, since then (including a screen capture where my problem is highlighted), but it remains on hold (or closed ?) : how can I have it re-openned ?
Comment: I'd vote to close it again, since it's a bug report. And this belongs on drupal.org. Not here. Asking on DA if anybody else experienced this lacks the step to try to debug this yourself. We can't do this for you. Since we don't know your setup, your modules, your custom code and whatever else you configured on your page.
Answer:
how can I have it re-openned ?

Whenever an on-hold question is edited, it goes into a queue for re-opening. For whatever reason, it hasn't gathered the re-open votes necessary from the natural process while in that queue.
But your edits have done the trick, it's now a well framed question, so there's no reason to keep it on hold any longer; I've re-opened it.
Comment: -1 as the mentioned issue is a bug report which should be posted on drupal.org instead. Which makes it off-topic for DA.
Comment: Thank you Clive for re-openning. I cannot know wether this is a bug or a misuse (since VBO is not extensively documented). I accept to be closed if it is actually a bug (just tell me where I should report it).
Comment: @leymannx I read it more as "have I configured this properly?", that's why I re-opened it. Thanks for talking the OP through it in the comments. having read it again I think you're right, without more info it's probably a bug report
Comment: @Jacques-MarieMoranne I understand your predicament, it's often difficult to know if something's a bug or not. I think in this case you've done what would probably be considered the obvious thing to configure the redirect, and it hasn't worked - if you don't have any more context than that to share, it's likely to be a bug in the module and needs to be reported to the issue queue (leymannx provided a link in the comments on the original question)


How can I deal with a gap between replacement fenceposts and the rails?

Question: Our backyard fence is starting to show its age and the cedar 4X4s are slowly starting to break with our strong SW KS winds. I would like to start replacing the 4X4s with heavy gauge steel posts (we'll need about 80 or so).
Anyway, what I'm needing to deal with is the gap between the stringers once the wood post is removed. The brackets for the steel post are just barely able to reach the end of the stringers, so there's not much bite into them and I'm afraid it won't be very strong.
Any ideas to deal with an excessive gap without replacing all the stringers for the individual broken posts? I need to replace about 5 broken posts right now, but will eventually start doing one side of the fence at a time and obviously replacing stringers to fit at that point.
The posts will be 2-3/8" x 8' AP40 (10 gauge) steel using using three 2x4 cedar rails and cedar pickets with the posts being on 8' centers. I will be using these brackets. They are the heaviest and widest I could find.
I only get about an inch overlap onto the rails. If I use 5/16 galvanized lags they are just barely grabbing the end of the rails. I thought about temporarily putting an 8" mending plate on the backside of the rails between the rail and the pickets. At least until I can start rebuilding one whole side at a time. For right now I just need to replace the 5 until later this summer.
Answer:
Use larger steel posts so that when the brackets are mounted to them, the bracket comes close enough to the stringer that it can be securely attached.
Use deeper brackets to span the gap.
Both of the above. Larger posts in combination with longer brackets if neither alone will do the trick.
Bite the bullet and replace the stringers with longer ones.

Which you choose will probably be determined by cost. You may find that purchasing & preparing new lumber to make longer stringers is less expensive than larger posts and/or brackets. On the other hand, larger posts and/or brackets may be less expensive than lumber. It may depend on the day you make the purchase.
Answer: Your comment about the mending plate is going in the same direction I am, but you really want something long enough to be effective in tension--to do what the screws being so close to the end of the rails doesn't do. You also want something cheap and easy, since you'll need so many.
I think I'd try something like strips of heavy-gauge galvanized sheet steel, maybe from a 12" or 18" wide roll. Cut 3" strips off the end of the roll and use them to gusset the rails together on the back side prior to installing them in the bracket. This serves to transfer any tension load on one rail to the adjacent rail as well. Simple 1" or 1-1/4" flat-head screws should work well--they should pull in flush fairly easily.
It can be difficult to predict failure modes with something like this, so build a couple and try stepping up on the rails. See how things move. You may need to switch to light-gauge steel angle wrapping underneath, or even 1/8" bar stock underneath, to give more stability on the Y-axis.