text:
Q: Nunit Test Dependent Commits - By ID I have a method that does two commits - here is a simplified version of it:
    public void methodA(objectA objA, List<objectB> objB)
    {
         _repoA.AddAsync(objA);
         var id = _repoA.SaveChanges();
         if(id > 0) {
            foreach (var ob in objB)
            {
              ob.objAId = id;
              _repoB.AddRange(ob);
            }
           _repoB.SaveChanges();
         }
   }

How do I get/set the id in my unit test to see if my list's objAId is set and that it actually contains two object - right now as I cannot set/get id in first commit my test fails:
[Fact]
    public async void test()
    {
        var objA = new ObjA(null);
        var objB = new List<ObjB>
        {
           new ObjB(null, null, "Test"),
           new ObjB(null, null, "Test2")
        });

        var result = await _sut.methodA(objA, objB);

        Assert.NotNull(result);
        _mockFieldRepository.Verify(x => x.InsertAsync(It.IsAny<MyObjectA>()), Times.Once);
        _mockFieldOptionRepository.Verify(x => x.InsertAsync(It.IsAny<MyObjectB>()), Times.Once); //fails here
        _mockFieldOptionRepository.Verify(x => x.InsertAsync(It.Is<MyObjectB>(p => p.Id > 0 && p.objAId == objA.Id))); //fails here

    }

A: NOTE: I have to guess at some of your test setup and interfaces being mocked, so my answer may not be completely correct.
If we take your original code, there appears to be no Setup mocks to configure what the code is expecting to happen.  You are simply using Verify to make sure that some things DID happen.
So, the first thing we need to do is configure mock so that implied mocks are errors, and also Setup the expectations.
_mockFieldRepository = new Mock<IFieldRepository>(MockBehaviour.Strict);

You will now find that you get test errors because SaveChanges and AddRange are not Setup. This is good.  So add Setups for them too.
_mockFieldRepository.Setup(x => x.SaveChanges();
_mockFieldRepository.Setup(x => x.AddRange(It.IsAny<MyObjectA>());
_mockFieldRepository.Setup(x => x.InsertAsync(It.IsAny<MyObjectA>()));
_mockFieldOptionRepository.Setup(x => x.InsertAsync(It.IsAny<MyObjectB>()));
_mockFieldOptionRepository.Setup(x => x.InsertAsync(It.Is<MyObjectB>(p => p.Id > 0 && p.objAId == objA.Id)));

It's a good idea to use It.Is<> during setup, or for simple parameters (integers, strings etc), just pass the expected value, rather than It.Is.
In my opinion, the validation is not great, because It.IsAny<>() means, you don't care how that function is being called, so you should use It.Is (like the 3rd setup) to make 100% certain that the parameters you expect to be passed to the method ARE the parameters you do get.


text:
Q: Jquery Adding cloning form fields - increment name I'm looking at this fiddle http://jsfiddle.net/yezw6c51/1/ which does what I need to do with one exception.
When you load it has one Input field named 'phone_number'
When you click on Add phone number you can add multiple rows/input fields as such :

Each new input field that is added has had it's field name incremented. eg : phone_number1, phone_number2 etc. This works fine.
But I'd like the text before each input field to also have the incremented value adding as well, so you end up with :

So the text description is incremented with the same value as the phone_number field.
ie: Phone Number 2 = phone_number2 etc
How do I do that ?
Thanks

A: Wrap your text with span
Phone number :

Then your can change only the text inside span
$(this).parent().find('span').text('Phone number ' + phone_number_form_index);

fiddle: http://jsfiddle.net/yezw6c51/16/

A: instead of giving each input different names, you can use name="phoneNumber[]" and loop through the post keys in backend.
Demo: http://jsfiddle.net/artuc/yezw6c51/23/
HTML:
<form name="test">

        Phone Number 1:
        <input type="text" name="phoneNumber[]" />

    Add [+]
</form>

JS:
$(document).ready(function(){
$('.btnAdd').click(function(){
    base = $('.formRow:first');
    newRow = base.clone().insertAfter($('.formRow:last'));
    newRow.find('input').val('');
    newRow.find('label>span').text(newRow.index('.formRow')+1);
    newRow.append('<input type="button" class="btnRemove" value="Remove"/>');
});

$(document).on('click', '.btnRemove', function(){
    $(this).parent().remove();
    //update index
    $('.formRow').each(function(){
        target = $(this).find('label>span');
        target.text($(this).index('.formRow')+1);
    });
});

});

A: You can Use a Span After "Phone Number" in your HTML.
And make these changes in your script
$(document).ready(function(){
    var phone_number_form_index=1;
    $("#add_phone_number").click(function(){
        phone_number_form_index++;
        $(this).parent().before($("#phone_number_form").clone().attr("id","phone_number_form" + phone_number_form_index));
        $("#phone_number_form" + phone_number_form_index).css("display","inline");
        $("#phone_number_form" + phone_number_form_index).find("span").html(phone_number_form_index);
        $("#phone_number_form" + phone_number_form_index + " :input").each(function(){
            $(this).attr("name",$(this).attr("name") + phone_number_form_index);
            $(this).attr("id",$(this).attr("id") + phone_number_form_index);
            });
        $("#remove_phone_number" + phone_number_form_index).click(function(){
            $(this).closest("div").remove();
        });
    });
});

check out here
http://jsfiddle.net/yezw6c51/24/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use complete induction to prove that $a_n < 2^n$ for every integer $n \geq 2$ Define the sequence of integers $a_0, a_1, a_2, \cdots$ as follows
$$ a_i =
\begin{cases}
      i+1 & 0 \leq i \leq 2 \\
      a_{i-1} + a_{i-2} + 2a_{i-3} & i > 2 \\
   \end{cases}
$$
Use complete induction to prove that $a_n < 2^n$ for every integer $n \geq 2$
I will prove $a_n < 2^n, \forall n \geq 2$ by using complete induction
Base Case: Three cases $n = 2, 3, 4$
let $n = 2$
$a_{n} = a_{2} = 2 + 1 = 3 < 4 = 2^2 = 2^n$ By definition, and holds
let $n = 3$
$a_{n} = a_{3} = 3 + 2 + 1 = 6 < 8 = 2^3 = 2^n$ By definition, and holds
let $n = 4$
$a_{n} = a_{4} = 4 + 3 + 2 = 9 < 16 = 2^4 = 2^n$ By definition, and holds
Inductive step: let $n > 4$. Suppose $a_j < 2^j$ whenever $2 \leq j < n$. [Inductive hypothesis]
What to prove: $a_n < 2^n$
$a_{n} = a_{i-1} + a_{i-2} + 2a_{i-3}$ [By definition]
$< 2^{n-1} + 2^{n-2} + 2^{n-3+1}$ [By Inductive hypothesis]
$= 2^{n-1} + 2^{n-2} + 2^{n-2}$
$= 2^{n-1} + 2^{n-2 + 1}$
$= 2^{n-1 + 1}$
$= 2^n$
as wanted.
Would this be correct?

A: The second part is fine. But the base case is not just the $n=2$ case. You should have checked it for $n=0$, and $n=1$ too.


text:
Q: How to pick "full/thumbnail" images in the loop? I am picking the latest posts through the WordPress loop using the below code, but it's picking all images at full size:
if ( have_posts() ) :
    while ( have_posts() ) : the_post(); ?>

            <a class="post_image" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                <?php if ( has_post_thumbnail() ):
                    the_post_thumbnail('full');
                else : ?>
                    <img src="<?php echo get_template_directory_uri(); ?>/images/No-Thumbnail-Available.png" alt="<?php the_title(); ?>" />
                <?php endif; ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>

            <?php the_excerpt(); ?>

    <?php endwhile;
else: ?>

<?php _e('Sorry, No Article Is Available Here...'); ?>

<?php endif;

I want to pick the full image for the first post of the Loop and thumbnail images for all the rest of the posts in the Loop. I am able to do it via CSS, but that is not SEO friendly. I am using the below code but it's not working:
$first = true;
foreach ( $obj as $value ) {
    if ( $first ) { ?>

            <a class="post_image" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                <?php if ( has_post_thumbnail() ):
                    the_post_thumbnail('full');
                else : ?>
                    <img src="<?php echo get_template_directory_uri(); ?>/images/No-Thumbnail-Available.png" alt="<?php the_title(); ?>" />
                <?php endif; ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>

            <?php the_excerpt(); ?>

        <?php $first = false;
    } else { ?>

            <a class="post_image" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                <?php if ( has_post_thumbnail() ):
                    the_post_thumbnail('thumbnail');
                else : ?>
                    <img src="<?php echo get_template_directory_uri(); ?>/images/No-Thumbnail-Available.png" alt="<?php the_title(); ?>" />
                <?php endif; ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>

            <?php the_excerpt(); ?>

    <?php }
}

A: Try just using the traditional $i iterator (untested) but I can't see why this wouldn't work..
<?php
$i = 0;
while ( have_posts() ) : the_post();
    $i++;
    if ( $i == 1 ): ?>

        <a class="post_image" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
            <?php if ( has_post_thumbnail() ): ?>
                <?php the_post_thumbnail('full'); ?>
            <?php else : ?>
                <img src="<?php echo get_template_directory_uri(); ?>/images/No-Thumbnail-Available.png" alt="<?php the_title(); ?>" />
            <?php endif; ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>

        <?php the_excerpt(); ?>

<?php else: // else $i == 1 ?>

        <a class="post_image" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
            <?php if ( has_post_thumbnail() ): ?>
                <?php the_post_thumbnail('thumbnail'); ?>
            <?php else : ?>
                <img src="<?php echo get_template_directory_uri(); ?>/images/No-Thumbnail-Available.png" alt="<?php the_title(); ?>" />
            <?php endif; ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>

        <?php the_excerpt(); ?>

<?php endif; // endif for $i == 1 ?>
<?php endwhile; ?>


text:
Q: as.Date seems not te be working with excel dates Hi I have this input file
http://www.mediafire.com/file/a4yda7zmwvpd9zi/data.xlsx/file
MIN and MAX columns are Date type in the xls file and also after as.Date the Class is Date, the type is double as it should be.. but when I run the following code
library(ggplot2)
library(readxl)

out <- read_xlsx("C:/data.xlsx")

out

out$MIN <- as.Date(out$MIN)
out$MAX <- as.Date(out$MAX)
class(out$MIN)

#out$MIN <- as.Date(out$MIN, format = "%d/%m/%Y")

library(dplyr)

out %>%
  group_by(SEX) %>%
  tidyr::gather(key, value, -SEX) %>%
  ggplot(aes(SEX, value)) +
  geom_line(aes(color = SEX)) +
  coord_flip() +
  scale_y_date(breaks = c(out$MIN, out$MAX)) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
out

I keep getting the error date_trans works with objects of class Date only
I tried different formats.. even changed the excel original data types to different date formats but keep getting the same error..

A: You could try:
out %>%
  tidyr::gather(key, value, -one_of(c("ID", "SEX"))) %>%
  ggplot(aes(ID, value, group = ID)) +
  geom_line(aes(color = SEX)) +
  coord_flip() +
  scale_y_date(breaks = seq(min(out$MIN), max(out$MAX), by = "year")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

Though I doubt the usefulness of such charts, and how you'd solve the scale for dates (I made a sequence of years from the minimum to maximum), but that's up to you.


text:
Q: Vaadin 7: fill new data into Table dynamically I'm looking for right way to create a table that could upload new rows dynamically. As a DataSource I'm using SQLContainer with TableQuery. There could be much of data which should be uploaded quickly.
Anyway, my current realization is following:
Table messagesList = new Table();
...............................
messagesList.setCacheRate(0.1d);
messagesList.setContainerDataSource(messagesContainer);
messagesList.setSelectable(true);
messagesList.setImmediate(true);
messagesList.setSizeFull();
new InitializerThread().start();
...............................

Data is uploading using refreshRowCache method and Vaadin Push tecknology in another thread:
class InitializerThread extends Thread {
        @Override
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    Thread.sleep(refreshMessagesPeriod);
                } catch (InterruptedException e) {
                }
                access(new Runnable() {
                    @Override
                    public void run() {
                        if (messagesList != null && !messagesList.getItemIds().isEmpty()) {
                            messagesList.refreshRowCache();
                            messagesList.focus();
                        }
                    }
                });
            }
        }
}

