Login com facebook no Xamarin Forms com Azure Mobile Apps

Question: Estou construindo um app(com xamarin.forms pcl), onde tenho um login com facebook, utilizando o Azure Mobile Client SDK. É possível realizar a autenticação, porem, logo após a autenticação, eu tento fazer uma listagem na url da api: https://adoteumamigo.azurewebsites.net/api/Tipo e tenho o retorno 401 Unauthorized.
Sendo que o login com a rede social foi realizado com sucesso.
Segue as evidências:

Código onde tenho o problema:
public async Task<List<Tipo>> GetTipoAsync()
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await httpClient.GetAsync($"{BaseUrl}Tipo").ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    return JsonConvert.DeserializeObject<List<Tipo>>(
                        await new StreamReader(responseStream).ReadToEndAsync().ConfigureAwait(false));
                }
            }

            return null;
        }

Observação: Antes de colocar a autenticação com facebook, o acesso a api e o get dos dados para listagem funcionava corretamente.  O problema é porque está dando esse acesso sem autorização na url, mesmo após estar logado.
Observação 2: É possível testar a api no browser, com a autenticação do facebook, e a mesma funciona corretamente.
Comment: Está utilizando a classe `MobileServiceClient` para autenticação no Facebook?
Comment: @rubStackOverflow Estou sim. A authenticação funciona, logo no facebook, o MobileServiceCliente me retorna o sid e o token. Agora pela manhã andei pesquisando, e encontrei algo que pode ser o seguinte: Esse token quem esta me retornando é a Azure, e devo pegar o token do facebook e na hora de fazer a listagem da api, enviar o token do facebook... mas ainda não testei. Faz sentido?
Comment: Sim, é isso mesmo.
Answer: Me parece que está participando da Maratona Xamarin. Para pegar os dados do perfil fiz da seguinte forma:
public class AzureService
{
    List<AppServiceIdentity> identities = null;
    public MobileServiceClient Client { get; set; } = null;
    .....
}

......
identities = await Client.InvokeApiAsync<List<AppServiceIdentity>>("/.auth/me");
var name = identities[0].UserClaims.Find(c =>
c.Type.Equals("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname")).Value;

var userToken = identities[0].AccessToken;

var requestUrl = $"https://graph.facebook.com/v2.9/me/?fields=picture&access_token={userToken}";

var httpClient = new HttpClient();

var userJson = await httpClient.GetStringAsync(requestUrl);

var facebookProfile = JsonConvert.DeserializeObject<FacebookProfile>(userJson)
......

Fonte:
https://github.com/rubgithub/JogoDaVelhaMaratonaXamarin/blob/master/JogoDaVelhaMaratona/JogoDaVelhaMaratona/Service/AzureService.cs
Comment: Segui suas dicas, porem ainda não consegui resolver. Ao tentar utilizar o httpCliente para um getAsync na minha url https://adoteumamigo.azurewebsites.net/api/Tipo depois de logado com o facebook, continuo recebendo o código 401 Unauthorized.
Comment: e sim, estou fazendo a maratona sim, e seguindo os passos dos vídeos, porem ao fazer o login com facebook, e tentar utilizar uma api (q esta hospedada na azure) para listar itens estou tendo este problema.
Comment: Você está utilizando o token obtido aqui? `identities = await Client.InvokeApiAsync>("/.auth/me");`
Comment: estou sim. E ai me entra outra dúvida, eu posso ta fazendo algo errado na hora q eu faço o getAsync aqui var response = await httpClient.GetAsync($"{BaseUrl}Tipo").ConfigureAwait(false);


app.yaml skip_files skip an entire directory but one individual file

Question: I have an app.yaml file in which I want to skip the entire node_modules directory save for one file I added called helpers.js. Currently my file looks like this:
runtime: nodejs
vm: true
skip_files:
 - ^node_modules$

What's the best way of skipping the entire node_modules directory except for helpers.js?
Comment: it's not clear to me what you're asking.
Comment: @sweaver2112 I am asking for a regex which will exclude all files in the `node_modules` directory except for `helpers.js`
Answer: It would appear you can just use a negative lookahead in your regex to do this:
^node_modules/(?!node\.js$).*

*this post may be useful to you also.
Comment: for new runtimes it seems this is no longer supported and you need to use .gcloudignore files, which basically follows the same syntax as .gitignore


What is meant by $F(\beta )$ in field theory?

Question: I'm a self learning non-student, and I was working on some field theory from Fraleigh's text. There is a question which is numbered (29) in the document linked below. I cannot understand the solution. My question is how it is known that $F(\beta) = ${$f(\beta)/g(\beta) \, | \, where \,  f(x), g(x) \in F[x]$}. My understanding was that if an element $\alpha \in E$ was transcendental then we could apply that any element in F($\alpha$) was of the form $f(\alpha)/g(\alpha)$. Here it is not given that $\beta$ is transcendental over F, but it is $\alpha$ which is transcendental over F.
Link: http://www.ms.uky.edu/~okeefea/Teaching_files/Sect%2029%20Solutions.pdf
Comment: This is the definition of the notation $F(\beta)$ it is rational functions in $\beta$ with coefficients in $F$. So it is not known "because" of anything:  it is the definition.
Comment: @ Adam Hughes I don't see then that they use that alpha is transcendental over F at all anywhere in the proof.
Comment: I'm not sure I understand your response. I'm just noting that $F(\beta)$ or $F(\alpha)$ or whatever is just rational functions in the thing(s) inside the parentheses. How this definition is used in a proof is a wholly separate issue from what the notation means.
Comment: Adam : it's not really the definition, the correct answer is that of arctic tern
Answer: If $K/F$ is a field extension and $\beta\in K$  then $F(\beta)$ is the "smallest" subfield of $K$ that contains both the subfield $F$ and the element $\beta$. Among all subfields of $K$ with this property, is is the unique minimal one (where such subfields are partially ordered by containment), and it also equals the intersection of all of the subfields with this property (containing both $K$ and $\beta$).
Consider the subset $S$ of $K$ consisting of all elements expressible as rational expressions in $\beta$ with coefficients in $F$. This is closed under addition, subtraction, multiplication and division - so it is a subfield of $K$. Moreoever, it contains $F$ and $\beta$. Conversely, suppose $L$ is any subfield of $K$ that contains both $F$ and $\beta$. Then since $L$ is closed under the field operations, $L$ must also contain every rational expression in $\beta$ with coefficients in $F$, in other words $S\subseteq L$. Therefore, $S$ is the minimal subfield with this property, and $S=F(\beta)$.


Entity Framework - groupby and timespan calculation

Question: I want to calculate total hours of each person in EF.
I can calculate the total hours in MYSQL statement but I have problem with EF.
This is the SQL statement
<code>SELECT name, SEC_TO_TIME(Sum(TIME_TO_SEC(TIMEDIFF(ClockOutTime,ClockInTime))))
FROM Attendance
GROUP BY name
</code>
I want to convert the above statement to EF.
This is what I have so far in controller
<code> var model = db.Attendances
            .GroupBy(a => a.name)
            .Select(g => new AttendanceViewModel
            {
                name = g.Key,
                totalHours = SqlFunctions.DateDiff("seconds",
                                                   g.Select( a=> a.ClockInTime),
                                                   g.Select(a=>a.ClockOutTime))
            }).ToList();
</code>
The problem that I have is that g.Select( a=>a.ClockInTime) return IEnumrable, and hence I cannot use SqlFunctions.DateDiff direcly. How do I solve this problem? Is there alternative way?
Answer: You can select hours for each attendance and do totals calculation after grouping
<code>  db.Attendances
    .Select(a => new {
        a.name,
        hours = SqlFunctions.DateDiff("seconds", a.ClockInTime, a.ClockOutTime)
    })
    .GroupBy(x => x.name)
    .Select(g => new AttendanceViewModel {
        name = g.Key,
        totalHours = Sum(x => x.hours)
    })
   .ToList();
</code>
BTW why you named property hours if you are calculating seconds?
Comment: Thank you so much! Thank you for pointing out the property name also. I wasn't very careful about choosing the name.


How can I make random forest have multiple valid outcomes?

Question: I am new in machine learning I will describe my problem with similar approach.
I want to make a random forest with multiple but diffrent outcomes.
My example is I want the decision tree or random forest to decide which clothes should i wear in some event(example custome party or bussniess meeting...) but I need it to decide which hat is appropriate, which t-shirt is appropriate, shoes...
All have the same root that is me wearing them and the event but with diffrent clothes body parts.
For example in bussniss meeting  in my upper half I will wear a suit with tie or butterfly tie and blue texido or black texido
I mean in the same tree there will possible multiple outcomes.
I hope what I mean is clear.
Comment: Why does it have to be a single random forest for all of these clothing items instead of a random forest for hats, another random forest for shirts, and another random forest for pants?
Comment: Do you mean to say you'd like to classify the most likely clothing item based on variables such as event and body part the clothing covers?
Comment: Yes in that example the items can be independent of each other,  let's say I have customer who will write their own car specification with details for example the car must be medium sized with red color,  have wide back, turbo engine... With many diffrent specifications, and currently I have multiple cars that satisfy the customer needs and I need a random firest for it. I mean I want from natural language processing get the key words then with the decision tree I get the best fit or multiple fit.
Comment: Okay, well that's a very interesting problem. But it seems to me that your problem is very broadly stated here. That's normally okay by me, but it seems like you may be missing some pre-requisite ML/DL knowledge it would take to implement such a recommender system.  Perhaps you would be better served by checking out some online courses that cover ML/DL concepts, and then bring your specific questions?
Comment: Yes thank you,  I think I am trying to  make reverse decision tree, I think there is no need to do that, it can be achieved by maybe simple database filters after all. My project need me to do machine learning but I am not really convenced for the need of that.
Answer: If you mean to say you'd like to classify the most likely clothing item based on variables such as event and body part the clothing covers, it seems fairly trivial to condition a model off of those two variables such that your input is some tuple x = (event_type, body_part) and the output is y = clothing_item. For a full output, say hat, shirt and pants for a costume party, you'd need three inputs:

