Q:

NavigationService in universal app

I created a Windows Phone 8.1 project in which I used the following code in different pats of the code:
if (this.NavigationService.CanGoBack)
{
    this.NavigationService.RemoveBackEntry();
}

I tried porting this code to a universal app, and I get an error saying that the NavigationService could not be resolved. How do I handle navigation in the universal app world?

A:

I had the same issue and can't find NavigationSerice either.
But after some searching I found the solution for Navigate, I hope you can use something like this.
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(typeof(BasicPage2));
}

See this page for more information.
The BackButton works totaly different on Windows 8.1 you don't need to remove the BackEntry(). But instead you have to add some code when you want to Navigate Back.
For Example:
If you Navigate From Mainpage to Page1 and you want Navigate Back from Page1 to the Mainpage with the (Hardware)BackButton you have te add following to the Mainpage:
Add this inside the constructor:
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;

And create this method:
 void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
        if (Frame.CanGoBack)
        {
            Frame.GoBack();
            //Indicate the back button press is handled so the app does not exit
            e.Handled = true;
        }
    }

Now your app navigates back from Page1 to Mainpage using the BackButton.


Q:

Make a div inside a div scrollable on x-axis

I am trying to achieve what the following image suggest:

It's a view with, as you can guess, a list of Magic: The Gathering card sets. I'm trying to display them as shown, but I'm having huge troubles doing so. I need to make a
 inside a
 with a scroll bar in the x axis.