This approach has many disadvantages:
1. If there are many rows in the table, it is very inefficient way to refresh all row's cache in the table everytime.
2. Scroll bar jumps to the top of page in the table when the row's cache is refreshing. I didn't find the way to save the scroll's position and set the previous scroll position after refresh.
3. If I select some text in a cell of the table, the selection dissapears after row's cache refresh.
I hope that there is a lightweight and more nice technique to fill new data into Table dynamically.
I use Vaadin 7.1.15 and it is allowed to change version of Vaadin type of table (instead com.vaadin.ui.Table) if necessary.

A: I found a better solution - control container content manually. Using IndexedContainer as a data source instead TableQuery and periodically checking a new data using sql queries. Vaadin Push helps me to visualise new rows. To prevent a scroll bar jump (which is the result of calling refreshRowCache) I call the private method Table.setCurrentPageFirstItemId(int, boolean) with following parameters: a new row ID, false (do not call refreshRowCache).


text:
Q: Button for sqrt sign How to create a button, which has exactly the same functionality as pressing ctlr+2 in an inputField?
So it is basicly appending an sqrt sign to a string.

A: CreatePalette[{"Square root",PasteButton[Sqrt@\[SelectionPlaceholder]]}]


text:
Q: Can't figure why my if statement is not working I can't figure out why my if statement is not working. For some reason it always evaluates first if statement as true, and in result outputs the wrong value.
With numberOfDays = 19 it should output 4.95, but instead it outputs 1.65, because it evaluates first if statement as true and doesn't change the value of numberOf7DayPasses:
class TransitCalculator {

    int numberOfRides;
    int numberOfDays;
    double[] prices = { 2.75, 33.00, 127.00 };

    public TransitCalculator(int myRides, int myDays) {
        numberOfRides = myRides;
        numberOfDays = myDays;
    }

    public double unlimited7Price() {
        int numberOf7DayPasses = 1;

        if (numberOfDays % 7 != 0 && numberOfDays / 7 != 1 && numberOfDays / 7 > 1 && numberOfDays / 7 < 2) {
            numberOf7DayPasses = 2;
        } else if (numberOfDays % 7 != 0 && numberOfDays / 7 != 2 && numberOfDays / 7 > 2 && numberOfDays / 7 < 3) {
            numberOf7DayPasses = 3;
        } else if (numberOfDays % 7 != 0 && numberOfDays / 7 != 3 && numberOfDays / 7 > 3 && numberOfDays / 7 < 4) {
            numberOf7DayPasses = 4;
        } else if (numberOfDays % 7 != 0 && numberOfDays / 7 != 4 && numberOfDays / 7 > 4 && numberOfDays / 7 < 5) {
            numberOf7DayPasses = 5;
        } else if (numberOfDays % 7 == 0 && numberOfDays / 7 == 1) {
            numberOf7DayPasses = 1;
        } else if (numberOfDays % 7 == 0 && numberOfDays / 7 == 2) {
            numberOf7DayPasses = 2;
        } else if (numberOfDays % 7 == 0 && numberOfDays / 7 == 3) {
            numberOf7DayPasses = 3;
        } else if (numberOfDays % 7 == 0 && numberOfDays / 7 == 4) {
            numberOf7DayPasses = 4;
        } else if (numberOfDays % 7 == 0 && numberOfDays / 7 == 5) {
            numberOf7DayPasses = 5;
        }
        double priceOfOneRide = numberOf7DayPasses * prices[1] / numberOfRides;

        return priceOfOneRide;
    }

    public static void main(String[] args){
        TransitCalculator testPerson = new TransitCalculator(20, 19);
        System.out.println(testPerson.unlimited7Price());
    }
}

A: You say that you think it returns 1.65 because the first condition is evaluated true? So I guess you didn't use a debugger to step trough the code to see what really happens!
If the first condition would be evaluated to true, the output would be 3.3 (= 2*33/20)
The output is 1.65 which means none of the conditions evaluates to true.
The first condition (and the 2nd and the 3th and the 4th) can't evaluate to true because they will always be false. The 1st condition contains:
numberOfDays / 7 > 1 && numberOfDays / 7 < 2

NumberOfDays is an int and because of that the result of numberOfDays / 7 is also an int.
An int can't be greater than 1 and smaller than 2. So the condition will always be false. And in the 2nd, 3th and 4th condition, the numbers are different but they have the same problem.


text:
Q: Web API 2 OWIN Bearer token authentication/ How do I Change /Token path I'm writing a SPA application with OWIN authentication. Initially my app was built to run as the default app in IIS and so my Authorization options looked like this (TokenEndpointPath = "/Token")
OAuthOptions = new OAuthAuthorizationServerOptions
            {
                //Exposes Token endpoint
                TokenEndpointPath = new PathString("/Token"),
                //Use ApplicationOAuthProvider in order to authenticate
                Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath = new PathString("/MyApp/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), //Token expiration => The user will remain authenticated for 14 days
                AllowInsecureHttp = true
            };

However, I'm needing to move this so that it's no longer the default app but a child application within the default IIS app all of my api calls will go from this path:
http://localhost:22657/

to:
http://localhost:22657/MyApp

So, the /Token path is no longer reachable. So, I've altered my TokenEndpointPath to be:
TokenEndpointPath = new PathString("/MyApp/Token"),

However, when I authenticate my browser successfully makes the call, however, the response from the server is the HTML from my Index.cshtml file. I don't know how to diagnose why WebApi is processing the request that way (it's clearly not being processed by OWIN. When I set a breakpoint on my GrantResourceOwnerCredentials method the breakpoint isn't hit ).
None of my WebApi routes are configured with "Token" in it.
1) Does anyone know what is going on with the endpoint and why it's returning html rather than the bearer token or how I should go about troubleshooting it?
Update:
I guess it must be related to the following default route which specifies the Index. This is causing requests to /MyApp/Token to be routed to Home/Index.  Is there something else I could use in place of "{*url}" to prevent this?
routes.MapRoute(
                name: "Default",
                url: "{*url}",
                defaults: new { controller = "Home", action = "Index" }
            );

A: MVC was intercepting the call to the WebApi /MyApp/Token endpoint. In attempting to have MVC ignore this route I had added the second line below:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{Token}");

However, this wasn't working. When I moved the line to ignore "Token" to the top it worked:
routes.IgnoreRoute("{Token}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


text:
Q: How to assign Two segues on a table cell in SWIFT? I am totally new at IOS swift and working with android.
Here is my issue :
I'm developing a simple chatting App of IOS. I've already completed android ver and this is a kind of clone.
It has view controllers named VCList, VCMyFriends and VCChat. VCList is my very first view controller and has a table view. Touching a table view cell changes current view controller to VCMyFriends or VCChat.
When I touch a cell, app checks the member counts of the cell, so if it has other members then go to VCChat. If not, VCMyFriends on to invite my friends. Like following pic.

What I found is, I cannot assign two segues on a cell or split a segue with two ways. So I thought that can I change my VC without a segue? However I could not find any references or tutorial about it.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if( memberCnt == 0 ) {
        self.presentViewController(VCMyFriends(), animated: true, completion: nil);
    } else {
        self.presentViewController(VCChat(), animated: true, completion: nil);
    }
}

Above is my last try, and failed. It moves somewhere, but shows nothing at all. And if I can, I wish to use segues because have some datas to pass with segue.
Take care.

A: What I normally do is to create an instance of the controller via the instantiateViewControllerWithIdentifier and set the necessary member variables before calling presentViewController.  You can also add a NavigationController if you want the capability the go back to the previous window.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    let mainStoryBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    if( memberCnt == 0 )
    {
      let vcMyFriends = mainStoryBoard.instantiateViewControllerWithIdentifier("VCMyFriend") as! VCMyFriends
      vcMyFriends.membervar1 = membervar1
      vcMyFriends.membervar2 = membervar2

      self.presentViewController(vcMyFriends, animated: true, completion: nil)
    }
    else
    {
      let vcChat = mainStoryBoard.instantiateViewControllerWithIdentifier("VCChat") as! VCChat
      vcChat.membervar1 = membervar1
      vcChat.membervar2 = membervar2

      self.presentViewController(vcChat, animated: true, completion: nil)
    }
}

membervar and membervar2 are the data that you pass to the View Controllers.  You need to set it before calling presentViewController so that they will be available when viewDidLoad is called.

A: Simply do this
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if( memberCnt == 0 ) {
        performSegueWithIdentifier("VCMyFriends_segue", sender: self)
    } else {
        performSegueWithIdentifier("VCChat_segue", sender: self)
    }
}

In your storyboard, select the first segue (the red line in your image) and choose Attributes inspector, then add VCMyFriends_segue as identifier.
Do the same thing for the second line (blue) and add VCChat_segue identifier.
Hope this helps


text:
Q: Counting the Number of Occurrences of a Multi-Word Phrase in Text with PostgreSQL I have a problem, I need to count the frequency of a word phrase appearing within a text field in a PostgreSQL database.
I'm aware of functions such as to_tsquery() and I'm using it to check if a phrase exists within the text using to_tsquery('simple', 'sample text'), however, I'm unsure of how to count these occurrences accurately.

A: If the words are contained just once in the string (I am supposing here that your table contains two columns, one with an id and another with a text column called my_text):
SELECT
     count(id)