x = (party, head)
x = (party, torso)
x = (party, legs)

And hopefully, your random forest would give you three corresponding outputs based on your training data. Or, you could build a model that outputs a probability distribution based on each input, giving you some likely candidates to choose from.


How do I use an array of values to limit a for loop in perl?

Question: The question is rather vague I know, but I hope the space to explain may help shed light, this is something I've wracked my brain around all day and couldn't find any advice through searching.
Basically I have an array @cluster that I'm trying to use to make an iterator $x skip over the values located in that array. The array will vary in size, so I can't just (rather atrociously) make if statements to fit all cases unfortunately.
Normally when I need to do this with a scalar value I just do:
for my $x (0 .. $numLines){
    if($x != $value){
        ...
    }
}

Any advice?
Comment: do you mean something like `for my $x(@cluster)`?
Comment: Quite the opposite. I want any value in @cluster to not be used.
I suppose I could use another for loop like `for my $y(@cluster)` within my current for $x loop.
Comment: How do you know the values you want to skip?  Is it that it equals a particular value or is the n value processed?
Comment: It equals any value located in @cluster.
Answer: You can do:
my @cluster = (1,3,4,7);
outer: for my $x (0 .. 10){
    $x eq $_ and next outer for @cluster;
    print $x, "\n";
}

With Perl 5.10 you can also do:
for my $x (0 .. 10){
    next if $x ~~ @cluster;
    print $x, "\n";
}

or better to use a hash:
my @cluster = (1,3,4,7);
my %cluster = map {$_, 1} @cluster;
for my $x (0 .. 10){
    next if $cluster{$x};
    print $x, "\n";
}

Comment: Thanks, I was secretly hoping I would have an excuse to use a hash, I haven't had one in a long time. Many many thanks!
Comment: it's strange writing Perl and not using hashes :)
Comment: I'm unfortunately a Perl beginner but the hash type is so fascinatingly fun to me I've been trying to put it in everything I do, but currently the work I have is rather straightforward.
Comment: @SirLulzalot How could you not have a reason in a ***long*** time when you are a beginner?
Comment: Long in consideration to my life in Perl XD
Answer: Hmm... If you are skipping over lines, why not use that criteria directly instead of remembering the lines that need to be filtered out?
The grep function is a powerful construct for filtering lists:
my @array = 1 .. 10;

print "$_\n" for grep { not /^[1347]$/ } @array;  # 2,5,6,8,9,10
print "$_\n" for grep {     $_ % 2     } @array;  # 1,3,5,7,9

my @text = qw( the cat sat on the mat );

print "$_\n" for grep { ! /at/ } @text;           # the, on, the

Much less clutter, and much more DWIM!
Comment: Hmm, I haven't actually implemented anything using Perl's grep function, it was all over my studies in bash, but here I never thought about it. I'll consider it for future attempts, thanks!
Answer: Dou you mean something like that:
for my $x (0 .. $numLines){
    my $is_not_in_claster = 1;
    for( @claster ){
         if( $x == $_ ){
             $is_not_in_claster = 0;
             last;
         }
    }
    if( $is_not_in_claster ){
        ...
    }
}

?
Comment: Yeah this does the job, I was hoping perl had something a bit more elegant, but it is a rather complex logic statement, thanks!
Comment: Note that this solution has to loop over `@claster` for each `$x`, which will make it exponentially slower as `$numLines` and `@claster` grow.


Alterar estilo de classes repetidas de forma diferente com CSS

Question: Tenho uma classe "teste" com uma estilização e logo em seguida tenho outra class "teste". O que eu gostaria de saber é como alterar o estilo da outra class de forma diferente da primeira. O que me limita a fazer isso é que não posso alterar e nem adicionar classes, só posso usar ela do jeito que está. A unica coisa que tem diferente é que as duas classes estão dentro de containers diferentes, teria alguma forma de aplicar outro estilo no segundo exemplo, tendo como referência a class "tal2"?

Answer: É só você usar um seletor diferente apontando para a class .teste dentro da class .tal2:

.teste{
   color: red;
}

.tal2 .teste{
   color: blue;
}

texto vermelho

texto azul

O seletor .tal2 .teste irá alterar todas as class .teste dentro de .tal2. Você pode inclusive utilizar variações. Por exemplo, para alterar apenas filhos diretos de .tal2 que possuem a class .teste, utilize o símbolo > entre as classes:

.teste{
   color: red;
}

.tal2 > .teste{
   color: blue;
}

texto vermelho

texto azul

texto vermelho


How to get data from another different ModelForm

Question: Is it possible to auto populate data from a search to a two different ModelForm ?
What I want to do is when I "search" using a GET Method, it shows the Asset details, after the query. the page shows the Asset details with a "Assign" button, when pressed it passes on the "asset_id" and goes to the next HTML create form(LoanerForm). My problem is that on the LoanerForm does not auto populate the "asset_number". I dont get why, the pk is correct and I pass it on as instance on the Form. The other fields updates except the "asset_number" remains the default select option.
My View:
def loaner_view_page(request):
asset = request.GET.get('q')
my_asset = Asset.objects.filter(asset_number=asset)

print('Printing results', request.GET)
context = {
    'asset':my_asset,
}
return render(request, 'assets/asset_loaner_page.html', context)

def loaner_assign(request, pk):
asset = Asset.objects.get(id=pk)
form = LoanerForm(instance=asset)
if form.is_valid():
    print('Printing results', request.POST)
    form.save()
    return redirect('/Dashboard/')
context = {
    'form': form,
}
return render(request, 'assets/asset_loaner_assign.html', context)

My Model:
class Asset(models.Model):
model_item = models.ForeignKey(Model_Items, null=True, on_delete= models.SET_NULL)
po_number = models.ForeignKey(Po, null=True, on_delete= models.SET_NULL)
asset_number = models.CharField(max_length=10, default='')
serial_number = models.CharField(max_length=10, default='')
asset_location = models.ForeignKey(Location, null=True, on_delete= models.SET_NULL)
asset_type = models.CharField(max_length=10, default='')#primary device owner/loaner

def __str__(self):
    return self.asset_number

class Loaner(models.Model):
loaner = models.ForeignKey(Asset, null=True, on_delete= models.SET_NULL)
return_date = models.DateField(auto_now_add=False)
asset_type = models.CharField(max_length=10, default='')

My HTML:
{% for my_asset in asset %}

                {{ my_asset.asset_number }}
                {{ my_asset.id }}
                {{ my_asset.serial_number }}
                {{ my_asset.asset_location }}
                {{ my_asset.asset_type }}
                Assign
           {% endfor %}

My Form:
class AssetForm(ModelForm):
class Meta:
    model = Asset
    fields = ('__all__')

class LoanerForm(ModelForm):
    class Meta:
        model = Loaner
        fields = ('__all__')

My URL:
path('Asset_Loaner/', loaner_view_page, name="asset_loaner"),
path('Asset_Loaner_Assign/<str:pk>/', loaner_assign, name="asset_loaner_assign"),

Answer: form = LoanerForm(initial={'loaner': pk})

Fixed it by using initial instead of instance.


Add Click event to WPF DataGrid Button Column in PowerShell

Question: Normally the XAML I use for a data grid column with a button is something like this:
<DataGridTemplateColumn Header="ButtonColumn">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Click="Click_Handler">Do Something</Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

When using XAML in Powershell however Click= can't be used as far as I know, as it throws error:
 "Failed to create a 'Click' from the text 'ClickEvent'.

How can I get a reference to the button object at run time, to add the click event handlers? Or is there a way to create a function in Powershell that can be triggered by the name specified in XAML event handler.
Giving the object a name and using
$window.FindName("<button name>")

Doesn't work
A simplified example of the GUI being built:
 [xml]$xaml = @'
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window" Title="Demo" WindowStartupLocation = "CenterScreen"
        SizeToContent="WidthAndHeight"
        ShowInTaskbar = "True">

    <StackPanel Orientation="Vertical" Name="msiStackPanel">
        <TextBlock Margin="20,20,20,20" HorizontalAlignment="Center" FontSize="14" FontWeight="Bold">List of Stuff</TextBlock>
        <DataGrid Name="myGrid" ItemsSource="{Binding}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTemplateColumn Header="Launch">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Name="x:launchButton">Launch</Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Margin="20,20,20,20">Completed All Tests</Button>
    </StackPanel>
</Window>
'@

# Set PowerShell variable for each named object in GUI
Function Set-WpfVariables
{
  param($children)
    ForEach ($child in $children.Children)
    {
        Set-WpfVariables -Children $child
        if (![String]::IsNullOrEmpty($child.Name))
        {
            Write-Host "Set variable $($child.Name)"
            Set-Variable -Name $child.Name -Value $child -Scope global
        }
    }
}

# Build Window
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )

$controls = [System.Windows.LogicalTreeHelper]::GetChildren($window)
Set-WpfVariables -Children $controls

$table = New-Object System.Data.DataTable
$table.Columns.Add("Name")
$table.Rows.Add("Row 1")
$table.Rows.Add("Row 2")

$myGrid.DataContext = $table.DefaultView

$window.ShowDialog()

