text:
Q: Something breaking - WPF + DependancyProperties I'm trying to modify a dual handle slider to a generalised double model.
[UPDATED]: XAML Code:
<Slider x:Name="LowerSlider" DataContext="this" Template="{StaticResource simpleSlider}" Margin="10,0,0,0"
            IsEnabled="{Binding Path=IsUpperSliderEnabled}"
            Minimum="{Binding Path=Minimum}"
            Maximum="{Binding Path=Maximum}"
            Value="{Binding Path=LowerValue}"
            SmallChange="{Binding Path=SmallChange}"
            LargeChange="{Binding Path=LargeChange}" />
    <Slider x:Name="UpperSlider" DataContext="this" Template="{StaticResource simpleSlider}" Margin="10,0,0,0"
            IsEnabled="{Binding Path=IsUpperSliderEnabled}"
            Minimum="{Binding Path=Minimum}"
            Maximum="{Binding Path=Maximum}"
            Value="{Binding Path=UpperValue}"
            SmallChange="{Binding Path=SmallChange}"
            LargeChange="{Binding Path=LargeChange}" />

C# code-behind:
 #region Dependency Property - Minimum
    public Double Minimum
    {
        get { return (Double)GetValue(MinimumProperty); }
        set { SetValue(MinimumProperty, value); }
    }

    public static readonly DependencyProperty MinimumProperty =
        DependencyProperty.Register("Minimum", typeof(Double), typeof(DualHandleSlider), new UIPropertyMetadata(0.0));
    #endregion

    #region Dependency Property - Lower Value
    public Double LowerValue
    {
        get { return (Double)GetValue(LowerValueProperty); }
        set { SetValue(LowerValueProperty, value); }
    }

    public static readonly DependencyProperty LowerValueProperty =
        DependencyProperty.Register("LowerValue", typeof(Double), typeof(DualHandleSlider), new UIPropertyMetadata(0.0));
    #endregion

    #region Dependency Property - Upper Value
    public Double UpperValue
    {
        get { return (Double)GetValue(UpperValueProperty); }
        set { SetValue(UpperValueProperty, value); }
    }

    public static readonly DependencyProperty UpperValueProperty =
        DependencyProperty.Register("UpperValue", typeof(Double), typeof(DualHandleSlider), new UIPropertyMetadata(5.0, new PropertyChangedCallback(OnUpperValueChanged)));

    public static void OnUpperValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

    }
    #endregion

    #region Dependency Property - Maximum
    public Double Maximum
    {
        get { return (Double)GetValue(MaximumProperty); }
        set { SetValue(MaximumProperty, value); }
    }

    public static readonly DependencyProperty MaximumProperty =
        DependencyProperty.Register("Maximum", typeof(Double), typeof(DualHandleSlider), new UIPropertyMetadata(10.0, new PropertyChangedCallback(OnMaximumChanged)));

    public static void OnMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        DualHandleSlider slider = (DualHandleSlider)d;

        if (slider.IsUpperValueLockedToMax)
        {
            slider.UpperValue = (Double)e.NewValue;
        }
    }

    #endregion

    #region Dependency Property - Small Change
    public double SmallChange
    {
        get { return (double)GetValue(SmallChangeProperty); }
        set { SetValue(SmallChangeProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SmallChange.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SmallChangeProperty =
        DependencyProperty.Register("SmallChange", typeof(double), typeof(DualHandleSlider),
            new UIPropertyMetadata(1.0, new PropertyChangedCallback(OnSmallChangePropertyChanged)));

    protected static void OnSmallChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine(e.NewValue);
    }
    #endregion

    #region Dependency Property - Large Change

    public double LargeChange
    {
        get { return (double)GetValue(LargeChangeProperty); }
        set { SetValue(LargeChangeProperty, value); }
    }

    // Using a DependencyProperty as the backing store for LargeChange.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LargeChangeProperty =
        DependencyProperty.Register("LargeChange", typeof(double), typeof(DualHandleSlider),
                new UIPropertyMetadata(1.0, new PropertyChangedCallback(OnLargeChangePropertyChanged)));

    protected static void OnLargeChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine(e.NewValue);
    }
    #endregion

The problem is, the control does not react in any way to properties set when the control is implemented. Even programmatically editing the properties does not work? I figure it's a stupid mistake, but I've been pouring over this code for a while now. Any ideas?
EDIT: Still no luck! Nothing in output about binding errors.

A: You were close with your initial code prior to the latest edit. The key is to name your user control and to bind against the user control. This allows the DataContext to flow through naturally if you ever support embedded ContentControls. Setting DataContext="this" literally sets your data context to the string "this".
Instead add something like x:Name="ThisControl" to your <UserControl... line and then update the bindings to point to ElementName=ThisControl. Make sure the Slider.Value bindings are Mode=TwoWay (which is the default if you don't specify a mode):
<UserControl x:Class="NameSpace.ThisControl"
             x:Name="ThisControl">
<Grid>
    <Slider x:Name="LowerSlider"
            IsEnabled="{Binding IsUpperSliderEnabled, ElementName=ThisControl}"
            Minimum="{Binding Minimum, ElementName=ThisControl}"
            Maximum="{Binding Maximum, ElementName=ThisControl}"
            Value="{Binding LowerValue, ElementName=ThisControl}"
            SmallChange="{Binding SmallChange, ElementName=ThisControl}"
            LargeChange="{Binding LargeChange, ElementName=ThisControl}" />
    <Slider x:Name="UpperSlider"
            IsEnabled="{Binding IsUpperSliderEnabled, ElementName=ThisControl}"
            Minimum="{Binding Minimum, ElementName=ThisControl}"
            Maximum="{Binding Maximum, ElementName=ThisControl}"
            Value="{Binding UpperValue, ElementName=ThisControl}"
            SmallChange="{Binding SmallChange, ElementName=ThisControl}"
            LargeChange="{Binding LargeChange, ElementName=ThisControl}" />

A: Are you setting the control DataContext property to the right value? You can see the output window to see the Binding errors you may have.
EDIT: Using ElementName=root you're directing your binding to something called root. The normal way of doing this (IMHO) is to delete the ElementName part of all the bindings and setting the DataContext = this to be able to bind to its own DP.


text:
Q: firemonkey indy udp Synchronize Thread Good day.
I create a class instance Thread.
In this thread I create udpserver.
UDPREAD synchronizes with the main thread.
Question: How to synchronize not with the main thread but with the thread that is the parent of the UDP
thank you

A: TIdUDPServer is a multi-threaded component.  Internally, it runs a separate reading thread for each item that you setup in the TIdUDPServer.Bindings collection.  When a given Binding receives incoming data, the corresponding thread reads the data and then fires the OnUDPRead event.
By default, the OnUDPRead event handler is called in the context of the main UI thread, via a call to TThread.Synchronize().  If you want to avoid that, you need to set the TIdUDPServer.ThreadedEvent property to true.  The event handler will then be called in the context of the Binding's reading thread directly, and you can synchronize your event handler's code with your server's parent thread however you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как растянуть сайдбар до футера, вне зависимости от количества контента на странице? Делаю тему для сайта.
Первый вопрос - как растянуть сайдбар до футера, вне зависимости от количества контента на странице?
Второй вопрос - почему на страницах статей картинка уходит под сайдбар?
Третий вопрос - как сделать так, чтобы футер подстраивался под высоту контента и был прилеплен к низу экрана?
Заранее спасибо за помощь!
A: *

*http://www.getincss.ru/2009/07/11/4-sposoba-kak-sozdat-bloki-kolonki-odinakovoj-vysoty/

*Это вы, видимо, уже исправили.

*http://grigoriev.pw/articles/pure-sticky-footer/ , а чтоб подстраивался, напишите так:
var footer_height = $('.footer').height();
$('body').css('margin-bottom', footer_height);
$('.footer').css('height', footer_height);
Как-то так. )

A: Вот решение на третий вопрос:

html {
  height: 100%; /* Растягиваем документ на всю высоту окна */
}

body {
  position: relative;
  min-height: 100%; /* Растягиваем body по высоте html */
}

main {
  padding-bottom: 30px; /* Выставляем отступ с высотой footer */
}

footer {
  position: absolute; /* Позиционируем footer внизу main */
  bottom: 0;
  width: 100%;
  height: 30px; /* Высота footer */
}
<body>
  <header>
   header
  </header>
  <main>
   main
  </main>
  <footer>
   footer
  </footer>
</body>


text:
Q: Facebook ios sdk: Page not found message after integrate it into my App I have searched for a lot of questions regarding this The page you requested was not found.  when I do it in sample app then it work nicely and it connecting to facebook and posting work successfuly. But when I integrate it in my App then when I click on Facebook share button then after login it gives The page you requested was not found  what problem is this please help while I m using the latest facebook ios sdk
Please Help!!!
This is my code
facebook = [[Facebook alloc] initWithAppId:@"App_id" andDelegate:self];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FBAccessTokenKey"]
    && [defaults objectForKey:@"FBExpirationDateKey"]) {
    facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
    facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
}

if (![facebook isSessionValid]) {
    [facebook authorize:nil];
}
else {
    [self showShareDialog];
}

///// show ShareDialog Method
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"App_id", @"app_id",nil];
[facebook dialog:@"feed" andParams:params andDelegate:self];

Oho i dont know how to handle this problem. i tried all the solution but no one work for me. problem is when i make a new application and then use facebook ios sdk then it work nice but when i do the same thing in my own application then it gives to problem.
1) The requested page not found
2) does not display dialog screen niether it post it came back to the main facebook page.
What the problem is This Please Help!!!
i have set the url in .plist file everything but not work. i m busy with this since Last week please help

A: The problem is in the URL. You might have edited the URL of the FBConnect SDK. Check it again. Or Re-Integrate it.
Edited Code
Add this code
-(void)BtnClick{
    NSArray *permissions =[[NSArray arrayWithObjects:
                       @"email", @"read_stream", @"user_birthday",
                       @"user_about_me", @"publish_stream", @"offline_access", nil] retain];
    Facebook *fb=[[Facebook alloc] initWithAppId:kappId];
    [fb authorize:permissions andDelegate:self];

}
- (void)fbDidLogin {

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:msg, @"message",nil];
    [fb requestWithGraphPath:@"me/feed"
                                                andParams:params
                                            andHttpMethod:@"POST"
                                              andDelegate:self];

}

A: Please verify the Callback URL is verified correctly in the APP settings, this might be a URL related issue.

A: You should have to set this in your .plist file.
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>000000000000000</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb164798790305117</string>
        </array>
    </dict>
</array>

where 164798790305117 is your AppID of Facebook and replace it with your AppID.