FROM
     my_table
WHERE
     my_text ~* 'the_words_i_am_looking_for'

If the occurrences are more than one per field, this nested query can be used:
SELECT
     id,
     count(matches) as matches
FROM (
     SELECT
          id,
          regexp_matches(my_text, 'the_words_i_am_looking_for', 'g') as matches
     FROM
          my_table
) t
GROUP BY 1

The syntax of this function and much more about string pattern matching can be found here.


text:
Q: Gödel's incompleteness wrt weakend versions of ZFC Suppose for the sake of argument that we look at ZFC with the axiom of infinity removed.
http://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems#First_incompleteness_theorem
http://en.wikipedia.org/wiki/G%C3%B6del%27s_incompleteness_theorems#Second_incompleteness_theorem
We would then be in a position where the hypotheses of Gödel's theorems are not satisfied, correct? Basically, I want to remove, for the sake of argument, a minimal amount of axioms of ZFC so that ZFC minus some axiom(s) leads to a theory that does not include arithmetical truths and is not capable of expressing elementary arithmetic.
Is it possible that ZFC- (my shorthand for ZFC with some axiom(s) removed) is consistent and complete?

A: ZF minus the axiom of infinity plus a new axiom negating the axiom of infinity is bi-interpretable with Peano Arithmetic. And the two equivalent theories are both subject to Gödelian incompleteness.
For the equivalence claim, see Richard Kaye and Tin Lok Wong's paper On interpretations of arithmetic and set theory (which incidentally explores some of the complications alluded to in the answer by @zyx).

A: In addition to Peter Smith's very correct answer, it should be noted that one can also remove the axioms of choice and regularity without any substantial change.
The reason is that we can still define the relevant finite ordinals and their arithmetics needed for the incompleteness theorems (and because arithmetical truths are absolute between inner models with the same ordinals, so they are true in $L$ which is a model of $\sf ZFC$).
Note also that if $T\subseteq\sf ZFC$ is consistent and complete then $\sf ZFC$ is complete as well (it extends a complete theory), but we know it isn't complete, so no smaller theory is complete -- regardless to the provability of the incompleteness theorems.

A: The standard answer is slightly incomplete. The true state of things is beautifully explained in Emil Jerabek's comments at https://mathoverflow.net/questions/63887/non-standard-models-of-finite-set-theory/ .  Just to record it in one place, and to bring out a surprising point from that MO thread:

*

*It is well known that, in a suitable sense, the ZF theory of non-infinite sets is equivalent to PA.

*Less well known, but familiar to experts, is that there is a subtle point about how to define ZF minus infinity for the equivalence to PA to hold.

*But the story does not end there, and is not only about this PA/ZF- equivalence!  As revealed in the comments by Blass and Jerabek, the ZF axiom of foundation is oversimplified.  In more general situations, one wants not foundation but $\in$ induction. In full ZF one can do without it, but this is not an indication of how to axiomatize the same idea in more finitistic or constructive forms of set theory, including variants of ZF.

A: There are two "atomic" sets that exist because an axiom says it does.  One axiom for the empty set and one axiom for infinite sets.  The other few axioms input a set, or multiple sets, and predicates, and output a set that will exist under specific circumstances.  So we have two "seeds" and more than half a dozen inference-rule-like axioms.  A thing, then, is a set if it is either an atomic set, namely Ø or a set equipollent to the set of natural numbers, or the result of applying finitely many other axioms to get "new" sets.  If a property of sets is true of the atomic sets (i.e., the sets in the set theory for which there is an unqualified existential statement like "there is a set with the property that some formalism of 'is empty'.") and closed under the more than half dozen other axioms, then it is true of all sets.
At any rate, I think everyone might have been mistaken about how many axioms I am willing to drop (i.e., not adding its negation to the list, simply removing it from the list of axioms) in order to try to break incompleteness.
I blame myself for my lack of articulative quality in my original question.  I am looking for the precise moment in a formal system when incompleteness is broken.  If a FS can "model" a variant of ZFC or a variant of ZF, it can "model" PA.  PA is what Godel used to prove incompleteness.
How about if we just had the empty set axiom (not even its more general brother the comprehension axiom) and the pair set axiom?  Could that system model PA?  Well I guess it would because we would still have something infinite going on, roughly speaking, and when that happens incompleteness creeps near.