Answer: Here's a working script for anybody interested:
[xml]$xaml = @'
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window" Title="Demo" WindowStartupLocation = "CenterScreen"
        SizeToContent="WidthAndHeight"
        ShowInTaskbar = "True">

    <StackPanel Orientation="Vertical" Name="msiStackPanel">
        <TextBlock Margin="20,20,20,20" HorizontalAlignment="Center" FontSize="14" FontWeight="Bold">List of Stuff</TextBlock>
        <DataGrid Name="myGrid" ItemsSource="{Binding}">
            <DataGrid.Columns>
            </DataGrid.Columns>
        </DataGrid>
        <Button Margin="20,20,20,20">Completed All Tests</Button>
    </StackPanel>
</Window>
'@

# Set PowerShell variable for each named object in GUI
Function Set-WpfVariables
{
  param($children)
    ForEach ($child in $children.Children)
    {
        Set-WpfVariables -Children $child
        if (![String]::IsNullOrEmpty($child.Name))
        {
            Write-Host "Set variable $($child.Name)"
            Set-Variable -Name $child.Name -Value $child -Scope global
        }
    }
}

# Build Window
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )

$controls = [System.Windows.LogicalTreeHelper]::GetChildren($window)
Set-WpfVariables -Children $controls

$table = New-Object System.Data.DataTable
$table.Columns.Add("Name")
$table.Rows.Add("Row 1")
$table.Rows.Add("Row 2")
$table.Rows.Add("Row 3")

#$myGrid.DataContext = $table.DefaultView #This did not work for me. so...
$myGrid = $window.FindName("myGrid")
$myGrid.ItemsSource = $table.DefaultView

[System.Windows.RoutedEventHandler]$clickEvent = {
param ($sender,$e)
    Write-Host "Clicked row $($myGrid.SelectedItem.Row.Name)"
}

$buttonColumn = New-Object System.Windows.Controls.DataGridTemplateColumn
$buttonFactory = New-Object System.Windows.FrameworkElementFactory([System.Windows.Controls.Button])
$buttonFactory.SetValue([System.Windows.Controls.Button]::ContentProperty, "Launch")
$buttonFactory.AddHandler([System.Windows.Controls.Button]::ClickEvent,$clickEvent)
$dataTemplate = New-Object System.Windows.DataTemplate
$dataTemplate.VisualTree = $buttonFactory
$buttonColumn.CellTemplate = $dataTemplate
$myGrid.Columns.Add($buttonColumn)

$myGrid.DataContext = $table.DefaultView

$window.ShowDialog()

Answer: In PowerShell, the simplest way to bind the events, is after the XAML has been parsed.
This example, from this site gives a very basic, but complete example:
[xml]$xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window"
Title="Blend and PowerShell"
Width="640" Height="480" AllowsTransparency="False">
<Grid x:Name="LayoutRoot">
  <Rectangle Margin="22,8,22,0" VerticalAlignment="Top" Height="178" Stroke="#FF000000">
   <Rectangle.Fill>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
     <GradientStop Color="#FF000000" Offset="0"/>
     <GradientStop Color="#FF861A1A" Offset="1"/>
    </LinearGradientBrush>
   </Rectangle.Fill>
  </Rectangle>
  <Button Margin="121,0,129,96" VerticalAlignment="Bottom" Height="100" Content="Button"
    x:Name="Close"/>
</Grid>
</Window>
"@

# create an xml reader, then load the xaml
$reader = New-Object System.Xml.XmlNodeReader $xaml
$d = [Windows.Markup.XamlReader]::Load($reader)

# find the button by name, then add a click event to it (which closes the window).
$d.FindName("Close").add_click({
    $d.Close()
})

# show the wpf window
$d.ShowDialog() | out-null

Comment: Yes I'm aware of using find name, but this doesn't find the button object in data grid column template, even if I give it a name
Answer: Creating the button column programmatically, allows you to set the Event handler:
[System.Windows.RoutedEventHandler]$clickEvent = {
param ($sender,$e)

    Write-Host "Clicked row $($myGrid.SelectedItem.Row.Name)"
}

$buttonColumn = New-Object System.Windows.Controls.DataGridTemplateColumn
$buttonFactory = New-Object System.Windows.FrameworkElementFactory([System.Windows.Controls.Button])
$buttonFactory.SetValue([System.Windows.Controls.Button]::ContentProperty, "Launch")
$buttonFactory.AddHandler([System.Windows.Controls.Button]::ClickEvent,$clickEvent)
$dataTemplate = New-Object System.Windows.DataTemplate
$dataTemplate.VisualTree = $buttonFactory
$buttonColumn.CellTemplate = $dataTemplate
$myGrid.Columns.Add($buttonColumn)

$myGrid.DataContext = $table.DefaultView

$window.ShowDialog()

For a column that already exists:
$buttonFactory = New-Object System.Windows.FrameworkElementFactory([System.Windows.Controls.Button])
$buttonFactory.SetValue([System.Windows.Controls.Button]::ContentProperty, "Launch")
$buttonFactory.AddHandler([System.Windows.Controls.Button]::ClickEvent,$clickEvent)
$dataTemplate = New-Object System.Windows.DataTemplate
$dataTemplate.VisualTree = $buttonFactory
$myGrid.Columns[1].CellTemplate = $dataTemplate

Answer: Set the Name if you want to get a reference to the button :
<Button x:name="button" Click="Click_Handler">Do Something</Button>

Then in your code behind you can use "button".
button.Click += Click_Handler

I find your error odd, does the short example you posted cause the error? Can you post the code behind where you create your Click_Handler?
Comment: Yes this will work easily in C# but in PowerShell I'm not sure how this will be achieved. Added complete example.


Programmatically create result row in views

Question: I have created a bunch of content types. Since I am using Drupal only for displaying results fetched from another service I was wondering if there is a way to display results in a view without actually having objects in the database?
For example, I get data from a certain endpoint and I want to display them in a table view. Is there a way to achieve that or would another approach be recommended?
Answer: The short answer is No. Views is only capable of returning Content entities.
The approach I recommend is to use Feeds to import your data into custom entities. You can either define your own custom content entity, or use ECK to define a custom content entity via UI.
In our organization, we use this basic Feeds -> ECK -> Views approach all the time and it has the benefit of not requiring our support staff to know any PHP. You might also find the Ultimate Cron module to be useful if you need to retrieve data at a frequency shorter than one hour.


Definition and Interpretation of Likelihood for non-PhD's

Question: Regarding "non-PhD" in the question title, please answer this question for the audience of   people with a solid understanding of probability distributions but no knowledge of the nuances of different statistical paradigms (e.g., frequentism, Bayesianism, likelihoodism).
After reading through the existing stack exchange questions on this topic, I am confused as I have seen multiple top-voted answers that seem to contradict each other, and seem to contradict a highly regarded machine learning book.
Here is what I've gathered, please comment on what is correct / wrong. If something is both correct and wrong depending on the statistical paradigm one subscribes to, please say so instead of stating the belief dependent only on one paradigm. Please only comment if you are an expert on this topic, as this seems to be a contentious topic.

Firstly, I'll state that:

likelihood is not a PMF / PDF as its integral does not sum to 1
discrete / continuous functions have probabilities / probability densities

So no need to expend energy there.

Secondly, both Wikipedia and a forum top comment (Macro) agree that probability (density) and likelihood produce the same value, given some data X and some parameters $\theta$:
Wikipedia:

$\mathcal{L}(\theta|x) = P(X=x|\theta)$

$\mathcal{L}(\theta|x) = f(x|\theta)$

Macro:

the likelihood is not the probability of the parameter value being correct or anything like that - it is the probability (density) of the data given the parameter value

Which contradict two other forum top comments, which say that likelihood is proportional but not equal to probability:
hello_there_andy + ars:

Although it seems like we have simply re-written the probability function, a key consequence of this is that the likelihood function does not obey the laws of probability (for example, it's not bound to the [0, 1] interval). However, the likelihood function is proportional to the probability of the observed data.

Sextus Empiricus:

In your class they introduced the likelihood as being equal to the conditional probability $\mathcal{L}(\theta;x) = f(x;\theta)$, but this was just a simplification. The likelihood does not need to be equal and it is proportional.

I was tempted to just take hello_there_andy, ars, and Sextus Empiricus answer and move on, but I wrote this question so that we could have a clear comparing of these top answers.

Thirdly, Aurélien Géron's "Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow" states:

Given a statistical model with some parameters θ, the word
"probability" is used to describe how plausible a future outcome x is
(knowing the parameter values θ), while the word "likelihood" is used
to describe how plausible a particular set of parameter values θ are,
after the outcome x is known.

This seems to contradict the current Wikipedia definition, which includes this statement:

The likelihood function does not specify the probability that $\theta$ is the truth, given the observed sample X=x.

As well as part of Macro's answer:

the likelihood is not the probability of the parameter value being correct or anything like that

Maybe I am wrong in equating "plausibility" with "probability".
If I am wrong here, is it correct to say that likelihood:

Is representative of the plausibility of $\theta$, given X, while not being the probability of $\theta$, given X.

Is proportional (or equal...) to the probability of data x occurring, given parameters $\theta$.
Comment: The illustration and explanation here: https://stats.stackexchange.com/a/284827/805 may resolve one of the issues you appear to have; note that while the likelihood (a red curve for some data, $x$) is equal to a joint density (black curve, for some parameter $\theta$) *at every point*, the functions operate in different directions and mean different things. The black curves are densities, the red curves *join points from different densities* and are *not densities*; they might not even be integrable. ... ctd
Comment: I do not have time for an answer now, but here are some earlier answers of mine which can help:  https://stats.stackexchange.com/questions/345069/likelihood-comparable-across-different-distributions/355836#355836, https://stats.stackexchange.com/questions/97515/what-does-likelihood-is-only-defined-up-to-a-multiplicative-constant-of-proport/97522#97522, or @whuber answer at https://stats.stackexchange.com/a/397166/11887
Comment: I'm just here to say that it's a subtle distinction between probability and likelihood, so one should expect to struggle with it before understanding.
Comment: ctd ... Indeed, it's perfectly possible for one to be discrete and the other continuous (either way around). Once this distinction between the two is clearly understood, a lot of common misconceptions fall away.
Comment: Bayesians knew all along you have to multiply the likelihood by a prior to get a posterior probability distribution. The problem is there is no universally agreed upon prior for any given data analysis, the differences are not even proportional to each other. For frequentists, the absolute value of a likelihood means nothing. L=50 may as well be L=0.0005. For nicely behaved families (concave, regular exponential famliies) indexed by $\theta$, the maximum is an interesting estimator, but much breaks down when you go beyond that.
Answer: The likelihood does give us what can often be equated with 'plausibility', but it is important to say that it is the relative plausibility according to the statistical model. And it is probably useful to note that you are, in effect, using likelihood as a definition of (statistical?) plausibility. That is, in my opinion, a reasonable usage, but it will likely grate on people who view likelihood-based inference with mistrust. The problem is that 'plausible' refers to a state of mind as much as it refers to a statistically definable thing, and different minds are, well, different.
Your statement 2 seems to match Fisher's original definition of likelihood and so it must be at east approximately correct. I would say that it would be greatly improved by omitting the "(or equal...)" and by adding something like 'according to the statistical model being used.'
Because likelihoods always have arbitrary scaling we really can only make inferences about plausibility of parameter values with reference to the plausibility of at least one other parameter value. The likelihoods that give those plausibilities must be taken from the same statistical model and data, as a ratio of likelihoods across models is meaningless with respect to parameter values, even if they might be helpful when choosing the statistical models themselves.
The sentence you've taken from Wikipedia ("The likelihood function does not specify the probability that  is the truth, given the observed sample X=x.") is correct, but it is correct in a way that people seem to miss. Because the likelihoods only exist and are relevant to other likelihoods within a statistical model, their relevance to any real-world truth value is necessarily limited by the statistical model, and we respect the notion that all models are wrong!
Answer: Your interpretations 1 and 2 are both wrong.

Bayesians knew all along you have to multiply the likelihood by a prior to get a posterior probability distribution. The problem is there is no universally agreed upon prior for any given data analysis, the differences are not even proportional to each other.

For frequentists, the absolute value of a likelihood means nothing. L=50 may as well be L=0.0005. The relative likelihood (such as a ratio) tells us more. When ratios are monotone, Karlin Rubin tells us that the likelihood ratio test has optimal power. For nicely behaved families (concave, regular exponential famliies) indexed by $\theta$, the maximum is an interesting estimator, but much breaks down when you go beyond that.
Comment: I disagree with your statement that the interpretations are both wrong. They may be limited, and they might be improved with more words, but they are not wrong. Your two numbered statements do not seem to say why the questioner's statements are wrong.
Comment: @MichaelLew I believe that I hit the two key issues: if you want a probability for a parameter's unknown value, a Bayesian treatment is required. And regarding the interpretation of an absolute likelihood value, your answer and mine agree it's only useful to compare relative values in the same dataset and within the same probability model. You can't, for instance, compare likelihoods to decide if a probit or a logit model is "better". I think the real difference here is that I take the hard line and you are nudging in a more enlightened direction.
Comment: Why can you not use likelihood to choose between logit or probit? Those are models defined with respect to the same underlying measure, so it should be fine?
Comment: @kjetilbhalvorsen well, you could use the AIC, and, for models having the same number of parameters, ranks for models for selection would equate to using the likelihood. The problem is that the exact and asymptotic properties of the AIC are not well understood. I often see "Model Selection and Multimodel Inference" by Burnham, Anderson cited for this, but I can't get a copy. This is why any "choice" along these lines made by AIC is generally regarded as pragmatic.
Comment: Ok, thanks for the answer. I thought you had objections to the logic of comparing this likelihood, seems you have not. These doubts come up often here, iwill try to write an answer addressing it. But it must wait ... My computer is at a repairshop now


Prediction on mixed effect models: what to do with random effects?

Question: Let's consider this hypothetical dataset:
set.seed(12345)

num.subjects <- 10

dose <- rep(c(1,10,50,100), num.subjects)
subject <- rep(1:num.subjects, each=4)
group <- rep(1:2, each=num.subjects/2*4)

response <- dose*dose/10 * group + rnorm(length(dose), 50, 30)

df <- data.frame(dose=dose, response=response,
                 subject=subject, group=group)

we can use lme to model the response with a random effect model:
require(nlme)
model <- lme(response ~ dose + group + dose*group,
             random = ~1|subject, df)

I would like to use predict on the result of this model to get, for instance, the response of a generic subject of group 1 to a dose of 10:
pred <- predict(model, newdata=list(dose=10, group=1))

However, with this code I get the following error:
Error in predict.lme(model, newdata = list(dose = 10, group = 1)) :
cannot evaluate groups for desired levels on 'newdata'

To get rid of it I need to do, for instance
pred <- predict(model, newdata=list(dose=10, group=1, subject=5))

This, however, does not really make much sense to me... the subject is a nuisance factor in my model, so what sense does it have to include it in predict? If I put a subject number not present in the dataset, predict returns NA.
Is this the wanted behaviour for predict in this situation? Am I missing something really obvious?
Comment: @user11852: I am not looking for estimate on the same subject. I do repeated measures on various subjects in order to get population estimates. I do not care for the subjects that I already tested as I already have the experimental answer... I want to be able to predict how a new subject of a specific group will respond to the stimulus. Greg answer solves the problem indeed.
Comment: I think you are looking for a population response rather than a mean prediction. The unconditional `model` does assume that your mean is given by $X\beta + Z\gamma$  (in particular $y \sim N(X\beta+Z\gamma, \sigma^2 I)$ so it will expect some values for the *nuisance* parameter also. There are situations that it might not even make sense to assume your evaluation point is hierarchy-free (so no $Z$). That's why fitted() gives you results "with nuisance" in the first place. (And actually I don't think it nuisance but rather a extra info but OK...)
Comment: @user11852: just to clarify, I am thinking about this as a model to be used, for instance, in case of repeated measures for the same subject.
Comment: Given you are are looking estimates for the same subject, why exclude it then? If you want population level estimates (no $Z$ information) then it is a difference question. As Greg says in his response you can get estimates for the population if you want but that won't be subject specific.
Answer: If you look at the help for predict.lme you will see that it has a level argument that determines which level to make the predictions at.  The default is the highest or innermost which means that if you don't specify the level then it is trying to predict at the subject level.  If you specify level=0 as part of your first predict call (without subject) then it will give the prediction at the population level and not need a subject number.


Is it possible to preserve YAML block structure when dumping a parsed document?


Proving a function $f(m,n)$ which satisfies two conditions is a constant

Question: I found the following question in a book only with one sentence. "This question can be solved by an elementary way. Note that the following two are false: (1) If a function is bounded from below, then it has minimum value. (2) A monotone decreasing sequence reaches a negative value."
Question: Let $m,n$ be integers. Supposing that a function $f(m,n)$ defined by $m,n$ satisfies the following two conditions, then prove that $f(m,n)$ is a constant.
1. $f(m,n)\ge0$.
2. $4f(m,n)=f(m-1,n)+f(m+1,n)+f(m,n-1)+f(m,n+1)$.
I suspect this question can be solved by a geometric aspect. I've tried to prove this, but I'm facing difficulty. Could you show me how to prove this?
Comment: It is a discrete version of Laplace equation
$\nabla^{2}\Phi = 0$ which leads to $\int\Psi\nabla^{2}\Psi\,{\rm d}V = 0$ and to
$\int\left\vert\nabla\Psi\right\vert^{2} = 0$ which involves an integration by parts. The discrete version requires "Abel Summations by part" identity (  http://en.wikipedia.org/wiki/Summation_by_parts ).
Comment: Where did you get this problem? It feels familiar to me for some reason.
Comment: @mixedmath: I found this in the book which a friend of mine has, but I don't know its name. I'll ask him.
Comment: @FelixMarin: Thank you for nice information.
Comment: @mathlove You're welcome.
Answer: A probabilistic proof is given at the bottom of this page.


high mysql CPU usage more than %1500 on centos 6

Question: I am running a high traffic websites on a Dedicated-Virtual 24GB RAM CentOS server hosted by the planet.
Very often the server dies because of high CPU usage (%1500)
When i check the running processes using "top" command i see a hight load average more than 100 always and cpu mysql often more than 1500%
I have tried to tune mysql, tune apache, my.cnf, httpd.cnf, removed
Apache modules that i do not use but that does not solve the problem.
Please let me know what values do you need to know in my server config in order to help me diagnosis the problem.
Thanks in advance.
<code>    Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                16
On-line CPU(s) list:   0-15
Thread(s) per core:    2
Core(s) per socket:    4
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 44
Stepping:              2
CPU MHz:               2400.093
BogoMIPS:              4799.88
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              12288K
NUMA node0 CPU(s):     0-3,8-11
NUMA node1 CPU(s):     4-7,12-15

top - 05:37:00 up 4 days, 22:04,  2 users,  load average: 136.61, 145.42, 139.03
Tasks: 565 total,   8 running, 554 sleeping,   0 stopped,   3 zombie
Cpu(s): 28.6%us, 70.6%sy,  0.1%ni,  0.2%id,  0.0%wa,  0.0%hi,  0.5%si,  0.0%st
Mem:  24596732k total, 13172200k used, 11424532k free,   630632k buffers
Swap:  2097144k total,        0k used,  2097144k free,  7648348k cached
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
  4850 mysql     15  -5 12.4g 1.1g 6036 S 1545.1  4.7  12992:15 mysqld
  15846 root      20   0  162m  22m  916 R  4.2  0.1   0:00.62 lfd
  15509 apache    20   0  632m 129m 5460 S  3.0  0.5   0:01.59 httpd
  15276 apache    20   0  632m 128m 5504 R  2.7  0.5   0:01.85 httpd
  15505 apache    20   0  634m 130m 5460 R  2.1  0.5   0:01.49 httpd
  15792 apache    20   0  630m 125m 4816 S  2.1  0.5   0:00.43 httpd
  3058 nginx     20   0 76576  34m 2268 S  1.8  0.1 107:48.32 nginx
  15585 apache    20   0  632m 128m 5268 S  1.8  0.5   0:01.25 httpd
  15827 apache    20   0  629m 124m 3752 S  1.8  0.5   0:00.10 httpd

cat /proc/meminfo
MemTotal:       24596732 kB
MemFree:        13807688 kB
Buffers:         1108524 kB
Cached:          4888972 kB
SwapCached:            0 kB
Active:          4929640 kB
Inactive:        3225108 kB
Active(anon):    1523440 kB
Inactive(anon):   635484 kB
Active(file):    3406200 kB
Inactive(file):  2589624 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       2097144 kB
SwapFree:        2097144 kB
Dirty:             16032 kB
Writeback:             0 kB
AnonPages:       2114752 kB
Mapped:            52792 kB
Shmem:              1648 kB
Slab:            2155004 kB
SReclaimable:    2028484 kB
SUnreclaim:       126520 kB
KernelStack:        5184 kB
PageTables:       105004 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    14395508 kB
Committed_AS:   16484584 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      463816 kB
VmallocChunk:   34345823536 kB
HardwareCorrupted:     0 kB
AnonHugePages:    800768 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:        5696 kB
DirectMap2M:     2082816 kB
DirectMap1G:    23068672 kB

my.cnf
[mysqld]
tmpdir=/var/tmpfs
local-infile=0
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
#general_log=1
slow_query_log= 0
long_query_time =9
log_queries_not_using_indexes =0
max_connections = 400
key_buffer_size = 256M
myisam_sort_buffer_size = 256M
myisam_max_sort_file_size = 2048M
max_heap_table_size = 600M
tmp_table_size = 600M
read_buffer_size = 320M
sort_buffer_size = 320M
join_buffer_size = 3G
table_definition_cache = 8000
table_open_cache = 220000
thread_cache_size = 384
wait_timeout = 50
interactive_timeout = 30
connect_timeout = 10
max_allowed_packet = 265M
max_seeks_for_key = 1000
group_concat_max_len = 1024
max_length_for_sort_data = 1024
net_buffer_length = 16384
max_connect_errors = 100000
concurrent_insert = 2
read_rnd_buffer_size = 786432
bulk_insert_buffer_size = 8M
query_cache_limit = 256M
query_cache_size = 200M
query_cache_type = 1
query_prealloc_size = 262144
query_alloc_block_size = 65536
range_alloc_block_size = 4096
transaction_alloc_block_size = 8192
transaction_prealloc_size = 4096
default-storage-engine = MyISAM
open_files_limit = 3G
max_write_lock_count = 8
innodb_open_files = 500
innodb_data_file_path= ibdata1:10M:autoextend
innodb_buffer_pool_size = 60M
innodb_additional_mem_pool_size = 32M
innodb_log_files_in_group = 2
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
innodb_thread_concurrency = 0

trafic shown by phpmyadmin for just one hour and half
Trafic réseau depuis le démarrage : 123 Gio

Ce serveur MySQL fonctionne depuis 0 jours, 1 heures, 33 minutes et 58 secondes. Il a démarré le Jeu 28 Janvier 2016 à 13:21.
Trafic  ø par heure
Reçu    445 Mio 284,2 Mio
Envoyé  122,6 Gio   78,3 Gio
Total   123 Gio 78,6 Gio
Connexions  ø par heure %
max. de connexions simultanées  170 ---     ---
Tentatives échouées 3 253   2 077,12    0,55%
Arrêts prématurés   306     195,39  0,05%
Total   591 k   377,53 k    100,00%
</code>
Comment: What is the output of `iostat`? Is your MySQL using innodb tables at all? I see default table type 'MyISAM', but If innodb is used, then you need to look at your variables - and correct the invalid ones such as `open_files_limit = 3G`. innodb_buffer_pool_size = 60M is very low for a busy server. `innodb_flush_log_at_trx_commit = 2` is a bad idea too if the server is crashing, you could be loosing data.

There are tons of resources on MySQL tuning - here is one to start `https://www.percona.com/blog/2014/01/28/10-mysql-settings-to-tune-after-installation/`
Comment: avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          28.28    0.12   63.93    0.04    0.00    7.63

Device:            tps   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn
sda              93.39      1457.66      1833.18  648275580  815283098
sdb               1.75         4.86       626.23    2159818  278509440
Comment: database using only MyISAM
Comment: innodb_buffer_pool_size = 60M is small because we using only myisam not a table using innodb engine
Comment: I've changed innodb_buffer_pool_size to 15G and innodb_log_file_size=4G but still nothing changed in the hight load average and the high mysql cpu, I don't see the utilitity of changing innodb config, because I'm not using it !
Comment: See this thread `http://serverfault.com/questions/686665/mysql-showing-100-cpu-usage`. I would look at switching tables to InnoDB to take advantage of row-level locking.
Comment: thanks, changing myisam tables to innodb solved the problem, now mysql CPU is at most 300% and normal load average peak 5%
Answer: thanks, changing myisam tables to innodb solved the problem, now mysql CPU is at most 300% and normal load average peak 5%


Spring Security with JWT: JWT filter which validates the token is not invoked

Question: I am using Spring Security with JWT for authenticating rest apis. On login, the JWT token is generated and shared to the mobile client. But, the token in the subsequent requests are not been validated. Is there anything wrong in the security configuration ?
Spring security version - 5.1.6.RELEASE
// Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.
            httpBasic().disable().
            csrf().disable().
            exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
            and().
                addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).
                sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
            and().
                authorizeRequests().antMatchers("/user/login").permitAll().
                antMatchers("/user/test").authenticated().
                anyRequest().authenticated();
    }

}