Here's part of my view:

                Type one ability per line:

                @Html.TextAreaFor(_item => _item.mTextAbilities, new { @id = "cardAbilities" })

                        @Html.CheckBoxFor(_item => _item.mAllCardSets)

                        All

                    @{
                        for (int i = 0; i < Model.mListCardSets.Count; i++)
                        {
                            if (i == 0)
                            {
                                @Html.Raw("
")
                            }
                            else if (i % 6 == 0)
                            {
                                @Html.Raw("

")
                            }
                            else if(i == Model.mListCardSets.Count -1)
                            {
                                @Html.Raw("
")
                            }

                                @Html.HiddenFor(_item => _item.mListCardSets[i].Name)
                                @Html.HiddenFor(_item => _item.mListCardSets[i].Code)
                                @Html.CheckBoxFor(_item => _item.mListCardSets[i].IsChecked, new { @class = "checkGroup4", @id = Model.mListCardSets[i].Name })
                                @Html.DisplayFor(_item => _item.mListCardSets[i].Name)
                                @Html.Image("~\\Images\\CardSetRarity\\" + Model.mListCardSets[i].Code + "_R.jpeg", Model.mListCardSets[i].Name, new { @title = Model.mListCardSets[i].Name })

                        }
                    }

And the related css classes:
.formStyle {
    -ms-border-radius: 10px;
    border-radius: 10px;
    padding: 5px;
    background-color: white;
    border: 4px solid darkgrey;
    margin: 5px;
    overflow: hidden;
}

.inline-block {
    max-height: 30%;
    min-height: 30%;
    height: 30%;
    width: 100%;
    display: inline-block;
}

.cardColumn {
    display: table-cell;
    width: 30%;
    padding: 5px;
    position: relative;
}

.wideColumn {
    overflow: auto;
    width: 60%;
    display: table-cell;
}

.blackBorder {
    border: 2px solid black;
}

.scrollX {
    overflow-y: hidden;
    overflow: auto;
}

.row {
    height: 40px;
    line-height: 40px;
}

.columnText {
    max-width: 30%;
    -moz-min-width: 30%;
    -ms-min-width: 30%;
    -o-min-width: 30%;
    -webkit-min-width: 30%;
    min-width: 30%;
}

.columnValue {
    width: 70%;
}

So far I have not succeeded and any help would be appreciated.
Here's a render of how it comes:

A:

TRY overflow-x: scroll; on the div you want element inside it to be scrolling.


Q:

Linq, streaming & collection

I have this method which return an array of string :
    private static string[] ReturnsStringArray()
    {
        return new string[]
        {
            "The path of the ",
            "righteous man is beset on all sides",
            "by the inequities of the selfish and",
            "the tyranny of evil men. Blessed is",
            "he who, in the name of charity and",
            "good will, shepherds the weak through",
            "the valley of darkness, for he is",
            "truly his brother's keeper and the",
            "finder of lost children. And I will ",
            "strike down upon thee with great",
            "vengeance and furious anger those",
            "who attempt to poison and destroy my",
            "brothers. And you will know my name",
            "is the Lord when I lay my vengeance",
            "upon you"
        };
    }
}

I want to write a method which use this method. As this method returns an array and not a IEnumerable, is there the same result to write this :
    private static IEnumerable<string> ParseStringArray()
    {
        return ReturnsStringArray()
            .Where(s => s.StartsWith("r"))
            .Select(c => c.ToUpper());
    }

and this :
    private static List<string> ParseStringArray()
    {
        return ReturnsStringArray()
            .Where(s => s.StartsWith("r"))
            .Select(c => c.ToUpper())
            .ToList(); // return a list instead of an IEnumerable.
    }

Thank you.
EDIT
My question is : Is there any interest or benefits that the method ParseStringArray() returns an IEnumerable instead of a List because of this method calls ReturnsStringArray that returns an array of string and not a IEnumerable

A:

When you return a List, you are saying that "all processing has been done, and the List contains the results".
However, when you return an IEnumerable, you are saying that "processing might still need to be done".
In your example, when you return an IEnumerable, the .Where and .Select have NOT bee processed yet.  This is known as "deferred execution".
If the user uses the result 3 times, then the .Where and .Select will execute 3 times.  There are a good number of tricky issues that can come from this.
I recommend using a List as often as possible when returning values from a method.  In addition to the additional functionality you'll get from a List, .NET has many optimizations that require a List, debugging support is better, and there's a reduced chance of unintended side effects!


Q:

How to validate click of h:outputLink with imagined required="true"?

I'm trying to put validation in my Link. when the user click on commandButton without click on outputLink user gets an error message. I'm using required="true" but it doesn't work.
<h:form>
    <h:outputLink value="https://www.google.com/" required="true">test</h:outputLink>
    <h:commandButton value="Submit"    action="#{userTest.test()}"/>
</h:form>

A:

Associate a required hidden input with the link and set its value via JS.
Here's a kickoff example which assumes the hidden input is 1st sibling of the link.
<h:form>
    <h:outputLink
        value="http://google.com"
        target="_blank"
        onclick="this.nextSibling.value=true">test</h:outputLink>
    <h:inputHidden
        required="true"
        requiredMessage="You need to click that link!" />
    <h:commandButton value="submit" />
    <h:messages />
</h:form>


Q:

Exporting jar libraries in an Eclipse plugin

I am working on an Eclipse plugin that has several components. Previously this was a single plugin and everything worked great. However, I recently broke this into multiple plugins that are part of a single feature.
The structure is there are a whole bunch of plugins in the feature. There is one "core" plugin that contains common code and libraries. Every other plugin relies on the core plugin.
The problem is while the plugins compile fine and there are no warnings regarding the plugin.xml, manifest, etc., the plugins do not work at runtime due to missing classes. Specifically, I have Google Guava in the core plugin and the classes in the Guava jar cannot be found at runtime. There are other jars but this is the first one to blow up.
I have tried several ways to resolve this:

Exporting packages contained in the Guava jar in the core project has the same results: does not work.
Putting the Guava jar in each plugin does work, but is undesirable due to the extra size.
According to my searches, I can add a <runtime> tag to my plugin.xml, which Eclipse promptly ignores because I have a manifest. I have not found a way to add an equivalent setting to the manifest.

The only way that actually works is to create a library plugin which essentially unpacks and merges all of the jar files. The problem here is I then have a mishmash of random files. If I want to upgrade a jar file, it is tedious to regenerate the project and I suspect would be clear as mud when searching through SVN history for the project.
Is there another way to accomplish this that makes it easy to drop in updated jar files and have it work with minimal changes?

A:

Exporting packages contained in the Guava jar in the core project has the same results: does not work.

Have your wondered on this?
As far as I am aware, In Eclipse Equinox is OSGi container and in OSGi we have the facility of using other bundles resources.
So, here make sure that you are exporting the right things from the right place.
Probably, the other bundles are not able to recognize the classes exported from core bundle (check import-package here in all your child bundles) OR
something miss-happenings in classloaders.
Try using "Eclipse-Buddy policy" attribute in manifest. It may work :-)


Q:

google chrome: any extensions for code syntax highlighting on some website?

any extensions for code syntax highlighting on some website?

A:

You may want to take a look at Syntaxtic!.


Q:

Argc/Argv C Problems

If I have the following code:
main(int argc, char *argv[]){
 char serveradd[20];
 strcpy(serveradd, argv[1]);
 int port = atoi(argv[2]);
 printf("%s %d \n", serveradd, port);

The first two arguments to the command line are printed. However, if I do this:
 char serveradd[20];
 strcpy(serveradd, argv[1]);
 int port = atoi(argv[2]);
 char versionnum[1];
 strcpy(versionnum, argv[3]);
 printf("%s %d %s \n", serveradd, port, versionnum);`

The first argument (serveradd) does not print out to the screen and is not being stored... Why is this happening and how can I fix it? Thanks!

A:

char versionnum[1];
strcpy(versionnum, argv[3]);

Wild guess but you are smashing the stack with these lines. Make versionnum bigger; as it stands, it can only safely hold the empty string.

A:

You're probably nuking memory with
char versionnum[1];
strcpy(versionnum, argv[3]);

Given that any non-empty null-terminated string is going to be > 1 character long.
Never use straight strcpy(); use strncpy() instead (note the - 1 to preserve space for the null terminator):
char serveradd[20] = { 0 };
strncpy(serveradd, argv[1], sizeof(serveradd) - 1);
int port = atoi(argv[2]);
char versionnum[2] = { 0 };
strcpy(versionnum, argv[3], sizeof(versionnum) - 1);
printf("%s %d %s \n", serveradd, port, versionnum);


Q:

Div slide from the left side after a button is clicked

The picture explains it better than I do.
Before I click on it - screenshot1
After: screenshot2
It's a fixed button on the side of a window and it slides out when it's clicked.
I've been searching the web for so long and can't find the solution. Could you guys help me please?

A:

below code can help you.
HTML

   <

CSS
#hiddenPanel {position:fixed; top:0; right:-200px; width:200px; background-color:grey; height:250px;}
#close-bar { position:absolute; left:-20px; background:red; color:white; width:20px; height:250px;}

jQuery Code
var speed = 300;
    $('#close-bar').on('click', function(){

        var $$ = $(this),
            panelWidth = $('#hiddenPanel').outerWidth();

        if( $$.is('.myButton') ){
            $('#hiddenPanel').animate({right:0}, speed);
            $$.removeClass('myButton')
        } else {
            $('#hiddenPanel').animate({right:-panelWidth}, speed);
            $$.addClass('myButton')
        }

    });

http://jsfiddle.net/Rxsd5/


Q:

I know there must be an easier way to do this: Javascript function model returning a date

I have to say, I am not an expert with Javascript dates.. at all!  I have looked at DateJS for instance, however my problem is not just a simple date conversion (or maybe it should be!).
Quick background:
I have a service call which returns some JSON data that include the dreaded Epoch style date from WCF/REST (I can't use Webapi at the moment - which would give me native JSON.NET?).
So a date examlple from the JSON object is:
StartDate: "/Date(1343378404560+0100)/"
Now, the JSON returned from my call has more information that I need for my Wijmo event calendar object, so I thought ok, will create a Javascript function/model for my Wijmo event object, and use jQuery MAP function to select only the fields I need.
My Javascript event model looks like this:
function wijmoEventModel(in_id, in_calendar, in_subject, in_location, in_start, in_end, in_description, in_colour, in_allday, in_tag) {

    this._id = in_id;
    this._calendar = in_calendar;
    this._subject = in_subject;
    this._location = in_location;
    this._start = jsonDate(in_start);
    this._end = jsonDate(in_end);
    this._description = in_description;
    this._colour = in_colour;
    this._allday = in_allday;
    this._tag = in_tag;

    //  Public Properties/Methods
    return {
        id: this.id,
        calendar: this._calendar,
        subject: this._subject,
        location: this._location,
        start: this._start,
        end: this._end,
        description: this._description,
        color: this._colour,
        allday: this._allday,
        tag: this._tag
    }
};

So, I have another little function that uses the jQuery MAP function as so:
function returnWijmoCalendarObject(diaryEventData) {

    //  Using jQuery map, reduce our raw event data down to only the required wijmo calendar items
    var _calobj = $.map(diaryEventData, function (fld) {
        return new wijmoEventModel(fld.ID, fld.ResourceCalendarID, fld.EventTitle, fld.Location, fld.StartDate, fld.EndDate, fld.Description, fld.ResourceColour, fld.AllDay);
    });
    return {
        calendardata: _calobj
    }
};

SO the above function just selects the required fields from my original full JSON return, and uses my Javascript function/model to return a new "calendardata" JSON object which I can use with my Wijmo event calendar..
There is one more small function which converts the Epoch style date "/Date(1343378404560+0100)/"
into (I think!) a real Javascript Date object.. like this:
function jsonDate(rawDate) {

    var d = new Date();
    d.setMilliseconds = parseInt(rawDate.substr(6));
    return d;
}

So the above little function of course is used in the first code block above to hopefully convert that Epoch style original date into a Javascript Date.
SO MY QUESTION/PROBLEM IS:
The model above, and jQuery map function works well, I get a subset JSON object of exactly the structure I need, however the dates returned (wijmoEventModel.start & end) don't come back as a Javascript Date object??  even though debuging in that wijmoEventModel definitely has the dates as JS date objects??
Obviously I am missing/not understanding some vital and fundamental aspects here!!!
PLEASE! if anyone can help as this is driving me crazy...
David.

A:

Setting milliseconds only sets the milliseconds part of a date, it doesn't set the date from an epoch.
At the heart of a javascript date object is a number of milliseconds since 1970-01-01 00:00:00 in UTC. So if the "time since epoch" that you have is the same, if you convert it to a number you can do:
var d = new Date( Number(millisecondsSinceEpoch) );

See ECMA-262 15.9.3.2
This will create a date object in the local timezone based on the "time since epoch" in UTC. So in different time zones it will show a different time that represent the same instant in UTC.
e.g.
var millisecondsSinceEpoch = '1343378404560';
alert( new Date(Number(millisecondsSinceEpoch))); //Fri Jul 27 2012 18:40:04 GMT+1000 (EST)

The time in the OP is '1343378404560+0100' which implies an offset that I'll assume is hhmm. So that needs to be subtracted from the number before passing it to Date:
var s = '1343378404560+0100';
var t = s.split('+')[1];

if (t) {
  t = t.substring(0,2)*3600 + t.substring(2)*60;
} else {
  t = 0;
}

var d = new Date(parseInt(s) - t * 1000);  // Fri Jul 27 2012 17:40:04 GMT+1000 (EST)

Edit
The above assumes a sign of "+", the string should be split on either "+" or "-", then the sign detected and applied later, e.g.
var t = s.split(/[-+]/)[1];

After setting the value of t, apply the sign:
t *= /-/.test(s)? -1000 : 1000;
var d = new Date(parseInt(s) - t);

Or some variation of the above.


Q:

use operator as constructor in prolog

I'm writing a function called leagalCourse, it takes just one parameter, a course list. A course like, for example, john+mary+94 would represent a project done by John and Mary with a mark of 94.

It should be true if the course data is “legal”, which means that it  must not have a project with the same name twice such as john+john+70.
There also must not be two projects in the list containing the same pair of students. So if there’s a project harry+ron+82 in the list, it would be illegal for the list also to contain harry+ron+90 or ron+harry+63.

There is a sample output:
?- legalCourse([one+two+3,four+five+6,one+six+7]).
true.

?- legalCourse([one+two+3,four+four+6,one+six+7]).
false.

?- legalCourse([one+two+3,four+five+6,one+two+7]).
false.

?- legalCourse([one+two+3,two+one+6,one+six+7]).
false.

This is what I tried:
legalCourse([]).
legalCourse(X) :-
        diffName(X).
legalCourse([Project|M]):-
        diffName(Project),
        not(samePair([Project|M])),
        legalCourse(M).

diffName(Name1+Name2+_) :-
        Name1 \= Name2.

/*can not have duplicated group*/
samePair([Name1+Name2+_|More]) :-
        append([[head],tail,More]),
        member(Name1,[head]),
        member(Name2,[head]).

The function partially worked before I added the samePair predicate.

A:

I think this works, you need to switch the vars and check both are different in check_no_dups/1.
legalCourse(List):-
 maplist(triple_double,List,ListDouble),
 check_no_dups(ListDouble).

check_no_dups([]).
check_no_dups([H|T]):-
   H =X+Y,
   maplist(dif(H),T),
   H2 =Y+X,
   maplist(dif(H2),T),
   check_no_dups(T).

triple_double(X+Y+_Z,X+Y):-dif(X,Y).


Q:

How many ways can a sequence of $1$s be partitioned into pairs or singles?

How many distinct ways can a sequence of $n$ $1$s be partitioned into pairs or singles, in which $\{1,1\}=\{2\}$ is considered a pair and $\{1\}$ is considered a single?

For example $\{1,1,1,1\}$ can be partitioned into:
$\{2,2\}$
$\{1,2,1\}$
But
$\{2,1,1\}$
and
$\{1,1,2\}$
are equivalent to $\{2,2\}$
No result containing $\{1,1,1\}$ should be enumerated since this is a triple and has not been partitioned into pairs or singles.
So for $n=4$, the answer is $2$ ways.
I think the answer to this question describes the the number of Dyck words which give unique results when exponentiating powers of $2$... as discussed in this question.  Or it is at least part of the answer in respect of the fact that it factors out the identity $2^4=4^2$.

A:

I guess what you are trying to ask is:
"In how many way you can express $n\ge 1$ as ordered sum of $1$ and $2$ so that there are no two consecutive ones?"
Solution: Suppose that $n$ is even, i.e., $n=2k$. Then we can place at most $k$ times the number $2$. So, given $i \in \{0,\ldots,k\}$, we miss to place (if possible) $n-2i$ times the number $1$ in the $i+1$ possible positions. Hence the total number is
$$
1+\binom{k}{2}+\binom{k-1}{4}+\cdots=\sum_{j\ge 0}\binom{k+1-j}{2j}.
$$
With a similar argument, if $n$ is odd, i.e., $n=2k+1$, we obtain
$$
(k+1)+\binom{k}{3}+\binom{k-1}{5}+\cdots=\sum_{j\ge 0}{\binom{k+1-j}{2j+1}}.
$$

A:

A composition of $n$ can either be a composition of $n-2$ followed by a $2$ or a composition of $n-3$ followed by $2,1$.  This gives the recurrence $f(n)=f(n-2)+f(n-3)$ with $f(1)=1, f(2)=1, f(3)=2.$  We find it, offset, in OEIS A000931 and it begins $1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, 351, 465, 616, 816, 1081, 1432, 1897, 2513, 3329, 4410, 5842, 7739, 10252, 13581, 17991, 23833, 31572, 41824, 55405, 73396, 97229, 128801, 170625$


Q:

Round Raster to next higher or lower int

I am using ArcGIS 10.1.
I am searching for a solution to calculate a raster.
The values are like:
0.2
0.6
5.3
i.e.
How can I now get 0.2 as 0 and 0.6 to 1 and 5.3 to 5? In the end integer numbers.
The "roundup" and "rounddown" functions are worse to do this.
Thanks for any hints.
Luigi

A:

Int(yourraster + 0.5) will round to the nearest integer.
For rasters that may contain negative values:
Con(yourraster < 0, Int(yourraster - 0.5), Int(yourraster + 0.5))


Q:

asp.net sql selecting data from multiple tables

[IMG]http://i62.tinypic.com/2141deb.jpg[/IMG]
The image above is my 3 tables i have created and filled up with my data. I am using Visual Studio 2013, though i think with my question all details are irrelevant as it is a basic sql problem.
< <asp:SqlDataSource ID="SqlDataSource1" runat="server"
 ConnectionString="<%$ ConnectionStrings:ConnectPizza %>"
SelectCommand="SELECT users.[title], users.[gname], users.[sname], users.[suburb], users.[postcode], pizzas.[type], orders.[pizza-size] orders.[quantity]
FROM orders JOIN users ON users.[username]=orders.[username] JOIN pizzas ON pizzas.[pizza-id] = orders.[id]">
 <SelectParameters>
 <asp:SessionParameter SessionField="login_username"
 Name="username" />
 </SelectParameters>
 </asp:SqlDataSource>

When i do this code i get a basic syntax error "Incorrect syntax near '.'. "
What am i doin wrong, i know since there is a hyphen in one of my column names pizza-id I decided to put braces around all of them. Any help would be grateful

A:

you frogot a comma in:
SELECT users.[title], users.[gname], users.[sname], users.[suburb], users.[postcode], pizzas.[type], orders.[pizza-size] orders.[quantity]

between orders.[pizza-size] and orders.[quantity]
    SELECT u.title, u.gname, u.sname, u.suburb, u.postcode, p.type, o.pizza-size, o.quantity
      FROM orders o
INNER JOIN users u ON u.username=o.username
INNER JOIN pizzas p ON p.pizza-id = o.id

and remove the []


Q:

Animated gif File In NSImageView eats the Memory (Mac Development)

I just try to put Animated gif file with 6 frames acquired from url Request and create nsimage with the response ,,, then set the Image in NSImageView ...
I use this
// Where returnedImage is nsImage I created with response of the connection ..
    [myImageView setImage:[response returnedImage]];

I use this code to change the Image displayed when some user actions happen
I observe that The memory allocated to the program is increased linearly with large scale .. and the application might crash
I make sure that my code has no leaks ...
I do not Know why it is increases , do I have to release the previous Image that was set
Any Idea will be appreciated.

A:

I delete and recreate the NSImageView In the Nib File ... I may be an xcode Deployment bug or something ,,, But i was allocate some memory to graphics card continuously increasing


Q:

Making text bold with django

I have to send make some text bold in between plain text and send it to the template from the view. I do this:
I save a string like this TextPlaintext in a variable and return it to the template.
The "" tags are not interpreted.
How can make some text bold in a django view?

A:

Django automatically escapes string values in templates, to improve security.
If you know that a value has HTML in it, and is trusted, then you can turn off escaping:
{{my_trusted_html|safe}}

A:

Making a text bold shouldn't be done in the view. Indeed, the view should not take care of formatting (which is the role of templates). What you can do however, is adding an extra variable to the rendering context, and depending on its value, make the text bold or not in the template.
For example :
In the view :
#...
is_important = True if something else False
extra_context.update({'is_important': is_important})
#...

In the template :
...
{% if is_important %}{{ text_to_render }}{% else %}{{ text_to_render }}{% endif %}
...

But more generally, deciding if a text is bold or not, is not even formatting, rather styling and should not be made in the template (so you shouldn't use the <bold> markup). So I would suggest :
...

{{ text_to_render }}

...

And a stylesheet :
.is-important{
    font-weight: bold;
}


Q:

Easy way to get NUMBERFMT populated with defaults?

I'm using the Windows API GetNumberFormatEx to format some numbers for display with the appropriate localization choices for the current user (e.g., to make sure they have the right separators in the right places).  This is trivial when you want exactly the user default.
But in some cases I sometimes have to override the number of digits after the radix separator.  That requires providing a NUMBERFMT structure.  What I'd like to do is to call an API that returns the NUMBERFMT populated with the appropriate defaults for the user, and then override just the fields I need to change.  But there doesn't seem to be an API to get the defaults.
Currently, I'm calling GetLocaleInfoEx over and over and then translating that data into the form NUMBERFMT requires.
NUMBERFMT fmt = {0};
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT,
                  LOCALE_IDIGITS | LOCALE_RETURN_NUMBER,
                  reinterpret_cast<LPWSTR>(&fmt.NumDigits),
                  sizeof(fmt.NumDigits)/sizeof(WCHAR));
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT,
                  LOCALE_ILZERO | LOCALE_RETURN_NUMBER,
                  reinterpret_cast<LPWSTR>(&fmt.LeadingZero),
                  sizeof(fmt.LeadingZero)/sizeof(WCHAR));
WCHAR szGrouping[32] = L"";
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SGROUPING, szGrouping,
                  ARRAYSIZE(szGrouping));
if (::lstrcmp(szGrouping, L"3;0") == 0 ||
    ::lstrcmp(szGrouping, L"3") == 0
) {
    fmt.Grouping = 3;
} else if (::lstrcmp(szGrouping, L"3;2;0") == 0) {
    fmt.Grouping = 32;
} else {
    assert(false);  // unexpected grouping string
}
WCHAR szDecimal[16] = L"";
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SDECIMAL, szDecimal,
                  ARRAYSIZE(szDecimal));
fmt.lpDecimalSep = szDecimal;
WCHAR szThousand[16] = L"";
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_STHOUSAND, szThousand,
                  ARRAYSIZE(szThousand));
fmt.lpThousandSep = szThousand;
::GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT,
                  LOCALE_INEGNUMBER | LOCALE_RETURN_NUMBER,
                  reinterpret_cast<LPWSTR>(&fmt.NegativeOrder),
                  sizeof(fmt.NegativeOrder)/sizeof(WCHAR));

Isn't there an API that already does this?

A:

I just wrote some code to do this last week.  Alas, there does not seem to be a GetDefaultNumberFormat(LCID lcid, NUMBERFMT* fmt) function; you will have to write it yourself as you've already started.  On a side note, the grouping string has a well-defined format that can be easily parsed; your current code is wrong for "3" (should be 30) and obviously will fail on more exotic groupings (though this is probably not much of a concern, really).


Q:

Remove pages from Pages

I have decided to turn my two page document in Pages to just one page. I cannot seem to delete the second page. It is the flyer template.

A:

If you delete everything on the second page, the second page should disappear. Maybe the template needs to be removed or there are spaces on page 2 that you don't see.
To avoid a lot of guesswork, the function "View -> Show invisibles" should make obvious what is on the page:

Invisible characters will then show on the page:


Q:

Set a rep threshold for editing closed questions?

Reviewing proposed edits I've found this one:

I've rejected it as "no improvement whatsoever", but also the question seemed poor quality and I've opened that too. It's closed as too broad, so it shouldn't have been edited just to make it a bit more beautiful.
Should users with low reputation also restricted from editing closed questions (of course everybody should be able to edit his own question)?
Edit
I've just realized I've written "old questions" in the last sentence, I've thought "closed questions" as in the title (sorry from them who commented on my request for old questions!).
In addition to my first thoughts; I regularly check reopen votes, they're quite rare, generally done by the question's author, sometimes by somebody else, but I still think that substantially improving a closed question is a tough job if you aren't its author, and quite unlikely a new user will do it.

A:

I'm going to go out on a limb and say a restriction of this type would be a bad thing.
Keep on rejecting edits that aren't good edits, per editing guidelines, but not allowing new users to edit a question that is closed could lead to not allowing a user to edit a question that they found via search, but was abandoned the first time, leading to a collective didn't you SEARCH?!?!

A:

I whole-heartedly agree with Raystafarian's answer, but I have another point of view to add.
"Having low reputation" is not the same as "being new to Stack Exchange".
For instance, I have been using Stack Overflow for years, read tons of questions, and have read various variants (official or endorsed) "how to ask a good SO question" several times. And yet, only a couple of days ago I got above 15 reputation threshold, since almost every question I could potentially ask has already been asked before, the ones I could ask are so specific practically nobody cares, and every question I could potentially answer is either: asking about something completely esoteric and/or in technology I have hardly heard of, or answered within minutes by 10k+ users.
Sometimes, very rarely, I find I could contribute to discussion by placing a comment, but I have no way of doing this, and I have no way of gaining enough reputation.
(Plus there are things like 40-minute cooldown on posting until you have 125+ reputation.)
I love the idea of StackExchange, but it really makes me feel like a pariah sometimes.
Therefore, I am opposed to putting even more barriers to prevent low-rep users from proving themselves. Every edit should be judged on its own.


Q:

Why are aircraft windshields not unbreakable?

From a materials engineering standpoint, cockpit windshields,
  typically weighing between 25-40 pounds, depending on the type of
  windshield build, are typically constructed of several layers:
(1) A glass face-plate, roughly 1/10" thick;
(2) A Polyvinyl Butryal (PVB) layer, about 1/8" thick;
(3) A stretched acrylic layer, approximately 1" thick;
(4) An additional PVB layer, nearly 1/10" thick;
(5) An additional stretched acrylic layer, approximately 1" thick. Source

But even then, it is not unbreakable. We have had several cases of broken windshields, as mentioned in above source. Also, the co-pilot  in Varig Flight 254 crash was wounded from a tree, which struck his shoulder after crash landing.
So, why are aircraft windshields not made from unbreakable Glass Ceramics ?

A:

Windshields
In the US, aircraft windshields must conform to 14 CFR 25.775 - Windshields and windows

(b) Windshield panes directly in front of the pilots in the normal conduct of their duties, and the supporting structures for these panes, must withstand, without penetration, the impact of a four-pound bird when the velocity of the airplane (relative to the bird along the airplane's flight path) is equal to the value of V C, at sea level, selected under § 25.335(a).

So, windshields are not indestructible partly because they are not required to be.
I guess windshields are not required to be indestructible because bodies like the FAA probably take the view that when an aircraft impacts a massive object at high speed, say a large mountain at 500 MPH, it is of no consequence whether the windshield survives intact at the bottom of a large crater of tiny aircraft fragments. It serves little purpose to make the windshield substantially stronger than the surrounding airframe.
Glass-Ceramics
Glass Ceramics are not unbreakable. For example a glass-ceramic might have a bending strength of 340 MPa (Ref p9)


Q:

Implement WinForms using WPF?

This question is a result of a lunch-time conversation with a co-worker...I've read questions like WPF vs. Winforms...and I personally think that long term WPF is the way to go.  The problem/question is what to do in the meantime.
Yes, WPF certainly has its advantages; not being built on GDI/USER is one of them.  But at this point in time (i.e., late 2009; using VS2008 or perhaps even VS2005; Silverlight3 recently released and not yet widely adopted/deployed), WPF almost looks like it might be an "over engineered" solution.  While I'm sure that will change with time, it doesn't make things any easier today, nor for the immediate (say <36 mo) future.
And let's face it, WinForms is really simple and easy; especially for the many co-workers who are still "happily" using MFC.  Yes, it may be difficult to do slick animation, 3D graphics, gradients, etc.; but it's a very utilitarian solution that a lot of people (i.e., C++/MFC developers) readily understand today.
With that longish introduction--has anybody thought/tired/etc. about the idea of implementing (most of) WinForms using WPF (i.e., WinForms sans GDI/USER)?  I'm sure given things like Control.Handle, 100% re-implementation isn't possible.  But it certainly seems like many WinForms controls could be re-implemented using WPF "under the hood".  Or is this really border-line impossible?
By "re-implement", I envision removing assembly references to System.Windows.Forms replacing them with (say) Microsoft.Wpf.WinForms and then rebuilding my application.  After that I would expect to fix some (relatively small number of) compiler and/or runtime errors (say P/Invokes to Win32 APIs).
Something like this seems like a nice complement to Microsoft's various WinForms/WPF interop strategies such as WindowsFormsHost.  For example, developers could start to use/learn WPF in a much more incremental fashion.
Edit: While the various "why?" discussions are interesting, they don't answer the basic technical question: "yes., ..here's how....; or no, ...because...".

A:

Honestly, I think you could probably implement a layer to allow you to port most of WinForms to WPF, but you really shouldn't. Let me use an analogy - Moving from WinForms to WPF is like moving from an imperative language to an object oriented one (or from OO to pure functional). It's really hard, nothing seems to work right, solutions don't make sense, everything seems over-engineered, and then... you get it. You have a flash of insight, the light bulb goes on and you see a whole new world where tasks are easier to accomplish and easier to maintain (than in WinForms).
But first you have to grok it. It's really easy to keep coding in the WinForms style in WPF so you have to force yourself not to or you'll never take that next step. Force yourself to start from a clean slate, learn how to apply MVVM, take a look at Prism, build some really simple apps and then add to them to explore how to manage complexity the WPF way. You might implement WinForms in WPF but all you would ever have is people coding WinForms in WPF. You basically end up with the equivalent of (from the Imperative -> OO days) making every class a singleton with all static methods. You might be "using" WPF, but you (and/or your coworkers) will never grow past that stage.
From what I can glean from your situation I would recommend that you not try to switch to WPF unless you are writing a new application with a small team. If that does end up being the case then the small team can be a nucleus for change because once one person in your organization "gets it" they will teach others near them until the light bulbs start turning on all around over the place. That's what we've done in my current organization and looking back the progress everyone's made just in the last 6 months is staggering.

A:

First off, WPF isn't "over engineered". I would say it is just perfectly engineered, as it is an extremely complex endevor to implement a UI framework that supports rich composability, rich databinding, 2D and 3D in a single platform.
WPF has a slight learning curve, but it isn't very steep, and occurs in stages. Give yourself 2 days with it, and you will NEVER look back. WinForms is easy for easy things. WPF is easy for just about anything, and the capabilities you have via its extensive composability and databinding will put WinForms to shame for anything more complex than your most basic app.
As for WinForms controls being reimplemented...there is little need. A lot of the highly complex WinForms controls that are available from third parties are only required because of how difficult it is to customize the UI of any WinForms control. With WPF, enhancing any OOB control is easy, and nearly limitless.
I highly recommend WPF as the UI platform of choice, unless your target hardware is incapable of rendering WPF.

A:

I'm not really sure I understand your question - it is already possible to use WPF libraries in a Winforms like fashion (assemble everything in code with no XAML), and most of the common Winforms controls have their direct WPF analogs.
The real question is why would you want to? Many of the big challenges of developing Winform applications are easily solved with WPF databinding and templating techniques.
And I'm not even talking about fancy visual effects, which just take waaaaaaaay too much work in winforms, but simply something like visualizing a list of arbitrary items in a collection.
Furthermore, if you assemble everything in code Winforms style you don't get the design time editing support.


Q:

PHPUnit - Not seeing code coverage on simple function

I'm trying to troubleshoot an issue where in my test, my assert passes.. but neither my expects() passes, nor am I seeing coverage executing in the resulting code coverage generated html.
error: Method was expected to be called 1 times, actually called 0 times.
I'm starting with a very basic example (below). I must be missing something obvious with phpunit that I haven't wrapped my head around with yet, apparently. I double-checked that the function I'm trying to test is in fact a public function.
At this point, I would just like to be able to see some coverage executing in the generated code coverage html.
Any ideas are greatly appreciated.
public function returnVal()
{
  return 5;
}

public function test_returnVal()
{
    $testVal = 5;
    $controllerMock = $this->getMockBuilder('MyClass')
        ->setMethods(null)
        ->disableOriginalConstructor()
        ->getMock();

    $controllerMock->expects($this->any())
        ->method('testReturnVal')
        ->with($testVal);

    $testResult = $controllerMock->testReturnVal($testVal);
    $this->assertEquals($testResult, $testVal);
}

A:

You do not see any code coverage, as you never actually execute the returnVal() function.  Your test suite uses a Mock which does not call the original function, but it references a Mock function (testReturnVal) instead.
$controllerMock->expects($this->any())
    ->method('testReturnVal')
    ->with($testVal);

When testing, Mocks are handy for hiding external dependencies and keeping a known state.  However, for simply functions (add 2 numbers for instance) you can simply create the object and call the code.
For your situation, simply add an additional test into the test code:
public function test_RealReturnVal()
{
     $TestObject = new MyClass();
     $this->assertEquals(5, $TestObject->returnVal());
}

This new test will actually call your real code and execute the returnVal() call.  This will cause the code coverage to show these lines as executed.


Q:

React js Material-UI responsive table

I am building a web application in react js and I'm using the material-ui components library. I'm using the table component and it looks good on desktop but I want it to adjust and look good also on mobile browser. Is material-ui supports such thing? How can I do it? Example of the current situation:
PC\Mobile:

Source code:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
  },
  table: {
    minWidth: 700,
  },
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const data = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function SimpleTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>

        <TableHead>
          <TableRow>
            <TableCell>Dessert (100g serving)</TableCell>
            <TableCell numeric>Calories</TableCell>
            <TableCell numeric>Fat (g)</TableCell>
            <TableCell numeric>Carbs (g)</TableCell>
            <TableCell numeric>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(n => {
            return (
              <TableRow key={n.id}>
                <TableCell component="th" scope="row">
                  {n.name}
                </TableCell>
                <TableCell numeric>{n.calories}</TableCell>
                <TableCell numeric>{n.fat}</TableCell>
                <TableCell numeric>{n.carbs}</TableCell>
                <TableCell numeric>{n.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>

    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleTable);

A:

For Material-UI tables padding-right and padding-left of every table cell should be changed,
you can have code in Codesandbox
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const styles = theme => ({
  root: {
    display: 'flex',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'hide',
  },
  table: {
    minWidth: 340,
  },
  tableCell: {
    paddingRight: 4,
    paddingLeft: 5
  }
});

let id = 0;
function createData(name, calories, fat, carbs, protein) {
  id += 1;
  return { id, name, calories, fat, carbs, protein };
}

const data = [
  createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
  createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
  createData('Eclair', 262, 16.0, 24, 6.0),
  createData('Cupcake', 305, 3.7, 67, 4.3),
  createData('Gingerbread', 356, 16.0, 49, 3.9),
];

function SimpleTable(props) {
  const { classes } = props;

  return (
    <Paper className={classes.root}>

        <TableHead>
          <TableRow>
            <TableCell className={classes.tableCell}>Dessert (100g serving)</TableCell>
            <TableCell numeric className={classes.tableCell}>Calories</TableCell>
            <TableCell numeric className={classes.tableCell}>Fat (g)</TableCell>
            <TableCell numeric className={classes.tableCell}>Carbs (g)</TableCell>
            <TableCell numeric className={classes.tableCell}>Protein (g)</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(n => {
            return (
              <TableRow key={n.id}>
                <TableCell component="th" scope="row" className={classes.TableCell}>
                  {n.name}
                </TableCell>
                <TableCell numeric className={classes.tableCell}>{n.calories}</TableCell>
                <TableCell numeric className={classes.tableCell}>{n.fat}</TableCell>
                <TableCell numeric className={classes.tableCell}>{n.carbs}</TableCell>
                <TableCell numeric className={classes.tableCell}>{n.protein}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>

    </Paper>
  );
}

SimpleTable.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SimpleTable);

To make it responsive you need to use Grid system in the first place, For example this is grid system for full-page:
 <Grid item xs={12}>

  </Grid>


Q:

undefined local variable or method `number_to_delimited'

I'm using rails 4.2.5.
And in rails API (for v4.2.5.2) I see this helper:
number_to_delimited(number, options = {})

Formats a number with grouped thousands using delimiter (e.g., 12,324). You can customize the format in the options hash.

http://api.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_delimited
But when I using this help in my views, it throws an error:
undefined methodnumber_to_delimited' for #<#:0x0000000b091b30>`
Other helpers, such like number_to_currency， all works well. What's wrong with me?

A:

Try to call ActiveSupport::NumberHelper instead.
ActiveSupport::NumberHelper.number_to_delimited(12345678)
 => "12,345,678"

Or you could do also with this:
include ActiveSupport::NumberHelper
number_to_delimited(12345678)
 => "12,345,678"

UPDATE:
I see you said in comment above that you're using haml code and you can do it like:
= ActiveSupport::NumberHelper.number_to_delimited(12345678)

Or
- include ActiveSupport::NumberHelper
= number_to_delimited(12345678)


Q:

Run local Java Heroku

I'm going through the Heroku Getting Started for Java, but I'm having trouble running the example app locally.
https://devcenter.heroku.com/articles/getting-started-with-java#run-the-app-locally
https://devcenter.heroku.com/articles/getting-started-with-java#define-a-procfile
After I run it, I get the "starting web.1 on port 5000", but when I open localhost:5000, it just gives me "This webpage is not available."
Here is the output from CLI
$ heroku local web -f Procfile.windows
forego | starting web.1 on port 5000
web.1  | Usage: java [-options] class [args...]
web.1  | in the version search
web.1  |            show splash screen with specified image
web.1  |

Let me know if you need more information.
UPDATE:  So I actually ran the command on my own, when I realized, that's all that Procfile does, and the last line I get is
sh.exe": target\dependency\*: No such file or directory

When this is obviously is a target\dependency made from mvn clean install?
What am I typing wrong?
$ java -cp target\classes;"target\dependency\*" Main

A:

This has a lot to do with compatibility.
What I didn't mention, which had a lot to do with it, was that I was running this on GitBash.  So it was taking everything differently.
Ex.  I had to escape the semicolon for the cp argument.
Short story the Procfile.windows should be
web: java -cp target/classes\;target/dependency/* Main

no quotes anywhere...
I'm leaving this up in case anyone else has issues


Q:

Email body empty when select to send email by Gmail

I'm using this code:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",email, null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(emailIntent, "Send feedback to xyz"));

for 2 years. And until now everything worked fine. User can select message client and send feedback with prefilled data inside. It worked fine for all mail clients.
Recently noticed that if I select gmail client - body of message remains empty, but on other mail clients body is filled with text.
Any ideas?

A:

Thanks for help
Made tests with lots of suggested answers.
adding "text/plain" or "message/rfc822" made my app to stop offering mail clients.
Fount this answer that fixed my issue:
https://stackoverflow.com/a/59365539/973233
Most interesting part for me is having 2 intents:
Intent selectorIntent = new Intent(Intent.ACTION_SENDTO);
selectorIntent.setData(Uri.parse("mailto:"));
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, text);
emailIntent.setSelector( selectorIntent );
activity.startActivity(Intent.createChooser(emailIntent, "Send feedback to XYZ"));

This solved problem.


Q:

How to add a package declaration to java generated by SWIG

I'm using SWIG to generate a bunch of Java files -- I want the files to be part of a certain package ... right now after I generate them I have to go in and manually add the import declaration ... is there a way to template this into swig?

A:

Just need to specify the package as follows
mkdir -p com/example/package
swig -java -package com.example.package -outdir com/example/package example.i


Q:

creating a counter cell and static cells in excel

Problem:

I have a counter cell:  A1 with a value of =COUNTIF(B:B;"FOO")

This gives me a current "count" of all instances of "FOO" in column B.

I have a value cell C1 with a formula of:  =IF(B1="FOO";"FOO_" & A1;)

This gives me a result of FOO_1 if "FOO" only exists once in Column B

Question:

I want to be able to reference the value of A1 at the time I write out the contents to the cell of C1.  When A1 updates, I do not want C1 to be modified.  C2 should now take the update of A1 (which would now be 2) and C2 would be:  FOO_2 for example:

A1 = 1
B1 = FOO
C1 = FOO_1
A1 = 2
B2 = FOO
C2 = FOO_2
C1 still remains FOO_1 based on the value of A1 before a new row was added to column B
Looking for an automated way to create an ID, like an increment value in MySQL, and not looking for a solution that involves a person copy / pasting..

A:

The problem with your approach is that, A1 will always change to reflect the COUNT, you can't use a value that WAS. What else is going into the remaining cells in Column A that you could not use the Count in the adjacent row as @JMax suggests?
If you have to increment with fixed Counts, I would recommend you think of a simple macro on a change event of whichever cell you are wanting. For instance everytime you enter "FOO" or "BAR" or anything, it would do a COUNTIF of the Range in B:B and concatenate the result entering it in the adjacent C.
No reason to depend upon A1 at all, and it possibly changing.
This example may get you started. And the Countif may use a ';' for your version of Excel
It assumes you are doing data entry and then moving to the next cell down. It also checks whether you have already made an entry in the adjacent cell in C so it does not change the count if you revisit a cell.
Which means it will be wrong in that adjacent cell unless you delete the value in C first before making a change. Of Course If you have 4 FOOs and then delete one you will still have FOO_4 and it won't change so if you change the 4th FOO to BAR first delete FOO_4. If the Increment HAS to match actual counts for some other reason, I would not rely upon this for that.
Sub doIncrement()
 If ActiveCell.Column = 2 And ActiveCell.Offset(-1, 1) = "" Then
 ActiveCell.Offset(-1, 1) = ActiveCell.Offset(-1, 0) & "_" & WorksheetFunction.CountIf(Range("B:B"), (ActiveCell.Offset(-1, 0)))
 Else: Exit Sub 'or do something else
 End If
End Sub

Then call this in
Private Sub Worksheet_Change(ByVal Target As Range)
 Call doIncrement
End Sub


Q:

ParseInt crashes on longer numbers

After a few weeks i finally found out how to parse my numbers through my app. But now the app crashes when given a number in the following format: 92839283982938 or 22.483.84.3883.
I just dont know how to make it accept those number formats. The problem is connected to a barcode scanner, so i really need it to accept those number formats.
The code i used to parse is:
JSONObject c = user.getJSONObject(Integer.parseInt(xyz)-1);

A:

For longer number you should use Long.parseLong() instead of Integer.parseInt().
Next case 22.483.84.3883 not a numeric. You will get NumberFormatException from here.
You can use
try{
   long val=Long.parseLong("xxxx")
}catch(NumberFormatException e){
   // exception
}

If you want to consider 22.483.84.3883 or 22-483-84-3883 as a valid case, you need to replace . or - first.
Eg:
 long val=Long.parseLong("22.483.84.3883".replaceAll("\\.", ""));
 System.out.println(val);


Q:

What is the point of having Geo-redundant recovery service vault with/without Cross region restore?

There are two back up configuration options for Azure Recovery Service Vault - LRS vs GRS
This is a question regarding Azure Recovery Service Vault.
How does geo-redundant enabled recovery service vault being handled when its residing region failed ?
If the cross region restore is not being enabled for a recovery service, which by default it isn't, what will happen to my recovery service vault ?
I am trying to find out the difference between enabling cross region restore and not to.
There is not much info that i can find through the internet and official documents.
Configure cross region restore for recovery service vault
There is one more helpful link GRS vs LRS. However, as of time writing, seems like cross region restore has not been enabled, and right now, it is on enabled in west central us. However, we can enable GRS for all(most) regions.

A:

The Recovery Services vault is an entity that stores the backups and recovery points created over time. Azure Backup automatically handles storage for the vault. The LRS and GRS mean to the Storage Replication type. Read the storage replication strategy.

Locally redundant storage (LRS) replicates your data three times
within a single data center.
GRS replicates your data to another data
center in a secondary region, but that data is available to be read
only if Microsoft initiates a failover from the primary to secondary
region.

Storage Replication type by default is set to Geo-redundant. The CRR feature is based on A vault created with GRS redundancy. So you can enable GRS for all(most) regions but CRR is currently available in the WCUS region. Read here.
As the GRS storage replication, If the primary region that geo-redundant enabled recovery service vault residing on failed, Microsoft initiates a failover from the primary to a secondary region. The secondary region serves as a redundant source for your data.
With CRR enabled service, The restore operation on the secondary region can be performed by Backup Admins and App admins. Which gives you full control to restore data to a secondary region. The secondary region is an Azure paired region.
Without CRR enabled service, you probably could not restore all the Azure VMs for the selected recovery point if the backup is done in the secondary region. You can create a new VM from a restore point, restores a VM disk, replace a disk on the existing VM. See the restore options.
Hope this could help you.


Q:

How to show that the Billiard flow is invariant with respect to the area form $\sin(\alpha)d\alpha\wedge dt$

Consider a plane billiard table $D \subset \mathbb{R}^2$ (i.e. a bounded open connected set) with smooth boundary $\gamma$ being a closed curve. Next, let $M$ denote the space of tangent unit vectors $(x,v)$ with $x$ on $\gamma$ and $v$ being a unit vector pointing inwards. We then define the billiard map
$$
T : M \to M.
$$
To understand the map $T$, we consider a point mass traveling from $x$ in direction $v$. Let $x_1$ be the first point on $\gamma$ that this point mass intersects and suppose that $v_1$ is the new direction of the mass upon incidence. Then $T$ maps $(x,v)$ to $(x_1, v_1)$.
We now introduce an alternate ''coordinate system'' describing $M$. Parametrize $\gamma$ by arc-length $t$ and fix a point $(x,v) \in M$. We can find $t$ such that $x = \gamma(t)$ and let $\alpha \in (0, \pi)$ be the angle between the tangent line at $x$ and $v$. The tuple $(t, \alpha)$ uniquely determines the point $(x,v)$ in $M$, and thus offers and alternative description of this space.

My question is as follows: I want to show that the area form given by
$$
\omega := \sin{\alpha}\,\mathrm{d}\alpha \wedge \mathrm{d}t
$$
is invariant under $T$.

I found a proof of this invariance property proof in S. Tabachnikov's Geometry and billiards but I'm having some trouble understanding a critical part of the proof.
If anyone can explain the proof to me (or provide me with another proof) I would highly appreciate it. An intuitive explanation is also appreciated, but I am looking for a rigorous proof if possible. We restate this theorem formally below and provide the proof as given by Tabachnikov.
Theorem 3.1. The area form $ω = \sin α \,dα \wedge dt$ is $T$-invariant.
Proof. Define $f(t, t_1)$ to be the distance between $\gamma(t)$ and $\gamma(t_1)$. The partial derivative $\frac{\partial f}{\partial{t_1}}$ is the projection of the gradient of the distance $\left\vert{\gamma(t)\gamma(t_1)}\right\vert$ on the curve at point $\gamma(t_1)$. This gradient is the unit vector from $\gamma(t)$ to $\gamma(t_1)$ and it makes angle $\alpha_1$ with the curve; hence $\partial f/\partial t_1 = \cos{\alpha_1}$. Likewise, $\partial f/\partial t = -\cos{\alpha}$. Therefore,
$$
  \mathrm{d}f = \frac{\partial f}{\partial t} \mathrm{d}t + \frac{\partial f}{\partial t_1}\mathrm{d}t_1
= -\cos{\alpha}\,\mathrm{d}t + \cos{\alpha_1}\,\mathrm{d}t_1
$$
and hence
$$
0 = \mathrm{d}^2f = \sin{\alpha}\mathrm{d}\alpha \wedge \mathrm{d}t - \sin{\alpha_1} \mathrm{d}\alpha_1 \wedge \mathrm{d}t_1.
$$
This means that $\omega$ is a $T$-invariant form.
The above proof is copied directly from the book. I have the following questions about his method:

Is the domain of $f$ the set $M\times M$?
In the proof, are we specifically considering $(t, \alpha)$ and $(t_1, \alpha_1)$ such that $T (t, \alpha) =(t_1,\alpha_1)$?
I am having a hard time understanding how the author obtains $\partial f/\partial t_1 = \cos{\alpha_1}$ and $\partial f/\partial t = -\cos{\alpha}$. The explanation given feels mostly heuristic, how could I go about constructing a rigorous proof?

A:

As you explain in your question, the set $M$ consists of points $(x,v)$, where $x$ is a point of $\partial D$ and $v$ is an inward pointing unit vector. Now you chose to parametrize the set of points in $M$ differently: If $\gamma:[0,\ell)\to\partial D$ is the parametrization of $\partial D$, this gives rise to a map $f:[0,\ell)\times[0,\ell)\to (0,\infty)$, where actually $f$ is bounded by $\operatorname{diam}(D)$. I hope this helps for the first question. For the third question: Since $f$ is defined to be the distance between $\gamma(t)$ and $\gamma(t_1)$ you may write
$$
f(t,t_1)=|\gamma(t_1)-\gamma(t)|.
$$
In this way you can compute
$$
\partial_{t_1}f(t,t_1) = \frac{\langle \gamma(t_1)-\gamma(t),\dot\gamma(t_1)\rangle}{|\gamma(t_1)-\gamma(t)|}.
$$
Since $\gamma$ is a unit speed curve, you can write
$$
\partial_{t_1}f(t,t_1) =\frac{\langle \gamma(t_1)-\gamma(t),\dot\gamma(t_1)\rangle}{|\gamma(t_1)-\gamma(t)||\dot\gamma(t_1)|}=\cos\left(\sphericalangle(\gamma(t_1)-\gamma(t),\dot\gamma(t_1))\right).
$$
According to your definition, the angle
$$
\sphericalangle(\gamma(t_1)-\gamma(t),\dot\gamma(t_1))=\alpha_1.
$$
Finally, for the second question, the answer is yes.


Q:

How to get GAL from outlook on the web

Is there any way to pull data from something like a GAL(global address list) in outlook on the web?
An example would be to be able to search for a contact and then taking their data from the server to be stored to local variables.
Only Use the [outlook.office.com] website
it going to run in node.js
Is there any other way to use create new app registrations in the Azure Management Portal?

A:

You will have to use Exchange Web Services to search the GAL, as I don't think the People REST API can search it:
FindPeople operation:
https://msdn.microsoft.com/en-us/library/office/jj191039(v=exchg.150).aspx


Q:

Evaluating big-O vs big-Omega for two functions

We were tasked with comparing the complexities of two functions: $n$ and $n^{0.99} (\log(n))^2$.
As I understand it, the general construct of these equations is $\lim_{x \rightarrow \infty} \frac{f(n)}{g(n)}$. If the limit evaluates to 0, we have $f \in O(g)$. If the limit evaluates to infinity, $f \in \Omega(g)$. If it evaluates to a constant, then $f \in \Theta(g)$.
If we plot the quotient of these two functions, then we clearly see that the result approaches 0:
Wolfram Alpha Plot
However, if we plug the limit into Wolfram Alpha, we get
$\lim_{x \rightarrow \infty} \frac{x}{x^{0.99} (\log(x))^2} = \infty$
These two results seem to be contradictory. Interestingly enough, if we ask for $\lim_{x \rightarrow \infty} \frac{d}{dx}\frac{x}{x^{0.99} (\log(x))^2}$, Wolfram Alpha gives 0. I don't think it's possible for a limit to be infinity and the derivative's limit to be 0...
I must be missing something, but I can't figure out what. Any ideas?
Edit: Got it, graphs are useless in this scenario. However, suppose I had to do this calculation manually. How would I go about evaluating the limit?

A:

Two further points.
First, your definition of big-O notation is not quite right.

If the limit $\lim_{n \to \infty} \frac{f(n)}{g(n)}$ evaluates to $0$, then $f \in o(g)$; we have $f \in O(g)$ if the limit is either $0$ or a constant. In other words, $O(g) = o(g) \cup \Theta(g)$. Similarly, we write $f \in \omega(g)$ when the limit is $\infty$ and $\Omega(g) = \Theta(g) \cup \omega(g)$. A function in $\Theta(g)$ is in both $O(g)$ and $\Omega(g)$, but isn't in $o(g)$ or $\omega(g)$.
Technically, we can also have $f \in \Theta(g)$ if the limit $\frac{f(n)}{g(n)}$ as $n \to \infty$ doesn't exist because of oscillation, but the ratio is still bounded for all sufficiently large $n$. For example, we want $1 + \frac12 \sin n$ to be $\Theta(1)$, though the limit doesn't exist here. But this doesn't usually come up much.

Second, to answer your question of how we'd figure this out.
First, we should simplify as much as possible. Comparing $n$ to $n^{0.99} (\log n)^2$ can be reduced to comparing $n^{0.01}$ to $(\log n)^2$, which can in turn be reduced to comparing $n^{0.005}$ to $\log n$.
In practice, you just learn the asymptotic comparisons between common functions. One of them is that $\log n \in o(n^\alpha)$ for any $\alpha > 0$, which answers this question. But if we wanted to understand the comparison above better, we could also substitute $n = k^{200}$, which gives us the comparison $(k^{200})^{0.005} = k$ vs. $\log (k^{200}) = 200\log k$. This comparison goes the same way as $k$ vs. $\log k$, which is hopefully more clear-cut.


Q:

jQuery $.address() plugin: hashbang links colliding with HTML5 state support

Here's a scenario that describes the problem:
User A has a browser with HTML5 state support, and sends this link to User B:
http://domain.tld/node
User B, who uses a browser without HTML 5 state support, navigates to another node, and sends the link back to User A:
http://domain.tld/node#!/another-node
But when User A clicks the link, the content for /node is shown instead of /another-node.
Querying Asual's jQuery $.address() plugin shows that it is interpreting the "hashbang address" as the hash value:
> $.address.value()
  "/node#/another-node"
> $.address.path()
  "/node"
> $.address.hash()
  "/another-node"

(Curiously the "!" is dropped from the hashbang.)
Can this ambiguity be overcome with a change in my implementation?
I could disable support for the history API if a hashbang is found in the URI, but I'd rather not.

A:

I was able to solve this issue by changing my implementation a bit.
Basically, I determine what the address should be based on the browser's capabilities, check that against what the address actually is, and if it doesn't match, use location.replace() to replace the address without creating a new history entry.
var addressValue = $.address.value(),
    initPath = window.location.pathname.replace(stateBasePath, ""),
    newLocation = baseUrl +stateBasePath + (supports_history_api() ? "" : "/#!") + (addressValue != "/" ? addressValue : initPath + window.location.search);
if (newLocation != window.location.href) {
    window.location.replace(newLocation);
}

This code should be executed as soon as possible – outside of a DOM ready function.

stateBasePath is equivalent to the value you would use for $.address.state() (just an empty string if the site is located at the document root)
baseUrl is the URI protocol and domain, e.g. http://domain.tld (no trailing slash)
supports_history_api() is a little ditty taken from Mark Pilgrim


Q:

Tilda: no contrast between active and inactive tabs

This topic is very close to what was suggested in Gnome-terminal tabs: no contrast between active and inactive tabs.
I'm using Ubuntu 14.04 and although the gtk.css configuration works fine with default gnome terminal, it does not apply to my tilda terminal.
Does anyone know how to get the same effect on tilda ?

A:

You could use following configuration placed in ~/.config/tilda/style.css file:
GtkWindow#Main {
    #background-color: rgba(0, 0, 0, 0);
    background-color: #000000;
}

GtkWindow#Main .notebook {
    padding: 0px;
}

GtkWindow#Main .notebook tab GtkLabel {
    padding-left: 15px;
    padding-right: 15px;
    color: #505050;
}

GtkWindow#Main .notebook tab {
    background-color: #101010;
}

GtkWindow#Main .notebook tab:active {
    #background-color: rgba(0, 0, 0, 0.85);
    background-color: #181818;
}


Q:

Android: How can I get the file size of a FTP file via FTPClient?

How can I read the file size of a file that is stored on my ftp server?
I don't like to implement another libary.
I am working with commons-io-2.4 and commons-net-3.1
Answer and code from talhakosen (thanks!)
private long getFileSize(FTPClient ftp, String filePath) throws Exception {
    long fileSize = 0;
    FTPFile[] files = ftp.listFiles(filePath);
    if (files.length == 1 && files[0].isFile()) {
        fileSize = files[0].getSize();
    }
    Log.i(TAG, "File size = " + fileSize);
    return fileSize;
}

A:

Hi you can use the code below,
private void ftpDownload() {
    FTPClient ftp = null;
    try {
        ftp = new FTPClient();
        ftp.connect(mServer);

        try {
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new Exception("Connect failed: " + ftp.getReplyString());
            }
            if (!ftp.login(mUser, mPassword)) {
                throw new Exception("Login failed: " + ftp.getReplyString());
            }
            try {
                ftp.enterLocalPassiveMode();
                if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
                    Log.e(TAG, "Setting binary file type failed.");
                }
                transferFile(ftp);
            } catch(Exception e) {
                handleThrowable(e);
            } finally {
                if (!ftp.logout()) {
                    Log.e(TAG, "Logout failed.");
                }
            }
        } catch(Exception e) {
            handleThrowable(e);
        } finally {
            ftp.disconnect();
        }
    } catch(Exception e) {
        handleThrowable(e);
    }
}

private void transferFile(FTPClient ftp) throws Exception {
    long fileSize = getFileSize(ftp, mFilePath);
    InputStream is = retrieveFileStream(ftp, mFilePath);
    downloadFile(is, buffer, fileSize);
    is.close();

    if (!ftp.completePendingCommand()) {
        throw new Exception("Pending command failed: " + ftp.getReplyString());
    }
}

private InputStream retrieveFileStream(FTPClient ftp, String filePath)
throws Exception {
    InputStream is = ftp.retrieveFileStream(filePath);
    int reply = ftp.getReplyCode();
    if (is == null
            || (!FTPReply.isPositivePreliminary(reply)
                    && !FTPReply.isPositiveCompletion(reply))) {
        throw new Exception(ftp.getReplyString());
    }
    return is;
}

private byte[] downloadFile(InputStream is, long fileSize)
throws Exception {
    byte[] buffer = new byte[fileSize];
    if (is.read(buffer, 0, buffer.length)) == -1) {
        return null;
    }
    return buffer; // <-- Here is your file's contents !!!
}

private long getFileSize(FTPClient ftp, String filePath) throws Exception {
    long fileSize = 0;
    FTPFile[] files = ftp.listFiles(filePath);
    if (files.length == 1 && files[0].isFile()) {
        fileSize = files[0].getSize();
    }
    Log.i(TAG, "File size = " + fileSize);
    return fileSize;
}


Q:

ng2-modal's Modal is closing unexpectedly

I have used ng2-modal for my modal.
When I call the following function I have created:
deleteCommitee(id:number){
  var length = this.addnewCommitee.length;
  for(var i = 0;i<length;i++){
    if(id == i){
     this.addnewCommitee.splice(i,i);
    }
  }
}

the modal disappears. I have replicated the situation in plunker.
In the plunker example please click the button to trigger the modal open and then click on cross button below 'email id 0' input field
Actually through this function I want to remove an element from addNewCommittee array.

A:

You are missing event.stopPropagation() to prevent the click from propagating through the DOM.
Updated plunker
deleteCommitee
deleteCommitee(id:number,event:any){
    //event.preventDefault();
    event.stopPropagation();
    for(var i = 0;i<this.addnewCommitee.length;i++){
      console.log(this.addnewCommitee[i]);
      if(id == this.addnewCommitee[i].count){
        //console.log(this.addnewCommitee[i]);
        console.log(this.addnewCommitee.splice(i,1));
      }
    }
  }

HTML
 <div class="close_icon_div cursor_pointer" (click)="deleteCommitee(newCommitee.count,$event)" >


Q:

Help with event signup module

I'm looking for a module that allows registered users to signup to events with a few options. I found the "Signup Module" but I can't figure out how to make it work, at least to try it out. So two questions:

Does the Signup Module allow for getting different input depending on the event type? For example, if an event is a dinner, I would need to get the menu choice and any dietary requirements.
If the above is a yes, how can I make it work? I can't find much documentation around and I'm still a Drupal newbie. If the above is no, can you please recommend a more adeguate module?

Thanks in advance for any hints!

A:

I think you can use the Signup Module for this. The Signup form itself can be modified and changed for your needs. Have a look at the file signup_form.inc in the signup/theme folder. Copy the theme_signup_user_form($variables) function to your template.php in your theme and start modifying the form.


Q:

Why isn't this displaying my info for mysql table?

Isn't displaying any information. Getting errors and i'm really not sure why?
Thanks.
    <?php

    $mysqli = new mysqli("localhost", "root", "", "insuredcars");
     if ($_POST['formcar'] == '1' || $_POST['formage'] == '18' ||  $_POST['formNCD'] ==          '0' || $_POST['formPoints'] == '0' )
    $query = $mysqli->query("SELECT * FROM insurance WHERE insuranceid = '1'");
while($row = mysql_fetch_array($result))
 {
 echo "
";
 echo "" . $row['insuranceprice'] . "	";
 echo "
";
  }
 echo "
";

 mysql_close($con);

 ?>

The errors im getting:
Notice: Undefined variable: result in C: on line 8
Warning: mysql_fetch_row() expects parameter 1 to be resource, null given in C:\xampp\htdocs\search.php on line 8
Notice: Undefined variable: con in C: on line 16
Warning: mysql_close() expects parameter 1 to be resource, null given in C: on line 16

A:

mysqli_fetch_row fetches just one row as the function name says.
$mysqli = new mysqli("localhost", "root", "", "insuredcars");
if ($_POST['formcar'] == '1' || $_POST['formage'] == '18' || $_POST['formNCD'] == '0' || $_POST['formPoints'] == '0') {
    $query = $mysqli->query("SELECT * FROM insurance WHERE insuranceid = '1'");
    while ($row = mysqli_fetch_assoc($query)) {
        echo "
";
        echo "" . $row['insuranceprice'] . "	";
        echo "
";
    }
    echo "
";
}

mysql_close($con);


Q:

Different output between compilers

I am doing the first problem on Project Euler.
I have the following code:
#include <stdio.h>

int main() {
    int number;
    int sum;
    while (number < 1000) {
        if (number % 3 == 0 || number % 5 == 0) {
            sum += number;
            number++;
        }
        else {
            number++;
        }
    }
    printf("The answer is %d", sum);
    return 0;
}

When I compile this via compileonline.com, I get 233168. When I compile this in gcc I get 2686824. What causes this difference?

A:

Compileonline probably initializes the variables.
You have to initialize them manually.
#include <stdio.h>

int main() {
    int number = 0;
    int sum = 0;
    while (number < 1000) {
        if (number % 3 == 0 || number % 5 == 0) {
            sum += number;
            number++;
        }
        else {
            number++;
        }
    }
    printf("The answer is %d", sum);
    return 0;
}


Q:

Ветвления if и мой пример

друзья! Дали задание сделать ветвления в Java, так вот хотел бы спросить правильно ли сделан мой код или нет:
public static void main(String[] args) {
    int age = 13;
    if (age == 25) {
        if (age == 33) {
            if (age == 50) {
                System.out.println("Igor");
            }
        }
    } else {
        System.out.println("Error");
    }
}

A:

"Цикл" сделан неправильно. Замените его на гораздо более простой код:
    if (age != 25) {
        System.out.println("Error");
    }


Q:

Get spiderable: phantomjs failed because of permission denied

I bundled my application and put it onto my server. I am running the app via upstart:
exec sudo -u myuser PORT=3005 MONGO_URL=mongodb://localhost:27017/ms ROOT_URL=http://www.example.com/ /usr/bin/node /var/www/priv/example.com/bundle/main.js >> $

The important part (i think) is:
exec sudo -u myuser

When i curl my app via:
curl http://www.example.com/?_escaped_fragment_=

I get an empty body. My log file says:
spiderable: phantomjs failed: { [Error: Command failed: /bin/bash: /root/.bashrc: Permission denied
Can't open '/dev/stdin'
] killed: false, code: 255, signal: null }
stderr: /bin/bash: /root/.bashrc: Permission denied
Can't open '/dev/stdin'

I did chmod 777 on /root/.bashrc but without any success. If i do /bin/bash /root/.bashrc as 'myuser' i also get permission denied.
Could any one tell me how to set the permissions so that phantomjs can do what it has to do? Can i specify that ~/.bashrc is used anywhere? I would really love to see my stuff on google :-)
Thanks alot!
Manuel
Updates:
I have phantom.js 1.8.2 installed via npm.
Running the application as root does not help. Error then is:
spiderable: phantomjs failed: { [Error: Command failed: Can't open '/dev/stdin' ] killed: false, code: 255, signal: null } stderr: Can't open '/dev/stdin'

I found out, that it seems to be a package that causes the problem. I opened an issu here:
github.com/alanning/meteor-roles/issues/3

A:

Alanning fixed the problem but spiderable still did not work. The solution was to remove phantomjs because i installed it via npm. I then reinstalled it from http://phantomjs.org/download.html directly. Now it is working!


Q:

Why is my WinPE 4 image growing and growing after every commit?

I am currently building a WinPE 4 ISO and I am wondering why the ISO file keeps growing after every commit and iso build. All i am changing is some lines of powershell code, which for sure are not as long as 1 MB.
name: winpe4_v16.iso size: 305'131'520 bytes
name: winpe4_v17.iso size: 306'417'664 bytes
name: winpe4_v18.iso size: 307'703'808 bytes

A:

I have noticed this too. When I'm done with any particular set of updates, I export the image to a new one. The less memory used on a PXE boot, the better.
When you modify an image, DISM stores additional resource files that increase the overall size of the image. Exporting the image will remove unnecessary resource files.
http://technet.microsoft.com/en-us/library/hh825258.aspx


Q:

Mercurial push --new-branch. abort: authorization failed

I have the same problem as Mercurial push, abort: authorization failed however I do not have control over any permissions. I am able to access the repository from a web browser and hg outgoing is successful. I have also tried resetting my password with no change.
The command:
$ hg push --new-branch --debug --traceback -f > pushlog.log
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 87, in _runcatch
  return _dispatch(req)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 684, in _dispatch
  cmdpats, cmdoptions)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 466, in runcommand
  ret = _runcommand(ui, options, cmd, d)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 738, in _runcommand
  return checkargs()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 692, in checkargs
  return cmdfunc()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 681, in <lambda>
  d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/usr/lib/python2.7/dist-packages/mercurial/util.py", line 458, in check
  return func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/mercurial/commands.py", line 4333, in push
  if not c.sub(s).push(opts.get('force')):
File "/usr/lib/python2.7/dist-packages/mercurial/subrepo.py", line 524, in push
  return self._repo.push(other, force)
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 1535, in push
  ret = remote.unbundle(cg, remote_heads, 'push')
File "/usr/lib/python2.7/dist-packages/mercurial/wireproto.py", line 300, in unbundle
  ret, output = self._callpush("unbundle", cg, heads=heads)
File "/usr/lib/python2.7/dist-packages/mercurial/httprepo.py", line 199, in _callpush
  r = self._call(cmd, data=fp, headers=headers, **args)
File "/usr/lib/python2.7/dist-packages/mercurial/httprepo.py", line 169, in _call
  fp = self._callstream(cmd, **args)
File "/usr/lib/python2.7/dist-packages/mercurial/httprepo.py", line 120, in _callstream
  raise util.Abort(_('authorization failed'))
Abort: authorization failed
abort: authorization failed

The log:
pushing to https://host/hg/myProject
using https://host/hg/myProject
sending capabilities command
using auth.TR.* for authentication
host certificate matched fingerprint

f4:57:8a:83:46:9a:d1:eb:7a:c6:58:ac:dd:ea:ed:36:42:ee:2c:56
using auth.TR.* for authentication
http auth: user wilson.droter, password ********
using auth.TR.* for authentication
host certificate matched fingerprint f4:57:8a:83:46:9a:d1:eb:7a:c6:58:ac:dd:ea:ed:36:42:ee:2c:56
pushing subrepo subProject to http://host/hg/subProject
using http://host/hg/subProject
sending capabilities command
using auth.TR.* for authentication
host certificate matched fingerprint f4:57:8a:83:46:9a:d1:eb:7a:c6:58:ac:dd:ea:ed:36:42:ee:2c:56
using auth.TR.* for authentication
http auth: user wilson.droter, password ********
using auth.TR.* for authentication
mercurial.int.thomsonreuters.com certificate matched fingerprint f4:57:8a:83:46:9a:d1:eb:7a:c6:58:ac:dd:ea:ed:36:42:ee:2c:56
query 1; heads
sending batch command
using auth.TR.* for authentication
http auth: user wilson.droter, password ********
using auth.TR.* for authentication
host certificate matched fingerprint f4:57:8a:83:46:9a:d1:eb:7a:c6:58:ac:dd:ea:ed:36:42:ee:2c:56
searching for changes
all remote heads known locally
2 changesets found
list of changesets:
877b46d2cc15a8d0a5ea3a6879a5eea14af87c0f
52cabd379e04b56af0d44ba3d3673764d6de9b9e
bundling: 1/2 changesets (50.00%)
bundling: 2/2 changesets (100.00%)
bundling: 1/2 manifests (50.00%)
bundling: 2/2 manifests (100.00%)
bundling: py_util/hadoop/hadoop.conf 1/50 files (2.00%)
bundling: py_util/hadoop/hadoop_archive.log 2/50 files (4.00%)
bundling: py_util/hadoop/lib/antlr-runtime-3.2.jar 3/50 files (6.00%)
bundling: py_util/hadoop/lib/asm-3.2.jar 4/50 files (8.00%)
bundling: py_util/hadoop/lib/avro-1.7.1.cloudera.2.jar 5/50 files (10.00%)
bundling: py_util/hadoop/lib/commons-beanutils-1.7.0.jar 6/50 files (12.00%)
bundling: py_util/hadoop/lib/commons-beanutils-core-1.8.0.jar 7/50 files (14.00%)
bundling: py_util/hadoop/lib/commons-cli-1.2.jar 8/50 files (16.00%)
bundling: py_util/hadoop/lib/commons-codec-1.4.jar 9/50 files (18.00%)
bundling: py_util/hadoop/lib/commons-collections-3.2.1.jar 10/50 files (20.00%)
bundling: py_util/hadoop/lib/commons-configuration-1.6.jar 11/50 files (22.00%)
bundling: py_util/hadoop/lib/commons-digester-1.8.jar 12/50 files (24.00%)
bundling: py_util/hadoop/lib/commons-el-1.0.jar 13/50 files (26.00%)
bundling: py_util/hadoop/lib/commons-io-2.1.jar 14/50 files (28.00%)
bundling: py_util/hadoop/lib/commons-lang-2.5.jar 15/50 files (30.00%)
bundling: py_util/hadoop/lib/commons-logging-1.1.1.jar 16/50 files (32.00%)
bundling: py_util/hadoop/lib/commons-math-2.1.jar 17/50 files (34.00%)
bundling: py_util/hadoop/lib/commons-net-3.1.jar 18/50 files (36.00%)
bundling: py_util/hadoop/lib/guava-11.0.2.jar 19/50 files (38.00%)
bundling: py_util/hadoop/lib/hadoop-auth-2.0.0-cdh4.1.2.jar 20/50 files (40.00%)
bundling: py_util/hadoop/lib/hadoop-common-2.0.0-cdh4.1.2.jar 21/50 files (42.00%)
bundling: py_util/hadoop/lib/hadoop-core-2.0.0-mr1-cdh4.1.2.jar 22/50 files (44.00%)
bundling: py_util/hadoop/lib/hadoop-hdfs-2.0.0-cdh4.1.2.jar 23/50 files (46.00%)
bundling: py_util/hadoop/lib/hadoop_archive.log 24/50 files (48.00%)
bundling: py_util/hadoop/lib/hsqldb-1.8.0.10.jar 25/50 files (50.00%)
bundling: py_util/hadoop/lib/jackson-core-asl-1.8.8.jar 26/50 files (52.00%)
bundling: py_util/hadoop/lib/jackson-mapper-asl-1.8.8.jar 27/50 files (54.00%)
bundling: py_util/hadoop/lib/jasper-runtime-5.5.23.jar 28/50 files (56.00%)
bundling: py_util/hadoop/lib/jersey-core-1.8.jar 29/50 files (58.00%)
bundling: py_util/hadoop/lib/jersey-server-1.8.jar 30/50 files (60.00%)
bundling: py_util/hadoop/lib/jetty-6.1.26.cloudera.2.jar 31/50 files (62.00%)
bundling: py_util/hadoop/lib/jetty-util-6.1.26.cloudera.2.jar 32/50 files (64.00%)
bundling: py_util/hadoop/lib/jline-0.9.94.jar 33/50 files (66.00%)
bundling: py_util/hadoop/lib/jsch-0.1.42.jar 34/50 files (68.00%)
bundling: py_util/hadoop/lib/jsp-api-2.1.jar 35/50 files (70.00%)
bundling: py_util/hadoop/lib/jsr305-1.3.9.jar 36/50 files (72.00%)
bundling: py_util/hadoop/lib/junit-4.8.2.jar 37/50 files (74.00%)
bundling: py_util/hadoop/lib/log4j-1.2.17.jar 38/50 files (76.00%)
bundling: py_util/hadoop/lib/mockito-all-1.8.5.jar 39/50 files (78.00%)
bundling: py_util/hadoop/lib/paranamer-2.3.jar 40/50 files (80.00%)
bundling: py_util/hadoop/lib/pig-0.10.0-cdh4.1.2.jar 41/50 files (82.00%)
bundling: py_util/hadoop/lib/protobuf-java-2.4.0a.jar 42/50 files (84.00%)
bundling: py_util/hadoop/lib/servlet-api-2.5.jar 43/50 files (86.00%)
bundling: py_util/hadoop/lib/slf4j-api-1.6.1.jar 44/50 files (88.00%)
bundling: py_util/hadoop/lib/slf4j-log4j12-1.6.1.jar 45/50 files (90.00%)
bundling: py_util/hadoop/lib/snappy-java-1.0.4.1.jar 46/50 files (92.00%)
bundling: py_util/hadoop/lib/xmlenc-0.52.jar 47/50 files (94.00%)
bundling: py_util/hadoop/lib/zookeeper-3.4.3-cdh4.1.2.jar 48/50 files (96.00%)
bundling: py_util/hadoop/run_pig.py 49/50 files (98.00%)
bundling: py_util/hadoop/run_pig.py.orig 50/50 files (100.00%)
sending unbundle command
sending 23785866 bytes
using auth.TR.* for authentication
sending: 64/46456 kb (0.14%)
...
sending: 23228/46456 kb (50.00%)
http auth: user wilson.droter, password ********
using auth.TR.* for authentication
mercurial.int.thomsonreuters.com certificate matched fingerprint f4:57:8a:83:46:9a:d1:eb:7a:c6:58:ac:dd:ea:ed:36:42:ee:2c:56
sending: 23292/46456 kb (50.14%)
...
sending: 46456/46456 kb (100.00%)

The push works for a small change to a text file. I think the problem is with adding files.
Do I need to get permissions changed or is there another solution.

A:

You need to get permissions changed.  You have write permission to the .hg/store/... files that already exist, which is why you can change that file, but probably not write permissions to the .hg/store directory itself so you can't create new files.
You need to make sure your user or group on that server has rwx access to all the files and directories from the repository directory on down.  If it's group access that's letting you in she may need to set the sticky group bit too.


Q:

QGIS 3.4 Modeler: Select a band of a raster layer for processing

As model input data I select a raster stack with three bands. The first processing tool just needs specific bands of this stack which I like to select in the input dialog.
I create a 'Raster Layer' input that lets me select the layer. Then, I also create a 'Raster Band' input that has the 'Raster Layer' input as parent. In the GUI that is displayed as a drop-down menu and I can choose between the bands.
However, the model always takes the first band of the raster layer, no matter which band I select. The processes following the layer/band selection are connected to the selection of the layer, because there is no possibility of selecting the bands (see screenshot):

How can I make the processing tools to use a specific band of a layer?

A:

I solved it. It seems, that not all tools can work with a band selection as input. The used GDAL "Clip raster by extent" tool was not able to deal with that.
I then inserted the GDAL "Rearrange bands" tool before the clipping tool. That tool is able to choose a specific band based on the input selection and to forward it to the next tool.


Q:

How do i implement Location Based Service in my web application? except $_SERVER['REMOTE_ADDR'] .. In PHP

I want to know how to implement Location Based service in my website where i can find the exact location of the user who is accessing my site.. I tried with $_SERVER['REMOTE_ADDR'], but its giving ISP IP .. which is a bit inaccurate..
Thanks in Advance.

A:

I recently implemented geolocation with GeoIP (a PEAR package). It is not terribly accurate, but it gives country ok, region/state ok and major nearest city almost always right.
Once you install the package, you have to download the latest data file from maxmind, and it can be as easy to use as this:
require_once "Net/GeoIP.php";
$geoloc = Net_GeoIP::getInstance('/var/www/GeoIP.dat');
try{
    $countryCode = $geoloc->lookupCountryCode($_SERVER['REMOTE_ADDR']);
}
catch(Exception $e) {}


Q:

Eagerly load many to many associations in Sequel

I'm writing an application and I have two models, a Post and a Tag model. They have a many-to-many association. I would like to load all of the tags for a post when retrieving a post, so I don't have to run multiple trips to the DB.
The models look roughly like this (i've omitted some private details):
class Post < Sequel::Model
  many_to_many :tags
end

class Tag < Sequel::Model
  many_to_many :posts
end

I have tried Post.eager_graph(:tags)[id], which had some success, but it only loaded the first tag and prefixed all the tag column names with tags_ instead of chucking it in to an array or something. Is there a way to have it load all of the tags at once, or am I going to have to keep them separate queries?
Thanks for your help!

A:

Unless you are eagerly loading multiple posts, it makes no sense to automatically load the tags when retrieving posts.  It's going to take multiple queries anyway unless you JOIN, and I'm guessing a JOIN is going to be slower than two separate queries when considering the additional overhead required by Sequel to split the JOINed results.


Q:

Rooting ICS emulator; pushing su fails with "Out of memory"

I'm trying to root my ICS AVD, and have tried this:
adb shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system
adb push su /system/xbin/su
adb shell chmod 06755 /system
adb shell chmod 06755 /system/xbin/su

It fails with the following error:

failed to copy 'su' to '/system/xbin/su': Out of memory

How can I fix this?

A:

This blog explains the problem:

To avoid the "Out of memory" error when trying to copy the su-executable to /system/bin, you need to start the emulator manually with a large –partion-size argument:
$ emulator -avd MYNAME -partition-size 300

Then:
$ adb remount
$ adb push su /system/bin/su
$ adb shell chmod 06755 /system/bin/su

Note that MYNAME above is the name of the emulator. Also note that if you are using snapshots, you will need to start the emulator without it due to the change in hardware configuration. Append -no-snapshot-load to do so.

A:

With this you'll have 512MB of size on /system
ICS is the name I gave to my android emulator:
android-sdk-linux/tools$ emulator -avd ICS -partition-size 512


Q:

Android - How to maintain 3g connection when wifi available

My app connects with a persistent connection to a server.  If the device is currently using 3G it will connect over 3g.
The problem is that if it connected using 3G and moved into wifi the connection drops. How do I prevent it from disconnecting?

A:

Sounds like the server is unable to accommodate clients seamlessly switching to a different IP address, or it may be using something like keep-alive packets to maintain connection state, and when the 3G connection drops, it disconnects your session.
This may not be something you have control over. From the Android point of view - the device will prefer WiFi depending on user preferences and you will likely not have any direct control over that either.
In a nutshell - if you can't modify or reconfigure the communications protocol to allow client IP changes on the fly, then there's nothing you can do with Android to mitigate the problem.
All mobile devices, and to a lesser extent, desktops/laptops will at some point change their public facing IP address, so it sounds like a bug or oversight in the server/protocol design to me.

EDIT:
In response to your comment, and in the interests of UX, you should be very careful about finding a way to force your app (possibly even the entire device) to remain on 3G when the user has requested that it use WiFi.
Most people have capped data plans with their device and wouldn't be very pleased if they think they are using WiFi (which is most likely free, or at least no additional cost) when in fact you've forced their device to continue using potentially very expensive 3G data instead.
This is especially important when any method would likely be actively circumventing the reasonable limits the Android environment presents you with, and therefore would probably not be flagged as a "Service that costs you money" when installed.

EDIT 2:
So, there may be a way for you to do it, but it relies on unsupported, private Android APIs which may change at any moment - usual disclaimer applies.
Take a look here where they access the ConnectivityManager object to allow you to enable mobile data.
This method does require you to build against the Android source tree, and use a shared user ID with "system" so may or may not be suitable, but these APIs are private (as apps are not supposed to be able to do this without user action), but it may help you.


Q:

Mysql partition by key shows only 1 partition

I have a scenario like I have a product table with different categories. So queries will be specific to category. So I thought if I can separate each category as each partition it will improve performance.
DROP TABLE IF EXISTS products;

CREATE TABLE products (
 id int(11) AUTO_INCREMENT,
 pname varchar(11) default '',
 category char(10) default 'general',
 PRIMARY KEY thisKey (id,category)
)
PARTITION BY KEY (category)
;

I loaded data from two categories. But its showing only one partition:
mysql> EXPLAIN PARTITIONS SELECT * FROM products\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: products
   partitions: p0
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 3
        Extra:

Can somebody help me why its not having two partition, or I choose wrong partition type for this requirement?

A:

You are missing the number of partitions, after the partition by key put something like that (for 5 partitions)
PARTITION BY KEY (category)
PARTITIONS 5;

Are you using the best strategy with partitions? depends.
You have a lot of categories with similar number of products and also there are new categories added frequently. BY KEY or BY HASH are good options, with this options the products will distribute randomly over the number of partitions
Also with this kind of partition you dont have the warranty that inserting two products with diferent categories they go inside diferent partitions (the hash key could be the same)
You have a fixed number of categories, with heavy diferences between the numer of products in each category. Probably BY LIST is your friend, you select which category goes inside every partition.
Do you have a relative small number of products or you need to mix products from several categories in queries? Probably you dont need a partition.


Q:

Merge OCX with .NET EXE

Is there any tool, commercial or freeware, that allows merging OCX files with .NET executable?
I know it's possible to make an isolated OCX reference, but that's not sufficient in my case, I need to get a single exe without installation requirement.
Thanks.

A:

Apparently, VMware ThinApp allows this.


Q:

UITableView is not smoothly when using downloading images

I am new in IOS development using Swift. I created 1 UITableView and displaying images after downloading data. But it is not smooth and some time images are displaying in wrong place when i am scrolling.
I am using AlamofireImage library for image downloading and displaying. Is there any fast library?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell:HomePageCell = tableView.dequeueReusableCell(withIdentifier: "HomePage", for: indexPath) as! HomePageCell

    cell.configure( homeData[0], row: indexPath, screenSize: screenSize,
                    hometableview: self.homeTableView);

    return cell
}

import UIKit
import Alamofire
import AlamofireImage

class HomePageCell: UITableViewCell {

@IBOutlet weak var bannerImage: UIImageView!

func configure(_ homeData: HomeRequest, row: IndexPath, screenSize: CGRect, hometableview: UITableView) {

   let callData = homeData.banner_lead_stories[(row as NSIndexPath).row]
   let url = Constants.TEMP_IMAGE_API_URL + callData.lead_story[0].bg_image_mobile;

    if( !callData.lead_story[0].bg_image_mobile.isEmpty ) {

        if bannerImage?.image == nil {

            let range = url.range(of: "?", options: .backwards)?.lowerBound
            let u = url.substring(to: range!)

            Alamofire.request(u).responseImage { response in
                debugPrint(response)

                //print(response.request)
                // print(response.response)
                // debugPrint(response.result)

                if let image = response.result.value {
                    //   print("image downloaded: \(image)")

                    self.bannerImage.image = image;

                    self.bannerImage.frame  = CGRect(x: 0, y: 0, width: Int(screenSize.width), height: Int(screenSize.width/1.4))

                }
            }

        }

    } else {
        self.bannerImage.image = nil;
    }
}

 }

A:

It can be not smooth, because you need to cache your images and make a downloading process not in main thread(read about GCD).
For caching you can go two ways (atleast):
1) Make your own array of images where they will be cached
2) Use KingFisher for example click. It will cache your images.
For example:
yourImageView.kf.setImage(with: URL) // next time, when you will use image with this URL, it will be taken from cache.

Hope it helps


Q:

How to pass struct byref and readonly to a function in C#?

Is it possible to pass a struct byref and readonly to a function? (just like T const& in C++)
struct A
{
    public int b;
}
void func1(ref A a)  // I want to make this `a` immutable
{

}

How to do that?
Update
My biggest concern is passing (1) immutable state (2) efficiently. Second concern is the mutating the state must be simple and easy as like mutable object.

A:

Currently I am doing this like this. A kind of boxing.
class
ImmutableBox<T> where T : struct, new()
{
    public readonly T state;
    ImmutableBox(T state)
    {
        this.state = state;
    }
}

struct
ExampleStateA
{
    public string someField;
}

void
func1(ImmutableBox<ExampleStateA> passImmutableStateWithBox)
{
}

By keeping the instance of ImmutableBox<T>, I can pass immutable object with pointer copy, and it's still easy to edit State because State is mutable. Also I gain a chance to optimize equality comparison to pointer comparison.