text:
Q: Table of multiple lm() models using apsrtable in Rmarkdown Goal
Present the results of multiple models, created using the lm() function, together in a nicely-formatted table. This table will be generated in a .Rmd file and output to a PDF document.
Proposed Solution
In Reproducible Research with R and RStudio, there is an example using the apsrtable() function to display multiple models side-by-side. This book provides the following code (p. 173-174):
Code
\begin{table}
    \caption{Example Nested Estimates Table with \emph{aprstable}}
    \label{BasicApsrTableExample}
        \begin{center}
<<results= asis , echo=FALSE>>=
# Load apsrtable package
library(apsrtable)
# Create nested regression model table
apsrtable(M1, M2, M3, M4, M5, Sweave = TRUE,
      stars = "default")
@
       \end{center}
\end{table}

where the models M1 ... M5 are created in chunks using M2 <- lm(Examination ~ Education + Agriculture, data = swiss).
Output
Below is a screen grab of the results, as reported in the book. This is exactly the table I want to create in my .Rmd file and output to a PDF document.

Issues
Attempt 1
When I try to use this code inside a code chunk—as shown below—and the output to a PDF, I get a an error message: Error: $ operator is invalid for atomic vectors
```{r}
t.model2 = xtable(model2,label = NULL)
t.model3 = xtable(model3,label = NULL)

library(apsrtable)

apsrtable(t.model2, t.model3, Sweave = TRUE, stars = "default")
```

Attempt 2
When I use the above code outside a code chunk, the .Rmd file outputs to PDF, but displays the following:

Questions
My Questions

*

*Why are these attempts failing?

*What is the correct way to use the
apsrtable function inside a .Rmd?

*Will this method work to ouput this .Rmd file to PDF?

Related Stack Overflow Questions

*

*Tools for making latex tables in R

*Include apsrtable (or stargazer) output in an Rmd file

*Combining several regression tables into one for use in xtable with Sweave in R

A: You need to take care of the following two things:

*

*Chunk option results='asis'

*\usepackage{dcolumn} must be in the preamble as stated in the help file.

Another option would be the stargazer package, which allows to knit not only to PDF but to HTML as well (see screenshot).
---
title: "stargazer"
author: "hplieninger"
date: "3 August 2018"
output: pdf_document
header-includes:
    - \usepackage{dcolumn}
---

```{r}
m1 <- lm(Fertility ~ Education , data = swiss)
m2 <- lm(Fertility ~ Education + Agriculture, data = swiss)
m3 <- lm(Fertility ~ . , data = swiss)
```

```{r, results='asis'}
apsrtable::apsrtable(m1, m2, m3, Sweave = TRUE)
```

```{r, results='asis'}
# If output: pdf_document
stargazer::stargazer(m1, m2, m3)
# If output: html_document
# stargazer::stargazer(m1, m2, m3, type = "html")
```


text:
Q: Error Trying To Get Property Of Non-Object In Laravel 5.6 so I am trying to loop through an array of objects to update certain values in my database with the values from the object
When I run this loop in my controller
foreach($statuses as $status){
            $workflow->statuses()->where('id', $status->id)->update([
                'status' =>  $status->status
            ]);
        };