// JWT Token Auth Filter - This is never invoked
@Component
public class JwtTokenAuthenticationFilter extends GenericFilterBean {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        String token = jwtTokenProvider.resolveToken((HttpServletRequest) req);
        if (null != token && jwtTokenProvider.validateToken(token)) {
            Authentication auth = jwtTokenProvider.getAuthentication(token);
            if (null != auth) {
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        filterChain.doFilter(req, res);
    }
}

I was expecting that all the requests after login will be authenticated against the JWT token.
I tried putting the name of the service to be authenticated as below:
antMatchers("/user/test").authenticated().

Also, any request authenticated is also added, but neither of them worked.
anyRequest().authenticated();

Answer: Try to replace
addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).

by
addFilterBefore(jwtTokenAuthenticationFilter), BasicAuthenticationFilter.class);

If not runs, change jwtTokenAuthenticationFilter class to avoid to be a Spring bean and use like this:
addFilterBefore(new JwtTokenAuthenticationFilter(jwtTokenProvider)), BasicAuthenticationFilter.class);

And add the following code on Security Class:
@Autowired
private JwtTokenProvider jwtTokenProvider;

Comment: Had tried these options already, but no luck. Then only, I put the question on stack. Is there anything else you think could do the trick ?
Comment: From where do you get this class JwtTokenProvider?
Comment: JwtTokenProvider is a custom class with the operations to validate and create JWT tokens.


How to transform ES6 AST into ES5 AST directly?

Question: I learnt that packages like Babel can do the job converting ES6 code to JavaScript in ES5, but can I just start from the ES6 AST I got somewhere?
Comment: So, you have an ES6 AST and you want to create an ES5 AST from it?
Comment: @bali182 Yes. That ES6 AST is generated from other tools. It's also fine if it  outputs JavaScript directly.
Comment: But why don't you just don't parse the ES6 code at all, and let for example Babel do the converting it right into ES5 code? Also, If you would find a tool that converts an AST to something else, it would require the AST to be in a specific format, and you would have to do some nasty transforming (most likely)
Comment: @bali182 Yes. It was actually an AltJS language, I suppose it might interesting if I generates ES6 AST and let babel or whatever that transforms AST into ES5 JavaScript .
Answer: I posted a similar question in babel's Issues and got an anwser from the maintainer:
https://github.com/babel/babel/issues/1122
require("babel").transform.fromAST(ast, originalCode, options);

variable originalCode could be null and that will finish this task.
Comment: Some poking around the source code revealed the same thing: https://github.com/babel/babel/blob/master/src/babel/transformation/index.js#L12-L19


MySQL 3 table join on user_id, not getting NULL values, instead duplicate entries

Question: I have 3 tables users, breaks, clock_in_out shown below:
Users:

Breaks:

Clock_in_out table:

The query I need is something like what I have below:
SELECT `clock_in_out`.`created`, `breaks`.`in`, `breaks`.`out`, `clock_in_out`.`user_id`, `users`.`id`,
`clock_in_out`.`loggedin`, `clock_in_out`.`loggedout`, `users`.`firstname`, `users`.`lastname`
FROM (`clock_in_out`)
JOIN `users` ON `users`.`id` = `clock_in_out`.`user_id`
JOIN `breaks` ON `users`.`id` = `breaks`.`user_id`
WHERE `loggedin` LIKE "%2015-03-18%"
AND `clock_in_out`.`user_id` = '88'
ORDER BY `created` ASC