text:
Q: How to not share grails datasource across session? We have a Grails project that is set up to where we change the dataSource's username, password, and url at runtime.  The problem we are seeing is that the dataSource's properties are being changed across all sessions, causing issues when multiple users are in the application at the same time.
I have tried copying the dataSource and placing it in the session itself, but this did not work.
Is there a property on the dataSource for it to not be shared?

A: The datasource is a singleton - it's registered as a Spring bean, and they are singletons by default. There is no way to change that at runtime, but you can create your own datasources however you like. There's a plugin that can help with this - http://grails.org/plugin/runtime-datasources
There is some documentation in the plugin's readme at Github: https://github.com/domurtag/runtime-datasources


text:
Q: Find the probability mass function of the (discrete) random variable $X = Int(nU) + 1$. For a non-negative real number $x$, write $Int(x)$ for the largest integer that is less than or equal to $x$. Let $U$ be a uniform random variable on $(0,1)$ and $n \geq 1$ an integer. Find the probability mass function of the (discrete) random variable $X = Int(nU) + 1$.
I don't really know how to start on this question, can someone please give me some hints?

A: We analyze in detail the case $n=3$. We will use the standard notation $\lfloor x\rfloor$ for what in the OP is called $\text{Int}(x)$.
(i) For $0\lt u\lt \frac{1}{3}$, we have $\lfloor 3u\rfloor +1=1$. So for these $u$, $X=1$.
(ii) For $\frac{1}{3}\le u\lt \frac{2}{3}$, we have $\lfloor 3u\rfloor +1=2$. So for these $u$, $X=2$.
(iii) Finally, for $\frac{2}{3}\le u\lt 1$, we have $\lfloor 3u\rfloor +1=3$. For these $u$, $X=3$.
Since the range of $U$ is $(0,1)$, $X$ can take on no values other than $1$, $2$, or $3$.
The probability that $X=1$ is the probability that $0\lt U\lt \frac{1}{3}$. Since $U$ is uniform on $(0,1)$, we conclude that $\Pr(X=1)=\frac{1}{3}$. The same sort of calculation shows that $\Pr(X=2)=\Pr(X=3)=\frac{1}{3}$.
Thus $X$ has the discrete uniform distribution on the set $\{1,2,3\}$.
A very similar analysis shows that for general $n$, your random variable $X$ has the discrete uniform distribution on the set $\{1,2,3,\dots,n\}$.
For general $n$, the random variable $X$ takes on the value $1$ if $0\lt u\lt \frac{1}{n}$, the value $2$ if $\frac{1}{n}\le u\lt \frac{2}{n}$, the value $3$ when $\frac{2}{n}\le u\lt \frac{3}{n}$, and so on.  Each of these intervals has length $\frac{1}{n}$.  In general, because $U$ has continuous uniform distribution on $(0,1)$, $U$ lands in any such interval with probability $\frac{1}{n}$.
Remark: The typical pseudo-random number generator simulates a continuous uniform distribution on $(0,1)$. By using the method described in this problem, we can use the pseudo-random number generator to simulate certain discrete uniform distributions. For example, by taking $n=6$, we can simulate the result of throwing a fair die.


text:
Q: How would you condense a data frame into a few concise rows? Let's say, for example, we have data.frame 'IRIS_FD_UP' that looks like this:
IRIS_FD_UP <- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         NA           NA          NA   NA
1          NA          3.5          NA          NA   NA
1          NA          NA           1.4         NA   NA
1          NA          NA           NA          0.2  NA
1          NA          NA           NA          NA   setosa
2          4.6         NA           NA          NA   NA
2          NA          3.2          NA          NA   NA
2          NA          NA           1.5         NA   NA
2          NA          NA           NA          0.2  NA
2         NA          NA           NA          NA   setosa

How would we condense it to something like this:
IRIS_NOT_FD_UP <- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.6         3.2          1.5         0.2  setosa