It gives me error trying to get property of non-object
When I do a `return response($request->statuses) this is the data structure I see in the console

here is the complete controller
public function workflowStatuses(Request $request, Workflow $workflow)
    {

        // validate form data
        $data = $request->validate([
            'workflow' => 'required|string',
        ]);

            // validate form data
        $oldStatuses = $request->validate([
            'statuses' => 'required|array'
        ]);

        // validate form data
        $newStatuses = $request->validate([
            'newStatuses' => 'required|array',
        ]);

        $workflow->update($data);

        $statuses = $oldStatuses;

        foreach($statuses as $status){
            $workflow->statuses()->where('id', $status['id'])->update([
                'status' =>  $status->status
            ]);
        };

        $workflow->statuses()->saveMany($newStatuses);

        return response($workflow, 200);

    }

A: You can think of the return value of $request->validate() as the array of all request input filtered to only include the data that's being validated.  If that validated data contains arrays, you'll have a multi-dimensional array.
Here, $oldStatuses is going to be an array that contains a key named statuses that contains the actual array you're looking for.
$oldStatuses = $request->validate([
   'statuses' => 'required|array'
]);

// $statuses should get 'statuses' out of this validated array
$statuses = $oldStatuses['statuses'];

Instead, you may want to clean this up and not call validate three times.  It's usually better to run all the validation rules in one validate() call, unless you have good reason to logically separate them.
$validated = $request->validate([
   'workflow' => 'required|string',
   'statuses' => 'required|array',
   'newStatuses' => 'required|array',
]);

$statuses = $validated['statuses'];

A: Try:
foreach($statuses as $status){
   $workflow->statuses()->where('id', $status['id'])->update([
   'status' =>  $status['status'] //$status['status'] should also be accessed by key
   ]);
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: The type "FrameworkAppContextSwitches" is not accessible I am working on a WPF application.  I am attempting to adjust the style for TextBox.  I used "Style Snooper" to grab the default style for that control and pasted it in the App.xaml file in my project (I have also done this for the CheckBox and Button styles).
I get the following error:

The type "FrameworkAppContextSwitches" is not accessible.

On the following line of code:
<DataTrigger Binding="{Binding Path=(msi:FrameworkAppContextSwitches.UseAdornerForTextboxSelectionRendering)}" Value="false" xmlns:msi="clr-namespace:MS.Internal;assembly=PresentationFramework">

I can post the rest of the style code if you need, but it's like 150 lines long so I didn't want to clutter up my question.
The beginning of the App.xaml file looks like this (no reference to msi:):
<Application x:Class="PartsBookAssembler.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:PartsBookAssembler"
         xmlns:s="clr-namespace:System;assembly=mscorlib"
         Startup="Application_Startup">

What namespace reference do I need?  Does anyone know how to fix this?


text:
Q: Convert delimited String to delimited Long as per String to Long mapping I have a string :
My name is amit

and a mapping :
My   -> 1121
name -> 1122
is   -> 1123
amit -> 1124

I want to get back :
1121 1122 1123 1124

where every word is mapped to its corresponding long value which is held in a HashMap.
Here is my version:
public String delimtedStringToLong(String input, String delimiter, Map<String, Long> map) {
        String[] arr = input.split(delimiter);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(String.valueOf(map.get(arr[i])) + delimiter);
        }
        return sb.toString();
    }

I am doing this in Java 8. Can there be better approach for this. Thanks!

A: I'd split the input string, stream it through a mapping function that takes the value from the map and then collect it back:
String input = "My name is amit";
Map<String, Long> map = new HashMap<>();
map.put("My",   1121L);
map.put("name", 1122L);
map.put("is",   1123L);
map.put("amit", 1124L);

String output =
    Arrays.stream(input.split(" "))
          .map(s -> String.valueOf(map.get(s)))
          .collect(Collectors.joining());


text:
Q: Expansion of the $S$-operator and Normal Ordering To phrase my question I will use the example, which we used as an exercise in my introducory QFT lecture. We considered a theory of a real scalar field $\Phi$ and a complex scalar field $\phi$. The Lagrangian of the theory was given as
$$
\mathcal L = \frac 1 2\partial_\mu \Phi\partial^\mu\Phi - \frac 1 2M^2\Phi^2 + (\partial_\mu \phi^\dagger)(\partial^\mu \phi) - m^2 \phi^\dagger\phi + \lambda\phi^\dagger\phi\Phi .
$$
So now we had to expand the $S$-operator up to quadratic order in the coupling $\lambda$. Hence I calculated the following
$$
\begin{align}
S &= T\left\{\exp\left(i\int \text d^4x\ \ \mathbf{: }\,\lambda\phi^\dagger\phi\Phi\,\mathbf{:}\right)\right\}\\
&= \mathbf 1 + i\lambda \int\text d^4x\ \ T\left\{\mathbf{:}\phi^\dagger(x)\phi(x)\Phi(x)\mathbf{:}\right\} \\ & \phantom{=1i}+ \frac{(i\lambda)^2}{2}\int\int\text d^4x_1 \text d^4x_2 T\left\{\mathbf{:}\phi^\dagger(x_1)\phi(x_1)\Phi(x_1)\mathbf{:}\ \mathbf{:}\phi^\dagger(x_2)\phi(x_2)\Phi(x_2)\mathbf{:}\right\} + \mathcal O(\lambda^3),\quad(1)
\end{align}
$$
where $T\{\circ\}$ denotes the time ordering of operators and $\mathbf{:}\circ\mathbf{:}$ denotes the normal ordering of operators.
This expression I further "simplified" using Wicks Theorem. But in the solution to the exercise there was no normal ordering right at the start, so the solution wrote
$$
\begin{align}
S &= T\left\{\exp\left(i\int \text d^4x\ \lambda\phi^\dagger\phi\Phi\right)\right\}\\
&= \mathbf 1 + i\lambda \int\text d^4x\ \ T\left\{\phi^\dagger(x)\phi(x)\Phi(x)\right\} \\ & \phantom{=1i}+ \frac{(i\lambda)^2}{2}\int\int\text d^4x_1 \text d^4x_2 T\left\{\phi^\dagger(x_1)\phi(x_1)\Phi(x_1)\phi^\dagger(x_2)\phi(x_2)\Phi(x_2)\right\} + \mathcal O(\lambda^3),\quad (2)
\end{align}
$$
and then applied Wicks theorem. So one can see that these two approaches do not lead to the same answer, since by applying Wicks theorem on approach $(1)$ you won't get any contraction between fields evaluated at the same point in space-time (for terms quadratic in the coupling). Whereas in approach $(2)$ you will get contractions between fields evaluated at the same point in space-time.
So to my understanding we need the normal ordering of the field operators to make "sense" out of products of "distribution-valued" operators. Therefore I used approach (1), since I thought that equation (2) would be even less sensible.
But the tutor said that if we would not normal order in the first place the terms we would get additionally would cancel with their counter terms in renormalization. So actually I am pretty confused,
is eq. (1) or eq. (2) right or both? And if both are "correct" depending on how the result is treated in further calculations could someone shed some light on why eq. (2) makes any sense in the first place (since I thought we need normal ordering due to the
distributional nature of the field operators)?
Edit:
As discussed in the comments this might boil down to the fact that the quantization procedure itself does not contain the "need" or rather require normal ordering, but we need to make sense of the whole calculation and it does not matter when to do so. (Which is actually not really satisfying)


text:
Q: Do booleans require additional syntax in case when/then statements? I have this simple case statement :
  class_name = case link_path
    when current_page?(jobs_path)               then 'current'
    when current_page?(open_estimates_path)     then 'current'
    when current_page?(tasks_path)              then 'current'
    when current_page?(calendar_dispatch_path)  then 'current'
  end
  debugger

At my break point, I can ask, current_page?(tasks_path), and it will return true.
Then I ask class_name, and it returns nil.
What syntactical error am I making here?
ruby 1.9.2p136
Rails 3.0.10

A: The case statement doesn't do what you think it does. It compares the subject to all the values stated in the when branches and returns the value of the first matching one. For example:
color = case num_color
          when 1 then 'red'
          when 2 then 'green'
          when 3 then 'blue'
        end

You are giving it link_path as the subject, so it compares link_path to each of the booleans in your when branches. As link_path is probably not a boolean value, none of the branches will be evaluated. Maybe you want something like this instead:
class_name = current_page?(link_path) ? 'current' : ''

This will set class_name to "current" if link_path is the current page, otherwise to "".

A: You're comparing string to a boolean.
link_path is compared against every value you put in where until a match is found. Here, obviously, there's no match.

A: You're comparing a Boolean with link_path so none of the cases are going be matched. Why not use if/elsif instead?


text:
Q: "Confused" vs. "bewildered" Is there any major difference in the meanings of bewildered/bewildering and confused/confusing? How about the context in which they can be used?

A: The definitions of the two are as follows:
Confuse:

1 archaic: to bring to ruin
2
    a: to make embarrassed : abash
    b: to disturb in mind or purpose : throw off
3
   a: to make indistinct : blur
   b: to mix indiscriminately : jumble
   c: to fail to differentiate from an often similar or related other

Bewilder:

1: to cause to lose one's bearings
  2: to perplex or confuse especially by a complexity, variety, or multitude of objects or considerations

Additionally, they are listed as synonyms, so I would say it is safe to use them interchangeably where their meanings overlap. Just make sure it's a case where they do mean the same.
One example where they aren't interchangeable:

I confused you with your sister.

means I couldn't tell the difference, or thought one was the other.

I bewildered you with your sister.

means I used your sister to cause you confusion. Granted, the first example could mean that, but wouldn't be understood in that sense.

A: As Jim says, if you confuse X with Y, you're mistakenly thinking X is Y and/or that Y is X. But in practice, people usually say "I [mis]took you for someone else", rather than "I confused you with someone else". You normally hear that "misclassification" sense in constructions like "Don't confuse [my good idea] with [someone else's bad idea]" where there's an element of your thinking is sloppy / unfocussed / confused.
For most other contexts, the two words are effectively synonyms, but consider the usage history...

If that's not enough to convince you that confused is probably the better choice, consider this chart...

...which clearly shows that in "conversational" contexts, confused is overwhelmingly the preferred term.


text:
Q: Unable to determine the principal end of OR "Value cannot be null, parameter name 'key'" I have tried almost everything from StackOverflow to prevent these errors. I have no idea what am I doing wrong. When I'm starting with some changes to remove one bug, the second appear and vice versa. I don't know if it connects to DB, or can it initialize DB, or cannot. It looks like my DB file is empty - I'm using SQLite and I want to use Code First mechanism of EF.
My code
using System.Data.Entity;
using ControlCenter;

namespace ControlCenter
{
    public class IncomingMessaggesContext: DbContext
    {
        public DbSet<UnifiedPositionMessage> UnifiedPositionMessages { get; set; }
        public DbSet<MessageDescription> MessageDescriptions { get; set; }

        static IncomingMessaggesContext()
        {
            Database.SetInitializer<IncomingMessaggesContext>(null);
        }
    }
}

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ControlCenter.CommunicationGateway
{
    using System;
    using TrackingDevices.Positioning;

     public class UnifiedPositionMessage
     {

         public int Id { get; set; }

         public uint DeviceID { get; set; }
         public DateTime ReceiveTime { get; set; }
         public PositionBase DevicePosition { get; set; }
         public object UserPayload { get; set; }

         public int MessageDescriptionId { get; set; }

        [ForeignKey("Id")]
        [Required]
        public virtual MessageDescription MessageDescription { get; set; }

     }

     public class MessageDescription
     {
         public int Id { get; set; }
         public bool IsMessageValid { get; set; }

         public virtual UnifiedPositionMessage UnifiedPositionMessage { get; set; }
     }
}

Calling DB
using (var db = new IncomingMessaggesContext()  )
{
    var msgDesc = new MessageDescription() {IsMessageValid = true, Id = 0, UnifiedPositionMessage = e.Frame};
    db.MessageDescriptions.Add(msgDesc);
    db.UnifiedPositionMessages.Add(e.Frame);
    db.SaveChanges();
}

And connection settings
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <connectionStrings>
      <add name="IncomingMessaggesContext"
       connectionString="Data Source=c:\temp\Messages.db;"
       providerName="System.Data.SQLite" />
    </connectionStrings>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <add name="SQLite Data Provider"
            invariant="System.Data.SQLite"
            description="Data Provider for SQLite"
            type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
</configuration>

A: You're defining a 1 (MessageDescription) : 0..1 (UnifiedPositionMessage) association here.
What EF wants to do is define a primary key in one table that at the same time is a foreign key to the other table. In your case, UnifiedPositionMessage would have an non-autoincrementing Id field that points to MessageDescription.Id, which is an auto-incrementing identity column. So any UnifiedPositionMessage record can only exist if its MessageDescription exists. This is enforced by the [Required] attribute.
In this scenario it is no use to have explicit foreign key fields in your entities: there's only one FK that's also a PK, so you will never be able to set it.
So you can remove MessageDescriptionId from your model and, second, tell EF how to map your entities:
modelBuilder.Entity<UnifiedPositionMessage>()
            .HasRequired(u => u.MessageDescription)
            .WithOptional(md => md.UnifiedPositionMessage);

(this is in the DbContext.OnModelCreating override)

A: That is probably because Id can't be 0!
var msgDesc = new MessageDescription() {IsMessageValid = true, Id = 0, UnifiedPositionMessage = e.Frame};

You can set your msgDesc as
var msgDesc = new MessageDescription {IsMessageValid = true, UnifiedPositionMessage = e.Frame};

So your records in the db all will have unique Id's.

A: This is not a struct! public PositionBase DevicePosition { get; set; }. Changing it according to rules from:
  public class PositionBase
  {
    public DateTime GPSTime { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float Speed { get; set; }    // [km/h]
    public float Course { get; set; }   // [°]
}

to
public class PositionBase
{
    public int Id { get; set; }
    public DateTime GPSTime { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float Speed { get; set; }    // [km/h]
    public float Course { get; set; }   // [°]

    [ForeignKey("Id")]
    [Required]
    public virtual UnifiedPositionMessage UnifiedPositionMessage { get; set; }
}

and adding it to DbContext solves the problem.
public DbSet<PositionBase> PositionBases { get; set; }

Second challenge is that EF doesn't support object types, so it also can cause problems!


text:
Q: Bootstrap `make` error: cannot remove `docs/assets/bootstrap.zip` I have applied make to a github bootstrap clone (git clone https://github.com/twitter/bootstrap.git) and I receive the following output:
mkdir -p bootstrap/img
mkdir -p bootstrap/css
mkdir -p bootstrap/js
cp img/* bootstrap/img/
lessc ./less/bootstrap.less > bootstrap/css/bootstrap.css
lessc --compress ./less/bootstrap.less > bootstrap/css/bootstrap.min.css
lessc ./less/responsive.less > bootstrap/css/bootstrap-responsive.css
lessc --compress ./less/responsive.less > bootstrap/css/bootstrap-responsive.min.css
cat js/bootstrap-transition.js js/bootstrap-alert.js js/bootstrap-button.js js/bootstrap-carousel.js js/bootstrap-collapse.js js/bootstrap-dropdown.js js/bootstrap-modal.js js/bootstrap-tooltip.js js/bootstrap-popover.js js/bootstrap-scrollspy.js js/bootstrap-tab.js js/bootstrap-typeahead.js > bootstrap/js/bootstrap.js
uglifyjs -nc bootstrap/js/bootstrap.js > bootstrap/js/bootstrap.min.tmp.js
echo "/**\n* Bootstrap.js by @fat & @mdo\n* Copyright 2012 Twitter, Inc.\n* http://www.apache.org/licenses/LICENSE-2.0.txt\n*/" > bootstrap/js/copyright.js
cat bootstrap/js/copyright.js bootstrap/js/bootstrap.min.tmp.js > bootstrap/js/bootstrap.min.js
rm bootstrap/js/copyright.js bootstrap/js/bootstrap.min.tmp.js
rm docs/assets/bootstrap.zip
rm: cannot remove `docs/assets/bootstrap.zip': No such file or directory
make: *** [docs] Error 1

My bootstrap/bootstrap folder contains:
├── css
│   ├── bootstrap.css
│   ├── bootstrap.min.css
│   ├── bootstrap-responsive.css
│   └── bootstrap-responsive.min.css
├── img
│   ├── glyphicons-halflings.png
│   └── glyphicons-halflings-white.png
└── js
    ├── bootstrap.js
    └── bootstrap.min.js