This returns:

The above result is exactly what I need except where there is 1 row in clock_in_out and 2 rows in breaks it adds duplicate values in to clock_in_out's loggedin and loggedout fields (I want these to be NULL)
Answer: LEFT JOIN should work
SELECT `clock_in_out`.`created`, `breaks`.`in`, `breaks`.`out`,`clock_in_out`.`user_id`, `users`.`id`,
`clock_in_out`.`loggedin`, `clock_in_out`.`loggedout`, `users`.`firstname`, `users`.`lastname`
FROM (`clock_in_out`)
LEFT JOIN `users` ON `users`.`id` = `clock_in_out`.`user_id`
LEFT JOIN `breaks` ON `users`.`id` = `breaks`.`user_id`
WHERE `loggedin` LIKE "%2015-03-18%"
AND `clock_in_out`.`user_id` = '88'
ORDER BY `created` ASC

If not try RIGHT JOIN
Comment: Tried left join and righty join before posting neither work, both get the sam,e result as pictured above.
Comment: LEFT or RIGHTJOIN doesn't modify this comportement.
It only put NULL if the join with the second table doesn't return results on each fields of the second table.
Answer: Your query return 2 results because your break table contains 2 lines for the user 88.
Sql return 1 row from your clock_in_out
with the join on users, it completes this row with user information
but with the join on break, it retrieve 2 lines for user 88.
Beacause of that you have 2 results
Comment: So is there no way to get what I want? I need 2 results just not duplicated fields where there should be NULL
Comment: why you need to join to break?
Comment: Because I have coded all my loops that are working out time differences on this result set, I understand I could do two queries but I would have to rewrite quite a lot of code in 4 different views
Comment: Correct, JOIN results inherently create duplicate entries in some columns of the output result set in a one-to-many situation. That's how RDMSs work. Many people write a loop in application code to detect changes between the previous and current row.
Comment: Do you need the first, last or (first in last out) break of a user?
Comment: Would doing a select DISTINCT on the first select statement be a solution..? Think I will try this..
Comment: I need all of them, its a reporting tool


Which type of embedding is in keras Embedding layer, like word2vec or GloVe, or some other

Question: How can i change the type of word embedding in keras.layers.Embedding to word2vec or someother
Answer: You can construct a frozen Embedding layer with pre-trained word vectors:
embedding_layer = Embedding(num_words,
                            EMBEDDING_DIM,
                            embeddings_initializer=Constant(embedding_matrix),
                            trainable=False)

where embedding_matrix is a regular NumPy matrix of shape (num_words, EMBEDDING_DIM). So you have to load in word2vec etc into a numpy array with correct indices and set it as the initial values of your embedding layer. For a concrete examples have a look at Keras example.
Answer: You can think of keras.layers.Embedding is simply a matrix that map word index to a vector, AND it is 'untrained' when you initialize it.
You can either train your word embedding so that the Embedding matrix will map your word index to a word vector based on your training.
Or, you can initialize the Embedding layer and then load pre-trained weight from word2vec or GloVe.
From keras example https://keras.io/examples/pretrained_word_embeddings/, you can see that it loads pre-trained GloVe embeddings weight (the Matrix) and then load it into the Embedding layer. embeddings_initializer=Constant(embedding_matrix) where embedding_matrix is the data from the loaded GloVe and have set trainable=False
embedding_layer = Embedding(num_words,
                            EMBEDDING_DIM,
                            embeddings_initializer=Constant(embedding_matrix),
                            input_length=MAX_SEQUENCE_LENGTH,
                            trainable=False)

If you dont' initalize your Embedding layer, it is just randomized weight. You cannot use it as you expected, or you have to train it yourself.


How to resolve a vii°6 when there is a D5 in the upper parts

Question: According to what I have learned, the dissonant interval of an A4 can resolve to a P4 when going from vii°6 to I but if there is a D5 it must resolve properly (a D5 can go to P5 under certain circumstances but this doesn't seem to be one of them). I wrote this progression but am not really happy with it. The problem is that if I move the tenor to E4 and the alto and soprano down to A4 and C#4 I wont resolve the tritone properly. What should I do in this case?
Answer: May I ask you to cite where it says a diminished fifth must resolve properly? I ask because there will be moments later, with more advanced chords, that diminished fifths can't resolve properly. (One will be a vii°7/V, where resolving diminished fifths properly will result in a doubled leading tone, one of the worst of all voice-leading discretions!)
In my experience, a leading tone in an inner voice can always resolve down, no matter if it's part of a diminished fifth or not. As such, this tenor G♯ can resolve down to E no problems.
More problematic, however, are the parallel octaves going into the final chord: both the alto and the bass have B moving down to A.
Lastly, is this an exercise you were given, or one you composed? These vii°6 chords are very often passing chords that move from I to I6 or vice-versa. They do happen as neighbor chords (as you have here—note that the bass B is a neighbor to the surrounding As), but that seems to be a bit less common than moving up to I6. It's possible you're ears want to hear that passing progression, and that's why you're "not really happy with it."
Comment: I still have not gotten to more advanced voice leading so that could be why but this is what my book says https://ibb.co/cg17bMk In other words D5 to P5 only when moving to I6. This is an exercise that gives me a bassline to harmonize. I am aware of the passing function of vii but as you say, it is used as a neighbor too :)
Comment: @armani Have you encountered inversions of V7 yet? A V43 seems much more idiomatic to me here than viio6.
Comment: Yes I have but in this exercise I can only use vii6 for the ^2. Perhaps my soprano is wrong? my book shows this progression but the soprano would do ^1 ^7 ^1 or ^3 ^2 ^3. Not ^5 ^4 ^3 as I have.
Comment: @armani it's just difficult to harmonize vii°6 to I in four voices. You basically have to bend a rule to introduce the fourth voice, because if you double either note in the tritone, one of the two voices will suffer frustrated expectations in the resolution, and if you double the bass, you either have parallel octaves or a doubled third in the resolution. Since the rules dictate a second chord with no fifth, a common solution would be to double ^4 and have one voice move to ^5, frustrated expectations notwithstanding. Whether that's acceptable at this point in your study I couldn't say.


JW Player HTML5-only mode

Question: I'm trying to setup JW Player to playback in HTML5-only mode.
Apparently it doesn't work and I only get to see the flash fallback.
My setup:

This text will be replaced

Am I doing something wrong or is this feature not yet available?
Comment: Which browser are you trying this in? If a non MP4 supporting browser such as Firefox or Opera is being used, then it will default to Flash.
Comment: Try a WebM or OGG file in firefox and see what happens, this would confirm it for you.
Comment: Thank you, I guess this is the answer.
I was using Firefox.
Answer: If a non MP4 supporting browser such as Firefox or Opera is being used, then it will default to Flash.
– Ian Devlin Jan 23 '12 at 14:11

JW Player HTML5-only mode


Where can I find the nowhere subdifferentiable example of rockafellar?

Question: I'm told that Rockafellar gave an example of a real extended function defined on a locally convex space, whose subdifferential is empty at each point of its domain. The function is proper, lower semicontinuous and convex. Of course this function cannot be defined on a Banach space, becuase we know that in that case the domain of the subdifferential is dense on the domain of the function, and hence nonempty.
Where can I find this example?
Answer: A. Br¢ndsted and R. T. Rockafellar,"On the subdifferentiability of convex
functions", Bull. Amer. Math. Soc. 16 (1965), 605-611. (see section 5)


converter json para objeto php

Question: UPDATE
Encontrei esta resposta do SOen, no link sugerido pelo @Pedrox, fala sobre reflection, seria aplicavel a este caso também?

Conforme já me foi respondido aqui no SOpt, eu estava tentando converter uma lista de objetos para  json. Bom, agora eu preciso recuperar esta lista do json para um array de objetos.
O problema é que o json_decode, conforme diz a documentação, me retorna um array ora de um objeto especial chamado stdObject ou um array associativo, no meu caso este:
Array
(
    [0] => Array
        (
            [Corrente] => Array
                (
                    [tarifaManutencao] => 12.5
                    [numero] => 123
                    [proprietario] => teste
                    [saldo] => 3.1
                    [permissoesEspeciaisHabilitadas] =>
                )

        )

    [1] => Array
        (
            [Poupanca] => Array
                (
                    [quantidadeConsultas] => 0
                    [numero] => 456
                    [proprietario] => testeprop
                    [saldo] => 50
                    [permissoesEspeciaisHabilitadas] =>
                )

        )

    [2] => Array
        (
            [Especial] => Array
                (
                    [limite] => 500
                    [valorEmprestado] => 0
                    [jurosCobrados] => 0
                    [tarifaManutencao] => 20
                    [numero] => 789
                    [proprietario] => teste4
                    [saldo] => 100
                    [permissoesEspeciaisHabilitadas] =>
                )

        )

)

O que eu precisava era retornar o array como lista de objetos, semelhante ao que as funções serialize e unserialize fazem.Vi neste tópico que no java tem como fazer isso, passando o json e a classe POJO do objeto customizado para um método da lib Gson, e ele converte automaticamente, e também que posso fazer isso usando um foreach ou for.
É possível eu recuperar meus objetos Corrente, Poupanca e Especial do json de forma semelhante ao java?
Comment: O problema que vc tem é não pode chamar os métodos `sacar()`, `depositar()`, `cobrarTarifa()` por exemplo?
Comment: @rray não entendi, como assim?
Comment: Por exemplo se vc fizer um foreach e dentro dele chamar o `sacar()` independente do tipo de conta, funciona? ou da erro?
Comment: @rray acredito que sim, pois no foreach eu teria que ficar dando `new` no objeto de acordo com o tipo e setando os atributos no construtor.
Answer: Se eu entendi direito, você quer transformar a array gerada pelo json em object. Eu fazeria desta duas formas:
$json = (object) $json;

ou
foreach ($a as $key => $value) {
    $objeto->$key = $value;
}

Comment: "fazeria" -> faria
Comment: Pensei nisso, porém, o array(ou json) guarda objetos diferentes, veja no código que postei. Corrente, Especial, Poupanca são objetos diferentes.
Answer: Dessa forma funciona:
https://stackoverflow.com/a/3243949/4566483
Na função "arrayToObject" no primeiro parametro vc passa o retorno do json_decode($string, true) e no segundo a string com o nome da classe para o qual vc precisa fazer o cast.
Segue o exemplo:
function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(serialize($array), ':')
    ));
}