text:
Q: PCI Passthrough - Code 12 on Windows 7 Guest I've gotten fairly far in setting this up, but I'm left with both the Video and Audio devices in my GTX 1070 unable to load because of this error This device cannot find enough free resources that it can use. (Code 12)
Specs:
 - i7-5820K (OC'd to 3.8GHz)
 - MSI x99 SLI Krait Edition
 - Passing: GTX 1070 (Founder's)
 - Host: Linux Mint 18.1 x64
 - Guest: Windows 7 Ultimate x64
 - Using Virtual Box


text:
Q: What are the efficiency limits of the Peltier effect? I understand that thermoelectric coolers are perhaps a quarter as efficient as heat pumps. Why? What is the source of this efficiency limit? What would have to change for thermoelectric coolers to be more efficient?

A: Consumer peltier modules consist of P doped semiconductor connected in series (by wire) to an N doped semiconductor. This is daisy chained into a long string to be useful at a higher voltage. The majority carriers in each section are pushed in one direction by an electric field to create a temperature gradient. The majority carriers being electrons or holes are physically carrying their own heat from one side to the other. The inefficiency should becomes obvious when you realize that while the electrons and holes are travelling towards one side, phonons (lattice vibrations) can travel in the opposite direction. So while you're trying to move heat using the free carriers, phonons are constantly trying to make the entire item reach thermal equilibrium. Basically, you need to minimize thermal conductivity while increasing electrical conductivity.
Usually these two kinds of conductivity are quite related, but there are some unique materials that separated them. Carbon aerogel is one example of a material that may make for a good peltier device if it can be doped to have oppositely charged majority carriers.

A: The Peltier effect happens between two junctions of electrically conductive materials with different atomic lattice structures. Flow of current creates temperature difference between two junctions, but also generated the Joule heat in conductors. Also the link between two junctions is thermally conductive. So the thermolelectric element efficiency is limited by thermal "short" from cooled surface to hot surface and parasitic heat from dissipation in conductors. To increase element efficiency (aka "figure of merit", zT) the thermal conductance needs to be minimized, while electrical conductivity increased.
Unfortunately, Physics of thermal conductivity and electrical conductivity is bounded to the same internal mechanism - collective oscillations of atomic lattice, or phonons. Scholars figured out that the thermal conductivity has bottom limit for amorphous state of materials, which, unfortunately, has the lowest electrical conductivity. So the efficiency requirements for thermoelectric elements are inherently contradictory, and there is only so much one can do to improve the situation with band structure engineering using additions of different impurities.


text:
Q: how to exclude some block statement from transaction - Laravel 5.7 I need some statement (that's exist in transaction block) to be executed directly to Database without transaction , example :
DB::beginTransaction();

//query A : insert or update to some tables in transaction

//**I need some of the result of (query A) to be saved in Database without transaction**

//insert or update to some tables in transaction

DB::commit();

A: [EDIT] After reading your question again, it seems i may have misundersood some parts.  If by saying

I need some of the result of (query A) to be saved in Database without transaction

You mean "use the values inserted within the transaction before the transaction end", i guess it's not possible. You can still use my answer to insert or update data instantaneously, but you'll not be able to read something you inserted in the transaction before the transaction end.

You can duplicate the connection you are using for the transaction in database.php. For this example, let's assume you call it 'mysql_outside_transaction'. You should have something like this in the database.php file, after your default connection:
'mysql_outside_transaction' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

From there, since you have a second connection to the same database available, you can use it to save the data you need directly within the transaction.
Again, to make an example, if you have a instance of $modelA, you can tell it to use your second connection: $modelA->setConnection('mysql_outside_transaction');. From there, every database operation originating from this instance will be done outside your transaction (because it'll use the second connection you configured and not the one used for the transaction).
Don't forget you can set the connection to use in many ways. It could be directly on model class attributes (protected $connection = 'your_connection';), with the DB facade (DB::connection('your_connection');) and probably in other ways i don't think about right now :)


text:
Q: pass value to same php file I have one php block under html for dropdown list which is under loop.Another php block is for popup window using facebox. Now How by clicking dropdown content pass value to second php block.
<?php

         $msql="select notification_id,applicant_id,notification_dis from app_notification where applicant_id=$app_id order by notification_id desc " ;
        $result_msql=$bd->query($msql);
        while($messagecount=$result_msql->fetch_assoc())

        {
        $not_id=    $messagecount['notification_id'];
        $comment=$messagecount['notification_dis'];

        ?>

        <a href="#info"  class='view_comments' rel='facebox' id="<?php echo $not_id; ?>">
   <?php echo "check1---$not_id".$comment."";?>

////Another is
      <?php

        echo $_POST['not_id'];
       $mysql_hostname = "localhost";
      $mysql_user = "root";
      $mysql_password = "";
   $mysql_database = "test";
   $prefix = "";

        $bd = new mysqli($mysql_hostname, $mysql_user,           $mysql_password,$mysql_database) or die("Opps some thing went wrong");

            echo "check2---$not_id";

            $msql_show="select  header_type,notification_main,notification_dis from app_notification where notification_id=$not_id";
            $show_msql=$bd->query($msql_show);

            while($message_show=$show_msql->fetch_assoc())
            {
                $header=$message_show['header_type'];
                $main=$message_show['notification_main'];

            $msql_multi="SELECT file_name FROM biz_logo WHERE    w_id=(SELECT w_id FROM post_job
            WHERE job_id=(SELECT job_id FROM job_notice WHERE
            notice_id=(SELECT notice_id FROM app_notification where notification_id=$not_id)))";
            }
            $msql_multi=$bd->query($msql_multi);
            while($message_multi=$msql_multi->fetch_assoc())
            {

              $file_name=$message_multi['file_name'];

            }

            print "
".$header."$not_id
";
    print"

<t>".$file_name."</t>

".$main."

 ";
            ?>

        <?php }?>

A: in php manually you can use sessions or if you need
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".
";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

or if you need use html you can use inputbox and post get method


text:
Q: How to restart a Kinect So I'm writing an XNA app using the Kinect SDK and when my game changes from the game screen to another screen, I stop the Kinect by using
sensor.Stop();
sensor.Dispose();

And while it does work it has considerable lag and makes my game look unresponsive for at least 10 seconds. Then after that screen I go back to a game screen again but with different settings. So I use
//set all my event handlers
sensor.blahStream += myFunction;
sensor.Start();

Is this the best way to restart a Kinect?

A: Just fiddled around some more, putting the stopping on a separate thread seems to work.
stopGameThread = new Thread(new ParameterizedThreadStart(stopGame));
stopGameThread.Start();

that calls this method:
void stopGame(object sender)
{
    gScreen.sensor.Stop();
    gScreen.sensor.Dispose();
    running = false;
}

gScreen is the game screen contained in this game screen wrapper.
If anyone has any better answers feel free to post them.


text:
Q: Removed event handler continues to fire during postbacks After checking and rechecking my code, I cannot understand why the btnBack_Click event continues to fire after I've removed the event and registered another one in Page_Load
btnBack.Click -= new EventHandler(btnBack_Click);

btnBack.Click += new EventHandler(btnPreviewBack_Click);

Is it the postback? Is it because I haven't removed the OnClick on the aspx?

A: We can't see exactly where in your Page Lifecycle you are changing the Click event, however, remember that absolutely everything (as far as event handler changes) is "undone" once the lifecycle begins (although events that caused the postback will still get executed).
When a postback happens (whether async or not), all the event handlers are restored to their original configuration.
The best approach is to add your event handler changes to the Page_PreRender event:
protected void Page_PreRender(Object sender, EventArgs e)
{
    if (_MustChangeEventHandler)
    {
        btnBack.Click -= new EventHandler(btnBack_Click);

        btnBack.Click += new EventHandler(btnPreviewBack_Click);
    }
}


text:
Q: How to select distinct from two tables and then join them I've seen similar questions, but none of the fits my issue.
I have two tables:
WorkTable

WorkCode
WorkDescription

220001
WorkDescription1

220002
WorkDescription2

220003
WorkDescription3

220004
WorkDescription4

TasksTable

TaskCode
WorkCode
TaskDescription

AV0001

TaskDescription1

AV0002
220002
TaskDescription2

AV0003
220003
TaskDescription3

AV0004
220003
TaskDescription4

I need to get this results
ResultTable

TaskCode
WorkCode
TaskDescription
WorkDescription

220001

WorkDescription1

AV0001
TaskDescription1

220002
AV0002
TaskDescription2
WorkDescription2

220003
AV0003
TaskDescription3
WorkDescription3

220003
AV0004
TaskDescription4
WorkDescription3

220004

WorkDescription4

I've tried several queries, but it lefts out the TaskCodes that have no WorkCode associated:
WrongResultTable

TaskCode
WorkCode
TaskDescription
WorkDescription

220001

WorkDescription1

220002
AV0002
TaskDescription2
WorkDescription2

220003
AV0003
TaskDescription3
WorkDescription3

220003
AV0004
TaskDescription4
WorkDescription3

220004

WorkDescription4

Can someone help me?
Thank you

A: It's not very elegant, but see below.
--This section is just creating the temp tables with the data you provided.
DECLARE @WorkTable TABLE (
WorkCode INT,
WorkDescription NVARCHAR(50))

INSERT INTO @WorkTable (WorkCode, WorkDescription)
VALUES (220001, 'WorkDescription1') , (220002, 'WorkDescription2'), (220003, 'WorkDescription3'),  (220004, 'WorkDescription4')

DECLARE @TasksTable TABLE (
TaskCode NVARCHAR(50),
WorkCode INT ,
TaskDescription NVARCHAR(50))

INSERT INTO @TasksTable (TaskCode, WorkCode, TaskDescription)
VALUES ('AV0001', NULL, 'TaskDescription1') , ('AV0002', 220002, 'TaskDescription2'), ('AV0003', 220003, 'TaskDescription3'),  ('AV0004', 220003, 'TaskDescription4')

;

--Actual SQL query starts here
WITH a as (
select distinct w.WorkCode, t.TaskCode, t.TaskDescription, w.WorkDescription
from @WorkTable w
LEFT JOIN @TasksTable t
    on t.WorkCode = w.WorkCode) ,

b as (
SELECT distinct a.WorkCode, tt.TaskCode, tt.TaskDescription, a.WorkDescription
FROM @TasksTable tt
left join a
        on tt.WorkCode = a.WorkCode) ,

c as (

select *
from a

union all

select *
from b)

select distinct c.WorkCode, c.TaskCode, c.TaskDescription, c.WorkDescription
from c


text:
Q: Parse callback after Oncreate and how to pass data to Fragments When I use Parse Query to retrieve data from Parse DB, I found that data existed after Oncreate() all executed but I need to pass the retrieved data to the FragmentAdapter in order to pass data to the three Fragments, and set the corresponding textView.
These are part of the code inside Oncreate()
try {
            loadData();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        initSpinner();
        viewPager = (ViewPager)findViewById(R.id.detail_tab_viewpager);
        if (viewPager != null){
            setupViewPager(viewPager);
        }

        TabLayout tabLayout = (TabLayout)findViewById(R.id.detail_tab_layout);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

These are codes of loadData(),
JD and Req are declared in this way in a AppCompatActivity class called "InternDetailActivity":
final List JD = new ArrayList();
final List req = new ArrayList();
The problem is I need to set the FragmentPagerAdapter and pass the List JD and req with data to the three fragments after Parse callback, but not before the Parse callback. I set the Toast.makeText to see the sequence of code run and it is wrong in order. the List of JD and req size keeps zero during Oncreate() even i called loadData(). Please explain why as I am not professional programmer but I am willing to learn the basic concept. And any suggestion..., Thanks!!~
public void loadData() throws InterruptedException {
    // TODO Auto-generated method stub
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pd.setMessage("Loading Data");
    pd.setIndeterminate(false);
    pd.setCancelable(false);
    pd.show();

    Thread LoadData = new Thread(){

    public void run(){
        try{
            ParseQuery<Jobs> query = ParseQuery.getQuery(type);

            query.getInBackground(InternDetailActivity.this.job_id, new GetCallback<Jobs>(){

                            @Override
                            public void done(Jobs Jobs, ParseException e) {
                                // TODO Auto-generated method stub

                            Log.v("TESTING INSIDE 1", Integer.toString(JD.size()));
                            if(e==null){
                            JD.add(Jobs.getDescription());
                            req.add(Jobs.getReq());
                            MainApplication.tempjd = Jobs.getDescription();

                            if(e==null && Jobs.getList("Comment")!=null){

                                Log.v("Check Array",Jobs.getList("Comment").get(0).toString());
                                if(Jobs.getList("Comment").size()>0){
                                  for(int i=0;i<=Jobs.getList("Comment").size()-1;i++){
                                  gossip.add(Jobs.getList("Comment").get(i).toString());
                                  }
                                }
                            }

                            else{

                            }

                            }

                            else{

                            }

                            pd.dismiss();

                            }
            });

        }
        finally{
            interrupt();
        }
    }};

    LoadData.start();

}

setupViewPager code:
private void setupViewPager(ViewPager viewPager){
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new GossipFragment(), "Gossip");
    adapter.addFrag(new JDFragment(), "JD & Req");
    adapter.addFrag(new PrepareFragment(), "Preparation");
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(5);
}

ViewPagerAdapter code, I think people should be very familiar with this, haha
static class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<Fragment>();
    private final List<String> mFragmentTitleList = new ArrayList<String>();

    public ViewPagerAdapter(FragmentManager manager){
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position){
        return mFragmentTitleList.get(position);
    }
}

A: Do the Parse update from in the fragment.
Do the ArrayAdapter for the VP in the same fragment.
Consider using a 'ViewHolder' pattern with the adapter ( google it)
Use a Model or the idea of a Model as common object collaborates with:
Parse Insert
Parse Callback ( if necessary for getting OID into the model )
Model to Array, Array Element to ViewHolder thats used by Adapter
On a CallBack from parse insert, call a function that inserts a model's required attribute into the Adapter's Array. Depend on adapter type you may have to use special "insert() " method .
Then, call the "notifyall()" on the adapter.
It should all just work.


text:
Q: Javascript count checked checkbox I know that may have a few similar questions @stackoverflow, but I didnt found any solution to my problem yet :s
<?php
while($rowVideo = mysql_fetch_array($ResultQueryVideo))
{
?>
<input type="checkbox" name = "checkbox-1[]" class="checkbox" value ="<?php echo $rowVideo['idVideo'] ?>" /> <?php....some code...

This results a few checkbox's, the same number as idVideo..thats the point.
Now, before the submit, I need to be sure that at least one checkbox is checked. But i was not sucesseful :x
function isCountCheck (helperMsg) {
    var chkCnt = 0;
    var Frm = document.forms[0];
    var dLen = Frm.length - 1;
    for (i=0;i<=dLen;i++) {
        if(document.form1.["checkbox-1[]"].checked) chkCnt++;
    }

    if (chkCnt>0) {
        return true;
    } else {
        alert(helperMsg);
        return false;
    }
}

Extra details:
form name = "form1"
Can you guide me a litle ?
Thanks
EDIT:
function isCountCheck(){
    if($("input[type=checkbox]:checked").length > 0)
    {
    return true;
    }
    else
    {
    alert('Invalid');
    return false;
    }
}

But still not working..even that alert is shown..

A: The main problem is that you're not using the i index within the loop to reference the individual checkboxes, and you've got a . just before the [ which is a syntax error. So change:
if(document.form1.["checkbox-1[]"].checked) chkCnt++;

To:
if(document.form1["checkbox-1[]"][i].checked) chkCnt++;

But you can neaten up the function somewhat as follows:
function isCountCheck(helperMsg) {
    var i, dLen = document.form1["checkbox-1[]"].length;
    // if the length property is undefined there is only one checkbox
    if (typeof dLen === "undefined") {
        if (document.form1["checkbox-1[]"].checked) return true;
    }
    else {
        for (i = 0; i < dLen; i++) {
            if (document.form1["checkbox-1[]"][i].checked) return true;
        }
    }
    alert(helperMsg);
    return false;
}

Demo: http://jsfiddle.net/nnnnnn/ZjK3w/1/
Or just loop through all inputs in the form, checking the type (and/or the name) of each one:
function isCountCheck(helperMsg) {
    var i, len, inputs = document.form1.getElementsByTagName("input");
    for (i = 0, len = inputs.length; i < len; i++) {
        if (inputs[i].type === "checkbox"
            && inputs[i].checked)
            return true;
    }
    alert(helperMsg);
    return false;
}

Demo: http://jsfiddle.net/nnnnnn/ZjK3w/2/

A: Simplest solution:
var form = document.forms[0]; // your form element (whatever)
var checkedElms = form.querySelectorAll(':checked').length;

No need for jQuery. Supported down to IE8. use polyfill for older browsers if you wish.

A: Use Jquery:
function isCountCheck(helperMsg){
    if($("input[type=checkbox]:checked").length > 0)
        return true;
    alert(helperMsg);
    return false;
}


text:
Q: MySQL Function only once with group by I have the following statement:
SELECT user_id, myMysqlFunction(user_id) FROM users_to_days GROUP BY user_id;

The table stores one row per user and day.
The problem is that MySql calls the Function "myMysqlFunction(user_id)" for every row and groups the rows after that.
My target is to execute the Function just once (for performance reasons).
I tried the following state without success:
SELECT user_id, IF(`date` = min(`date`),myMysqlFunction(user_id),0) FROM users_to_days GROUP BY user_id;

MySql still executes the statement for every row.
If I write a static date (for example '2014-09-01') - it works:
SELECT user_id, IF(`date` = '2014-09-01',myMysqlFunction(user_id),0) FROM users_to_days GROUP BY user_id;

But I don't know the min. date for the user at the time of execution. (its not the same for every user)

A: you could try a subquery:
SELECT user_id, myMysqlFunction(user_id)
FROM (SELECT user_id
      FROM users_to_days
      GROUP BY user_id);

A: Edit: comment got split up, I wanted to say:
I meant: try $date = date('Y-m-d');, that will get the time the user runs it. Put that in min($date), and it should be working.


text:
Q: Ubuntu 11.10 Faulty install, how do I rollback or troubleshoot? So stupidly I allowed the upgrade of Oneiric before I thought better of it. I have gone through the installation and it has evidently bricked.
Errors observed:

*

*Eternally stuck at loading screen

*Network connection failed waiting 60 seconds

*initctl event failed

*modem_manager[1153] Could not get system bus

Could someone give me a hand figuring out exactly what is going on?
After F6'ing at startup this is what I get


text:
Q: GET NOT by primaryKEY I am using this function to query a table by its primary ID.
 public virtual List<TModel> LoadAllWithChildren()
 {
     lock(Connection)
     {
         var result = LoadAll();

         foreach (var item in result)
         {
             try
             {
                 Connection.GetChildren(item);
             }
             catch (Exception e)
             {
                DebugTraceListener.Instance.WriteLine(GetType().Name,
                     "Can not load Child for itemType: " + item.GetType().Name + " reason: " + e);
             }
         }

         return result;
     }
 }

But this always return results in regards to the primary key. The table I am querying on looks like this:

So when I do this, I get all entries in this table (not just the ones you see in the picture, those are the ones that I want)
So I did a small workaround:
 var persistance = await Task.Run(() => PersistenceService.PresentationSequence.LoadAllWithChildren());
                 List<PresentationSequence> resSequence = new List<PresentationSequence>();
                 foreach(var elem in persistance)
                     if (elem.PresentationId == 166)
                         resSequence.Add(elem);

The result is the list as seen in the picture.
This, however, is slow.
Is there a way to use another SQlite function that will give me the list already filter for "166" in "presentationID"?
(So no local work is done)
EDIT: I have tried using this function:
public virtual TModel LoadById(int id)
        {
            lock(Connection)
            {
                try
                {
                    var result = Connection.Get<TModel>(id);
                    return result;
                }
                catch (Exception ex)
                {
                    DebugTraceListener.Instance.WriteLine(GetType().Name, $"Cannot find item with ID: {id}\n\n{ex}");
                    return null;
                }
            }
}

But this will only take the primary key in. But I want to query for presentation ID and not get a single result from the ID column

A: I ended up going with the query function:
try
                {
                    var result = Connection.Query<TModel>(querystring);
                    return result;
                }


text:
Q: Appending linearly independent vectors Suppose i have a set of linearnly independent vectors v1,v2,v3 outside span[b1,b2] and i wanna check that $v_1,v_2,v_3,b_1,b_2$ forms a linearnly independent set.
Can i do this mini-checkups of linearnly independence :
1 - $b_1,b_2,v_1$ ;
2 - $b_1,b_2,v_2$ ;
3-  $b_1,b_2,v_3$ ;
4 - $b_1,b_2,v_1,v_2$ ;
5 - $b_1,b_2,v_2,v_3$ ;
to conclude that $v_1,v_2,v_3,b_1,b_2$ are linearly independent ?
Do I also need the last test :
6 - $b_1,b_2,v_1,v_3$ ; ?
Or actually the only way is to append one by one and check if it remains linear independent until I append every vector ?
If I can do the mini-checks, can I generalize to any number of vectors $b_1,b_2,...,b_z$ and $v_1,v_2,...,v_n$ provided I do the necessary mini-checks ( dictated by combinatorics ) ?

A: It is possible to have a set of $n$ linearly dependent vectors such that all nonempty proper subsets are linearly independent.
For example, in $\mathbb{R}^{n-1}$, take the standard basis vectors $e_1,\ldots,e_{n-1}$ along with the vector $e_1+\ldots+e_{n-1}$.  All together, the vectors form a linearly dependent set, but any $n-1$ of them are linearly independent.
So to check for linear independence, you cannot do so by 'mini-checks'.


text:
Q: About a Lipschitz property $\|f^{\mu}(x)-f^{\mu}(y)\| \leq L^{\mu}\|x-y\|^{\mu}$ For a function $f(x)=[f_1(x),f_2(x),\cdots,f_m(x)]^T:\mathbb{R}^n\to\mathbb{R}^m$ where $f_i(x):\mathbb{R}^n\to \mathbb{R}$ is a real-value function, $f(x)$ is Lipschitz, i.e., there exists a positive real constant $L$ such that $\|f(x)-f(y)\|\leq L\|x-y\|$.
Then, the question is whether there exist the following inequations
$$\|f^{\mu}(x)-f^{\mu}(y) \|\leq L^{\mu}\|x-y\|^{\mu}, \forall \mu>1,$$
and
$$\|f^{\mu}(x)-f^{\mu}(y)\| \leq L^{\mu}\|x-y\|^{\mu}, \forall \mu<1$$
where $f^{\mu}(x)=[f_1^\mu(x),f_2^\mu(x),\cdots,f_m^\mu(x)]^T$.
Thanks very much.

A: Clearly we need $f\ge0$ if $\mu$ is not an integer, which I will assume.

$\mu > 1:$

Simple counterexample in dimension 1. let $f:\mathbb R\to\mathbb R$, $f(x)=x$, $y=1$, and $\mu=2$. Then
the wanted inequality is
$$ |x^2 - 1| \stackrel{?}{\le} C(x-1)^2$$
Lets put $x=1+\epsilon$, for $\epsilon>0$. Then this reads
$$ \epsilon^2 + 2\epsilon\stackrel{?}{\le} C\epsilon^2 $$
which is easily seen to be  wrong for any $C>0$, once $\epsilon\ll1$.
In fact, the inequality implies that $f$ is everywhere differentiable with derivative $0$, so the only such $f$ are (locally) constant.

$\mu \in (0,1)$:

This is true, at least up to a constant. Recall that $x^\alpha$ is $\alpha$-Hölder with constant 1. So for each coordinate, we have
$$ |f_i^\mu(x) - f_i^\mu(y)| \le |f_i(x) - f_i(y)|^{\mu} \le L^\mu |x-y|^\mu$$
which implies the result with a potentially different constant depending on the precise choice of norm $\|\cdot\|$.


text:
Q: Multiple Fields for Prefix in ElasticSearch and auto From and Size limit I got 2 questions related to ElasticSearch.
1) First Question, I have this query with prefix
"must": [
        {
           "prefix": {
              "user": "John"
           }
        }
     ]

with this query, I can Prefix John with User field so it results those documents in which John is found in User field. Now how can I make this query to see if John is prefixed in either any of User or email fields.

2) Second Question, I know we can apply Size and from in ElasticSearch to limit Result but I want to know that do I have to explicitly provide  Size and from every time I query in ElasticSearch to continue last result or is there any other way to let the ElasticSearch do it for me that I just query and it will give results in a series left from previous.

A: First, note that the prefix-query does not do any text analysis, so you will not be matching e.g. john with your query.
You should look into the multi_match-query which takes the options of the match-query as well. Thus, you can combine multi_match with phrase_prefix and get the best of both: matching on multiple fields, and text analysis.
Here is a runnable example you can play with: https://www.found.no/play/gist/8197442
#!/bin/bash

export ELASTICSEARCH_ENDPOINT="http://localhost:9200"

# Index documents
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '
{"index":{"_index":"play","_type":"type"}}
{"user":"John Smith","email":"john.smith@gmail.com"}
{"index":{"_index":"play","_type":"type"}}
{"user":"Alice Smith","email":"john.smith@gmail.com"}
'

# Do searches

curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
    "query": {
        "multi_match": {
            "fields": [
                "user",
                "email"
            ],
            "query": "john",
            "operator": "and",
            "type": "phrase_prefix"
        }
    }
}
'