Do I need to worry about the make error, or am I good to go? (I've never used Bootstrap before).
Thanks!
Ryan
EDIT:
Applying make -i (thanks Beta) produces the following output (continuing on from the above output) and seems to be okay:
rm: cannot remove `docs/assets/bootstrap.zip': No such file or directory
make: [docs] Error 1 (ignored)
zip -r docs/assets/bootstrap.zip bootstrap
  adding: bootstrap/ (stored 0%)
  adding: bootstrap/js/ (stored 0%)
  adding: bootstrap/js/bootstrap.js (deflated 82%)
  adding: bootstrap/js/bootstrap.min.js (deflated 74%)
  adding: bootstrap/css/ (stored 0%)
  adding: bootstrap/css/bootstrap-responsive.min.css (deflated 77%)
  adding: bootstrap/css/bootstrap.min.css (deflated 84%)
  adding: bootstrap/css/bootstrap.css (deflated 85%)
  adding: bootstrap/css/bootstrap-responsive.css (deflated 80%)
  adding: bootstrap/img/ (stored 0%)
  adding: bootstrap/img/glyphicons-halflings.png (deflated 4%)
  adding: bootstrap/img/glyphicons-halflings-white.png (deflated 4%)
cp bootstrap/js/bootstrap.js docs/assets/js/bootstrap.js
cp bootstrap/js/bootstrap.min.js docs/assets/js/bootstrap.min.js
rm -r bootstrap
lessc ./less/bootstrap.less > ./docs/assets/css/bootstrap.css
lessc ./less/responsive.less > ./docs/assets/css/bootstrap-responsive.css
node docs/build
cp img/* docs/assets/img/
cp js/*.js docs/assets/js/
cp js/tests/vendor/jquery.js docs/assets/js/

A: You haven't given us much to go on. This error can mean trouble in two ways: 1) Make aborts, when it may have had important things still to do, and 2) the absence of an expected file may indicate that something has gone wrong.
If you want Make to soldier on despite the error, just use make -i. This will prevent the first problem, but will do nothing about the underlying problem if there is one.


text:
Q: Display progress with discrete color fill of an image in silverlight In Silverlight, I want to display progress of, for example, an uploading process as a sequence of incremental color fills on an image.
For example,
this is when progress is 0:
this is when 30%:
and 100% is a fully colored image:
How can I control the color fill (I know this will be with the help of a trick, like a final image overlaying the original one or something) to display progress?
My task may be tricky since the image is an OpacityMask for a button in Windows Phone project.
P.S. Just to avoid confusion, as am concerned about the design side of a problem. Logic for hooking up progress with some actions is already in place. I just need to lay out the presentation of a progress.

A: EDIT
I made an implementation. A more thorough explanation and download of the code can be found on my blog.
C#:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CustomControls
{
    [TemplatePart(Name="CLIPRECTANGLE", Type=typeof(RectangleGeometry))]
    public class ImageProgressBar : ProgressBar
    {
        public ImageProgressBar()
        {
            this.DefaultStyleKey = typeof(ImageProgressBar);
        }

        public ImageSource Source
        {
            get { return (ImageSource)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageProgressBar), new PropertyMetadata(null));

        public Brush Fill
        {
            get { return (Brush)GetValue(FillProperty); }
            set { SetValue(FillProperty, value); }
        }

        public static readonly DependencyProperty FillProperty =
            DependencyProperty.Register("Fill", typeof(Brush), typeof(ImageProgressBar), new PropertyMetadata(null));

        private RectangleGeometry _clip;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _clip = this.GetTemplateChild("CLIPRECTANGLE") as RectangleGeometry;
            this.ValueChanged += ImageProgressBar_ValueChanged;
            this.SizeChanged += ImageProgressBar_SizeChanged;
        }

        void ImageProgressBar_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            UpdateClip();
        }

        void ImageProgressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            UpdateClip();
        }

        private void UpdateClip()
        {
            if (_clip != null)
            {
                _clip.Rect = new Rect(0, 0, this.ActualWidth, this.ActualHeight * ((this.Value - this.Minimum) / (this.Maximum - this.Minimum)));
            }
        }
    }
}

Template: generic.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:CustomControls">
    <Style TargetType="local:ImageProgressBar">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:ImageProgressBar">
                    <Border BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Margin="{TemplateBinding Margin}"
                            Background="{TemplateBinding Background}"
                            Width="{TemplateBinding Width}"
                            Height="{TemplateBinding Height}">
                        <Grid>
                            <Image Source="{TemplateBinding Source}"
                                   Stretch="Fill" />
                            <Rectangle Fill="{TemplateBinding Fill}">
                                <Rectangle.OpacityMask>
                                    <ImageBrush ImageSource="{Binding Path=Source, RelativeSource={RelativeSource TemplatedParent}}"
                                                Stretch="Fill" />
                                </Rectangle.OpacityMask>
                                <Rectangle.Clip>
                                    <RectangleGeometry x:Name="CLIPRECTANGLE" />
                                </Rectangle.Clip>
                            </Rectangle>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

How to use:
<my:ImageProgressBar Width="100"
                        Height="100"
                        Fill="Red"
                        Source="ProgressBar.png"
                        Minimum="100"
                        Maximum="200"
                        Value="{Binding ElementName=slider1, Path=Value, Mode=TwoWay}" />
<Slider Margin="0"
        Name="slider1"
        VerticalAlignment="Top"
        Minimum="100"
        Maximum="200"
        Value="125" />

Works like a charm:

Original Answer
You could create a Linear gradient brush like this:
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
    <GradientStop Color="Black" Offset="0"/>
    <GradientStop Color="Black" Offset="1"/>
    <GradientStop Color="Lime" Offset="1"/>
    <GradientStop Color="Lime" Offset="1"/>
</LinearGradientBrush>

And draw the shape/character/text/whatever using this brush.
To show progress just update the Offsets of the middle two gradientstops. You can bind these to make it easier.
To make a real progress bar: Make a Template for the ProgressBar and (multi)bind the Offsets to the Value, Minimum and Maximum of the Progressbar and calculate the offset by (Value - Minimum)/(Maximum - Minimum)
To use a bitmap (PNG):
<Grid HorizontalAlignment="Center"
        VerticalAlignment="Center">
    <Image Source="ProgressBar.png"
            Width="100"
            Height="100" />
    <Rectangle Fill="Lime">
        <Rectangle.OpacityMask>
            <ImageBrush ImageSource="ProgressBar.png" />
        </Rectangle.OpacityMask>
        <Rectangle.Clip>
            <RectangleGeometry Rect="0,25,100,75"/>
        </Rectangle.Clip>
    </Rectangle>
</Grid>

Replace the Rect when the progress changes. To cut off the correct amount.
Note that the same image is used for the mask.

A: I made a custom ProgressBar the other day. Im not going to tell you exactly how to do yours (because im not a designer), but its not that difficult.
Create a Template
<ControlTemplate x:Key="CustomProgressBarTemplate" TargetType="ProgressBar">
    <Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Determinate"/>
                <VisualState x:Name="Indeterminate">
                    <!--Modyify your Storyboard-->
                    <Storyboard RepeatBehavior="Forever">
                        <DoubleAnimation Storyboard.TargetName="IndeterminateGradientFill"
                            Storyboard.TargetProperty="(Shape.Fill).(LinearGradientBrush.Transform).(TransformGroup.Children)[0].X"
                            Duration="00:00:.5" From="0" To="20" />
                        <ObjectAnimationUsingKeyFrames Duration="00:00:00" Storyboard.TargetName="IndeterminateRoot" Storyboard.TargetProperty="(UIElement.Visibility)">
                            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                                <DiscreteObjectKeyFrame.Value>
                                    <Visibility>Visible</Visibility>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Duration="00:00:00" Storyboard.TargetName="DeterminateRoot" Storyboard.TargetProperty="(UIElement.Visibility)">
                            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                                <DiscreteObjectKeyFrame.Value>
                                    <Visibility>Collapsed</Visibility>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <!--Default Root Visuals for either type of ProgressBar-->
        <Border x:Name="ProgressBarTrack" CornerRadius="3" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" />
        <Grid x:Name="ProgressBarRootGrid" >
            <Grid Margin="1">
            </Grid>
            <!-- Beginning of Indeterminate Progress Bar Visuals-->
            <Grid x:Name="IndeterminateRoot" Opacity="0.88" Visibility="Collapsed">
            </Grid>
            <!-- Beginning of Determinate Progress Bar Visuals-->
            <Grid x:Name="DeterminateRoot" Margin="1" >
            </Grid>
        </Grid>
    </Grid>
</ControlTemplate>

In the Determinant and Indeterminant  Grids just draw the image using paths and shapes
(Storyboard.TargetProperty="(Shape.Fill).(LinearGradientBrush.Transform).(TransformGroup.Children)[0].X" The LinearGradientBrush is the brush I used to fill my objects in the Grids.)
Apply the Template
 <ProgressBar Template="{StaticResource CustomProgressBarTemplate}"/>

Your going to have to play around with the design make sure your just fill in the correct UIElement. I hope this is a good start for you


text:
Q: Embed config is not supported in RemoteEmbeddedPlayer When I try to play a youtube video on android using the youtube official api I get this error in logcat

E/YouTubeAndroidPlayerAPI: Embed config is not supported in RemoteEmbeddedPlayer.

and then the onError callback is triggered with NOT_PLAYABLE reason.
Is it something configured incorrectly for the video?
This is the video:
https://www.youtube.com/watch?v=sw6Mg81YMg0

A: had same problem when I created my project for Android TV as the target device, then I create a new project for phone and tablet. Now it works
hope this helps.


text:
Q: Script fails when form selection GT 9 Would love some help here. I'm sure it's simple enough, I'm just a bit flummaxed by it.
This script I am working on: http://jsfiddle.net/rVPnu/9/ fails when the selection is greater than 9.
Can someone explain why and how I fix this so if I select 11 it shows 11 divs?
I did notice this line in the code:
// var gh = tee.charAt(tee.length-1);  // get the int form id will (fail if GT 9)

Many thanks!!

A: The issue is var gh = tee.slice(-1);. It takes the last character of the elements ID, which in the case of the 11th select is npup10 and returns 0.
If all elements are going to start with npup you could instead do tee.slice(4).


text:
Q: Appium iOS kill app without the plist being removed I am trying to run the following steps:
1. Launch app the first time, see terms and agreement
2. Agree to terms and agreement
3. Kill app and relaunch
4. You should not see terms and agreement
Right now, appium is running on without the --no-reset flag, since I do need the app to be reset between scenarios, but the following re-launched the app with the plist deleted (it's like remove the app and relaunch again)
sleep(3)
pf_name = $driver.caps['platformName']
pf_ver = $driver.caps['platformVersion']
dev_name = $driver.caps['deviceName']
auto_accept_alert = $driver.caps['autoAcceptAlerts']
app_path = $driver.caps['app']
Appium::Driver.new({ caps: { platformName: pf_name, platformVersion: pf_ver, deviceName: dev_name, autoAcceptAlerts: auto_accept_alert, app: app_path, noReset: true} })
$driver.restart
$driver.close_app
$driver.launch_app

I also tried $driver.close_app and $driver.launch_app, but they did the same thing (remove the plist as well as killing the app).
Is there any way I can just kill the app without removing plist?

A: I found the answer.
It's somewhat of an all-around involved sort of answer.

*

*Tag the scenario that needs killing and relaunching without resetting with something, say @needPlist

*In the hooks.rb, in the Before for @needPlist, call the Appium::Driver.new with the noReset flag set to true. Call a $driver.restart (Make sure that in the After for the same tag, you call the Appium::Driver.new with the noReset flag set to false, and restart the driver again)

*In the step definition, you can now call $driver.close_app and $driver.launch_app without losing your plist

That should do the trick, I think.


text:
Q: Pandas - replace values with a certain pattern In my dataframe:.
df = pd.DataFrame(zip(datetimes, from_, message), columns=['timestamp', 'sender', 'message'])
df['timestamp'] = pd.to_datetime(df.timestamp, format='%d/%m/%Y, %I:%M %p')

There are some problematic values, defined by a clear pattern:
    timestamp                              sender                               message
    113381 2020-06-04 11:59:24              Jose                               bom te ver feliz\r\n
    113382 2020-06-04 11:59:29              Jose                                              ❤\r\n
    113383 2020-06-04 11:59:40              Maria                Estar bem com você me faz feliz\r\n
    113384 2020-06-04 12:00:57              Maria   Estava falando com uma amiga de infância aque...
    113385 2020-06-04 12:01:14              Maria           Ela teve uma briga feia com o marido\r\n
    113386 2020-06-04 12:01:24   Maria: <attached        00113509-PHOTO-2020-06-04-12-01-25.jpg>\r\n
    113387 2020-06-04 12:02:54              Maria                       e assim leva-se a vida, um\n
    113388 2020-06-04 12:03:21              Maria                  Pelo menos ela riu isso ajuda\r\n
    113389 2020-06-04 13:06:39    Jose: <attached        00113512-PHOTO-2020-06-04-13-06-40.jpg>\r\n

Names will always vary, and could well be:
John
John: <attached
Mary
Mary: <attached

But : <attached will always be there.

How do I perform string replacement which corrects that, independently of the string, ending up with:
timestamp                              sender                               message
113381 2020-06-04 11:59:24              Jose                               bom te ver feliz\r\n
113382 2020-06-04 11:59:29              Jose                                              ❤\r\n
113383 2020-06-04 11:59:40              Maria                Estar bem com você me faz feliz\r\n
113384 2020-06-04 12:00:57              Maria   Estava falando com uma amiga de infância aque...
113385 2020-06-04 12:01:14              Maria           Ela teve uma briga feia com o marido\r\n
113386 2020-06-04 12:01:24              Maria        00113509-PHOTO-2020-06-04-12-01-25.jpg>\r\n
113387 2020-06-04 12:02:54              Maria                       e assim leva-se a vida, um\n
113388 2020-06-04 12:03:21              Maria                  Pelo menos ela riu isso ajuda\r\n
113389 2020-06-04 13:06:39              Jose       00113512-PHOTO-2020-06-04-13-06-40.jpg>\r\n

A: This should work;
df['sender'] = df['sender'].str.replace(u': \u200e<attached', '')

A: data
df = pd.DataFrame({'sender': ['Jose','Jose','Maria','Maria','Maria','Maria: <attached','Maria','Maria','Jose: <attached']})

Solution
df.sender = df.sender.str.split(': <attached').str[0]

   sender
0   Jose
1   Jose
2   Maria
3   Maria
4   Maria
5   Maria
6   Maria
7   Maria
8   Jose

A: 8-Bit Borges, you may have a \u200e character in your data. I have run into similar issues with split doing nothing, because of strange characters like this. This is my solution:
a = df['sender'].to_dict()

Then, I saw what the actual value is when you send it to a dict. The value was : \u200e<attached. Then, I simply did:
df['sender'] = df['sender'].str.split(': \u200e<attached').str[0]

More information about \u200e here: decoding \u200e to string


text:
Q: Should I resolve or reject when no action is taking place? In one of my applications I have a function which returns a Promise() and since this action requires updating an API, I am checking if the last function call asked to send the same information:
module.exports = function updateSidebar(sidebar) {
  return new Promise(function(resolve, reject) {
    if (sidebar === lastSidebar) {
        // What to I do here?
    } else {
        // Application Logic
    }
  });
}

In this instance, would I reject() the Promise(), for giving me "invalid" data, or do I resolve() implying the action has been completed successfully? (which it has, just earlier)
Any advice is very welcome!

A: If you already have the result you want, then just resolve(result).  That works perfectly fine and unless you consider this an error (in which case you would reject), then you should just resolve with some successful result.
module.exports = function updateSidebar(sidebar) {
  return new Promise(function(resolve, reject) {
    if (sidebar === lastSidebar) {
        resolve(someSuccessfulResult);
    } else {
        // Application Logic
    }
  });
}


text:
Q: Jquery изменить только текущий $('span').text() Здравствуйте, есть n div'ов, которые находятся на одной странице и идут друг за другом с подобным кодом:

 280
 <select class="target">
   <option value="280">25</option>
   <option value="380">33</option>
 </select>

Необходимо менять $('.price').text() на option.val() и в ссылке получать параметры с выбранного элемента в select.
Пробовал сделать так:
$('.target').change(function() {
    var text = $('.target').val();
$('span').text(text);

});

Текст меняется во всех span на странице, а надо только в текущем.

A: Помимо prev, который для каждого из выбранных элементов находит предшествующий ему элемент (но только если он лежит на том же уровне иерархии DOM)  надо еще брать значение текущего селекта, на котором произошло событие. Это можно сделать с помощью this, т.е. указание на то, что надо взять значение в текущем контексте, т.е. на исполняемом элементе.

$('.target').change(function() {
  // this указывает на конкретный элемент,
  // на котором только что произошло событие 'change'
  var text = $(this).val();
  $(this).prev().text(text);
});

  280
  <select class="target">
    <option value="280" selected="selected">25см</option>
    <option value="380">33см</option>
  </select>

  2801
  <select class="target">
    <option value="2801" selected="selected">25см</option>
    <option value="3801">33см</option>
  </select>

  28011
  <select class="target">
    <option value="28011" selected="selected">25см</option>
    <option value="38011">33см</option>
  </select>


text:
Q: Discord.py Join/Leave expect when Kicked/Banned I have been trying to learn through searching websites to see how you can make it so that if a member of a server gets kicked it won't send a on_member_leave message that I have added. And so far I've found nothing on how to do it.

A: From what I have seen there is no on_member_leave in the discord.py rewrite.
I believe what you are looking for is discord.on_member_remove.
It is a client event that is called when a member leaves a guild

Discord.py rewrite docs

discord.on_member_join(member)
discord.on_member_remove(member)
Called when a Member leaves or joins a Guild.
Parameters
member (Member) – The member who joined or left.


text:
Q: algorithm to compress bunch of (string pairs) I have bunch of strings which come in pairs
For example, these are three pairs. First one has two string "a", "1"
a,1
a,2
b,1

In my project, i need to compress this data.
For the above data, compressed data is. (compressed to back uncompressed is cartesian product)
{a} <=> {1,2}
{b} <=> {1}

What is the best algorithm to come up with the optimal compressed data. Optimal here is fewer number of mappings
I could write a simple script which creates a hash table with the first string. Even though it gives optimal compressed data in some cases (above case) but it doesnt always.
For example,
a,1
a,2
b,1
c,2

Hash table with first string as a key would give me below compressed data
{a} <=> {1,2}
{b} <=> {1}
{c} <=> {2}

But that's not optimal compressed data. I will get below compression if i used second string
{a,b} <=> {1}
{a,c} <=> {2}

What is the best algorithm to compress the data?

A: This problem is equivalent to covering the 1's or 0's of a binary matrix with a minimum number of lines.
For instance, consider the example : a1,b1,b2,c1,c2,d2,d3,d4,e3,e4,e5. This can be put in a matrix as follows:
  1 2 3 4 5
a 1
b 1 1
c 1 1
d   1 1 1
e     1 1 1

A minimal solution is to cross the lines d and e to give:
d : {2, 3, 4}
e : {3, 4, 5}

and the columns 1 and 2
1 : {a, b, c}
2 : {b, c, d}

so as to reach a minimum number of entries in the compressed map of 4.
The solution of this problem is treated elsewhere on stackoverflow in Hungarian Algorithm: How to cover 0 elements with minimum lines?

A: This is definitely not speed-optimized, but this problem really captured my attention. I wasn't really sure about the input format, but that should be trivial to change. Here is my idea, basically I think that you need a two-pass, because you can't know which compression is best until you reach the end of your data:
use strict;
use warnings;

use Data::Dumper;

sub compress_strings {
    my @strings = @_;
    my %keys_hash;
    my %values_hash;
    my %second_hash;
    my %third_hash;

    foreach my $string (@strings) {
        my ($key, $value) = split /,/, $string;
        push(@{$keys_hash{$key}}, $value);
        push(@{$values_hash{$value}}, $key);
    }

    foreach my $key (keys(%keys_hash)) {
        my $found = 0;
        foreach my $value (@{$keys_hash{$key}}) {
            if (@{$values_hash{$value}} > 1) {
                if (!grep {$value} @{$second_hash{join(',', @{$values_hash{$value}})}}) {
                    push(@{$second_hash{join(',', @{$values_hash{$value}})}}, $value);
                }
                $found = 1;
            }
        }
        if (!$found) {
            $second_hash{$key} = $keys_hash{$key};
        }
    }

    %third_hash = map { $_ => join(',',@{$second_hash{$_}}) } keys(%second_hash);

    return \%third_hash;
}

print Dumper compress_strings( 'a,1', 'a,2', 'b,1', 'c,2', 'd,4' );
print Dumper compress_strings( 'a,1', 'a,2', 'b,3', 'c,3' );
print Dumper compress_strings( 'a,1', 'b,1' ,'b,2' ,'c,1' ,'c,2' ,'d,2' ,'d,3' ,'d,4' ,'e,3' ,'e,4' ,'e,5' );

Output:
$VAR1 = {
          'a,c' => '2',
          'a,b' => '1',
          'd' => '4'
        };
$VAR1 = {
          'a' => '1,2',
          'b,c' => '3'
        };
$VAR1 = {
          'a,b,c' => '1',
          'b,c,d' => '2',
          'd,e' => '3'
        };


text:
Q: Why do I need to put a 1ms setTimeout() between jQuery calls? I'm making a little countdown bar with a css transition:
.livebar {
  background-color: black;
  transition: width 15s linear;
  width: 100%;
  height: 5px;
}

This code doesn't work (in Chrome), in the sense that there is no transition. The width goes to 0 immediately:
$("#barbag").append("

");
$(".livebar").css("width", "0");

...but this code works beautifully:
$("#barbag").append("

");
setTimeout(function(){$(".livebar").css("width", "0")}, 1);

Also, doing the two statements separately in the console works, but pasting in both fails.
It seems like Chrome needs some time after creating the .livebar div to make the transition "active". Is this a known bug, or am I doing something wrong, or is something entirely different going on?

A: I think it has something to do with event loop
event loop process functions from stack, and setTimeout uses a callback function going to get queued in a stack whereas (".livebar").css("width", "0"); is just going to run as soon as processor sees it.
Zero delay doesn't actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. The execution depends on the number of awaiting tasks in the queue.
So in your case the animation has to wait for $("#barbag").append(""); to finish first then apply css. Therefor it needs to be queued in stack, or it will trigger too early.

A: You can use this code for fix issue:
Demo: https://output.jsbin.com/basusos
<!DOCTYPE html>

Animate Width Zero


text:
Q: Symfony .env secure passwords in production mode This is probably a dumb question for some people and I'm probably gonna get some down votes but I need to know.
How to secure passwords (sensitive info) for production mode in Symfony 4.2?
I thought when I compile composer dump-env prod it's gonna be secured and not visible to public but if I run phpinfo(); I can see all my passwords in plain text ...
DATABASE_URL
MAILER_URL

Should I store them in services.yaml as before under parameters?
But then why we even have .env file?
Or I shouldn't be bothered about that as soon as none has access to the CLI of my server?

A: The most common and safe'ish way i know of to store passwords in production, is to use environment variables. Writing passwords in .env or other files in the application repo can lead to accidental leaks through commits to GitHub, code sharing etc.
The .env file is an easy way to make environment variables and should mainly be used for local development.
In production you would create environment variables manually on the host and/or through something like the apache/nginx config, docker, kubernetes secrets etc.
The public should never have access to see phpinfo() or your environment variables.


text:
Q: Why doesn't my cookie authentication work in asp .net core? I have enabled authentication using cookies:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WebBasic.Core.Controllers;

namespace WebBasic.Core
{
  public class Startup
  {
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc();
      services.AddAuthentication().AddCookie(AuthController.AuthControllerAuthId);
      services.AddAuthorization(options => { options.AddPolicy("IsFoo", policy => policy.RequireClaim("FooType")); });
    }

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
    {
      app.UseMvc();
      app.UseAuthentication();
    }
  }
}

...and created a generic view to test claims:
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace WebBasic.Core.Controllers
{
  [Route("/api/[controller]/[action]")]
  public class AuthController : Controller
  {
    public const string AuthControllerAuthId = "AuthControllerAuthId";

    public IActionResult Test()
    {
      var claims = string.Join(", ", User.Claims.Select(i => i.Type));
      return Ok($"{User.Identity.IsAuthenticated}: {claims}");
    }

    public async Task<IActionResult> AuthFixed()
    {
      var claims = new List<Claim> {new Claim("FooType", "FooValue", ClaimValueTypes.String)};
      var userIdentity = new ClaimsIdentity(claims);
      var userPrincipal = new ClaimsPrincipal(userIdentity);
      await HttpContext.SignInAsync(AuthControllerAuthId, userPrincipal);
      return Ok("ok");
    }

    public async Task<IActionResult> Logout()
    {
      await HttpContext.SignOutAsync(AuthControllerAuthId);
      return Ok("ok");
    }
  }
}

When I get /api/auth/authfixed/ a cookie set:
Cache-Control:no-cache
Content-Type:text/plain; charset=utf-8
Date:Tue, 05 Sep 2017 13:57:39 GMT
Expires:-1
Pragma:no-cache
Server:Kestrel
Set-Cookie:.AspNetCore.AuthControllerAuthId=...; path=/; samesite=lax; httponly

...but when I return to api/auth/test I get:
False

ie. I am not authenticated? The authentication middleware is not picking up my cookie? Why not?
If I add [Authorize] I get:
System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
at Microsoft.AspNetCore.Authentication.AuthenticationService.<ChallengeAsync>d__11.MoveNext()

??? Why do I need to explicitly set that?
I know, I can set DefaultChallengeScene, DefaultAuthenticationScheme and DefaultScheme to CookieAuthenticationDefaults.AuthenticationScheme, but all that actually does is set to the string 'Cookies', and it still doesn't work.
What's actually happening here?

A: For anyone else who has this problem, the trick is that all your components need to refer to the same identity id.
In my case, I was using AuthControllerAuthId as my custom auth identifier, instead of the default Cookie. What I needed was to make sure all parts of the auth chain were using this value.
When adding authentication:
services.AddAuthentication(options =>
  {
    options.DefaultChallengeScheme = AuthController.AuthControllerAuthId;
    options.DefaultAuthenticateScheme = AuthController.AuthControllerAuthId;
    options.DefaultScheme = AuthController.AuthControllerAuthId;
  }).AddCookie(AuthController.AuthControllerAuthId)

When constructing the ClaimsIdentity:
var userIdentity = new ClaimsIdentity(claims, AuthControllerAuthId);
var userPrincipal = new ClaimsPrincipal(userIdentity);

When signing in:
await HttpContext.SignInAsync(AuthControllerAuthId, userPrincipal);

Everything was actually working, but specifically in my case, the trick is to look at the AuthenticationType on User.Identity and ensure that it is correctly set at all steps.


text:
Q: WiFi range is getting worse If I start up my laptop (EEE PC 701 running Lubuntu 14.10) my WiFi is normal, but every minute is the range 1% badder. And that's very annoying. If I use my laptop an hour, I have to restart it to have access to the internet. How can I fix that?
Link to wireless info (ubuntu paste)


text:
Q: C++: GetPrivateProfileStringA - random values? Let me start off by saying it's been several years (over 8) since I have had to mess with C++. I am very rusty again and it looks like I'll have to start doing some side projects to get the hang of it.
I know this is really simple and I'm sure it's something very small that I am doing incorrectly... I am receiving garbage characters from my returned value and I can't figure out why. Maybe it has to do with my encoding? Not sure.
A simple function to retrieve the value from an INI file in Windows:
LPCTSTR getConfigValue(LPCTSTR key) {
    char retval[256];

    DWORD dw;
    if ((dw = GetPrivateProfileStringA("RLWELF", "DestinationIP", NULL, retval, 256, ".\\rlwelf.ini")) > 0) {
        return NULL;
    }

    OutputDebugStringA(retval);

    return (LPCTSTR)retval;
}

Thank you in advance!

A: return (LPCTSTR)retval;

You are returning the address of a local variable. That local variable is destroyed as soon as the function returns. It is therefore undefined behaviour for the caller to de-reference the returned pointer. You would need to:

*

*Have the caller provide a buffer into which the function can write.

*Have the function allocate memory on the heap. The caller would need to deallocate it.

*Start using the C++ standard library and return a std::string.

Option 3 is head and shoulders above the others.
Beyond that the cast is dubious. I suspect that you are compiling with UNICODE defined. Which means that LPCTSTR expands to const wchar_t*. That in turn means that your cast would erroneous. You would be lying to the compiler. The compiler will always exact its revenge when you lie to it.
You should get out of the habit of using TCHAR. Compile with UNICODE defined and use the platform native UTF-16 character encoding for text.
Finally, GetPrivateProfileString is a really ancient API that is not encouraged to be used nowadays. The documentation says:

This function is provided only for compatibility with 16-bit Windows-based applications.

If you must use INI files, then use a good C++ library. This will result in a code writing experience that is many orders of magnitude cleaner, safer and quicker.

A: retval is a local variable, it is destroyed at the end of the function, so when you try to return it, the caller receives a pointer to garbage.
Instead, you could malloc a buffer and return it, take an output pointer in argument, or return a unique_ptr to a buffer.


text:
Q: Scatter plot with bar legend I have two data sets:
xy = {{x1, y1}, {x2, y2}, ...}
z = {z1, z2, ...}

I want to plot at each (xi, yi) a point in a two dimensional plane, but color coded according to the value of zi. Next to the plot I want a BarLegend with blue corresponding to the smallest z value and red corresponding to the largest z value.
I already have some code, but I think the Legend is still missing. Of course other more simpler solutions are also welcome.
 colorf = Blend[{{Min[z], Blue}, {Max[z], Red}}, #] &
 pl =
   Graphics[MapThread[{colorf[#1], Point[#2]} &, {z, xy}],
     Axes -> True, AspectRatio -> 1,
     AxesLabel -> {OverTilde["x"], OverTilde["y"]}]

A: xy = RandomVariate[NormalDistribution[], {5000, 2}];
z = RandomReal[1, 5000];
colorf = Blend[{{Min[z], Blue}, {Max[z], Red}}, #] &;

pl = Graphics[MapThread[{colorf@#, Point@#2} &, {z, xy}], AspectRatio -> 1, Axes -> True];
barlegend = BarLegend[{colorf, Through[{Min, Max}@z]}, 10,
   LegendMarkerSize -> 300, LegendLabel -> Style["legend", 16, "Panel"]];

Legended[pl, barlegend]


text:
Q: Data Through Year What does "data through" some year mean, like the following:

link
  Specifically, the short-run response based on data through 2005 is smaller than the short-run response based on data through 2000.

Is there a dictionary definition that would fit this usage of "through"?

A: See definition #4 in the World English Dictionary (scroll down to it):

chiefly  ( US ) up to and including: Monday through Friday

I don't know why they put "US" in parentheses.

See definition #5 at the Wiktionary:

(North America) To (or up to) and including, with all intermediate values.
  from 1945 through 1991;  the numbers 1 through 9;  your membership is active through March 15, 2013

Those are just the first two I checked. I think most dictionaries would have this definition.

A: It refers to data generated or collected until the end of the year 2005.

A: The answer depends on whether you are using American or British English.
In the US, it means data collected up to and including 2005.  In other words earlier years are included.
In Britain, it means data collected throughout 2005.  In other words, only during 2005.
The use of through as a synonym of until is not common outside the US.


text:
Q: Does a symmetric product of spinor spaces give an irreducible representation of so$(2n+1)$? The real Lie algebra so$(2n+1,\mathbb{R})$ has an irreducible representation on a vector space $S$ of dimension $2^n$, the spinor representation. For any integer $k>1$, we can consider the induced representation on $\mathrm{Sym}^k S$, the symmetric part of $\otimes^k S$. Is this representation irreducible?

I own a copy of Representation Theory by Fulton and Harris, but it's mostly example-based and mostly about complex Lie algebras. I didn't find the answer there. (Maybe it's there and I just didn't recognize the way it's expressed.) I've also tried searching online, but I haven't found any freely-accessible resources that address this.


text:
Q: Expected payoff based on two independent exponential distributions I am trying to check if I am formulating a problem correctly.
Suppose there are two independent exponential random variables $t_1$ with rate $x$ and $t_2$ with rate $y$. This means that the CDF of $t_1$ is $F(t_1)= 1 - e^{-xt_1}$ for $t_1\geq 0$ and the CDF of $t_2$ is $G(t_2)= 1 - e^{-yt_2}$ for $t_2\geq 0$.
If $t_1 \leq t_2$, the agent gets a flow payoff of 1 from $t_1$ until $t_2$ at which point the flow payoff changes to  $\alpha$ and lasts from $t_2$ until infinity. If instead $t_1 < t_2$, the agent receives a flow payoff of $1-\alpha$ from $t_1$ until infinity and no payoff before $t_1$. Payoffs are discounted exponentially with rate $r$; that means that if, for example, the agent was geting a deterministic flow payoff of $v$ from $\tau$ to $\tau^\prime$, the overall payoff would be $\int_{\tau}^{\tau\prime}ve^{-rs}ds$.
I want to write a formula for the expected overall payoff. I try to break it into two cases for whether $t_1$ is before or after $t_2$. I am not sure if I am correctly formulating the expected value.
The unconditional density of $t_1$ is $f(t_1) = xe^{-xt_1}$. The unconditional density of $t_2$ is $g(t_2) = ye^{-yt_2}$.
$\int_{t_1}^{\infty} ye^{-yt_2} dt_2 = e^{-yt_1}$, so the density of $t_2$ conditional on $t_1 < t_2$ is $$g_{\vert t_1<t_2}(t_2) = \frac{1}{e^{-yt_1}}ye^{yt_2}=ye^{-y(t_2-t_1)}$$
For a fixed $t_1$, the probability that $t_2\leq t_1$ is $G(t_1)$.
Note that with that in place, here is my attempted formula for the expected payoff.
\begin{equation}
\int_0^\infty f(t_1) (1 - G(t_1))
\int_{t_1}^{\infty} g_{\vert t_1<t_2}\left(t_2 \right) \left[ \int_{t_1}^{t_2}e^{-rs}(1)ds + \int_{t_2}^{\infty} e^{-rs}(\alpha)ds \right]dt_2 dt_1 \\
+ \int_0^\infty f(t_1) G(t_1) \int_{t_1}^{\infty}e^{-rs}(1-\alpha)dsdt_1
\end{equation}
\begin{equation}
\int_0^\infty \left( xe^{-xt_1} \right) \left(1 - \left(1 - e^{-yt_1} \right) \right)
\int_{t_1}^{\infty} ye^{-y(t_2 - t_1)} \left[ \int_{t_1}^{t_2}e^{-rs}(1)ds + \int_{t_2}^{\infty} e^{-rs}(\alpha)ds \right] dt_2 dt_1 \\
+ \int_0^\infty xe^{-xt_1} \left(1-e^{-yt_1} \right) \int_{t_1}^{\infty}e^{-rs}(1-\alpha)dsdt_1
\end{equation}
Is this correct?
Thanks

A: First, the payoff can be computed in general as
$$\int^{\tau'}_{\tau} ve^{-rs}ds = \frac{v}{r}\int^{\tau'}_{\tau} re^{-rs}ds = \frac{v}{r}\left(e^{-r\tau}-e^{-r\tau'}\right).$$
Thus, the agent's total (random) payoff becomes
\begin{eqnarray*}
P &=& 1_{\left\{T_1 < T_2\right\}}\left[\frac{1}{r}\left(e^{-rT_1}-e^{-rT_2}\right)+\frac{\alpha}{r}e^{-rT_2}\right] + 1_{\left\{T_1 \geq T_2\right\}}\frac{1-\alpha}{r}e^{-rT_1}\\
&=& 1_{\left\{T_1 < T_2\right\}}\frac{1}{r} e^{-rT_1} - 1_{\left\{T_1 < T_2\right\}}\frac{1-\alpha}{r}e^{-r T_2} + 1_{\left\{T_1 \geq T_2\right\}}\frac{1-\alpha}{r}e^{-rT_1}
\end{eqnarray*}
The expectation of each term can be represented as a double integral over some part of $\left[0,\infty\right)^2$. It looks like a tedious computation, but should be doable (also two of the three terms in the sum are symmetric -- if the two exponential rates were equal, their expectations would cancel out, but in any case computing one expectation will also tell you the form of the other).


text:
Q: Python: Tkinter TclError: can't invoke "image" command preface: I have currently tried most things and there are few qusestions asked on stackoverflow on this question and i cant seem to wrap my head around it so im going to need some help
application: the purpose of this program is to animate an oval and a picture, the oval works fine, but the picture is struggling, you could remove the image or alien2 and the program should run fine.
CODE
image form
from tkinter import *
import time
from PIL import Image,ImageFilter
from PIL import ImageTk

class alien(object):
     def __init__(self):

        self.root = Tk()
        self.canvas = Canvas(self.root, width=400, height = 400)
        self.canvas.pack()
        self.cardPath = Image.open('bubble.png')
        self.resCard = cardPath.resize((100,100))
        self.CardVar = ImageTk.PhotoImage(resCard,master=root)
        self.alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white',fill='blue')
        self.alien2 = self.canvas.create_image(100,100,CardVar,anchor=CENTER)
        self.canvas.pack()
        self.root.after(0, self.animation)
        self.root.mainloop()

     def animation(self):
        track = 0
        while True:
            x = 5
            y = 0
            if track == 0:
               for i in range(0,51):
                    time.sleep(0.025)
                    self.canvas.move(self.alien1, x, y)
                    self.canvas.move(self.alien2, x, y)
                    self.canvas.update()
               track = 1
               print("check")

            else:
               for i in range(0,51):
                    time.sleep(0.025)
                    self.canvas.move(self.alien1, -x, y)
                    self.canvas.move(self.alien2, -x, y)
                    self.canvas.update()
               track = 0
            print(track)

alien()

ERROR:
image

runfile('/Users/Stian/.spyder-py3/animation_test.py', wdir='/Users/Stian/.spyder-py3')
  Traceback (most recent call last):
File "", line 1, in
      runfile('/Users/Stian/.spyder-py3/animation_test.py', wdir='/Users/Stian/.spyder-py3')
File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
      execfile(filename, namespace)
File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
      exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/Stian/.spyder-py3/animation_test.py", line 57, in
      alien()
File "/Users/Stian/.spyder-py3/animation_test.py", line 25, in init
      self.CardVar = ImageTk.PhotoImage(resCard,master=root)
File "/anaconda3/lib/python3.6/site-packages/PIL/ImageTk.py", line 124, in init
      self.__photo = tkinter.PhotoImage(**kw)
File "/anaconda3/lib/python3.6/tkinter/init.py", line 3542, in init
      Image.init(self, 'photo', name, cnf, master, **kw)
File "/anaconda3/lib/python3.6/tkinter/init.py", line 3498, in init
      self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: can't invoke "image" command: application has been destroyed

I know the code is not beautiful, but it's a test environment and as mentioned everything should work flawless, but it breaks when an image is used instead of an oval which should not make a big difference. Thanks in advance!

PROBLEM SOLVED
turns out the problem turned up when assigning master inside PhotoImage(), when i removed that the application did not get the TclError
NEW PROBLEM

the changes i made to the code were from this:

        self.cardPath = Image.open('bubble.png')
        self.resCard = cardPath.resize((100,100))
        self.CardVar = ImageTk.PhotoImage(resCard,master=root)

to this:

    self.cardPath = Image.open('bubble.png')
    self.resCard = cardPath.resize((100,100))
    self.CardVar = ImageTk.PhotoImage(resCard)

THE NEW ERROR
image form

File "", line 1, in
      runfile('/Users/Stian/.spyder-py3/animation_test.py', wdir='/Users/Stian/.spyder-py3')
File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
      execfile(filename, namespace)
File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
      exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/Stian/.spyder-py3/animation_test.py", line 56, in
      alien()
File "/Users/Stian/.spyder-py3/animation_test.py", line 27, in init
      self.alien2 = self.canvas.create_image(100,100,CardVar,anchor=CENTER)
File "/anaconda3/lib/python3.6/tkinter/init.py", line 2486, in create_image
      return self._create('image', args, kw)
File "/anaconda3/lib/python3.6/tkinter/init.py", line 2477, in _create
      *(args + self._options(cnf, kw))))
TclError: unknown option "pyimage21"

A: You have a few places in your code where you forgot self. But the cause of your main error is that you need to pass the image name as a keyword arg. Here's a repaired version of your code.
from tkinter import *
import time
from PIL import Image,ImageFilter
from PIL import ImageTk

class alien(object):
     def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=400, height=400)
        self.canvas.pack()
        self.cardPath = Image.open('bubble.png')
        self.resCard = self.cardPath.resize((100, 100))
        self.CardVar = ImageTk.PhotoImage(self.resCard)
        self.alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white', fill='blue')
        self.alien2 = self.canvas.create_image(100, 100, image=self.CardVar, anchor=CENTER)
        self.canvas.pack()
        self.root.after(0, self.animation)
        self.root.mainloop()

     def animation(self):
        track = 0
        while True:
            x = 5
            y = 0
            if track == 0:
               for i in range(51):
                    time.sleep(0.025)
                    self.canvas.move(self.alien1, x, y)
                    self.canvas.move(self.alien2, x, y)
                    self.canvas.update()
               track = 1
               print("check")
            else:
               for i in range(51):
                    time.sleep(0.025)
                    self.canvas.move(self.alien1, -x, y)
                    self.canvas.move(self.alien2, -x, y)
                    self.canvas.update()
               track = 0
            print(track)

alien()

BTW, it's not a good idea to use time.sleep in GUI programs. It puts everything to sleep, so the GUI cannot update itself, or respond to any user input. It would be better to reorganize your code so that animation uses the .after method.
Here's a version of the animation method that doesn't use sleep. You need to add self.count = 0 to the __init__ method.
 def animation(self):
    y = 0
    x = 5 if self.count < 50 else -5
    self.count = (self.count + 1) % 100
    self.canvas.move(self.alien1, x, y)
    self.canvas.move(self.alien2, x, y)
    self.root.after(25, self.animation)

A: After a while i edited the code and made it work. here is the full code
from tkinter import *
import time
import PIL
from PIL import Image,ImageFilter
from PIL import ImageTk

class alien(object):
    def __init__(self):

    self.root = Tk()
    self.canvas = Canvas(self.root, width=400, height = 400)
    self.canvas.pack()

    CardVar = ImageTk.PhotoImage(file='bubble.png')
    self.alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white',fill='blue')
    self.alien2 = self.canvas.create_image((100,100),image=CardVar,anchor=CENTER)
    self.canvas.pack()
    self.root.after(0, self.animation)
    self.root.mainloop()

 def animation(self):
    track = 0
    while True:
        x = 5
        y = 0
        if track == 0:
           for i in range(0,51):
                time.sleep(0.025)
                self.canvas.move(self.alien1, x, y)
                self.canvas.move(self.alien2, x, y)
                self.canvas.update()
           track = 1
           print("check")

        else:
           for i in range(0,51):
                time.sleep(0.025)
                self.canvas.move(self.alien1, -x, y)
                self.canvas.move(self.alien2, -x, y)
                self.canvas.update()
           track = 0
        print(track)
alien()

The problem

the cardVar was never able to find the correct image even though it was in the same folder, so i tried to do cardVar.show() and another image that was located far away showed up so it seems like something was saved in my memory. so i decided to restart kernel and everything went smooth


text:
Q: prestashop regenerate category tree to c# I am trying to translate the Prestashop php code to c# but I can't figure it out about the array.
This part is the original code from Prestashop 1.7.6
$id = Context::getContext()->shop->id;
        $idShop = $id ? $id : Configuration::get('PS_SHOP_DEFAULT');
        $sql = new DbQuery();
        $sql->select('c.`id_category`, c.`id_parent`');
        $sql->from('category', 'c');
        $sql->leftJoin('category_shop', 'cs', 'c.`id_category` = cs.`id_category` AND cs.`id_shop` = ' . (int) $idShop);
        $sql->orderBy('c.`id_parent`, cs.`position` ASC');
        $categories = Db::getInstance()->executeS($sql);
        $categoriesArray = array();
        foreach ($categories as $category) {
            $categoriesArray[$category['id_parent']]['subcategories'][] = $category['id_category'];
        }

I created a test file to show the output which gives this (for example)
Array ( [0] => Array ( [subcategories] => Array ( [0] => 1 ) )
[1] => Array ( [subcategories] => Array ( [0] => 2 ) )
[2] => Array ( [subcategories] => Array ( [0] => 324 [1] => 3089 [2] => 394 [3] => 3110 [4] => 540 [5] => 3120 [6] => 667 [7] => 3145 [8] => 3 [9] => 1082 [10] => 3185 [11] => 26 [12] => 1125 [13] => 3792 [14] => 36 [15] => 1198 [16] => 48 [17] => 1310 [18] => 53 [19] => 1409 [20] => 63 [21] => 1456 [22] => 102 [23] => 2482 [24] => 210 [25] => 2517 [26] => 219 [27] => 2564 [28] => 238 [29] => 3069 [30] => 298 [31] => 3072 [32] => 308 [33] => 3075 ) )
[3] => Array ( [subcategories] => Array ( [0] => 1450 [1] => 2826 [2] => 3060 [3] => 3063 [4] => 4 [5] => 9 [6] => 12 [7] => 17 [8] => 19 [9] => 21 [10] => 30 [11] => 40 [12] => 51 [13] => 58 ) ) )

I tried it with a dictionary and added some classes to add the multidimensional array's but it won't work unfortunally. This is what I tried so far:
public bool ReGenerateEntireTree()
        {
            Database db = new Database();
            db.DbConnect();
            DataTable table = new DataTable();
            string query = "";
            query = "SELECT c.`id_category`, c.`id_parent` FROM `ps_category` c LEFT JOIN `ps_category_shop` cs " +
                    "ON c.`id_category` = cs.`id_category` AND cs.`id_shop` = 1 " +
                    "ORDER BY c.`id_parent`, cs.`position` ASC;";
            table = db.SelectWebsiteQuery(query);
            Dictionary<int, SubCategories> categoryArray = new Dictionary<int, SubCategories>();

            int categoryIndex = 0;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                int id_category = Convert.ToInt32(table.Rows[i]["id_category"]);
                int id_parent = Convert.ToInt32(table.Rows[i]["id_parent"]);

                if(!categoryArray.ContainsKey(id_parent))
                {
                    SubCategories sCategories = new SubCategories();
                    categoryIndex = 0;
                    sCategories.subCategories = "categories";
                    Categories Cat = new Categories
                    {
                        Index = categoryIndex,
                        CategoryIndex = id_category
                    };
                    sCategories.Categories = new Categories[2];
                    sCategories.Categories[categoryIndex].Index = categoryIndex;
                    sCategories.Categories[categoryIndex].CategoryIndex = id_category;
                    categoryArray.Add(id_parent, sCategories);
                    categoryIndex++;
                }
                else
                {
                    SubCategories sCategories = new SubCategories();
                    sCategories.subCategories = "categories";
                    Categories Cat = new Categories();
                    Cat.Index = categoryIndex;
                    Cat.CategoryIndex = id_category;
                    sCategories.Categories[categoryIndex] = Cat;
                    categoryArray[id_parent].Categories[categoryIndex] = Cat;
                    categoryIndex++;
                }
            }
            int n = 1;

            return true;
        }

public class SubCategories
    {
        public string subCategories {get; set;}
        public Categories[] Categories { get; set; }
    }
    public class Categories
    {
        public int Index;
        public int CategoryIndex;
    }


text:
Q: Refresh token using FastAPI and Swagger I am trying to create an API for our organization using FastAPI. It has a KeyCloak server that is used for all authentication, and OpenID Connect and JWTs in the way that is considered best practice.
In the simplest case, someone else takes care of acquiring a valid JWT token so that FastAPI then can simply decode and read the user and permissions.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)):

    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        jwt_token = jwt.decode(token, key=env.keycloak_server_public_key, audience='myorg')
        return jwt_token['preferred_username']
    except jwt.exceptions.ExpiredSignatureError:
        raise credentials_exception

Life is simple!
I do, however, want to try to let users explore the API using the Swagger page. I have created this function that lets users login using the UI:
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    login_request = requests.post(
        "https://mygreatorg.com/auth/realms/master/protocol/openid-connect/token",
        data={
            "grant_type": "password",
            "username": form_data.username,
            "password": form_data.password,
            "client_id": "fastapi-application",
        },
    )
    raw_response = json.loads(login_request.content.decode('utf-8'))
    raw_response['acquire_time'] = time.time()

    TOKEN_CACHE[form_data.username] = raw_response

    return {"access_token": raw_response['access_token'], "token_type": "bearer"}

This works fine. The auth header in Swagger is now the token, and it validates, for about a minute. The expire time for the tokens is set to a very short time. One is then expected to refresh them using the refresh_token provided in the raw_response payload.
I can very easily make another request to get a new valid access token given the refresh_token. But I am unable to get Swagger to change the token of the request in the UI. The only way I find is to log out and log in again, but users will be very annoyed if they only allow a minute without being kicked out.
One workaround would be to simply cache the token and ignore the expiration time and let the user be logged in for a while longer, but that defeats the purpose of the entire security setup and feels like a bad idea.
Any ideas on how to let the UI of FastAPI update the bearer token when it needs a refresh, without letting the user log in again?

A:
This is far from an answer and I will likely delete this later. It is a only a placeholder for outlining my research into this question

USE CASE: Swagger UI need to auto refresh with updated JWT token without closing the UI.
Systems/Applications:

*

*KeyCloak

*FastApi

*Swagger

*OpenID Connect and JWTs

When I looking into this question I noted that the issue in this question was raised in the issues at both FastApi and Swagger.
Swagger

When looking through the code base of Swagger, I noted an authorization parameter named persistAuthorization. According to the documentation this parameter will maintain authorization data and this data will not be lost on browser close/refresh.
In the Swagger code base I see this item:
  # source: /src/plugins/topbar/topbar.jsx
  #
  flushAuthData() {
    const { persistAuthorization } = this.props.getConfigs()
    if (persistAuthorization)
    {
      return
    }
    this.props.authActions.restoreAuthorization({
      authorized: {}
    })
  }

The code above makes calls to /src/core/plugins/auth/actions.js.
In the Swagger pull requests there is a pending feature named configs.preserveAuthorization This scope of this feature:

Refreshing or closing/reopening the the page will preserve authorization if we have configs.preserveAuthorization set to true.

It's unclear based on the comments how the features preserveAuthorization and persistAuthorization are different.
FastApi

When I was looking at the FastApi code base, I noted a OAuthFlowsModel named refreshUrl. I looked through the FastApi document and didn't see this mentioned.
# source: /fastapi/security/oauth2.py
#
class OAuth2AuthorizationCodeBearer(OAuth2):
    def __init__(
        self,
        authorizationUrl: str,
        tokenUrl: str,
        refreshUrl: Optional[str] = None,
        scheme_name: Optional[str] = None,
        scopes: Optional[Dict[str, str]] = None,
        auto_error: bool = True,
    ):
        if not scopes:
            scopes = {}
        flows = OAuthFlowsModel(
            authorizationCode={
                "authorizationUrl": authorizationUrl,
                "tokenUrl": tokenUrl,
                "refreshUrl": refreshUrl,
                "scopes": scopes,
            }
        )
        super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)

    async def __call__(self, request: Request) -> Optional[str]:
        authorization: str = request.headers.get("Authorization")
        scheme, param = get_authorization_scheme_param(authorization)
        if not authorization or scheme.lower() != "bearer":
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="Not authenticated",
                    headers={"WWW-Authenticate": "Bearer"},
                )
            else:
                return None  # pragma: nocover
        return param

Looking through the issues for FastApi I noted one asking for OAuth2RerefreshRequestForm to be added.  The scope of this issue is token refresh.
I also noted another issue refresh token with Keycloak and Fastapi

I apologize for not being able to provide a solid answer.


text:
Q: Back Button gets Disabled on IE 7,8 for an ASP.NET site In an ASP.NET 3.5 website we are noticing that the back button is not working properly. If the user does several postbacks (say 10 times), and than starts pressing back button - the back button gets disabled before the user gets through all the pages. The site does not use AJAX.net.
I can reproduce the issue on IE 7 and 8 almost always. The problem seems to be with some sort of limit IE has on History Cache for a given tab/instance. In the tests I did the post request to the server are large - around 83k, and the responses are are round 300k. It seems that with these request sizes the history does not hold more than 4 items. The moment I get to the 5 post, the first item i had selected is dropped.

A: We experienced the same issue. We would load a particular page, and after about 5 seconds, IE8 browser history would get blown away. As a result, history.back() would not work, and IE8 back button would not work. Eventually, we narrowed it down to the large "viewstate" (In our case, the size of the "viewstate" was like 600KB due to "Repeater" control having "viewstate" enabled).  When we disabled the "viewstate" on the "Repeater" control, the size came down to about 11KB. Now, both IE8 back button and history.back() work well.

A: The user has to have gone back to the first page; that's the only way I know of to disable the back button in IE (or any other browser).  Did the application open another tab; that could cause confusion on how far the back button will go.
Also, is the user getting prompted, by IE, to reapply changes when they hit the back button?  I know that is an issue with ASP.NET sites in general and that could cause problems in the browser with using the back button.

A: window.location.replace
or

   history.forward();

in the head

A: This is a bug in IE that has manifested in one way or another since (at least) IE6.  The bug is in the TravelLog code.  It sometimes gets confused.


text:
Q: VERIFIED PayPal IPN Response only in USD currency I used PayPal IPN for my website. My Website is in Multi-Currency and language. I have integrate PayPal IPN with sandbox for testing purpose and what I have faced that when I have paying with USD currency then IPN response is VERIFIED and status is also payment_status=Completed.
8
VERIFIED
0
But when I have login with EUR currency and paying with then IPN response is INVALID but status is payment_status=Completed.
7
INVALID
0
I don't getting what is the problem here so please could you help me?
It is really helpful if any one know this solution and reply to me. Thanks!!!

A: I guess the issue comes from the fact that somewhere in your listener code you are expecting $valid_currency to be returned as "USD", to fix this, create an array with all valid currencies that you accept for payment, and then check that mc_currency is in that array when it is passed via the IPN.
$valid_currency = array("USD", "GBP", "EUR");
if(!in_array($_POST['mc_currency'], $valid_currency) {
    //Not a valid currency according to your list
} else {
    //Is a valid currency according to your list
}


text:
Q: How to align the cells in the html table Here is my code:
  try {

    String name = "";
    String id1 = empid.getEmpId(id);
    System.out.println("id is ===> " + id1);
    Map < Object, Object > map = reporteeservice.getReportees(id1);
    Set < Map.Entry < Object, Object >> s1 = map.entrySet();
    PrintWriter out1 = response.getWriter();
    out1.println("\r\n" +
     "
Reportees List
" + "
\r\n" + "
\r\n" + "Number	" + "User Id	" + "Username	\r\n" + "");

    for (Iterator < Map.Entry < Object, Object >> iterator = s1.iterator(); iterator.hasNext();) {
     Map.Entry < Object, Object > entry = iterator.next();
     Object name1 = entry.getKey();
     Object value = entry.getValue();
     int num = Number++;

     String values = value.toString();
     //System.out.println("returning map");
     PrintWriter out = response.getWriter();
     System.out.println("values ==> " + values);
     request.setAttribute("empid", values);
     out1.println(

      // "
\r\n" +
      // "
\r\n" +
      // "User Id	\r\n" +
      // "Username	\r\n" +
      "
" + "
\r\n" + "
\r\n" + "" + num + "	" + "" + values.toUpperCase() + "	" + "" + name1 + "	" + "
\r\n" + "
");

    }

Actually I am trying to add the map objects which are dynamic(as they are being iterated over the loop)to html table in an java servlet.
My output is:
  Number                           User Id                     Username
   1              AR12355                                Anagha
   2            MS12345                         Madhusu S
   3             AT12345                          Amreen Tai

But I want the output in an aligned manner.
But I am not getting an idea how to append the values to the table.Please help.Thanks in advance

A: Your opening/closing
/
 are not symetric.
In addition, you should never have  and  tags in your iteration, because they should be uniq in the result.
Anyway, it will be easier for you to produce an output, and to validate it with w3c validator, and improve your model till you get a validated one.

A: A distinct non-answer: don't generate HMTL manually like this. People did that 20 years ago, but it is really a bad idea in 2019.
Why? Because you can easily generate invalid HTML, as your code just does, as the comments imply that you are at one point generating a closing TR tag, without having a matching opening one before.
So, the real answer is: use an existing tool, such as JSoup. See here for some more ideas.


text:
Q: Soft starter design Using Back to Back SCRs three phase induction motor I am seeking a help to design the firing angle technic of my Squirrel Cage Induction Motor Soft Starter of Back to Back SCRs. How to calculate the appropriate firing angle? and what are the wave forms required for each pulse from the firing angle?

A: From the way you worded your question, it appears you are totally unfamiliar with phase angle firing techniques for SCRs I don't think this is the place to try to learn complex concepts like that. If you are designing your own Soft Starter, good luck, there are lots of them on the market already and the market is shrinking. If you are just curious and want to try it yourself, you need to start at the very beginning of what SCRs are, how you fire them, then how that applies to 3 phase circuits and lastly, how that applies to motors. That took me about 4 years to learn, lots of mistakes along the way...


text:
Q: Oracle REGEXP_LIKE function to use index table scan? I am using regexp_like function to search specific patterns on a column. But, I see this query is not taking the index created on this column instead going for full table scan. Is there any option to create function based index for regexp_like so that my query will use that index? Here, the pattern SV4889 is not constant expression but it will vary every time.
select * from test where regexp_like(id,'SV4889')

A: Yup.  Regular expressions do not use indexes.  What can you do?
Well, if you are just looking for equality, then use equality:
where id = 'SV4889'

This will use an index on (id).
If you are looking for a leading value, then use like:
where id like 'SV4889%'

This will use an index because the wildcard is at the end of the pattern.
If you are storing multiple values in the column, say 'SV4889,SV4890' then fix your data model.  It is broken!  You should have another table with one row per id.
Finally, if you really need more sophisticated full text capabilities, then look into Oracle's support for full text indexes.  However, such capabilities are usually not needed on a column called id.

A: You can add a virtual column to your table to determine if the substring you're interested in exists in the field, then index the virtual column. For example:
ALTER TABLE TEST
  ADD SV4889_FLAG CHAR(1)
    GENERATED ALWAYS AS (CASE
                           WHEN REGEXP_LIKE(ID,'SV4889') THEN 'Y'
                           ELSE 'N'
                         END) VIRTUAL;

This adds a field named SV4889_FLAG to your table which will contain Y if the text SV4889 exists in the ID field, and N if it doesn't. Then you can create an index on the new field:
CREATE INDEX IDX_TEST_SV4889_FLAG
  ON TEST (SV4889_FLAG);

So to determine if a row has 'SV4889' in it you can use a query such as:
SELECT *
  FROM TEST
  WHERE SV4889_FLAG = 'Y'

db<>fiddle here


text:
Q: Styling html email with customised font without using
A: In short, no. You need to use

…

My Headline

Then, email clients like Mail on iOS that do support @font-face, will still be able to load the font, even though other clients will ignore the


text:
Q: Silverlight Prism Event Aggregator not reliable I'm experiencing some reliability issues with Prism/Silverlight. I got couple of modules one publishing events and other subscribing.
Every time when I run the application from VS on debug mode by pressing "F5", the events are published and subscribed as expected. However, when I run the application from visual studio by pressing "Ctrl+F5", then the event publication/subscription is matter of luck. Sometime its working, sometimes its not working.
Anyone experienced this issue?

A: The most common cause I've seen for this issue is that the subscriber is being GCed. This blog post gives an explanation of why it could happen and provides a way to solve it.
Other than that, I can think of no other cause for this to happen.
I hope this helps.
Thanks,
Damian

A: Usually this happens when you subscribe to events before their are published. Make sure that all your publishers are initialized first;


text:
Q: Почему writeObject() кидает NotSerializableException? import java.io.*;

public class Main implements Serializable {

    private int width;
    private int size;

    public void setWidth(int width) {
        this.width = width;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public static void main(String[] args) {
        Main m = new Main();
        m.setWidth(22);
        m.setSize(84);

        try {
            FileOutputStream fileOut = new FileOutputStream("andriy.ser");
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(objectOut);
            objectOut.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}

UPD. Пропустил, что нужно было передать ссылку на экземпляр класса Main

ObjectOutputStream не реализует Serializable, поэтому, наверное. Вообще строка objectOut.writeObject(objectOut); выглядит странно. – zRrr

Скриншот из Eclipse

A: objectOut.writeObject(objectOut);
Вы хотите, чтобы объект для записи сериализованных объектов записал сам себя? Если подходить более формально, то:

Only objects that support the java.io.Serializable interface can be
  written to streams

Класс ObjectOutputStream не реализует интерфейс java.io.Serializable, отсюда и исключение.
Скорее всего, вы хотели написать:
objectOut.writeObject(m);


text:
Q: extract file log from iphone i would like to know if there is a way to extract log files from an iphone (as iMazing)
I would to write a code to extract these files (for example history calls)
edit: I think use python as language, but it's not mandatory
Sorry for my bad english.
Thanks


text:
Q: echo PHP variable into JS parentheses In my loop I have a link that sends the ID via a query string, however I want to do it through AJAX. I've attempted to do this through setting the PHP variable to a JS variable and haven't had much success. Everything I try says illegal token.
(It's on the 8th line).
<?php
//We display the list of read messages
while($dn2 = mysql_fetch_array($req2))
{
?>

        <a href="#" onclick="hello('"<?php echo $dn1['id']; ?>"')"><?php echo htmlentities($dn2['title'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo $dn2['reps']-1; ?>
        <a href="profile.php?id='.<?php echo $dn2['userid']; ?>'."><?php echo htmlentities($dn2['username'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo date('Y/m/d H:i:s' ,$dn2['timestamp']); ?>

<?php
}

A: You have way to many quotes going on here. I've cleaned it up below.
<?php
//We display the list of read messages
while($dn2 = mysql_fetch_array($req2))
{
?>

        <a href="#" onclick="hello('<?php echo $dn1['id']; ?>')"><?php echo htmlentities($dn2['title'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo $dn2['reps']-1; ?>
        <a href="profile.php?id=<?php echo $dn2['userid']; ?>"><?php echo htmlentities($dn2['username'], ENT_QUOTES, 'UTF-8'); ?>
        <?php echo date('Y/m/d H:i:s' ,$dn2['timestamp']); ?>

<?php
}

A: You have too many quotes. Combining "' will cause you problems.
<a href="#" onclick="hello('<?php echo $dn1['id']; ?>')"><?php echo htmlentities($dn2['title'], ENT_QUOTES, 'UTF-8'); ?>

A: I think there is a typo:
you are writing $dn1['id'] instead of $dn2['id']
But that could be another problem. As others have pointed out, the problem seems to be your use of quotes.

A: Where is $dn1 coming from? I only see $dn2


text:
Q: Drawing outside canvas on android drawable I am trying to draw shadow on my drawable, but the shadow gets cropped, since the rectangle I am drawing is the size of canvas.getClipBounds().
In order to draw the shadow I set the hardware acceleration on the view
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

And I also set the Shadow Layer in my Custom Drawable
bgPaint.setShadowLayer(radius, 0, 0, Color.Black);

When I draw a small rectangle the shadow is rendered. So, I know my original problem is about the shadowing being discarded for being outside of the canvas.
I tried some approaches, such as:
Setting the Drawable's bounds,
Increasing the canvas' bounds,
Disable clipChildren on the parent view,
Overriding Drawable.getPadding()
But none of them helped me.


text:
Q: Trying to remove vowels from user input with function I am trying to remove vowels via user input. I have tried all sorts of things and looked up other question here as well and its just not working.
def d_vowel(word):
    word = input('give me a word: ')
    vowels = ['a', 'e', 'i', 'o', 'u']
    new_word = []
    for letter in word[:]:
        if not letter.lower() in vowels:
            new_word.append(letter)

    print(''.join(new_word))

d_vowel()


text:
Q: How can I delete the selected location in a pickerView using a UIButton? I'm trying to delete the elements of an pickerView using a UIButton, but after 3 consecutively deleted elements I get the error (Index out of Range).
Sorry for my bad english I am still young and live in Germany :D
import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    @IBOutlet weak var textFiled: UITextField!
    @IBOutlet weak var pickerView: UIPickerView!

    var Array = ["Blue", "Green", "Red", "White", "Grey"]
    var indexOfPicker = Int()

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView.dataSource = self
        pickerView.delegate = self
    }

    @IBAction func minusButton(_ sender: UIButton) {
        if Array.count != 0 {
            Array.remove(at: indexOfPicker)
            pickerView.reloadAllComponents()
        }
    }

    @IBAction func plusButton(_ sender: UIButton) {
        if textFiled.text != "" {
            Array.append(textFiled.text!)
            pickerView.reloadAllComponents()
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return Array.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return Array[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        indexOfPicker = row
    }
}

Thanks for any help!

A: This
if Array.count != 0 {

doesn't mean you can remove this index indexOfPicker , I think you need this
if indexOfPicker < Array.count {

As I guess you only select one time from the pickerView ( when the count is 5 which means indexOfPicker is in 0...4 ) then hit the minusButton 3 times

A: Just Replace your function
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return Array[row]
}

With
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        indexOfPicker = row
        return pickerArray[row]
}

Issue
While you remove an element from array index was not getting updated as func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) is only called when you change value in picker When Interacted
but while reloading you need to update index thus, func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int)  is called everytime when picker is reloaded which update your selected index when you reload or update array
Working Output


text:
Q: How to get original inner-elements for a component I am writing a simple component "special-div" that may look like the following in my markup...
<special-div>

This is some random markup

Anything could be inside the special div

</special-div>

I want to capture everything inside my component's tags and reuse those elements in my component's template. Let's say my component simply becomes a div with some title-text to it.. at it's most basic it would do this..
<special-div></special-div>

would yield...

I am a special div

.. what I can't figure out how to do is GET the original elements so they can also appear inside my new template. Example...
<special-div>

This is some random markup

Anything could be inside the special div

</special-div>

..become..

I am a special div

This is some random markup

Anything could be inside the special div

A: A way to achieve what you want can be done with something called content projection (renamed from transclusion as it was known in AngularJS).
Baiscally, it's like you leave a "hole" inside your template that you can fill in from the outside.

Your SpecialDivComponent would have a template such as the following.

I'm special because I always have this tag!

<ng-content></ng-content>

You would use this component like this.
<special-div>

Hello there!

  Nice to meet ya!
</special-div>

The result would be the following markup.
<special-div>

I'm special because I always have this tag!

Hello there!

  Nice to meet ya!
</special-div>