class Pessoa {
  public $nome;
  public function __construct($nome) {
    $this->nome = $nome;
  }

  public function getNome(){
      return $this->nome;
  }
}

$jsonPessoa = '{"nome":"Fulano"}';

$objPessoa = arrayToObject(json_decode($jsonPessoa, true), "Pessoa");

var_dump($objPessoa->getNome());

Comment: Poderia colocar o código da função na sua resposta?
Comment: A conversão parece bem interessante, mas não entendi o que está sendo feito no código, se você ou alguém que saiba inglês puder traduzir parte da resposta, seria bacana.
Answer: Agradeço a todos pela contribuição, mas depois de estudar as sugestões e pesquisar sobre reflection, consegui criar um conversor de json para meus objetos, inclusive resolvendo o problema da herança de atributos, já que a ReflectionClass não traz propriedades herdadas diretamente. Ao invés de trabalhar com decode do json em forma de array associativo(json_decode($file, true)), preferi deixar como objetos stdClass por me facilitar tratar os atributos de forma mais generica.
Meu json decodificado ficou dessa forma agora:
array (size=3)
  0 =>
    object(stdClass)[3]
      public 'Especial' =>
        object(stdClass)[4]
          public 'limite' => int 500
          public 'valorEmprestado' => int 0
          public 'jurosCobrados' => int 0
          public 'tarifaManutencao' => int 20
          public 'numero' => int 789
          public 'proprietario' => string 'teste4' (length=6)
          public 'saldo' => int 100
          public 'permissoesEspeciaisHabilitadas' => boolean false
  1 =>
    object(stdClass)[5]
      public 'Poupanca' =>
        object(stdClass)[6]
          public 'quantidadeConsultas' => int 0
          public 'numero' => int 456
          public 'proprietario' => string 'testeprop' (length=9)
          public 'saldo' => int 50
          public 'permissoesEspeciaisHabilitadas' => boolean false
  2 =>
    object(stdClass)[7]
      public 'Corrente' =>
        object(stdClass)[8]
          public 'tarifaManutencao' => float 12.5
          public 'numero' => int 123
          public 'proprietario' => string 'teste' (length=5)
          public 'saldo' => float 3.1
          public 'permissoesEspeciaisHabilitadas' => boolean false

Em cada classe(Conta, Corrente e Poupanca, sendo essas duas ultimas herdando da primeira), está implementado a interface JsonSerializable bem como seu método obrigatório, e nele eu crio um array contendo todos os atributos da classe(via jsonSerialize()) e, quando necessário, trago os métodos das classes ancestrais também, chamando o mesmo método(parent::jsonSerialize()).
No fim, minha classe ficou desta forma:
/**
 * Description of JSONToObject
 *
 * @author diego.felipe
 */
class JSONToObject {

    private $decodeJson;

    public function __construct($jsonFile) {
        if (file_exists($jsonFile)) {
            $strJson = file_get_contents($jsonFile);
            $this->decodeJson = json_decode($strJson);
            var_dump($this->decodeJson);
        }
    }

    public function getArrayObjects() {
        if (!is_null($this->decodeJson) && is_array($this->decodeJson)) {
            $lista = Array();
            foreach ($this->decodeJson as $stdClass) {
                $className = key($stdClass);
                $jsonObj = $stdClass->$className;
                $reflectionClass = new ReflectionClass($className);
                $instance = $reflectionClass->newInstanceWithoutConstructor();
                $allAttributes = Array();

                do {
                    $reflectionClassProperties = Array();
                    foreach ($reflectionClass->getProperties() as $classAttribute) {
                        $classAttribute->setAccessible(true);
                        $reflectionClassProperties[] = $classAttribute;
                    }
                    $allAttributes = array_merge($reflectionClassProperties, $allAttributes);
                } while ($reflectionClass = $reflectionClass->getParentClass());

                foreach ($allAttributes as $attribute) {
                    $attribute->setAccessible(true);
                    $attrName = $attribute->getName();
                    $attribute->setValue($instance, $jsonObj->$attrName);
                }
                $lista[] = $instance;
            }
            return $lista;
        } else {
            return null;
        }
    }

}

Answer: Tente algo como isso e me diz o que rolou?
function json_encode_private($object) {
    $public = [];
    $reflection = new ReflectionClass($object);
    foreach ($reflection->getProperties() as $property) {
        $property->setAccessible(true);
        $public[$property->getName()] = $property->getValue($object);
    }
    return json_encode($public);
}

Referência: SOen
Documentação: PHP.Net
Comment: O problema é que eu preciso retornar o json para meus objetos Poupanca, Corrente e Especial(tem um link de outra pergunta com as classes no texto). Porém, há heranças entre as classes e todas herdam de Conta, portanto, compartilham atributos.
Comment: Pelo que vi na outra questão, você está tentando gerar um json de atributos privados. Só que o uso do json é público. Para isso, use isso: http://php.net/manual/pt_BR/class.jsonserializable.php
Comment: Ivan, a outra questão está resolvida justamente com o uso do jsonserializable, veja minha resposta la, só que o site só permite marcar minha resposta como a correta depois de 2 dias. Converter meus objetos para json eu consegui usando essa interface. Agora preciso fazer o inverso. Parece que é possivel fazer isso usando Reflection mas não conheço muito esse método.
Comment: veja se isso te ajuda: https://3v4l.org/vvv2g/bytecode
Comment: Vou tentar aqui no código.
Comment: Sinceramente nem consegui implementar essa classe nas minhas :/
Comment: Editei a pergunta, espero que tenha solucionado. Agora Usando Reflection. Como você havia comentado.
Comment: Obrigado pela ajuda, mas na verdade eu preciso fazer o inverso, decode no json para objeto. Mas seu código já me deu uma base para fazer isso, vou tentar aqui.

converter json para objeto php


ionic2 accordion list render issue

Question: I am implementing an accordion list in my Ionic2 application. My component:
export class ContactPage {

    public days : any[];
    public shownGroup;

    constructor(public navCtrl: NavController) {

        this.days= [

        { "id": 0,
        "name": 'Ihr heutiger Trainingsplan',
        "exercises":[

        {"id":1,"name":'Best Stretch', "watchedToday": 'false', "type":"body"},
        {"id":8,"name":'Farben', "watchedToday": 'false', "type":"memory"},

        {"id":2,"name":'Butterfly reverse', "watchedToday": 'false', "type":"body"},
        {"id":9,"name":'Punktgenaue Reaktion', "watchedToday": 'false', "type":"memory"},

        {"id":3,"name":'SquatRow', "watchedToday": 'false', "type":"body"},
        {"id":10,"name":'Loslassen', "watchedToday": 'false', "type":"memory"},

        // {"id":13,"name":'Wortpaare 1', "watchedToday": 'false', "type":"memory"},
        {"id":4,"name":'Plank', "watchedToday": 'false', "type":"body"},
        {"id":11,"name":'Wortpaare', "watchedToday": 'false', "type":"memory"}, //word-pair 1 : just show words

        {"id":5,"name":'Push Up', "watchedToday": 'false', "type":"body"},
        {"id":12,"name":'Wortschatz', "watchedToday": 'false', "type":"memory"},

        // {"id":14,"name":'Wortschatz 1', "watchedToday": 'false', "type":"memory"}, // word-pair 2 : actual game
        {"id":6,"name":'Side Plank', "watchedToday": 'false', "type":"body"},
        {"id":7,"name":'Squat', "watchedToday": 'false', "type":"memory"}

        ]
    }

    ];

    this.days.forEach((value1, key) =>{

        value1.exercises.forEach((value2) =>{

        })
    });
}

    toggleGroup(group: any){

        if(this.isGroupShown(group)){
            this.shownGroup=null
        }
        else
        {
            this.shownGroup=group

        }
    }

    isGroupShown(group){

        return this.shownGroup==group;

    }
}

My template:
<ion-list>

         <ion-icon *ngIf="!isGroupShown(day)" name="add"></ion-icon>
         <ion-icon *ngIf="isGroupShown(day)" name="remove"></ion-icon>
        {{day.name}}

          {{exercise.name}}

</ion-list>

And css:
page-contact {

    .list .item.item-accordion {
        line-height: 50px;
        padding-top: 0;
        padding-bottom: 0;
        transition: 0.09s all linear;
    }
    .list .item.item-accordion.ng-hide {
        line-height: 0px;
    }
    .list .item.item-accordion.ng-hide-add,
    .list .item.item-accordion.ng-hide-remove {
        display: block !important;
    }
}