For your second question, look into the scroll API.


text:
Q: Seeding Database Setting Max Length Im trying to seed my database with Faker.net because I need a lot of data generated, is it possible to set the phone numbers to only create 11 numbers long?
var addresses = Builder<deliveryAddress>.CreateListOfSize(40)
                .All()
            .With(c => c.FirstName = Faker.Name.First())
            .With(c => c.LastName = Faker.Name.Last())
            .With(c => c.Address = Faker.Address.StreetAddress())
            .With(c => c.City = Faker.Address.City())
            .With(c => c.Country = Faker.Address.UkCountry())
            .With(c => c.PostalCode = Faker.Address.UkPostCode())
            .With(c => c.Mobile = Faker.Phone.Number().)
            .With(c => c.Phone = Faker.Phone.Number())
                .Build();

            context.deliveryAddresses.AddOrUpdate(c => c.AdressId, addresses.ToArray());

A: Based on Faker.NET source code, Faker.Phone.Number() can take a parameter. You can pass the pattern string like "###-####-#####" as a parameter to Faker.Phone.Number(string pattern).
Saw your question on the phone, haven't got chance to test it.

A: Use String format to limit your string Characters.
Ex. String.Format("{0:(###) ###-####}", 9912345678);
This will output "(991) 234-5678".

Or also you can try:
const int MaxLength = 11;
var name = "1234567910123456";
if (name.Length > MaxLength)
name = name.Substring(0, MaxLength); // name = "12345678910"

or Refer this trik.


text:
Q: How to determine if url is being requested from Facebook iFrame? I have a Google App Engine application and I want to serve a different django template if the request comes in from the Facebook Application.  How can I detect that?  I don't see anything unique in the Header.
I'm currently using the URL pattern:
r'/user/(.*)'

to map to a "user" request handler.  I suppose I could instead do:
r'/(.*)/user/(.*)'

and parametrize the first part of the path and check for 'facebook'.  This would require that I ensure all internal links served in the facebook iFrame are /facebook/.  Is there any danger in this approach?

A: .run_wsgi_app(webapp.WSGIApplication([(r'/page/(.*)', Page),
                (r'/user/(.*)', UserProfile),
                (r'/category/(.*)', CategoryProfile),
                (r'/location/(.*)', LocationProfile),
                (r'/facebook/page/(.*)', Page),
                (r'/facebook/user/(.*)', UserProfile),
                (r'/facebook/category/(.*)', CategoryProfile),
                (r'/facebook/location/(.*)', LocationProfile),
                ('/facebook/', BaseHandler),
                ('/', BaseHandler)],
                debug=DEBUG))