(I don't care about the table names btw :) )

A: Does this work:
data.frame(lapply(dat, function(x) x[!is.na(x)]))
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.6         3.2          1.5         0.2  setosa

Data used:
dat
# A tibble: 10 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <chr>
 1          5.1        NA           NA          NA   NA
 2         NA           3.5         NA          NA   NA
 3         NA          NA            1.4        NA   NA
 4         NA          NA           NA           0.2 NA
 5         NA          NA           NA          NA   setosa
 6          4.6        NA           NA          NA   NA
 7         NA           3.2         NA          NA   NA
 8         NA          NA            1.5        NA   NA
 9         NA          NA           NA           0.2 NA
10         NA          NA           NA          NA   setosa

A: I assume that instead of 'condensate', you mean 'remove the NA'.
The function is.na() can help you. In your case, it would be:
IRIS_FD_UP[!is.na(IRIS_FD_UP)]
Please, let me know if I misunderstood anything.

A: It looks like instead of replacing NA values and removing or filtering them, you want to fill in these values with the last occurring non-null value. I would make sure you have a good reason for doing this.
You can use the tidyr package for this. I created some dummy data to test this on:
dat<-head(as_tibble(iris))
dat<-dat %>%mutate(Sepal.Length = ifelse(Sepal.Length<5,NA,Sepal.Length), Sepal.Width = ifelse(Sepal.Width<3.1, NA,Sepal.Width), Petal.Width=ifelse(Petal.Width==0.2,NA,Petal.Width))
dat["Species"][c(1:3),]=NA

# A tibble: 6 x 5
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
         <dbl>       <dbl>        <dbl>       <dbl> <fct>
1          5.1         3.5          1.4        NA   NA
2         NA          NA            1.4        NA   NA
3         NA           3.2          1.3        NA   NA
4         NA           3.1          1.5        NA   setosa
5          5           3.6          1.4        NA   setosa
6          5.4         3.9          1.7         0.4 setosa

dat %>% fill(everything(), .direction = "up")

Which then gives you this:
# A tibble: 6 x 5
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
         <dbl>       <dbl>        <dbl>       <dbl> <fct>
1          5.1         3.5          1.4         0.4 setosa
2          5           3.2          1.4         0.4 setosa
3          5           3.2          1.3         0.4 setosa
4          5           3.1          1.5         0.4 setosa
5          5           3.6          1.4         0.4 setosa
6          5.4         3.9          1.7         0.4 setosa

This was my previous answer based on filtering NA's across multiple columns:
The tidyverse way would be to use across to apply to all columns. https://dplyr.tidyverse.org/articles/colwise.html
iris%>% filter(across(everything(), ~ !is.na(.x)))

You can test this using the built in data for starwars which has NAs:
data(starwars)
# A tibble: 87 x 14
   name      height  mass hair_color  skin_color  eye_color birth_year sex    gender homeworld species films  vehicles starships
   <chr>      <int> <dbl> <chr>       <chr>       <chr>          <dbl> <chr>  <chr>  <chr>     <chr>   <list> <list>   <list>
 1 Luke Sky~    172    77 blond       fair        blue            19   male   mascu~ Tatooine  Human   <chr ~ <chr [2~ <chr [2]>
 2 C-3PO        167    75 NA          gold        yellow         112   none   mascu~ Tatooine  Droid   <chr ~ <chr [0~ <chr [0]>
 3 R2-D2         96    32 NA          white, blue red             33   none   mascu~ Naboo     Droid   <chr ~ <chr [0~ <chr [0]>
 4 Darth Va~    202   136 none        white       yellow          41.9 male   mascu~ Tatooine  Human   <chr ~ <chr [0~ <chr [1]>
 5 Leia Org~    150    49 brown       light       brown           19   female femin~ Alderaan  Human   <chr ~ <chr [1~ <chr [0]>
 6 Owen Lars    178   120 brown, grey light       blue            52   male   mascu~ Tatooine  Human   <chr ~ <chr [0~ <chr [0]>
 7 Beru Whi~    165    75 brown       light       blue            47   female femin~ Tatooine  Human   <chr ~ <chr [0~ <chr [0]>
 8 R5-D4         97    32 NA          white, red  red             NA   none   mascu~ Tatooine  Droid   <chr ~ <chr [0~ <chr [0]>
 9 Biggs Da~    183    84 black       light       brown           24   male   mascu~ Tatooine  Human   <chr ~ <chr [0~ <chr [1]>
10 Obi-Wan ~    182    77 auburn, wh~ fair        blue-gray       57   male   mascu~ Stewjon   Human   <chr ~ <chr [1~ <chr [5]>
# ... with 77 more rows

starwars%>% filter(across(everything(), ~ !is.na(.x)))
# A tibble: 29 x 14
   name       height  mass hair_color  skin_color eye_color birth_year sex    gender homeworld species films  vehicles starships
   <chr>       <int> <dbl> <chr>       <chr>      <chr>          <dbl> <chr>  <chr>  <chr>     <chr>   <list> <list>   <list>
 1 Luke Skyw~    172    77 blond       fair       blue            19   male   mascu~ Tatooine  Human   <chr ~ <chr [2~ <chr [2]>
 2 Darth Vad~    202   136 none        white      yellow          41.9 male   mascu~ Tatooine  Human   <chr ~ <chr [0~ <chr [1]>
 3 Leia Orga~    150    49 brown       light      brown           19   female femin~ Alderaan  Human   <chr ~ <chr [1~ <chr [0]>
 4 Owen Lars     178   120 brown, grey light      blue            52   male   mascu~ Tatooine  Human   <chr ~ <chr [0~ <chr [0]>
 5 Beru Whit~    165    75 brown       light      blue            47   female femin~ Tatooine  Human   <chr ~ <chr [0~ <chr [0]>
 6 Biggs Dar~    183    84 black       light      brown           24   male   mascu~ Tatooine  Human   <chr ~ <chr [0~ <chr [1]>
 7 Obi-Wan K~    182    77 auburn, wh~ fair       blue-gray       57   male   mascu~ Stewjon   Human   <chr ~ <chr [1~ <chr [5]>
 8 Anakin Sk~    188    84 blond       fair       blue            41.9 male   mascu~ Tatooine  Human   <chr ~ <chr [2~ <chr [3]>
 9 Chewbacca     228   112 brown       unknown    blue           200   male   mascu~ Kashyyyk  Wookiee <chr ~ <chr [1~ <chr [2]>
10 Han Solo      180    80 brown       fair       brown           29   male   mascu~ Corellia  Human   <chr ~ <chr [0~ <chr [2]>
# ... with 19 more rows


text:
Q: Fisher-Yates Shuffle Algorithm error so I'm currently making a quiz game with Actionscript 3.0, and I wanna shuffle the questions with this Fisher-Yates Shuffle Algorithm:
This is my code:
var questions:Array = [1,2,3,4,5,6,7,8,9,10];
function ShuffleArray(input:Array)
{
    for (var i:int=input.length-1; i>=0; i--)
    {
        var randomIndex:int = Math.floor(Math.random() * (i+1));
        var itemAtIndex:int = input[randomIndex];
        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
}

function buttoncorrect(event:MouseEvent):void
{
ShuffleArray(questions);
trace (questions);
var quest:int = questions.splice(questions, 1)[0];
trace(quest);
}

btntry.addEventListener(MouseEvent.CLICK,buttoncorrect);

And here is the trace result:
9,7,5,10,4,8,6,2,1,3
9
7,1,2,6,8,10,5,4,3
7
5,2,3,10,6,1,8,4
5
4,3,10,6,2,8,1
4
2,1,8,3,6,10
2
10,8,6,1,3
10
3,8,6,1
3
1,8,6
1
6,8
6
8
0

Why do I always get the "0" value at the end? I should've get the value of "8" right?
Does someone know what's wrong with my code? Thank you.

A: The problem is this line:
var quest:int = questions.splice(questions, 1)[0];

The first parameter to splice() is supposed to be a start index. Since you want to remove the first element, it should be zero:
var quest:int = questions.splice(0, 1)[0];

The reason your code works for each case except the last one is because of the way automatic type conversion from Array to int works. ActionScript is automatically converting the array passed as the first parameter to a zero when it has more than one element, but converts it to the value of the only element in the array when it has a single element. So it is effectively:
var quest:int = questions.splice(0, 1)[0];

right up until the last call, when you pass in an array containing the single value 8. Then the last time it gets called, you are effectively doing this:
var quest:int = questions.splice(8, 1)[0];

Since that index is beyond the end of the array, an empty array is returned and traces out as 0.


text:
Q: Inserting a copyright / registered symbol in the installer using Wix I want to know if one a particular dialog i want to insert a copyright symbol , how would i do that i insert the symbol in th text options in the xml file howevr it results in an error while compiling the .wxs file.
Thanks

A: You have to make sure you save the WiX XML in UTF-8 encoding. The easiest way is to open the XML in Notepad, click File and then click Save as. Select UTF-8 in the Encoding list. And overwrite your current XML file.
Another way is use character codes: © for copyright and ® for registred symbols.

The thing is the regular English letters, or ASCII, are valid UTF-8 characters as they fit into 7-bits. The copyright and registred symbols are not valid characters because in UTF-8 they have to be encoded as two bytes rather than one.

A: Here is a solution:

*

*Copy the notepad++ file text say "index.html" into plain old notepad

*Close the notepad++ file.

*Re type the text where you want the Copyright symbol by holding down Fn+alt typing 0169 on the keypad

*Save the plain notepad file as (all Files) index.html to the folder your index.html file is in when asked to overwrite click yes.

*Now open the file using notepad++ and this file when saved after any other edits will not produce the accented A beside the copyright symbol ©
I do not know why the saved version in notepad++ works after "cleansing" in plain notepad but I have not had any other problems using the method to date.


text:
Q: Download File Using JavaScript/jQuery I have a very similar requirement specified here.
I need to have the user's browser start a download manually when $('a#someID').click();
But I cannot use the window.href method, since it replaces the current page contents with the file you're trying to download.
Instead I want to open the download in new window/tab. How is this possible?

A: Only seven years later here comes a one line jQuery solution using a form instead of an iframe or link:
$('<form></form>')
     .attr('action', filePath)
     .appendTo('body').submit().remove();

I've tested this in

*

*Chrome 55

*Firefox 50

*Edge IE8-10

*iOS 10 (Safari/Chrome)

*Android Chrome

If anyone knows of any downsides with this solution I'd be very happy to hear about them.

Full demo:

A: I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.

document.getElementById('download').click();

Note:
This is not supported on all browsers: http://www.w3schools.com/tags/att_a_download.asp

A: I recommend using the download attribute for download instead of jQuery:
 file_name

This will download your file, without opening it.

A: I don't know if the question is just too old, but setting window.location to a download url will work, as long as the download mime type is correct (for example a zip archive).
var download = function(downloadURL) {

   location = downloadURL;

});

download('http://example.com/archive.zip'); //correct usage
download('http://example.com/page.html'); //DON'T

A: You can simply make use of the Download attribute in HTML. Using good ol' Javascript, you can use this feature to download the file directly. The download attribute of the anchor tag should point to the link where the file to be downloaded is hosted.
Firstly, point the URL to your resource path:
var url = 'your url goes here';

Create an anchor tag, with the needed attributes as below:
var elem = document.createElement('a');
elem.href = url;
elem.download = url;
elem.id="downloadAnchor";

Append the anchor tag to the body element of the webpage.
document.body.appendChild(elem);

Now trigger the click event programmatically. Clicking on the anchor tag will trigger the download.
$('#downloadAnchor').click();

Putting it all together:
var url = 'your url goes here';
var elem = document.createElement('a');
elem.href = url;
elem.download = url;
elem.id="downloadAnchor";
document.body.appendChild(elem);
$('#downloadAnchor').click();

Additional Information: Nothing fancy in the above code, just client-side JavaScript which works from Chrome Devtools' Console, but powerful and also opens up a lot of possibilities like webpage crawling.
For e.g. the following chunk of code executed in the Devtools console will open all the links in the page in a new tab: Just goto this webpage , open devtools and run this script in the browser console and watch the power of JavaScript unfurl.  (Note: The below code is purely for educational purposes only.)
Make sure you enable pop-ups for that site, else your anchor clicks will get disabled by the default pop-up blocker.
var links = document.getElementsByClassName("_3ATBKe");
for(var i=0;i<links.length;i++){
    var title = document.getElementsByClassName("_3ATBKe")[i].firstElementChild.firstElementChild.innerText.replaceAll('|','-').replaceAll(':','x');
    console.log('Opening..'+title);
    links[i].firstElementChild.click();
}

Note: This is not just limited to anchor clicks, you can download almost anything you find on your webpage. If something (image, audio, video) loads on your webpage, you can probably write a script to download it, even if the provision is not provided to you from the UI.

A: Use an invisible :

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.
If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.
In jQuery:
$('a#someID').attr({target: '_blank',
                    href  : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

A: To improve Imagine Breaker 's answer, this is supported on FF & IE :
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

function downloadURI(uri, name) {
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.dispatchEvent(evt);
}

In other words, just use a dispatchEvent function instead of click();

A: Maybe just have your javascript open a page that just downloads a file, like when you drag a download link to a new tab:
Window.open("https://www.MyServer.
Org/downloads/ardiuno/WgiWho=?:8080")

With the opened window open a download page that auto closes.

A: Most Complete and Working (Tested) Code for Downloading Data For FireFox, Chrome and IE Code is Following. Assume that Data is in texarea field, that has id='textarea_area' and filename is name of file where data will be downloaded.
function download(filename) {
    if (typeof filename==='undefined') filename = ""; // default
    value = document.getElementById('textarea_area').value;

    filetype="text/*";
    extension=filename.substring(filename.lastIndexOf("."));
    for (var i = 0; i < extToMIME.length; i++) {
        if (extToMIME[i][0].localeCompare(extension)==0) {
            filetype=extToMIME[i][1];
            break;
        }
    }

    var pom = document.createElement('a');
    pom.setAttribute('href', 'data: '+filetype+';charset=utf-8,' + '\ufeff' + encodeURIComponent(value)); // Added BOM too
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { // IE
            blobObject = new Blob(['\ufeff'+value]);
            window.navigator.msSaveBlob(blobObject, filename);
        } else { // FF, Chrome
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        }
    } else if( document.createEventObject ) { // Have No Idea
        var evObj = document.createEventObject();
        pom.fireEvent( 'onclick' , evObj );
    } else { // For Any Case
        pom.click();
    }

}

and then just call
Download

For Download Initiating.
Array for setting correct MIME type for download dialog CAN BE following:
// ----------------------- Extensions to MIME --------- //

        // List of mime types
        // combination of values from Windows 7 Registry and
        // from C:\Windows\System32\inetsrv\config\applicationHost.config
        // some added, including .7z and .dat
    var extToMIME = [
        [".323", "text/h323"],
        [".3g2", "video/3gpp2"],
        [".3gp", "video/3gpp"],
        [".3gp2", "video/3gpp2"],
        [".3gpp", "video/3gpp"],
        [".7z", "application/x-7z-compressed"],
        [".aa", "audio/audible"],
        [".AAC", "audio/aac"],
        [".aaf", "application/octet-stream"],
        [".aax", "audio/vnd.audible.aax"],
        [".ac3", "audio/ac3"],
        [".aca", "application/octet-stream"],
        [".accda", "application/msaccess.addin"],
        [".accdb", "application/msaccess"],
        [".accdc", "application/msaccess.cab"],
        [".accde", "application/msaccess"],
        [".accdr", "application/msaccess.runtime"],
        [".accdt", "application/msaccess"],
        [".accdw", "application/msaccess.webapplication"],
        [".accft", "application/msaccess.ftemplate"],
        [".acx", "application/internet-property-stream"],
        [".AddIn", "text/xml"],
        [".ade", "application/msaccess"],
        [".adobebridge", "application/x-bridge-url"],
        [".adp", "application/msaccess"],
        [".ADT", "audio/vnd.dlna.adts"],
        [".ADTS", "audio/aac"],
        [".afm", "application/octet-stream"],
        [".ai", "application/postscript"],
        [".aif", "audio/x-aiff"],
        [".aifc", "audio/aiff"],
        [".aiff", "audio/aiff"],
        [".air", "application/vnd.adobe.air-application-installer-package+zip"],
        [".amc", "application/x-mpeg"],
        [".application", "application/x-ms-application"],
        [".art", "image/x-jg"],
        [".asa", "application/xml"],
        [".asax", "application/xml"],
        [".ascx", "application/xml"],
        [".asd", "application/octet-stream"],
        [".asf", "video/x-ms-asf"],
        [".ashx", "application/xml"],
        [".asi", "application/octet-stream"],
        [".asm", "text/plain"],
        [".asmx", "application/xml"],
        [".aspx", "application/xml"],
        [".asr", "video/x-ms-asf"],
        [".asx", "video/x-ms-asf"],
        [".atom", "application/atom+xml"],
        [".au", "audio/basic"],
        [".avi", "video/x-msvideo"],
        [".axs", "application/olescript"],
        [".bas", "text/plain"],
        [".bcpio", "application/x-bcpio"],
        [".bin", "application/octet-stream"],
        [".bmp", "image/bmp"],
        [".c", "text/plain"],
        [".cab", "application/octet-stream"],
        [".caf", "audio/x-caf"],
        [".calx", "application/vnd.ms-office.calx"],
        [".cat", "application/vnd.ms-pki.seccat"],
        [".cc", "text/plain"],
        [".cd", "text/plain"],
        [".cdda", "audio/aiff"],
        [".cdf", "application/x-cdf"],
        [".cer", "application/x-x509-ca-cert"],
        [".chm", "application/octet-stream"],
        [".class", "application/x-java-applet"],
        [".clp", "application/x-msclip"],
        [".cmx", "image/x-cmx"],
        [".cnf", "text/plain"],
        [".cod", "image/cis-cod"],
        [".config", "application/xml"],
        [".contact", "text/x-ms-contact"],
        [".coverage", "application/xml"],
        [".cpio", "application/x-cpio"],
        [".cpp", "text/plain"],
        [".crd", "application/x-mscardfile"],
        [".crl", "application/pkix-crl"],
        [".crt", "application/x-x509-ca-cert"],
        [".cs", "text/plain"],
        [".csdproj", "text/plain"],
        [".csh", "application/x-csh"],
        [".csproj", "text/plain"],
        [".css", "text/css"],
        [".csv", "text/csv"],
        [".cur", "application/octet-stream"],
        [".cxx", "text/plain"],
        [".dat", "application/octet-stream"],
        [".datasource", "application/xml"],
        [".dbproj", "text/plain"],
        [".dcr", "application/x-director"],
        [".def", "text/plain"],
        [".deploy", "application/octet-stream"],
        [".der", "application/x-x509-ca-cert"],
        [".dgml", "application/xml"],
        [".dib", "image/bmp"],
        [".dif", "video/x-dv"],
        [".dir", "application/x-director"],
        [".disco", "text/xml"],
        [".dll", "application/x-msdownload"],
        [".dll.config", "text/xml"],
        [".dlm", "text/dlm"],
        [".doc", "application/msword"],
        [".docm", "application/vnd.ms-word.document.macroEnabled.12"],
        [".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
        [".dot", "application/msword"],
        [".dotm", "application/vnd.ms-word.template.macroEnabled.12"],
        [".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"],
        [".dsp", "application/octet-stream"],
        [".dsw", "text/plain"],
        [".dtd", "text/xml"],
        [".dtsConfig", "text/xml"],
        [".dv", "video/x-dv"],
        [".dvi", "application/x-dvi"],
        [".dwf", "drawing/x-dwf"],
        [".dwp", "application/octet-stream"],
        [".dxr", "application/x-director"],
        [".eml", "message/rfc822"],
        [".emz", "application/octet-stream"],
        [".eot", "application/octet-stream"],
        [".eps", "application/postscript"],
        [".etl", "application/etl"],
        [".etx", "text/x-setext"],
        [".evy", "application/envoy"],
        [".exe", "application/octet-stream"],
        [".exe.config", "text/xml"],
        [".fdf", "application/vnd.fdf"],
        [".fif", "application/fractals"],
        [".filters", "Application/xml"],
        [".fla", "application/octet-stream"],
        [".flr", "x-world/x-vrml"],
        [".flv", "video/x-flv"],
        [".fsscript", "application/fsharp-script"],
        [".fsx", "application/fsharp-script"],
        [".generictest", "application/xml"],
        [".gif", "image/gif"],
        [".group", "text/x-ms-group"],
        [".gsm", "audio/x-gsm"],
        [".gtar", "application/x-gtar"],
        [".gz", "application/x-gzip"],
        [".h", "text/plain"],
        [".hdf", "application/x-hdf"],
        [".hdml", "text/x-hdml"],
        [".hhc", "application/x-oleobject"],
        [".hhk", "application/octet-stream"],
        [".hhp", "application/octet-stream"],
        [".hlp", "application/winhlp"],
        [".hpp", "text/plain"],
        [".hqx", "application/mac-binhex40"],
        [".hta", "application/hta"],
        [".htc", "text/x-component"],
        [".htm", "text/html"],
        [".html", "text/html"],
        [".htt", "text/webviewhtml"],
        [".hxa", "application/xml"],
        [".hxc", "application/xml"],
        [".hxd", "application/octet-stream"],
        [".hxe", "application/xml"],
        [".hxf", "application/xml"],
        [".hxh", "application/octet-stream"],
        [".hxi", "application/octet-stream"],
        [".hxk", "application/xml"],
        [".hxq", "application/octet-stream"],
        [".hxr", "application/octet-stream"],
        [".hxs", "application/octet-stream"],
        [".hxt", "text/html"],
        [".hxv", "application/xml"],
        [".hxw", "application/octet-stream"],
        [".hxx", "text/plain"],
        [".i", "text/plain"],
        [".ico", "image/x-icon"],
        [".ics", "application/octet-stream"],
        [".idl", "text/plain"],
        [".ief", "image/ief"],
        [".iii", "application/x-iphone"],
        [".inc", "text/plain"],
        [".inf", "application/octet-stream"],
        [".inl", "text/plain"],
        [".ins", "application/x-internet-signup"],
        [".ipa", "application/x-itunes-ipa"],
        [".ipg", "application/x-itunes-ipg"],
        [".ipproj", "text/plain"],
        [".ipsw", "application/x-itunes-ipsw"],
        [".iqy", "text/x-ms-iqy"],
        [".isp", "application/x-internet-signup"],
        [".ite", "application/x-itunes-ite"],
        [".itlp", "application/x-itunes-itlp"],
        [".itms", "application/x-itunes-itms"],
        [".itpc", "application/x-itunes-itpc"],
        [".IVF", "video/x-ivf"],
        [".jar", "application/java-archive"],
        [".java", "application/octet-stream"],
        [".jck", "application/liquidmotion"],
        [".jcz", "application/liquidmotion"],
        [".jfif", "image/pjpeg"],
        [".jnlp", "application/x-java-jnlp-file"],
        [".jpb", "application/octet-stream"],
        [".jpe", "image/jpeg"],
        [".jpeg", "image/jpeg"],
        [".jpg", "image/jpeg"],
        [".js", "application/x-javascript"],
        [".json", "application/json"],
        [".jsx", "text/jscript"],
        [".jsxbin", "text/plain"],
        [".latex", "application/x-latex"],
        [".library-ms", "application/windows-library+xml"],
        [".lit", "application/x-ms-reader"],
        [".loadtest", "application/xml"],
        [".lpk", "application/octet-stream"],
        [".lsf", "video/x-la-asf"],
        [".lst", "text/plain"],
        [".lsx", "video/x-la-asf"],
        [".lzh", "application/octet-stream"],
        [".m13", "application/x-msmediaview"],
        [".m14", "application/x-msmediaview"],
        [".m1v", "video/mpeg"],
        [".m2t", "video/vnd.dlna.mpeg-tts"],
        [".m2ts", "video/vnd.dlna.mpeg-tts"],
        [".m2v", "video/mpeg"],
        [".m3u", "audio/x-mpegurl"],
        [".m3u8", "audio/x-mpegurl"],
        [".m4a", "audio/m4a"],
        [".m4b", "audio/m4b"],
        [".m4p", "audio/m4p"],
        [".m4r", "audio/x-m4r"],
        [".m4v", "video/x-m4v"],
        [".mac", "image/x-macpaint"],
        [".mak", "text/plain"],
        [".man", "application/x-troff-man"],
        [".manifest", "application/x-ms-manifest"],
        [".map", "text/plain"],
        [".master", "application/xml"],
        [".mda", "application/msaccess"],
        [".mdb", "application/x-msaccess"],
        [".mde", "application/msaccess"],
        [".mdp", "application/octet-stream"],
        [".me", "application/x-troff-me"],
        [".mfp", "application/x-shockwave-flash"],
        [".mht", "message/rfc822"],
        [".mhtml", "message/rfc822"],
        [".mid", "audio/mid"],
        [".midi", "audio/mid"],
        [".mix", "application/octet-stream"],
        [".mk", "text/plain"],
        [".mmf", "application/x-smaf"],
        [".mno", "text/xml"],
        [".mny", "application/x-msmoney"],
        [".mod", "video/mpeg"],
        [".mov", "video/quicktime"],
        [".movie", "video/x-sgi-movie"],
        [".mp2", "video/mpeg"],
        [".mp2v", "video/mpeg"],
        [".mp3", "audio/mpeg"],
        [".mp4", "video/mp4"],
        [".mp4v", "video/mp4"],
        [".mpa", "video/mpeg"],
        [".mpe", "video/mpeg"],
        [".mpeg", "video/mpeg"],
        [".mpf", "application/vnd.ms-mediapackage"],
        [".mpg", "video/mpeg"],
        [".mpp", "application/vnd.ms-project"],
        [".mpv2", "video/mpeg"],
        [".mqv", "video/quicktime"],
        [".ms", "application/x-troff-ms"],
        [".msi", "application/octet-stream"],
        [".mso", "application/octet-stream"],
        [".mts", "video/vnd.dlna.mpeg-tts"],
        [".mtx", "application/xml"],
        [".mvb", "application/x-msmediaview"],
        [".mvc", "application/x-miva-compiled"],
        [".mxp", "application/x-mmxp"],
        [".nc", "application/x-netcdf"],
        [".nsc", "video/x-ms-asf"],
        [".nws", "message/rfc822"],
        [".ocx", "application/octet-stream"],
        [".oda", "application/oda"],
        [".odc", "text/x-ms-odc"],
        [".odh", "text/plain"],
        [".odl", "text/plain"],
        [".odp", "application/vnd.oasis.opendocument.presentation"],
        [".ods", "application/oleobject"],
        [".odt", "application/vnd.oasis.opendocument.text"],
        [".one", "application/onenote"],
        [".onea", "application/onenote"],
        [".onepkg", "application/onenote"],
        [".onetmp", "application/onenote"],
        [".onetoc", "application/onenote"],
        [".onetoc2", "application/onenote"],
        [".orderedtest", "application/xml"],
        [".osdx", "application/opensearchdescription+xml"],
        [".p10", "application/pkcs10"],
        [".p12", "application/x-pkcs12"],
        [".p7b", "application/x-pkcs7-certificates"],
        [".p7c", "application/pkcs7-mime"],
        [".p7m", "application/pkcs7-mime"],
        [".p7r", "application/x-pkcs7-certreqresp"],
        [".p7s", "application/pkcs7-signature"],
        [".pbm", "image/x-portable-bitmap"],
        [".pcast", "application/x-podcast"],
        [".pct", "image/pict"],
        [".pcx", "application/octet-stream"],
        [".pcz", "application/octet-stream"],
        [".pdf", "application/pdf"],
        [".pfb", "application/octet-stream"],
        [".pfm", "application/octet-stream"],
        [".pfx", "application/x-pkcs12"],
        [".pgm", "image/x-portable-graymap"],
        [".pic", "image/pict"],
        [".pict", "image/pict"],
        [".pkgdef", "text/plain"],
        [".pkgundef", "text/plain"],
        [".pko", "application/vnd.ms-pki.pko"],
        [".pls", "audio/scpls"],
        [".pma", "application/x-perfmon"],
        [".pmc", "application/x-perfmon"],
        [".pml", "application/x-perfmon"],
        [".pmr", "application/x-perfmon"],
        [".pmw", "application/x-perfmon"],
        [".png", "image/png"],
        [".pnm", "image/x-portable-anymap"],
        [".pnt", "image/x-macpaint"],
        [".pntg", "image/x-macpaint"],
        [".pnz", "image/png"],
        [".pot", "application/vnd.ms-powerpoint"],
        [".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"],
        [".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"],
        [".ppa", "application/vnd.ms-powerpoint"],
        [".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"],
        [".ppm", "image/x-portable-pixmap"],
        [".pps", "application/vnd.ms-powerpoint"],
        [".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"],
        [".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"],
        [".ppt", "application/vnd.ms-powerpoint"],
        [".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"],
        [".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
        [".prf", "application/pics-rules"],
        [".prm", "application/octet-stream"],
        [".prx", "application/octet-stream"],
        [".ps", "application/postscript"],
        [".psc1", "application/PowerShell"],
        [".psd", "application/octet-stream"],
        [".psess", "application/xml"],
        [".psm", "application/octet-stream"],
        [".psp", "application/octet-stream"],
        [".pub", "application/x-mspublisher"],
        [".pwz", "application/vnd.ms-powerpoint"],
        [".qht", "text/x-html-insertion"],
        [".qhtm", "text/x-html-insertion"],
        [".qt", "video/quicktime"],
        [".qti", "image/x-quicktime"],
        [".qtif", "image/x-quicktime"],
        [".qtl", "application/x-quicktimeplayer"],
        [".qxd", "application/octet-stream"],
        [".ra", "audio/x-pn-realaudio"],
        [".ram", "audio/x-pn-realaudio"],
        [".rar", "application/octet-stream"],
        [".ras", "image/x-cmu-raster"],
        [".rat", "application/rat-file"],
        [".rc", "text/plain"],
        [".rc2", "text/plain"],
        [".rct", "text/plain"],
        [".rdlc", "application/xml"],
        [".resx", "application/xml"],
        [".rf", "image/vnd.rn-realflash"],
        [".rgb", "image/x-rgb"],
        [".rgs", "text/plain"],
        [".rm", "application/vnd.rn-realmedia"],
        [".rmi", "audio/mid"],
        [".rmp", "application/vnd.rn-rn_music_package"],
        [".roff", "application/x-troff"],
        [".rpm", "audio/x-pn-realaudio-plugin"],
        [".rqy", "text/x-ms-rqy"],
        [".rtf", "application/rtf"],
        [".rtx", "text/richtext"],
        [".ruleset", "application/xml"],
        [".s", "text/plain"],
        [".safariextz", "application/x-safari-safariextz"],
        [".scd", "application/x-msschedule"],
        [".sct", "text/scriptlet"],
        [".sd2", "audio/x-sd2"],
        [".sdp", "application/sdp"],
        [".sea", "application/octet-stream"],
        [".searchConnector-ms", "application/windows-search-connector+xml"],
        [".setpay", "application/set-payment-initiation"],
        [".setreg", "application/set-registration-initiation"],
        [".settings", "application/xml"],
        [".sgimb", "application/x-sgimb"],
        [".sgml", "text/sgml"],
        [".sh", "application/x-sh"],
        [".shar", "application/x-shar"],
        [".shtml", "text/html"],
        [".sit", "application/x-stuffit"],
        [".sitemap", "application/xml"],
        [".skin", "application/xml"],
        [".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"],
        [".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"],
        [".slk", "application/vnd.ms-excel"],
        [".sln", "text/plain"],
        [".slupkg-ms", "application/x-ms-license"],
        [".smd", "audio/x-smd"],
        [".smi", "application/octet-stream"],
        [".smx", "audio/x-smd"],
        [".smz", "audio/x-smd"],
        [".snd", "audio/basic"],
        [".snippet", "application/xml"],
        [".snp", "application/octet-stream"],
        [".sol", "text/plain"],
        [".sor", "text/plain"],
        [".spc", "application/x-pkcs7-certificates"],
        [".spl", "application/futuresplash"],
        [".src", "application/x-wais-source"],
        [".srf", "text/plain"],
        [".SSISDeploymentManifest", "text/xml"],
        [".ssm", "application/streamingmedia"],
        [".sst", "application/vnd.ms-pki.certstore"],
        [".stl", "application/vnd.ms-pki.stl"],
        [".sv4cpio", "application/x-sv4cpio"],
        [".sv4crc", "application/x-sv4crc"],
        [".svc", "application/xml"],
        [".swf", "application/x-shockwave-flash"],
        [".t", "application/x-troff"],
        [".tar", "application/x-tar"],
        [".tcl", "application/x-tcl"],
        [".testrunconfig", "application/xml"],
        [".testsettings", "application/xml"],
        [".tex", "application/x-tex"],
        [".texi", "application/x-texinfo"],
        [".texinfo", "application/x-texinfo"],
        [".tgz", "application/x-compressed"],
        [".thmx", "application/vnd.ms-officetheme"],
        [".thn", "application/octet-stream"],
        [".tif", "image/tiff"],
        [".tiff", "image/tiff"],
        [".tlh", "text/plain"],
        [".tli", "text/plain"],
        [".toc", "application/octet-stream"],
        [".tr", "application/x-troff"],
        [".trm", "application/x-msterminal"],
        [".trx", "application/xml"],
        [".ts", "video/vnd.dlna.mpeg-tts"],
        [".tsv", "text/tab-separated-values"],
        [".ttf", "application/octet-stream"],
        [".tts", "video/vnd.dlna.mpeg-tts"],
        [".txt", "text/plain"],
        [".u32", "application/octet-stream"],
        [".uls", "text/iuls"],
        [".user", "text/plain"],
        [".ustar", "application/x-ustar"],
        [".vb", "text/plain"],
        [".vbdproj", "text/plain"],
        [".vbk", "video/mpeg"],
        [".vbproj", "text/plain"],
        [".vbs", "text/vbscript"],
        [".vcf", "text/x-vcard"],
        [".vcproj", "Application/xml"],
        [".vcs", "text/plain"],
        [".vcxproj", "Application/xml"],
        [".vddproj", "text/plain"],
        [".vdp", "text/plain"],
        [".vdproj", "text/plain"],
        [".vdx", "application/vnd.ms-visio.viewer"],
        [".vml", "text/xml"],
        [".vscontent", "application/xml"],
        [".vsct", "text/xml"],
        [".vsd", "application/vnd.visio"],
        [".vsi", "application/ms-vsi"],
        [".vsix", "application/vsix"],
        [".vsixlangpack", "text/xml"],
        [".vsixmanifest", "text/xml"],
        [".vsmdi", "application/xml"],
        [".vspscc", "text/plain"],
        [".vss", "application/vnd.visio"],
        [".vsscc", "text/plain"],
        [".vssettings", "text/xml"],
        [".vssscc", "text/plain"],
        [".vst", "application/vnd.visio"],
        [".vstemplate", "text/xml"],
        [".vsto", "application/x-ms-vsto"],
        [".vsw", "application/vnd.visio"],
        [".vsx", "application/vnd.visio"],
        [".vtx", "application/vnd.visio"],
        [".wav", "audio/wav"],
        [".wave", "audio/wav"],
        [".wax", "audio/x-ms-wax"],
        [".wbk", "application/msword"],
        [".wbmp", "image/vnd.wap.wbmp"],
        [".wcm", "application/vnd.ms-works"],
        [".wdb", "application/vnd.ms-works"],
        [".wdp", "image/vnd.ms-photo"],
        [".webarchive", "application/x-safari-webarchive"],
        [".webtest", "application/xml"],
        [".wiq", "application/xml"],
        [".wiz", "application/msword"],
        [".wks", "application/vnd.ms-works"],
        [".WLMP", "application/wlmoviemaker"],
        [".wlpginstall", "application/x-wlpg-detect"],
        [".wlpginstall3", "application/x-wlpg3-detect"],
        [".wm", "video/x-ms-wm"],
        [".wma", "audio/x-ms-wma"],
        [".wmd", "application/x-ms-wmd"],
        [".wmf", "application/x-msmetafile"],
        [".wml", "text/vnd.wap.wml"],
        [".wmlc", "application/vnd.wap.wmlc"],
        [".wmls", "text/vnd.wap.wmlscript"],
        [".wmlsc", "application/vnd.wap.wmlscriptc"],
        [".wmp", "video/x-ms-wmp"],
        [".wmv", "video/x-ms-wmv"],
        [".wmx", "video/x-ms-wmx"],
        [".wmz", "application/x-ms-wmz"],
        [".wpl", "application/vnd.ms-wpl"],
        [".wps", "application/vnd.ms-works"],
        [".wri", "application/x-mswrite"],
        [".wrl", "x-world/x-vrml"],
        [".wrz", "x-world/x-vrml"],
        [".wsc", "text/scriptlet"],
        [".wsdl", "text/xml"],
        [".wvx", "video/x-ms-wvx"],
        [".x", "application/directx"],
        [".xaf", "x-world/x-vrml"],
        [".xaml", "application/xaml+xml"],
        [".xap", "application/x-silverlight-app"],
        [".xbap", "application/x-ms-xbap"],
        [".xbm", "image/x-xbitmap"],
        [".xdr", "text/plain"],
        [".xht", "application/xhtml+xml"],
        [".xhtml", "application/xhtml+xml"],
        [".xla", "application/vnd.ms-excel"],
        [".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"],
        [".xlc", "application/vnd.ms-excel"],
        [".xld", "application/vnd.ms-excel"],
        [".xlk", "application/vnd.ms-excel"],
        [".xll", "application/vnd.ms-excel"],
        [".xlm", "application/vnd.ms-excel"],
        [".xls", "application/vnd.ms-excel"],
        [".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"],
        [".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"],
        [".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
        [".xlt", "application/vnd.ms-excel"],
        [".xltm", "application/vnd.ms-excel.template.macroEnabled.12"],
        [".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"],
        [".xlw", "application/vnd.ms-excel"],
        [".xml", "text/xml"],
        [".xmta", "application/xml"],
        [".xof", "x-world/x-vrml"],
        [".XOML", "text/plain"],
        [".xpm", "image/x-xpixmap"],
        [".xps", "application/vnd.ms-xpsdocument"],
        [".xrm-ms", "text/xml"],
        [".xsc", "application/xml"],
        [".xsd", "text/xml"],
        [".xsf", "text/xml"],
        [".xsl", "text/xml"],
        [".xslt", "text/xml"],
        [".xsn", "application/octet-stream"],
        [".xss", "application/xml"],
        [".xtp", "application/octet-stream"],
        [".xwd", "image/x-xwindowdump"],
        [".z", "application/x-compress"],
        [".zip", "application/x-zip-compressed"]
];

// ----------------------- End of Extensions to MIME --------- //

A: 2019 modern browsers update
This is the approach I'd now recommend with a few caveats:

*

*A relatively modern browser is required

*If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    // the filename you want
    a.download = 'todo-1.json';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    alert('your file has downloaded!'); // or you know, something with better UX...
  })
  .catch(() => alert('oh no!'));

2012 original jQuery/iframe/cookie based approach
I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

*

*Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too

*User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications

*successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation

*In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.
$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

A: function downloadURI(uri, name)
{
    var link = document.createElement("a");
    // If you don't know the name or want to use
    // the webserver default set name = ''
    link.setAttribute('download', name);
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    link.remove();
}

Check if your target browser(s) will run the above snippet smoothly: http://caniuse.com/#feat=download

A: There are so many little things that can happen when trying to download a file. The inconsistency between browsers alone is a nightmare. I ended up using this great little library.
https://github.com/rndme/download
Nice thing about it is that its flexible for not only urls but for client side data you want to download.

*

*text string

*text dataURL

*text blob

*text arrays

*html string

*html blob

*ajax callback

*binary files

A: let args = {"data":htmlData,"filename":exampleName}

To create a HTMl file and download
window.downloadHTML = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.html';
data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
console.log(data);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}

To create and download a CSV
window.downloadCSV = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.csv';
if (!csv.match(/^data:text\/csv/i)) {
    csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

}

A: You have to do it from two sides, from the server and from the client (web app).
From the server, set the header called Content-Disposition https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
// nodejs express
  res.set('Content-Disposition', `attachment; filename="${self.creationName}"`)

With the above header, the server will tell the browser that the response is a file and it should be downloaded and saved with given name, otherwise the browser may save the file as something like "attachments (1).zip"
Next we look at the client, we create an anchor link and automatically click it.
function downloadThroughAnchorLink(downloadUrl: string, fileName: string) {
    const a = document.createElement('a')
    a.href = downloadUrl;
    // We provided a header called Content-Disposition so we dont need to set "a.download" here
    // a.download = fileName || 'download'
    a.click()
}

That should do it.
Alternatively, you can download a file like this:
    const downloadUrl = 'https://localhost:3001/myfile.xlsx';
    const result = await fetch(downloadUrl, {
        headers: { authorization: `Bearer ${auth.authToken}` }
    })
    const file = await result.blob()
    const fileUrl = URL.createObjectURL(file)
    const filename = `Report - ${userName}.xlsx`
    downloadThroughAnchorLink(fileUrl, filename);

A: If you are already using jQuery, you could take adventage of it to produce a smaller snippet
A jQuery version of Andrew's answer:
var $idown;  // Keep it outside of the function, so it's initialized once.
downloadURL : function(url) {
  if ($idown) {
    $idown.attr('src',url);
  } else {
    $idown = $('', { id:'idown', src:url }).hide().appendTo('body');
  }
},
//... How to use it:
downloadURL('http://whatever.com/file.pdf');

A: This could be helpful if you are not require to navigate another page.
This is base javascript function, so can be used in any platform where backend is in Javascript
window.location.assign('any url or file path')

A: Works on Chrome, Firefox and IE8 and above.
var link=document.createElement('a');
document.body.appendChild(link);
link.href=url ;
link.click();

A: Simple example using an iframe
function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
};

Then just call the function wherever you want:
downloadURL('path/to/my/file');

A: I ended up using the below snippet and it works in most browsers, not tested in IE though.

let data = JSON.stringify([{email: "test@domain.com", name: "test"}, {email: "anothertest@example.com", name: "anothertest"}]);

let type = "application/json", name = "testfile.json";
downloader(data, type, name)

function downloader(data, type, name) {
 let blob = new Blob([data], {type});
 let url = window.URL.createObjectURL(blob);
 downloadURI(url, name);
 window.URL.revokeObjectURL(url);
}

function downloadURI(uri, name) {
    let link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

Update
function downloadURI(uri, name) {
    let link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

function downloader(data, type, name) {
    let blob = new Blob([data], {type});
    let url = window.URL.createObjectURL(blob);
    downloadURI(url, name);
    window.URL.revokeObjectURL(url);
}

A: for me this is working ok tested in chrome v72
function down_file(url,name){
var a = $("")
    .attr("href", url)
    .attr("download", name)
    .appendTo("body");
a[0].click();
a.remove();
}

down_file('https://www.useotools.com/uploads/nulogo[1].png','logo.png')

A: Only pass link of the file. It will download the file with it's original name.
function downloadFileWithLink(href) {
    var link = document.createElement("a");
    let name = (href?.split("/") || [])
    name = name[name?.length-1]
    link.setAttribute('download', name);
    link.href = href;
    document.body.appendChild(link);
    link.click();
    link.remove();
}

A: These functions are used in stacktrace.js:
/**
 * Try XHR methods in order and store XHR factory.
 *
 * @return <Function> XHR function or equivalent
 */
var createXMLHTTPObject = function() {
    var xmlhttp, XMLHttpFactories = [
        function() {
            return new XMLHttpRequest();
        }, function() {
            return new ActiveXObject('Msxml2.XMLHTTP');
        }, function() {
            return new ActiveXObject('Msxml3.XMLHTTP');
        }, function() {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    ];
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
            // Use memoization to cache the factory
            createXMLHTTPObject = XMLHttpFactories[i];
            return xmlhttp;
        } catch (e) {
        }
    }
}

/**
 * @return the text from a given URL
 */
function ajax(url) {
    var req = createXMLHTTPObject();
    if (req) {
        try {
            req.open('GET', url, false);
            req.send(null);
            return req.responseText;
        } catch (e) {
        }
    }
    return '';
}

A: I suggest you use the mousedown event, which is called BEFORE the click event. That way, the browser handles the click event naturally, which avoids any code weirdness:
(function ($) {

    // with this solution, the browser handles the download link naturally (tested in chrome and firefox)
    $(document).ready(function () {

        var url = '/private/downloads/myfile123.pdf';
        $("a#someID").on('mousedown', function () {
            $(this).attr("href", url);
        });

    });
})(jQuery);

A: Excelent solution from Corbacho, I just adapted to get rid o the var
function downloadURL(url) {
    if( $('#idown').length ){
        $('#idown').attr('src',url);
    }else{
        $('', { id:'idown', src:url }).hide().appendTo('body');
    }
}

A: Firefox and Chrome tested:
var link = document.createElement('a');
link.download = 'fileName.ext'
link.href = 'http://down.serv/file.ext';

// Because firefox not executing the .click() well
// We need to create mouse event initialization.
var clickEvent = document.createEvent("MouseEvent");
clickEvent.initEvent("click", true, true);

link.dispatchEvent(clickEvent);

This is actually the "chrome" way solution for firefox (I am not tested it on other browsers, so please leave comments about the compilability)

A: I have had good results with using a FORM tag since it works everywhere and you don't have to create temporarily files on server. The method works like this.
On the client side (page HTML) you create an invisible form like this
<form method="POST" action="/download.php" target="_blank" id="downloadForm">
    <input type="hidden" name="data" id="csv">
</form>

Then you add this Javascript code to your button:
$('#button').click(function() {
     $('#csv').val('---your data---');
     $('#downloadForm').submit();
}

The on the server-side you have the following PHP code in download.php:
<?php
header('Content-Type: text/csv');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=out.csv');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($data));

echo $_REQUEST['data'];
exit();

You can even create zip files of your data like this:
<?php

$file = tempnam("tmp", "zip");

$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$zip->addFromString('test.csv', $_REQUEST['data']);
$zip->close();

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file);

The best part is it does not leave any residual files on your server since everything is created and destroyed on the fly!

A: Using anchor tag and PHP it can be done, Check this answer
JQuery Ajax call for PDF file download
HTML
    Download pdf here

PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    }
    if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }
    readfile($fullPath);
    exit;
}
?>

I am checking for file size because if you load pdf from CDN cloudfront, you won`t get the size of document which forces the document to download in 0kb, To avoid this i am checking with this condition
 if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }

A: I know I'm late for the party, but I'd like to share my solution which is variation of Imagine Breaker's solution above. I tried to use his solution, because his solution seems most simple and easy to me. But like other said, it didn't work for some browsers, so I put some variation on it by using jquery.
Hope this could help someone out there.
function download(url) {
  var link = document.createElement("a");
  $(link).click(function(e) {
    e.preventDefault();
    window.location.href = url;
  });
  $(link).click();
}

A: The answer submitted by hitesh on Dec 30 '13 does in fact work.  It just requires a little adjusting:
The PHP file can call itself.  In other words, just create a file named saveAs.php, and put this code into it...
        Download pdf here

    <?php
        if (isset($_GET['file_source'])) {
            $fullPath = $_GET['file_source'];
            if($fullPath) {
                $fsize = filesize($fullPath);
                $path_parts = pathinfo($fullPath);
                $ext = strtolower($path_parts["extension"]);
                switch ($ext) {
                    case "pdf":
                    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
                    header("Content-type: application/pdf"); // add here more headers for diff. extensions
                    break;
                    default;
                    header("Content-type: application/octet-stream");
                    header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
                }
                if($fsize) {//checking if file size exist
                  header("Content-length: $fsize");
                }
                readfile($fullPath);
                exit;
            }
        }
    ?>

A: Note: Not supported in all browsers.
I was looking for a way to download a file using jquery without having to set the file url in the href attribute from the beginning.

jQuery('', {
    id: 'downloadFile',
    href: 'http://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png',
    style: 'display:hidden;',
    download: ''
}).appendTo('body');

$("#downloadFile")[0].click();

A: I use @rakaloof's solution without JQuery (because you don't need it here). Thank you for the idea! Here is a vanillaJS form-based solution:

const uri = 'https://upload.wikimedia.org/wikipedia/commons/b/bb/Test_ogg_mp3_48kbps.wav';
let form = document.createElement("form");
form.setAttribute('action', uri);
document.body.appendChild(form);
form.submit();
document.body.removeChild(document.body.lastElementChild);


text:
Q: When is the square root of a polynomial holomorphic? And how do you take the contour integral? I am asked to show that if $p(z)$ is a polynomial such that all the roots satisfy $|z| < R$, then for $|z| > R$ there is an analytic/holomorphic function $h(z)$ such that $(h(z))^2 = p(z)$ when $p(z)$ is of even degree.
I was tempted to think that this was trivially true, but I suppose it depends on the exponential definition of powers, specifically that $$z^a = e^{\frac{1}{2}log(z)}$$ where are appropriate branch of log is chosen. The evenness of $p$ then comes in handy since it ensures that if we cross over the branch cut, the total jump in the argument of the exponential is $2ni\pi$ for some integer $n$, thus ensuring that the square root of $p$ is well defined for $|z| > R$ where crossing over the branch cut ensures that every linear factor of $p$ also crosses it. This would explain why the conditions of $|z| > R$ and evenness were given.
Is this the right way to think about it?
In the next part of the question I am asked to compute $$\int_C \sqrt{z^4 -z} \; dz$$ where $C = \{z \in \mathbb C \;|\; |z| = 2\}$
It suggests that I work out the Laurent Series in order to do this question. I am not sure how to work out the Laurent expansion here, nor am I sure how else to do it.
I have thought that perhaps since the contour contains all the roots of $p(z) = z^4 - z $ and thus $h(z) = \sqrt{p(z)}$, and since all the roots are branch points, i.e. points that cannot have a defined argument, then I can apply the residue theorem and get:
$$ \int _ C \sqrt{z^4 - z} \;dz = \sum^{4}_{i=1} I(C,a_i)Res(h,a_i)$$ where $(a_1,a_2,a_3,a_4) = (0,1,w,w^2)$ and $w$ is a strictly complex cube root of unity.
But even if this were true, I don't know how to calculate the residues.
I feel like I'm missing something really simple. Any help would be appreciated, thank you!

A: To compute the integral, you need to compute the residue at infinity.
If you increase the radius, since the integrand is holomorphic outside of the unit disk, you don't change the value of the integral.
If you pick the branch $h(z)$ whose value at $z=2$ is $h(2) = +\sqrt{14}$, then $h$ has an asymptotic development at infinity :
$h(z) = z^2 -\frac 12 z^{-1} + O(z^{-4})$
Now, as the radius increases, the integral of the $O(z^{-4})$ term converges to $0$, and since it's independant of the radius, it is $0$.
Moreover, $\int z^2 dz = 0$, and $\int  z^{-1} dz = 2i\pi$, and so $\int h(z) dz = -i\pi$


text:
Q: Why don't the addresses in `/boot/System.map-*` and `/proc/kallsyms` match? Consider the output of /boot/System.map-5.8.0-50-generic and /proc/kallsyms on Ubuntu 20.10 (Groovy Gorilla):
$ sudo cat /boot/System.map-5.8.0-50-generic | grep sys_call_table
ffffffff820002e0 D sys_call_table
ffffffff82001360 D ia32_sys_call_table
ffffffff82002120 D x32_sys_call_table
$ sudo cat /proc/kallsyms | grep sys_call_table
ffffffff978002e0 D sys_call_table
ffffffff97801360 D ia32_sys_call_table
ffffffff97802120 D x32_sys_call_table

AFAIK, these files should contain the current load addresses of kernel symbols, so why don't they match?
Is it because only /proc/kallsyms is affected by KASLR? If so, how can I verify whether KASLR is enabled?

A: Yes, this is caused by KASLR. Note that all addresses are offset by the same amount. The kernel doesn't know about System.map so it doesn't update it.
I'm not aware of any way of detecting whether KASLR is enabled from userspace at runtime, short of comparing /proc/kallsyms and System.map, or possibly causing a panic on x86 (the kernel dumps its offset on panic there).


text:
Q: How to deploy angular universal on IIS Can someone help me to deploy angular universal build on IIS server?
I have integrated angular universal in existing angular 13 project and its working fine. but my problem with deployment on IIS when deploying build as website it's working for example on root (https:www.domain.com) but I want this to deploy as application not website (https:www.domain.com/myapp).
Where myapp is application which is under sites.
Facing issues like MIME type or unexpected syntax error for CSS/JS files.
Can someone please help me on this
Tried with Deploy Angular Universal to IIS
But this is for website, want to deploy as application on iis


text:
Q: Python API client doesn't recognize 'login' type for Reports API I've been trying to use Python and a service account to access the new Reports API to download user login information. I can successfully build a service account, and then I try to call activities.list using ApplicationName='login' (see snippet below).
def createAuditService():
  f = file(my-private-key, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(my-service-account, key,
      scope='https://www.googleapis.com/auth/admin.reports.audit.readonly')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('reports', 'v1', http=http)

def retrieveActivites(service):
  try:
    Logins = service.activities().list(userKey='all',applicationName='login').execute()
    return Logins.get('items',[])
  except errors.HttpError, error:
    log.error('An error occurred.',exc_info=True)
  return None

def main():
  service = createAuditService()
  activities = retrieveActivites(service)
  print activities

Instead I get the following error:
2013-11-28 09:51:17,727 - apiclient.discovery - INFO - URL being requested: https://www.googleapis.com/discovery/v1/apis/reports/v1/rest
2013-11-28 09:51:17,727 - oauth2client.client - INFO - Attempting refresh to obtain initial access_token
2013-11-28 09:51:18,135 - oauth2client.client - INFO - Refreshing access_token
Traceback (most recent call last):
  File "F:\Dropbox\code\glogin-audit\glogin.py", line 105, in <module>
    main()
  File "F:\Dropbox\code\glogin-audit\glogin.py", line 91, in main
    activities = retrieveActivites(service)
  File "F:\Dropbox\code\glogin-audit\glogin.py", line 75, in retrieveActivites
    Logins = service.activities().list(userKey='all',applicationName='login').execute()
  File "build\bdist.win32\egg\apiclient\discovery.py", line 595, in method
    (name, pvalue, regex))
TypeError: Parameter "applicationName" value "login" does not match the pattern "(admin)|(docs)"

Using 'admin' or 'docs' values instead of 'login' for the applicationName parameter produces valid data, so I'm fairly sure I have the syntax right (see the API reference here, and the Python client reference here).
Also, I was having the problem with the Python client v1.1, but I'm having the same problem after I upgraded to 1.2: easy_install --upgrade google-api-python-client
Any suggested next steps?

A: You need to replace the last line of your createAuditService() function:
return build('reports', 'v1', http=http)

with:
return build('admin', 'reports_v1', http=http)

in order to get the latest version of the discovery document which supports login reports.


text:
Q: Reference user supplied file with Flask app I am new to Flask and web applications in general.  I have images that could be located in different locations:
-directory1
  -image1
-directory2
  -subdirectory
    -image2
-directory3
  -flask_app
    -app.py
    -static

The purpose of the app is to dynamically provide access to the content in other directories which is not static and subject to change for each user.  The content cannot be moved or modified.
How do I display images from other directories within the app without moving or modifying them based on input values from the user?
I have the following so far but the image link is broken:
from flask import Flask, render_template, request, send_from_directory

current_filepath = /directory2/image{}.png

app = Flask(__name__, static_url_path='')

@app.route('/js/<path:filename>')
def download_file(filename):
    return send_from_directory('js', filename)

@app.route('/', methods=['GET','POST'])
def print_form():
    if request.method == 'POST':
        test = current_filepath.format(request.form['image_num'])
        return render_template('form.html', result=test)

    if request.method == 'GET':
        return render_template('form.html')

if __name__ == '__main__':
    app.run(debug=True)

With the following form.html file:
<!DOCTYPE html>

<form method="POST" action=".">
   <input id="post_form_id" name="image_num" value="" />
   <input type="submit">
</form>

{% if result %}
    {{ url_for('download_file', filename= result) }}

{% endif %}

A: app/
   app.py
   ...
uploads/
   dir1/
      img1.png
      ...
...
app.config['UPLOAD_FOLDER'] = 'path/to/uploads/dir1'

@app.route('/file/<path:filename>')
def img_file(filename):
    filename = filename + '.png'
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/', methods=['GET', 'POST'])
def index():
    filename = None
    if request.method == 'POST':
        filename = request.form['img_num']
    return render_template('form.html', filename=filename)

<form method="post" action="" >
    <input type="text" id="form_id" name="img_num">
    <input type="submit" value="submit">
</form>
    {% if filename %}

    {% endif %}


text:
Q: Transition element size caused by content changes I have a button that has some text in it. When you press it, the text changes. This makes the button's width change. It would be great if one could transition the change of an element's width with something like this:
#el {
    transition: width 150ms ease-out;
}

Of course, that only works when you explicitly change the width property.
Does anyone know of an elegant way to achieve this effect? Here's a (yet-to-function) fiddle to hack away at.

A: Try this fiddle that does it using jQuery.
$('button').click(function() {
    var width = $(this).css('width');
    var height = $(this).css('height');
    $(this).html('Hello, World!');
    var newWidth = $(this).css('width');
    $(this).css({'width': width, 'height': height});
    $(this).animate({'width': newWidth}, 1000);
});

A: With Maurice's answer, the button's text overflowed to a second line, which was worked around by forcing the height of the button to its original height.
Instead, use
button {
    white-space: nowrap;
}

so that the button's text stays on one line and is shown while in transition. Then the code no longer has to deal with the button's height, so it can become simpler:
$('button').click(function() {
    var width = $(this).css('width');
    $(this).text('Hello, World!');
    var newWidth = $(this).css('width');
    $(this).css({'width': width});
    $(this).animate({'width': newWidth}, 400);
});

http://jsfiddle.net/2rr54vp2/1/

A: I guess this' impossible, because the browser can't get the exact target width; Let's suppose it got the value before transition, but at that time ,the button has arrived the width! Maybe the tansition exists, and we can't see it.
so you need an initial width, and you need to know the target width too, us js


text:
Q: Symfony 3 authentication and authorization I'm building a site on top of latest Symfony framework (v3.3). I have no limitation on what packages to use. The authentication/authorization mechanism will get complicated over time; currently it has the following requirements:

*

*In-memory authentication for the  "root" user

*On top of the "root" authentication, one of:

*

*Local database user/pass authentication

*LDAP authentication

*Azure Active Directory (graph-api)

Regarding authorization,

*

*There are four levels: ROOT, ADMIN, USER, ANONYMOUS

*In case of USERS, we need to have a set of security groups that regulate what parts of data is accessible (ie. HARDWARE, SOFTWARE, ACCESSORIES).

So, the question is:
Does Symfony 3 provide a easy solution of such setup out of the box? (ie. using LdapUserProvider)
If the answer do the above question is "NO", I'm contemplate using FOSUserBundle and FR3DLdapBundle. As of mid 2017, will this decision complicate my life in long term or will it simplify it?

A: You can use FOS User Bundle. This Bundle is:

*

*easy to set up,

*is well known in community (which is important when you meet some issues)

*highly configurable, which allows you to set up authorization with LDAP


text:
Q: Saving NSTimer's time to disk on entering background and retrieving on foreground I want my timer to work in the background, and I have figured the only way to actually do that is to save the time on appliationDidEnterBackground and retrieve it with applicationDidLaunchWithOptions. My timer uses Core Data and my timeInterval (testTask.timeInterval) is saved after every decrement as so:
-(IBAction)startTimer:(id)sender{
    if (timer == nil) {
        [startButton setTitle:@"Pause" forState:UIControlStateNormal];
       timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    } else {
        [startButton setTitle:@"Resume" forState:UIControlStateNormal];
        [timer invalidate];
        timer = nil;
    }

}
-(void)timerAction:(NSTimer *)t
{
    if(testTask.timeInterval == 0)
    {
        if (self.timer)
        {
            [self timerExpired];
            [self.timer invalidate];
            self.timer = nil;
        }
    }
    else
    {
        testTask.timeInterval--;
        NSError *error;
        if (![self.context save:&error]) {
            NSLog(@"couldn't save: %@", [error localizedDescription]);
        }
    }
    NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
    NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
                        seconds / 3600, (seconds / 60) % 60, seconds % 60];
    timerLabel.text = string;
    NSLog(@"%f", testTask.timeInterval);
}
-(void)timerExpired{
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.alertBody = @"Time is up";
    localNotification.alertAction = @"Ok";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}

These methods are in a detail view controller, which is initialized by this:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *detailVC;
    if (![self.detailViewsDictionary.allKeys containsObject:indexPath]){
        detailVC = [[DetailViewController alloc]initWithNibName:@"DetailViewController" bundle:nil];
        [self.detailViewsDictionary setObject:detailVC forKey:indexPath];
        detailVC.context = self.managedObjectContext;
    }else{
        detailVC = self.detailViewsDictionary[indexPath];
    }
        Tasks *task = [[self fetchedResultsController] objectAtIndexPath:indexPath];
        detailVC.testTask = task;
        [[self navigationController] pushViewController:detailVC animated:YES];
    NSLog(@"%@", self.detailViewsDictionary);
}

What I don't understand is...how would I access the timeInterval (each detailviewcontroller has a different timeinterval...) such that I can put it in appliationDidEnterBackground? Also, I am guessing I should save the time that the application enters the background and then save the time when it enters the foreground, and subtract? and then I would subtract that value from the timeinterval, correct?

A: First, you shouldn't be using a direct countdown like this if you care at all about accuracy. The NSTimer will not fire on exact one-second intervals, and delays will accumulate. The better way to do this is to create an NSDate when the timer starts, and get the NSTimeInterval since then at each tick, then calculate the minutes and seconds.
For each view controller to store its own start time, you can register any object to receive the UIApplicationDidEnterBackgroundNotification. This is posted at the same time that the app delegate gets applicationDidEnterBackground:.

Also, I am guessing I should save the time that the application enters the background and then save the time when it enters the foreground, and subtract? and then I would subtract that value from the timeinterval, correct?

Yes:
NSTimeInterval idleTime = [dateReturnedToForeground timeIntervalSinceDate:dateEnteredBackground];
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];
elapsedTime -= idleTime;

will give you the active time that has elapsed for your timer.


text:
Q: To show series convergent if $\sum a_n $ converges If$ a_n> 0$ for n $\ge $1 and $ \lim_{n\to \infty} {a_n}^{\frac{1}{n}}=L<1$ which of following series is convergent:

*

*$ \sum \sqrt{a_na_{n+1}}$

*$\sum a_n^2$

*$ \sum \sqrt{a_n}$

4  $ \sum \frac{1}{\sqrt{a_n}}$
I tried showing $\sum a_n^2$ convergent by comparison test, but I am unsure of how to show others.

A: Use the root test.

*

*$\sqrt[n]{\sqrt{a_{n+1}a_n}}\to L<1$, convergent.

*$\sqrt[n]{a_n^2}\to L^2<1$, convergent.

*$\sqrt[n]{\sqrt{a_n}}\to \sqrt{L}<1$, convergent.

*$\sqrt[n]{\frac{1}{\sqrt{a_n}}}\to\frac{1}{\sqrt{L}}>1$, divergent.


text:
Q: BadDataError when converting .DBF to .csv I am trying to convert a .DBF file to .csv using Python3. I am trying using the dbf library (https://pypi.python.org/pypi/dbf)
import dbf

def dbf_to_csv(dbf_file_name, csv_file_name):
    dbf_file = dbf.Table(dbf_file_name, ignore_memos=True)
    dbf_file.open()
    dbf.export(dbf_file, filename = csv_file_name, format='csv', header=True)

The DBF file I am using can be opened in Excel and appears to be fine. However, when I run the above method I get an error on the dbf.export line above:
dbf.ver_33.BadDataError: record data is not the correct length (should be 1442, not 1438)

The dbf file opens fine in Excel, however, I need to automate this conversion. What should I be doing differently to get this method to create a pdf from a .DBF file?

A: If the file is opening correctly in Excel, then I suggest you use Excel to do the conversion for you to csv format as follows:
import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')

wb = excel.Workbooks.Open(r"input.dbf")
excel.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs(r"output.csv", FileFormat=6, ConflictResolution=2)
excel.Application.Quit()

Do not forget to add full paths to the required files. Note, FileFormat=6 tells Excel to save the file in CSV format.
To export the workbook as a PDF, you could use:
wb.ExportAsFixedFormat(0, r"output.pdf")

If you do not already have win32com installed you should be able to use the following:
pip install pypiwin32

This solution is suitable for Windows installations only.


text:
Q: Application error when access /_layouts/15/clientname.FBAProject.FBA2FA/Login.aspx, I have a sharepoint 2013 FBA web application, that was normally working, and suddenly in the login page I am getting 403 Access Denied
WHen I check the ULS logs I found this:

*

*The application poool is under an account sp_dev_farm which has access to both folders on the first line of the error.

*The applicaiton pool account also has permission on SQL Server, but I dont think it has anything to do with this.
Application error when access /_layouts/15/xxx.FBAProject.FBA2FA/Login.aspx, Error=Access to the path 'C:\inetpub\wwwroot\wss\VirtualDirectories\TwoFactorDllo80\bin' is denied.
 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
 at System.IO.FileSystemEnumerableIterator1.CommonInit()
 at System.IO.FileSystemEnumerableIterator1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
 at System.IO.DirectoryInfo.InternalGetFiles(String searchPattern, SearchOption searchOption)
 at System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory()
 at System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai)
 at System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig)
 at System.Web.UI.ScriptManager.get_DefaultAjaxFrameworkAssembly()
 at System.Web.UI.ScriptManager..ctor()
 at ASP._layouts_15_errorv15_master.__BuildControlScriptManager() in c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\errorv15.master:line 25
 at ASP._layouts_15_errorv15_master.__BuildControl__control19() in c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\errorv15.master:line 24
 at ASP._layouts_15_errorv15_master.__BuildControl__control3() in c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\errorv15.master:line 6
 at ASP._layouts_15_errorv15_master.__BuildControlTree(_layouts_15_errorv15_master __ctrl) in c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\errorv15.master:line 1
 at ASP._layouts_15_errorv15_master.FrameworkInitialize() in c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\6e7557e4\b1dd58aa\App_Web_errorv15.master.9c9699a8.qjxveg5g.0.cs:line 0
 at System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection)
 at System.Web.UI.Page.get_Master()
 at System.Web.UI.Page.ApplyMasterPage()
 at System.Web.UI.Page.PerformPreInit()
 at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)


text:
Q: Uniform convergence $\sum_{n=1}^\infty \frac{n^2-n^4}{n^5+n^3+1}\left(x^2\sin\left(\frac{\pi x}{2}\right)\right)^n$. Troubling finding the interval. I have to find the interval of uniform convergence, for the series
$$\sum_{n=1}^\infty \frac{n^2-n^4}{n^5+n^3+1}\left(x^2\sin\left(\frac{\pi x}{2}\right)\right)^n$$
Now my attempt has been to use the quotient (ratio) test to find the interval on which the series converges, so that I can find an upper bound. Taking the quotient test gives me the following:
$$\left|\frac{a_{n+1}}{a_n}\right|\rightarrow \left|x^2\sin\left(\frac{\pi x}{2}\right)\right|,   n \rightarrow \infty$$
Therefore the series must be absolutely convergent on when
$$\left|x^2\sin\left(\frac{\pi x}{2}\right)\right| < 1$$
However since this doesn't give me an upper bound, I'm stuck. The assignment offers me a few options to pick from, and there are no interval options above or below $\pm\sqrt{2}$, so I know that while there are intervals around all even numbers of $x$ these are not useful, though I do not know why. What am I missing?


text:
Q: Azure Shared Access Signature At a Folder Level Azure SAS
From what I have read you can put a SAS URI in the browser and bring up the file
You can also create a SAS with list and read permission to the container.  In .NET I follow how to use that.
Can you map that SAS list and read as a network drive in Windows Explorer and see the file?.

A: To my knowledge, for now, there is no existing tool able to map the azure storage as a network drive by SAS. (There are tools which can achieve it by account and primary key.)
The most similar tool which can allow user access the azure storage with GUI through SAS is Azure storage explorer. It's free and released by Microsoft.
Besides, the SAS can only be deployed on container level or blob level. We can not apply SAS on folders. Because there is no concept of folder in Azure storage. The folder is actually the part of the blob name.
Here is the screenshot of my lab:


text:
Q: Python - How to specify a relative path by jumping a subdirectory? I'm in one location i.e. 'c:/program files/java' and I want to jump two levels down without having to specify the subfolders i.e. I want to move to 'c:/program files/java/7.0/jre/bin' without specifying '/7.0/'.
A snippet I'm using is:
import os
os.chdir('c://program files//java')

os.getcwd()

'c:/program files/java'
Now I want to use os.chdir() to move to '/7.0/jre' so os.getcwd() is 'c://program files//java/7.0/jre'
without having to specify '7.0' i.e. os.chdir('.\**7.0**\jre')
Does anyone have any suggestions?

A: You can use glob.glob:
import glob
import os

os.chdir('c:/program files/java')
os.chdir(glob.glob('*/jre')[0])

Above code will change working directory to c:/program files/java/*/jre.
In case there are multiple java directory, and you want to go to specific directory (for example, to the newest version directory), you should manipulate the return value of glob.glob().