I want to get rid of anchor tag (the code was originally from angular1 which I needed for navigation) and replace it with button (to implement navigation, as an alternative to anchor). When I replace my template to:
  <ion-list>

         <ion-icon *ngIf="!isGroupShown(day)" name="add"></ion-icon>
         <ion-icon *ngIf="isGroupShown(day)" name="remove"></ion-icon>
        {{day.name}}

       <button ion-button clear class="item item-icon-left item-accordion" [hidden]="!isGroupShown(day)" *ngFor="let exercise of day.exercises">
          {{exercise.name}}
        </button>

</ion-list>

What I need to change here to render it as a proper accordion list like in the first pic (also the horizontal line bellow each list element is missing)?
Answer: ion-item was missing in my button tag:
<button ion-item class="item item-icon-left item-accordion" [hidden]="!isGroupShown(day)" *ngFor="let exercise of day.exercises">
          {{exercise.name}}
        </button>

ionic2 accordion list render issue


Create directories and filename all at once if it doesn't already exist

Question: I'm trying to create the full path all at once if it doesn't already exist, but I'm not sure it's possible. This is my code now:
absolute_path = '/home/{signup_code}/{resource}/process'
missing_file = absolute_path.format(resource='agents', signup_code=signup_code)
with open(missing_file, 'a') as f:
    f.write(listing_kwargs['agent_id'] + "\n")

And this is the error I'm getting:
FileNotFoundError: [Errno 2] No such file or directory: '/home/ith/agents/process'

Or do I have to do something like this:
path = '/home/{signup_code}/{resource}/'
os.makedirs(path, exist_ok=True)

process = os.path.join(path, 'process')

with open(process, 'a') as f:
    f.write(listing_kwargs['agent_id'] + "\n")

Comment: @StefanoSanfilippo doesn't that question provide a solution to recursively creating directories, while my question asks for a way to create the file in addition to the directories?
Comment: Once you have created all the directories in `absolute_path`, you can simply `open(missing_file, 'a')` and it will work. So yes, the real issue here is the one addressed in that question.
Comment: But my question asks to `Create directories and filename all at once` and if you're saying I can't, then the real answer is that the built-in `open()` function doesn't support that and there's no other Python function that supports that either.
Answer: There's no way to do this directly. You're going to need to break it down into two parts.  First, create the path using os.makedirs(), and then open the file.  The nice thing is that you can wrap this process in a function, so that it's easily repeatable:
import os
from contextlib import contextmanager

@contextmanager
def open_with_create_path(fname, file_mode='r', buffering=-1,
                          encoding=None, errors=None, newline=None,
                          dir_mode=0o777, exist_ok=True):
    os.makedirs(os.path.dirname(fname), mode=dir_mode, exist_ok=exist_ok)
    f = open(fname, mode=file_mode, buffering=buffering, encoding=encoding,
             errors=errors, newline=newline)
    try:
        yield f
    finally:
        f.close()

FNAME = r'C:\temp\foo\bar\baz.txt'
with open_with_create_path(FNAME, 'w') as f:
    print('foo', file=f)


Displaying pdf file stored in the server and downloading it using php

Question: I have stored .pdf, .doc, .txt files inside a directory in the web server. I am able to display all the files stored inside the directory but the download fails. Each time I click on the hyperlink sample.txt gets downloaded with blank contents. Please look into the codes and suggest me.
this is what I am using in show_directory.php
<?PHP
    // Define the full path to your folder from root
    $path = "/public_html/bc/upload/";

    // Open the folder
    $dir_handle = @opendir($path) or die("Unable to open $path");

    // Loop through the files
    while ($file = readdir($dir_handle)) {

    if($file == "." || $file == ".." || $file == "download_file.php" )

        continue;
        echo "$file
";

    }
    // Close
    closedir($dir_handle);
?>

The contents of download_file.php is:
<?PHP
//download.php
//content type
header('Content-type: text/plain');
//open/save dialog box
header('Content-Disposition: attachment; filename="sample.txt"');
//read from server and write to buffer
readfile('test.txt');
?>

Answer: ....
header('Content-Description: File Transfer');
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . 'test.txt' . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('test.txt');
....

why don't you use binary?
Comment: This doesn't help, look i have 2 files named abc.doc & xyz.pdf saved in a $path = "/public_html/bc/upload/" and i am using the loop to display both the files echo "$file";  The display part works properly but i am unable to download the files. After using binary as you suggested in your codes when i click on it a blank text file named test.txt is downloaded.


Como capturar um value digitado e usar para definir o valor de um atributo class (css)

Question: sou leigo em js, então até para achar algo assim está dificil para mim.
Estou querendo fazer o seguinte.
Digitar um valor número de 2 digitos num input e ao digitar, automaticamente, ir mostrando o valor em uma barra.
Essa barra é definida com "widht:0"
Se eu digitar 50, então o style ficaria "widht:50%"
Algo assim...

.bar-porcent {
  overflow: hidden;
  width: 50%;
}
.bar-porcent span {
    width: 100%;
    height: 14px;
    background-image: linear-gradient(-90deg, red, yellow);
}
<input type='text' id='porc1' value="50" >

Para entender melhor, o layout está ficando assim. Preciso digitar o número e a barra já ficar do tamanho do que digitei
http://gtecprovisorio.hospedagemdesites.ws/grafeno-digital/sistema/cadastro-cedente/participacao.html
Answer: Pode fazer assim:

const percent = document.querySelector('.porcentagem')

document.querySelector('input').addEventListener('input', function(event){

  if(!this.value) percent.style.width = 0

  percent.style.width = (this.value > 100 ? 100 : this.value) + '%'
})
.bar-porcent {
  border: 1px solid #ccc;
  height: 20px;
  width: 50%;
}
.bar-porcent .porcentagem {
    width: 50%;
    height: 100%;
    background-image: linear-gradient(-90deg, red, yellow);
}
<input type='number' value="50" max="100" >

Lembrando que no HTML5 já existe uma tag para tratar esse tipo de comportamento: <progress>

const progress = document.querySelector('progress')

document.querySelector('input').addEventListener('input', function(event){
  progress.value = this.value
})
<input type='number' value='50' max='100'>
<progress max='100' value='50'>
Comment: Muito massa Renan vou estudar esse código, achei bem sofisticado rss. E esse método `input` já junta o keyup e change ao mesmo tempo!
Answer: Fiz uma opção simples, na humildade mesmo rss
Primeiro vc tem que passar seu input para number, depois tem que colocar um max="100" para o contador do input só ir até 100,  e min="0" para não aceitar números negativos pelo contador, mas isso não evita que o usuário digite um número maior...
Depois vc usa o keyup e o change caso o user use o contador do input para ativar a função que passa o .value do input para o width da barra. Tb coloquei na função um if() para caso não tenha valor nenhum a barra fique com 0 width.

Como falei é um JS simples, mas espero que ajude em algo...

let inp = document.getElementById('porc1');

function mostraBarra() {
    let barra = document.querySelector('.bar-porcent');
    let x = inp.value;
    barra.style.width = x + "%";

    if (inp.value == '') {
        barra.style.width = "0%";
    }
}

inp.addEventListener('keyup', mostraBarra);
inp.addEventListener('change', mostraBarra);
.bar-porcent {
    overflow: hidden;
    width: 0%;
}

.bar-porcent span {
    display: inline-block;
    width: 100%;
    height: 14px;
    background-image: linear-gradient(-90deg, red, yellow);
}
<input type='number' id='porc1' value="0" max="100" min="0">

Answer:

<!DOCTYPE html>

  <title> Porcentagem na barra </title>

  <input type='text' id='porc1' onkeyup="contador()" maxlength="3" onfocus="this.select()">

Comment: Usei seu código, ficou perfeito. Muito obrigado.
É só para o cliente aprovar, mas ficou show. Talvez o programador que assumir mude tudo, mas o efeito visual que eu procurava ficou perfeito.
Veja como ficou:
http://gtecprovisorio.hospedagemdesites.ws/grafeno-digital/sistema/cadastro-cedente/participacao.html
Comment: Obrigado, olhei seu site e vi quando digita apenas um `type='text'` ele da NaN em Total pode fazer um validação em JavaScript para  quando digitar apenas um `type='text'` ele fique 0. Ou some somente valor 1 e quando o valor 2 for digitado ele some 1 + 2.
Comment: ou pode deixar os 2 `inputs` formatados para começar com o valor 0 da também :)


How to play the video on iPhone using MonoTouch?

Question: How to play the video on iPhone using MonoTouch? I get the Video's from server as binary format and need to play that video's with all controls like pause, play, stop. How its possible?
Answer: You need to add the player's view to your view hierarchy. For example, assuming you had already added a view named _someView, you can add the MPMoviePlayerController's view like this:
UIView _someView;
MPMoviePlayerController _moviePlayer;

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
    _someView = new UIView();
    _someView.Frame = window.Bounds;
    _moviePlayer = new MPMoviePlayerController (new NSUrl ("file.m4v"));
    _moviePlayer.View.Frame = _someView.Frame;
    _someView.AddSubview(_moviePlayer.View);

    window.AddSubview(_someView);

    _moviePlayer.Play ();

    window.MakeKeyAndVisible ();

    return true;
}

I added a simple example project here: https://docs.google.com/leaf?id=0B4a6jzbuiwbeOWQ5Y2JhZmQtMTNiYi00NWFiLTk3YmMtMTU1MjM2MjQxNTY4&hl=en_US
Comment: What if the video to be played exist in a memory stream and has to be played from the stream directly without saving it in a local file?
Comment: link is broken, where are you getting `window` from?
Answer: Tried this?
using MonoTouch.MediaPlayer;

var moviePlayer = new MPMoviePlayerController (new NSUrl ("file.m4v"));
moviePlayer.Play ();

I got it from here - http://wiki.monotouch.net/HowTo/Video/HowTo%3A_Playback_a_Video. - and there is reference to a MediaPlayer sample.