Then in each Handler I checked for a /facebook/ path:
if re.search(r".facebook\.*", path):

If True, then I directed to the appropriate "facebook" template.

A: Best way to detect facebook iframe is to compare HTTP_REFERER
import os
if os.environ['HTTP_REFERER'].find('http://apps.facebook.com/<Facebook_URLID>/') is not 0:
   self.redirect('<Facebook_Application_Page>')

just beware that it might not be there all the time so detect for the key first.
if your referer matches with your application url then pass the control else redirect the page to your facebook application.
Hope this helps you. :)


text:
Q: What else should I be doing to sanitize user input? Recently, I had an audit run on some of my sites by a client.  One of the things they came back with was that I could be sanitizing the input data a little better as people could still cause potential harm to the database.
The function below is what I am currently using (a leftover from the old developer) but I cannot see where the potential issue may lie.
The string that gets passed through to the database will be displayed via XML which in turn is read by a Flash application.
Could anyone tell me what I might be missing? Thanks
function secure_string($string)
{
    return (strip_tags(addslashes(mysql_real_escape_string(
                      stripslashes($string)))));
}

A: It looks like there's too much going on in that function. mysql_real_escape_string() already escapes everything you need to escape, so there's no need to run addslashes() on that. In fact, it could do more harm than good by escaping the backslashes mysql_real_escape_string() creates.

A: Better use the new PHP function filter_var() for cleaning input. New and better.

A: mysql_real_escape_string is the last step, you shouldn't use it your application logic. It's sole purpose is to pass strings to the database, so use it only when constructing queries. You can pass anything to mysql_real_escape_string and it will make sure you can safely store it in the database.
For the rest, it depends what do you want. If you want to strip tags, use strip_tags, etc.

A: Depends on where the "secured" string will be used. If it's going to be used in the database, you only need mysql_real_escape_string(), nothing more. If it's going to be displayed in html, you only need htmlentities(), nothing more. In short: your code is doing way too much, which could even be harmful.
If you want to store it in the database for displaying it in html lateron (like a comment, for example), you should be using mysql_real_escape_string() when storing the string and htmlentities() when displaying it.

A: If your server uses php 5.2 or better, you should use filter_var for the XML part.
$output = filter_var($input, FILTER_SANITIZE_STRING);

To store something into your database, use PDO and parameterized queries.

A: It's a misnomer to try and fix the problem at input time, since the problem happens at output time. See my answer over here:
What's the best method for sanitizing user input with PHP?


text:
Q: Objective C, app crashes when changing root view controller. Orphaned without delegate (bug!) I've implemented a dropdown menu into my iOS app that calls functions to navigate between different storyboards. Each element in that menu calls the following function in the AppDelegate class with a different storyboard name:
(void)changeController:(NSString*)storyboardName
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];

    //initialize the new view
    currentView = [storyboard instantiateInitialViewController];
    currentView.view.alpha = 0.0;
    currentView.view.frame = currentView.view.bounds;
    currentView.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    //the app crashes on this line with a Thread 1: signal SIGARBT message
    self.window.rootViewController = currentView;
    [self.window makeKeyAndVisible];

    //animate with a fade transition
    [UIView animateWithDuration:transitionDuration
                          delay:0.0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{currentView.view.alpha = 1.0;}
                     completion:^(BOOL finished){}];
}

The problem is that the function that gets called crashes the app inconsistently. It works from some screens and not others. And even worse, it sometimes works on screens that it normally crashes on.
There are two error messages that get dumped to the console, and they are (I've added line breaks for readability):
Objective: {
 objective 0x15e4b3c0: <750:-1.64135e-05> + <750:8.34465e-08>
 *<orphaned without delegate (bug!):0x1703c790>{id: 188} + <750:4.17233e-08>
 *<orphaned without delegate (bug!):0x1703c980>{id: 192} + <750:-2.68221e-08>
 *UIView:0x170c6e40.Height{id: 1091}
}

and
uncaught exception: <NSISEngine: 0x15e0b380>{ Rows:
    UIWindow:0x15db3160.Height{id: 140} == 960 + 1*0x15dd03e0.marker{id: 144}
    UIWindow:0x15db3160.Width{id: 137} == 640 + 1*0x15dd03b0.marker{id: 141}
    UIWindow:0x15db3160.minX{id: 136} == 0 + 2*0x15dd0200.marker{id: 135} + -0.5*0x15dd03b0.marker{id: 141}
    UIWindow:0x15db3160.minY{id: 139} == 0 + 2*0x15dd0350.marker{id: 138} + -0.5*0x15dd03e0.marker{id: 144}
    objective{id: 1} == {
         objective 0x15e4b3c0: <750:-1.64135e-05> + <750:8.34465e-08>
         *<orphaned without delegate (bug!):0x1703c790>{id: 188} + <750:4.17233e-08>
         *<orphaned without delegate (bug!):0x1703c980>{id: 192} + <750:-2.68221e-08>
         *UIView:0x170c6e40.Height{id: 1091}}

     Constraints:
         <NSAutoresizingMaskLayoutConstraint:0x15dd03b0 h=--- v=--- H:[UIWindow:0x15db3160(320)]>       Marker:0x15dd03b0.marker{id: 141}
         <NSAutoresizingMaskLayoutConstraint:0x15dd03e0 h=--- v=--- V:[UIWindow:0x15db3160(480)]>       Marker:0x15dd03e0.marker{id: 144}
         <_UIWindowAnchoringConstraint:0x15dd0200 h=--- v=--- UIWindow:0x15db3160.midX == + 160>        Marker:0x15dd0200.marker{id: 135}
         <_UIWindowAnchoringConstraint:0x15dd0350 h=--- v=--- UIWindow:0x15db3160.midY == + 240>        Marker:0x15dd0350.marker{id: 138}

    Integralization Adjustments:
         (none)

    Statistics:
    4 rows. Variable counts:
            1 ->   2
            2 ->   2
}: internal error.  Cannot find an outgoing row head for incoming head UIView:0x170c6e40.Height{id: 1091}, which should never happen.

It's the last line that really confuses me, "internal error .... which should never happen."
I'm curious if anyone else has encountered this error, and how they tackled it.

*

*Is this an issue with initializing the variable currentView, or perhaps something to do with the AppDelegate's window variable?

*Is this really an issue with storyboard constraints? And if so, is there a limit to the number of constraints I can/should put on a single screen?

EDIT:
I figured out that the error was really only caused when navigating away from one particular storyboard. A constraint on the screen was throwing the error.
So I added some code to the changeController: to programmatically remove the constraints from every subview and then remove every subview from the superview.
The problem was ultimately resolved when the constraints in the offending UIViewController were cleared and recreated.
Thanks for all your help and suggestions.


text:
Q: Маршрутизация между vlan Имеется следующая схема сети:

в iptables:
iptables -A FORWARD -i eth0.2 -o eth0.4 -s 192.168.2.0/24 -d 192.168.4.0/24 -j ACCEPT
iptables -A FORWARD -i eth0.4 -o eth0.2 -s 192.168.4.0/24 -d 192.168.2.0/24 -j ACCEPT

На сервере CentOS 6.5
Проблема в том, что ПК 192.168.2.228 почему-то не получает ответы на пинг от ПК и роутера из vlan2, ответ от принтера приходит. В то же время сервер получает ответы от всех устройств.
Как заставить проходить пинги с vlan1 в vlan2 и обратно без проблем для всех устройств?

A: То что не проходят пинги от определённых устройств говорит о том,
что эти устройства (скорее всего) просто не знают, куда посылать ответ.
Если маршрут в сеть 192.168.2.0/24 неизвестен на тех устройствах, с которых ответ не приходит, то именно в этом и заключается причина.
iptables в данном случае никак этому не мешает.
Чтобы убедиться в правильности данного предположения, вы можете:

*

*Проверить маршруты на устройствах;

*Запустить tcpdump на роутере и посмотреть, возвращаются ли ответы или нет.

Пример tcpdump:
sudo tcpdump -i eth0.2 -n icmp

В данном случае мы смотрим, идут ли ответы через интерфейс eth0.2.
Обновление
Вероятнее всего, что на устройствах, с которых не приходят ответы
просто не установлен маршрут по умолчанию.

A: Проверьте установку маршрутов к 192.168.2.0/24 на тех устройствах  в в vlan2 от которых не проходят пинги. Очень похоже на то что неправильно натсроены таблицы маршрутизации.


text:
Q: Как удалить все optinons из select? Использую selectize.js для модификации выпадающего списка. При выборе пункта в марках авто, аяксом грузится опции для списка Сервисных центров. Все приходит правильно, и аякс работатет, но вот проблема в том что почему то остаются опции от предыдущих выборов, как очистить все опции из списка сто перед отправкой аякса?

/*выбор МАРКи АВТО*/
var $selectAuto = $('.js-select').selectize({});

/*выбор СЕРВИСНЫЙ ЦЕНТР*/
var $selectService = $('.js-select-services').selectize({
  labelField: 'name',
  valueField: 'value',
  render: {
    option: function(data) {
      //console.log(data);
      return '
' + data.text + '
';
    },
    item: function(data) {
      //console.log(data);
      return '
' + data.text + '
';
    }
  }
});

var $selectServiceSelectize = $selectService[0].selectize;
var $selectAutoSelectize = $selectAuto[0].selectize;

$selectAutoSelectize.on('change', function(value) {
  $.ajax({
    type: 'POST',
    url: '/ajax/salons.php',
    dataType: 'json',
    data: {
      brand: value
    },
    success: function(response) {
      $selectServiceSelectize.load(function(callback) {

        $.each(response, function(value, text) {
          callback([{
            text: text,
            value: value
          }]);
        });
      });
    }
  })
})
<select name="brand" id="type-cars" class="js-select" data-typecars="all" size="1" name="form_text_<?=$arResult[" QUESTIONS "]["BRAND "]["STRUCTURE "][0]["ID "]?>">
  <option value="" data-type="">Выберете марку</option>
  <? $res=C IBlockSection::GetList(array( "SORT"=>"ASC"), array("IBLOCK_ID" => 40, "ACTIVE" => "Y"), false, array("ID", "NAME"), false); while ($ob = $res->GetNext()) { ?>
  <option value="<?=$ob[" NAME "]?>" data-type="type-cars">
    <?=$ob[ "NAME"]?>
  </option>
  <? } ?>
</select>

сервисный центр

<select name="services" id="type-services" class="js-select-services" data-typecars="all" size="1" name="form_text_<?=$arResult[" QUESTIONS "]["SERVICE_CENTER "]["STRUCTURE "][0]["ID "]?>">
  <option value="" data-type="">Выберете марку</option>
</select>

A: Если судить по этому вопросу и ответам к нему то вам надо вызвать $selectServiceSelectize.clear() перед отправкой AJAX. Т.е. будет что-то такое:
$selectAutoSelectize.on('change', function(value) {
  $selectServiceSelectize.clear();
  $.ajax({
    type: 'POST',
    url: '/ajax/salons.php',
    dataType: 'json',
    data: {
      brand: value
    },
    success: function(response) {
      $selectServiceSelectize.load(function(callback) {

        $.each(response, function(value, text) {
          callback([{
            text: text,
            value: value
          }]);
        });
      });
    }
  })
})


text:
Q: Error in outer() function in R for a specific case I have a matrix X of dimensions 942*50.
I want to create an affinity matrix with the Gaussian RBF Kernel. ie, for every pair of rows in the X matrix, I want to compute exp(-sigma*norm(x_i-x_j)^2) where x_i and x_j are rows of the X matrix and i,j vary from 1:nrow(X).
I am writing the code in R.
The piece of R code below throws up an error:
library('kernlab')
rbf <- rbfdot(sigma=15.0563)
func <- function(i,j){return(rbf(X[i,],X[j,]))}
rows <- cols <- 1:nrow(X)
outer(rows,cols,FUN=func)

I get the following error:
Error in outer(rows, cols, FUN = fun) :
  dims [product 887364] do not match the length of object [2500]

A: Outer expects a vectorized function (see ?outer). Hence your code should be:
library('kernlab')
rbf<-rbfdot(sigma=15.0563)
func<-Vectorize(function(i,j){return(rbf(X[i,],X[j,]))})
rows<-1:nrow(X)
cols<-1:nrow(X)
outer(rows,cols,FUN=func)


text:
Q: How can I get the current location? What is the easiest and shortest method to determine the current location of the device in Android? An approximate, city-level location is good enough, and I need the Lat/Long coordinates, not the name. Think of weather location. But I'm using it for sunrise/sunset calculations.
All other examples here on StackOverflow and the web are at least a page long and rely on callbacks. But I'm in the middle of a watch face draw function and can't wait for callbacks. I just want to get the last known location that is certainly already lying around somewhere in memory.
One answer pointed me to LocationManager.getLastKnownLocation() but Android Studio says it doesn't know that method. So it's probably outdated and removed from more recent APIs.
I'm new to Android development and don't have a clue where to search. Web snippets brought me here but this time no further.

A:
But I'm in the middle of a watch face draw function and can't wait for callbacks.

Frequently, you don't have a choice.

I just want to get the last known location that is certainly already lying around somewhere in memory.

Frequently, it is not lying around in memory.

One answer pointed me to LocationManager.getLastKnownLocation() but Android Studio says it doesn't know that method.

That method exists, as is seen in the documentation for that method.
Since your question does not have the code that you are trying, it is difficult for anyone to help explain why that code is not compiling. Perhaps you are trying to call getLastKnownLocation() on the LocationManager class, rather than an instance of LocationManager.
Bear in mind that getLastKnownLocation() frequently returns null, as the device usually is not actively tracking the user location. Also, the user may have disabled location access, or the device might be in airplane mode (and so has no access to non-GPS sources), or the device might be in a facility that leads to crappy signals (e.g., large parking structures), etc.
You could also use the Play Services' fused location provider, but it requires a callback.

A: Being in the middle of a watch face draw function or not should not make a difference.
Most of the snippets you will find on the web will indeed tell you to use callbacks. Not because it's "ok" in some cases, but because it is how the system works.
On a high level :
You'd let the system know that you're interested in the location of the device.

The system then starts computing information.

When a position has been determined, and then every-time the location changes significantly enough (as defined via accuracy), the system will let you know what the actual position of the device now is (through these callbacks).

My recommendation :
Start implementing this logic when the watch face renderer is created. Have the option to display a "location not known" (as @CommonsWare mentioned, location can be unavailable for a bunch of different reasons). And have your proper way (eventually) of storing the last know location (SharedPref sounds like a good option).

A: add these permissions to your manifest.xml

implement LocationListener in your activity, a method from this class will give you updates on the android devices location as it changes
@Override
public void onLocationChanged(Location location) {

}

call this startGettingLocations method in your oncreate method of the activity so that all permissions needed can be requested from the user
private void startGettingLocations() {
        Log.i("Process", "start getting locations");
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetwork = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean canGetLocation = true;
        int ALL_PERMISSIONS_RESULT = 101;
        long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100;// Distance in meters
        long MIN_TIME_BW_UPDATES = 1000 * 10 * 6 ;// Time in milliseconds

        ArrayList<String> permissions = new ArrayList<>();
        ArrayList<String> permissionsToRequest;

        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissionsToRequest = findUnAskedPermissions(permissions);

        //Check if GPS and Network are on, if not asks the user to turn on
        if (!isGPS && !isNetwork) {
            showSettingsAlert();
        } else {
            // check permissions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (permissionsToRequest.size() > 0) {
                    requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
                            ALL_PERMISSIONS_RESULT);
                    canGetLocation = false;
                }
            }
        }

        if(ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            Log.i("Permissions", "fine loc not granted");
        } else{
            Log.i("Permissions", "fine loc granted");
        }

        if(ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            Log.i("Permissions", "coarse loc not granted");
        } else{
            Log.i("Permissions", "coarse loc granted");
        }

        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission not Granted", Toast.LENGTH_SHORT).show();
            return;
        }

        //Starts requesting location updates
        if (canGetLocation) {
            if (isGPS) {
                lm.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

            } else if (isNetwork) {
                // from Network Provider
                lm.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            }
        }
        else{
            Toast.makeText(this, "Can't get location", Toast.LENGTH_SHORT).show();
        }
    }


text:
Q: How to make a wicket component that's re-rendered on every AJAX request to a page? Is there a way to make a Wicket component re-render itself on every AJAX request to a page? (Essentially to do what ajaxRendered="true" does in RichFaces.)
My application basically consists of the following:

*

*An editable datagrid records changes the user is doing

*These changes are stored in the session

*There are buttons to save the changes or to undo them.

The save and undo buttons should be enabled or disabled depending on if there are any recorded changes or not. Since there's several ways to input changes (editing, importing a CSV, etc.), I want to avoid having to intercept every action that might change the saved state.
Also, the buttons are only shown on some pages, so I don't want to have to sniff them in the page in a custom WebRequestCycle.
Is there a hook that Wicket calls when an AJAX request is about to be processed, that's called for every component on the page? I know there's Component#onBeforeRender() and Component#onConfigure(), but the documentation for them doesn't state when they're called for AJAX requests.

A: In Wicket 1.5 there is an event bus. For each Ajax request an event is sent to each component and the component can use AjaxRequestTarget to add itself for re-render.
E.g.:
class MyComponent ... {

 public void onEvent(Object payload) {

   if (payload instanceod AjaxRequestTarget) {
     ((AjaxRequestTarget) payload).add(this);
   }
 }

A: I was having a similar problem and thought of two possible solutions from which I used the second one.

*

*Call a method on your page in the Ajax-Handler, which in turn invokes a visitor to find all childs that need to be rerendered, adding them to the target.

*A variation of the observer-pattern...
I had my components register themselves as wantToUpdate at the page and triggered a function, adding them all to the Requesttarget in my Ajax-Handler. I couldn't use the observer pattern out of the box since my components don't know each other and I didn't want to introduce this kind of coupling.


text:
Q: Horizontal CSS Nav Padding differences in Firefox,IE9 vs Chrome, Opera I have a weird problem on a CSS menu. There's a difference in padding applied by both
Firefox & IE9 vs Chrome & Opera browsers. The space left after the last menu item at the end of the menu is different on both the browsers.
Please see the chrome.jpg and firefox.jpg inside zip file to see what I mean.
I have also attached the source html file.
here is the zip file -
https://www.sugarsync.com/pf/D6612639_7394829_952554
Chrome:

Firefox:

A: This is not padding but likely a difference in how the fonts are rendered in different browsers. Yeah that is pretty much impossible to solve unless you make the menu items fixed width. :)
The firefox version looks bolder (see it?!)... These are brainbreaking problems not fun to deal with but quite easy to explain.

A: IE9/Firefox use a different technique to render text than Chrome/Opera do.
IE9/Firefox use DirectWrite, and so the text comes out ever so slightly wider, adding up to a few pixels difference over all the menu items.
Read more here: http://www.basschouten.com/blog1.php/font-rendering-gdi-versus-directwrite
And read this, particularly the "Hinting and spacing differences" section: http://blog.mozilla.com/nattokirai/2011/08/11/directwrite-text-rendering-in-firefox-6/
Short of setting a fixed width on each menu item (don't), you can't fix it. However, you don't need to fix it: a few pixels difference between browsers does not matter. Remember, the users of your site are only looking at it using one browser.


text:
Q: AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync now failing on 4.0-preview with unknown_user I've got some code that uses ADAL v3, which uses the extension method in the title to get a token for the current Windows user. I tried the new v4 package, and now the call fails with "unknown_user: Could not identify logged in user".
Is this a known problem? Or do I need to do something different when using v4?
Here's the basic code I'm using:
$authAuthority = "https://login.microsoftonline.com/common"
$vstsResourceId = "XYZfake"
$vsClientId = "ABCfake"

$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext -ArgumentList $authAuthority
$userCredential = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential

$task = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $vstsResourceId, $vsClientId, $userCredential)
$task.GetAwaiter().GetResult()
$authResult = $task.Result

A: The reason for the failure is that I used the netstandard1.3 binary, and the PlatformInformation.GetUserPrincipalNameAsync() method is a dummy--it just returns an empty string.
    public override async Task<string> GetUserPrincipalNameAsync()
    {
        return await Task.Factory.StartNew(() => string.Empty).ConfigureAwait(false);
    }


text:
Q: double slit experiment question Are the results of this test, observable with the naked eye? the change from an interference pattern to two slits once there is some sort device that can  detect which slit an electron goes through, or is it so small for some reason it can only be measured?
Im just wondering what level of observation  is necessary in order  for this phenomenon  to occur. what is the cutoff point? like if you had a device that could barely detect electrons etc. etc.

A: You can. It's basically an interference pattern, and we see these all the time. I imagine you could set something up with a laser pointer, some slotted paper, some aluminum foil, and a black marker.

A: If you are talking about an at home experiment then shooting individual electrons would be very difficult. Photons would be easier, but still not easy. The way that you see the particle properties of light is you need to fire one at a time so that interference properties are not possible. The strange thing is, the individually fired photons still produce an interference pattern. So the interference pattern will still be created, but it will be created by "particles".  A while back I asked a question similar to yours. Here it is:Is there a double slit experiment that I can perform that will show the photons acting like particles?


text:
Q: Set property with this keyword, javascript How do I set a property in an object which points to an array in the same object?
The "this" keyword seems natural but i get an error.
This is my object. http://jsbin.com/IPuFEpa/1/edit?js,console,output . It is the property "activeFlowUnit" that is not working.
var Converter = {
  flow: {
    valueInSiUnit: 55,
    valueInUserUnit: 0.75
  },
  units: {
    flowUnits: [{
      title: 'm3/s',
      fullTitle: 'cubic meter / second',
      decimals: 5,
      factor: 1
    }, {
      title: 'l/s',
      fullTitle: 'liter / second',
      decimals: 3,
      factor: 1000
    }]
  },
  activeFlowUnit: this.units.flowUnits[0], //Not working
  greet: function(){
    return this.units.flowUnits[0]; //Works
  },
  convertUnit: function(valueInSIUnit, factor, decimalFactor){
    var decimalConvert = Math.pow(10, decimalFactor);
    return  Math.round((valueInSIUnit * factor)*decimalConvert)/decimalConvert;
  }
}

A: You need a function to create the right scope, as that's what functions do
activeFlowUnit: function() {
    return this.units.flowUnits[0];
},

then you would of course have to call it like a function as well

A: You just need to be aware of this :
var o = {
    prop: this === o, // false
    meth: function () {
        this === o; // true
    }
};
this === o; // false

A: I would give the Object.defineProperty a try to have a property with a getter and a setter :
Object.defineProperty(Converter, "activeFlowUnit", {
    get: function activeFlowUnit() {
        if (!this.units.active)
            this.units.active = this.units.flowUnits[0];
        return this.units.active;
    },
    set: function activeFlowUnit(val) {
        this.units.active = val;
    }
});

console.log(Converter.activeFlowUnit);
Converter.activeFlowUnit = Converter.units.flowUnits[1];
console.log(Converter.activeFlowUnit);

DEMO

A: You can't do it within the object initializer itself, there's no way to refer to the object that's being constructed by the initializer from the property initializers, because the object doesn't exist yet.
You can do it afterward, though:
var Converter = {
    // ...all of your other init
};
Converter.activeFlowUnit = Converter.units.flowUnits[0];

The reason this works within functions you use as property initializers is twofold:

*

*The function doesn't get called until later, after the object has been created

*Calling the function via the object reference (Converter.convertUnit) is what sets this.

A: this only points to the current object when a method is invoked. You can just assign the member of object to a temporary variable in the literal:
var units;
var Converter = {
  ...
  units: units = {
    flowUnits: [...]
  },
  activeFlowUnit: units.flowUnits[0], //Works
  ...
}

A: Quite common pattern with object init like that is to have init method.
 var Converter = {
   flow: {
      valueInSiUnit: 55,
      valueInUserUnit: 0.75
   },
   ...
   init : function() {
       this.activeFlowUnit = this.units.flowUnits[0]
   }
 }

 Converter.init()

A: I would rewrite the whole thing creating a prototype for the converter object (that does all the required initializations) and then instantiating object(s) from that.
This way:
// First create a prototype of your converter...

// ...this is the constructor

function Converter(params) {
    this.flow  = params.flow;
    this.units = params.units;
    this.activeFlowUnit = this.units.flowUnits[0];
}

// ...these are the methods

Converter.prototype.greet = function() {
    return this.units.flowUnits[0];
};

Converter.prototype.convertUnit = function(valueInSIUnit, factor, decimalFactor) {
    var decimalConvert = Math.pow(10, decimalFactor);
    return  Math.round((valueInSIUnit * factor)*decimalConvert)/decimalConvert;
};

// Then instantiate an object passing the parameters

var converter = new Converter( {
    flow: {
        valueInSiUnit: 55,
        valueInUserUnit: 0.75
    },
    units: {
        flowUnits: [{
            title: 'm3/s',
            fullTitle: 'cubic meter / second',
            decimals: 5,
            factor: 1
        }, {
            title: 'l/s',
            fullTitle: 'liter / second',
            decimals: 3,
            factor: 1000
        }]
    }
} );

Now
this.activeFlowUnit = this.units.flowUnits[0];

has a scope as this points to the new intatiated object.


text:
Q: how to pass the argument of a user-defined function to be a column name in data.table? How can I pass an argument to be a column name of data.table in side the function?
For example, I have a data called data1 with columns called 'hours' and 'location'. In the output, I want to find the outliers by location and named by 'hours'. I tried use substitute(y) and so forth, The output always uses 'y' as the column name. Could anyone help me? Thank you.
mf<-function(data, y){
newy<-as.name(deparse(substitute(y)))
output<-data[,.(y=boxplot.stats(eval(newy))$out),by=.(location)]
return(output)
}
mf(data=data1,y=hours)

A: It's better to write functions which take character values for choosing columns. In this case, your function can be rewritten as:
mf <- function(data, y){
  output <- data[, boxplot.stats(get(y))['out'], by = .(location)]
  setnames(output, 'out', y)
  return(output)
}

By using [ to subset the output of boxplot.stats, a named list with one element ('out') is returned. So output will have two columns: location and out.  Then you just need to change out to be whatever was given for y.
Example:
set.seed(100)
data1 <- data.table(
  location = state.name,
  hours    = rpois(1000, 12)
)
mf(data = data1, y = 'hours')
#           location hours
#  1:       Delaware    25
#  2:        Georgia    21
#  3:          Idaho     4
#  4:  Massachusetts     5
#  5:       Missouri     7
#  6: South Carolina     5
#  7: South Carolina     6
#  8:   South Dakota    20
#  9:          Texas     5
# 10:           Utah    22

Non-standard evaluation is tricky and only worth the effort if you can get something out of it. data.table uses it for optimization behind the scenes. tidyverse packages use it to allow in-database processing. If there's no benefit (besides not having to type a few quotation marks), there's only a cost.


text:
Q: Err TexShop Monterey 12.5.1 This is pdfTeX, Version 3.141592653-2.6-1.40.24 (TeX Live 2022) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
(./Recupero III Liceo.tex/Library/TeX/texbin/pdflatex: getwd: Operation not permitted


text:
Q: searching for a functional interface, without parameter, returning boolean Is there something close to Callable<Boolean>, which returns boolean not Boolean, and throwing no exception?
I'd like to use it like DoIt.until( ()-> someQueryWithBooleanResult() );
Yes, I know, Predicate<Void> is somewhat similar, but I would not like to use a dummy argument.

A: You are looking for BooleanSupplier.
Generally, any functional interface having no parameters and supplying a value has a name ending with Supplier.
As with most types there are variants for boolean, int, double, long and generic reference type. But note that there is no BooleanConsumer…


text:
Q: WPF: How to get a control's property value from an event raised by a template I need to allow the user to vertically resize a user control. So searching led me to a few examples on how to use the Thumb class and templates.  So I set up the templates:
<UserControl.Resources>

    <!-- ResizeDecorator Template -->
    <ControlTemplate x:Key="ResizeDecoratorTemplate" TargetType="{x:Type Control}">
        <Grid>
            <t:ResizeThumb Height="3" Cursor="ScrollNS" VerticalAlignment="Bottom" Margin="0 0 0 -4" ItemResizeCompleted="ResizeThumb_ItemResizeCompleted" />
        </Grid>
    </ControlTemplate>

    <!-- Designer Item Template-->
    <ControlTemplate x:Key="DesignerItemTemplate" TargetType="ContentControl">
        <Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
            <Control Template="{StaticResource ResizeDecoratorTemplate}" />
            <ContentPresenter Content="{TemplateBinding ContentControl.Content}" />
        </Grid>
    </ControlTemplate>

</UserControl.Resources>

Then I setup the ResizeThumb class:
Public Class ResizeThumb
Inherits Thumb

Public Event ItemResizeCompleted(sender As Object, e As TimeSlotPanelItemResizeEventArgs)
Public Property id As Integer

Public Sub New()
    AddHandler DragDelta, AddressOf ResizeThumb_DragDelta
End Sub

Private Sub ResizeThumb_DragDelta(sender As Object, e As DragDeltaEventArgs)
    e.Handled = True
End Sub

Private Sub ItemResized(sender As Object, e As DragCompletedEventArgs) Handles Me.DragCompleted
    Dim rs As ResizeThumb = CType(sender, ResizeThumb)
    Dim gd As Grid = CType(rs.Parent, Grid)

    Dim ee As New TimeSlotPanelItemResizeEventArgs
    ee.id = id
    ee.ResizeValue = e.VerticalChange
    RaiseEvent ItemResizeCompleted(Me, ee)
End Sub
End Class

my UserControls are added dynamically so I add the template at runtime:
    Dim si As New SchedItem(id, StartTime, Duration, SO, Title, UnitOfWork, BackgroundColor, Status, LastNote, Miles, Hours)
    Dim cc As ContentControl = New ContentControl
    cc.Content = si
    cc.Template = FindResource("DesignerItemTemplate")

Each SchedItem has an id.  Since the ResizeThumb class has a DragComplete event, I'm raising an event to pass back the VerticalChange and I want to also pass the id of the SchedItem that was resized.  I tried binding it to TemplatedParent but it's not allowed.  The only parent the ResizeThumb has is the Grid. I tried binding the Tag of the grid to the TemplatedParent but got nothing in the tag.
So now I have to ask; Is there any way to access the id property of the SchedItem from the ItemResized event handler in the ResizeThumb class?  If so, how?  If not, alternatives?

A: Holy cow! I figured it out.  Took me most of the day but it finally works.  Just had to figure out the correct binding to use.  So in my code, I set the Tag of the ContentControl to the id.
    Dim cc As ContentControl = New ContentControl
    cc.Tag = id  '<-- right here
    cc.Content = si
    cc.Template = FindResource("DesignerItemTemplate")

Then in the XAML, figured out how to bind that tag to the Grid that contains the ResizeThumb class's Tag property.
    <!-- ResizeDecorator Template -->
    <ControlTemplate x:Key="ResizeDecoratorTemplate" TargetType="{x:Type Control}">
        <Grid Tag="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Tag}">
            <t:ResizeThumb Height="3" Cursor="ScrollNS" VerticalAlignment="Bottom" Margin="0 0 0 -4" ItemResizeCompleted="ResizeThumb_ItemResizeCompleted" />
        </Grid>
    </ControlTemplate>

And now in the ItemResized event, I can get to the grid, which is the parent of the sender, and assign the Tag to the id of the event.
Private Sub ItemResized(sender As Object, e As DragCompletedEventArgs) Handles Me.DragCompleted
    Dim rs As ResizeThumb = CType(sender, ResizeThumb)
    Dim gd As Grid = CType(rs.Parent, Grid)

    Dim ee As New TimeSlotPanelItemResizeEventArgs
    ee.id = gd.Tag
    ee.ResizeValue = e.VerticalChange
    RaiseEvent ItemResizeCompleted(Me, ee)
End Sub

And now I get the id back in the event.