What is 'extension' in dart?

Question: Explain what's going on here in the following snippet.
enum WeatherStatus { initial, loading, success, failure }

extension WeatherStatusX on WeatherStatus {
  bool get isInitial => this == WeatherStatus.initial;
  bool get isLoading => this == WeatherStatus.loading;
  bool get isSuccess => this == WeatherStatus.success;
  bool get isFailure => this == WeatherStatus.failure;
}

Answer: An extension declaration associates members to a type.
Normally, in Dart, a method is either associated with a class or interface (instance methods) or with a static (class/mixin/library/etc) namespace (static methods).
An extension declaration instead associates methods directly with a type, which doesn't have to be an interface type (but can be).
When you try to call a method on something typed as WeatherStatus, say
var status = WeatherStatus.initial;
print(status.isInitial);

the compiler first checks whether the WeatherStatus interface has an isInitial instance member.
Since it doesn't, it then goes on to check if there are any extension methods associated with the WeatherStatus type.
There is (because the WeatherStatusX extension is in scope), and then it instead calls WeatherStatusX(status).isInitial which invokes that method with this bound to the status object.
It's a way to add members on a type from the side, without needing to add them to the class itself (which you can't if it's not your class).
The trade-off is that extension methods are not virtual. You can't add an override in a subclass, and get it called even if the caller only know the object at the superclass type, like you can for classes.
In reality, extension methods are most like static helper functions. You could write:
bool isInitial(WeatherStatus self) => self == WeatherStatus.initial;

and call it as isInitial(status). The extension declaration allows you to pretend that a static helper function is more like a special instance method, because you call it as status.isInitial, but it really isn't an instance method. It just looks like one.
In this particular case, I'd recommend using the newest version of the Dart SDK so you can use the new enhanced enum feature:
enum WeatherStatus {
  initial, loading, success, failure;
  bool get isInitial => this == initial;
  bool get isLoading => this == loading;
  bool get isSuccess => this == success;
  bool get isFailure => this == failure;
}

This makes the isInitial, etc., getters actual instance members on the enum class. (Still can't override them, since enums can't have subclasses, but you don't need to worry about whether extension WeatherStatusX is imported before you use them.)

What is 'extension' in dart?


$\ell^q$ stronger than $\ell^p$

Question: I have to show the following:

Let $1\le p<q\le \infty$. Then
  $$\|x\|_q\le\|x\|_p,\; \forall x \in \ell^p$$ with
$$\ell^p:=\{x \in \mathbb{K}^\mathbb{N}: \|x\|_p<\infty\}$$ and
  $$\|x\|_p:=\left(\sum_{n \in \mathbb{N}}|x_n|^p\right)^{\frac{1}{p}}$$

I know a theorem that helps me here. I need to find a $c>0$ so $\|x\|_p\le c\|x\|_q, \forall x\in\ell^p$. This is equivalent to showing the above, but no matter what I try, I can't find such a $c$. Can someone help me?
Comment: @Tobi92sr What is the theorem you are using?
Comment: Is $\frac{1}{p}+\frac{1}{q}=1?$
Comment: @MathOverview no, it's not
Answer: You can do it directly.
First show that $\|x\|_\infty\le\|x\|_p$. Then, assuming $q<\infty$, write
\begin{align*}
\|x\|_q
&= \left(\sum_{i=1}^\infty|x_i|^q\right)^{1/q} \\
&= \left(\sum_{i=1}^\infty|x_i|^{q-p}|x_i|^p\right)^{1/q} \\
&\le \left(\sum_{i=1}^\infty\|x\|_\infty^{q-p}|x_i|^p\right)^{1/q} \\
&= \|x\|_\infty^{(q-p)/q}\left(\sum_{i=1}^\infty|x_i|^p\right)^{1/q} \\
&= \|x\|_\infty^{(q-p)/q}\|x\|_p^{p/q} \\
&\le \|x\|_p^{(q-p)/q}\|x\|_p^{p/q} \\
&= \|x\|_p.
\end{align*}
Answer: The following trick will be very useful.
Note that $||x||_p \leq ||x||_q \iff||tx||_p \leq ||tx||_q$ for some $t > 0$. Hence, we can assume WLOG that $||x||_p = 1$, otherwise we can scale. Furthermore, we can assume that not all entries of $x$ are zero, otherwise the inequality  is trivial.
Now, $\left(\sum |x_n|^p\right)^ \frac 1p = 1$, so $\sum |x_n|^p= 1$, so this means that $|x_n| \leq 1$ for each $n$, and therefore $|x_n|^q \leq |x_n|^p$ since $q > p$. Therefore, it follows that $(\sum |x_n|^q) \leq 1$ and therefore that $\left(\sum |x_n|^q\right)^ \frac 1q \leq 1$.
Hence, we conclude that $||x||_q \leq ||x||_p$ for all $q > p$, and therefore the conclusion follows.

$\ell^q$ stronger than $\ell^p$


How to Save a Duration in a plist?

Question: How can I save a duration in a plist so that I can load up some sample data in Core Data?
By duration I mean a task has a time duration. Could be 1h12m. Could be 15m.
Using this category
+(NSDate *)dateWithHour:(NSInteger)hour minute:(NSInteger)minute
{
    NSDateComponents *components = [[NSDateComponents alloc]init];
    components.hour = hour;
    components.minute = minute;
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDate *date = [calender dateFromComponents:components];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSLog(@"**Date Utils** %@",[dateFormatter stringFromDate:date]);

    return date;
}

I can create a duration of 15minutes
 task.duration = [NSDate dateWithHour:0 minute:15];

It outputs to the console as:
0001-01-01 04:29:24 +0000

Which doesn't appear to be 15minutes. It looks like 4h29m24s. If I run the date back through a dateFormatter sure enough it prints out 15m.
How can I input a time duration in the plist as shown below?

What am I missing?
Comment: Don't really understand your question. Time and duration are different. How does the example show duration? All I see is a date. Not sure if NSDate is the right object to store a duration. You should probably just use an int and count the duration in seconds.
Comment: The example doesn't show a duration. I'm wanting to represent a duration with an NSDate since I've had some success doing that in code but also need to do it in a plist that i create dummy data using.
Answer: Dates are terribly complicated because of time zones and leap years and leap seconds and so on. They're not suitable for this use case and you will have all kinds of bugs trying to use them.
The correct data type for durations is NSTimeInterval, which is a 64 bit floating point number, in seconds. NSDate uses this data type internally as well.
The easiest way to create a time interval is:
NSDate *aDate = ...
NSDate *anotherDate = ...
NSTimeInterval duration = [aDate timeIntervalSinceDate:anotherDate];

And you'd save it to a plist with NSNumber:
NSNumber *durationNumber = [NSNumber numberWithDouble:duration];

Note that NSTimeInterval is actually a double.

How to Save a Duration in a plist?


Apollo useQuery hook on component mount

Question: I'm new to hooks and trying to use them more
How can I get data (with Apollo) when a component mount ?
I'm trying to use useQuery inside a useEffect, my code so far looks like this
const MyComponent = () => {
  const getME = () => {
      const { loading, error, data } = useQuery(ME);
      setMe(data.me) // useState hook
      console.log('query me: ', me);
  };

  useEffect(getME);
  return (<>
  ...
  </>)
}

but this gives me an error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

edit: this is the query
import { gql } from '@apollo/client';

export const ME = gql`
  query me {
    profile {
      firstName
      lastName
    }
  }
`;

Comment: Hello Mel could you please add a bit more of context for the hook you are trying to call
Comment: I've just added some more context
Comment: no need ... useQuery is already fired at start ... `data` is ready to render after loading
Answer: Here is an example on how you should use the useQuery hook and then stock the data in the state
const { loading, data, error } = useQuery(SOME_QUERY)
const [state, setState] = React.useState([])

useEffect(() => {
  // do some checking here to ensure data exist
  if (data) {
    // mutate data if you need to
    setState(data)
  }
}, [data])`enter code here`

from https://github.com/trojanowski/react-apollo-hooks/issues/158
Comment: no need to duplicate `data` into `state`, it's the same ... you can use `data` directly ... after loading, of course

Apollo useQuery hook on component mount


How do I send user credentials and get the access token?

Question: I am linking a Drupal site to an Android application. With the help of the Simple OAuth module, users will log in to my android app using their Drupal site credentials.
I understand that once the client application has the access token, it can be  included in the headers of any GET request to fetch JSON content from Drupal. I also know that https://example.com//simple-oauth/refresh will give a new access token, having the refresh token.
What should I do if both access and the refresh tokens are already expired?
How do I get them from scratch?
What is the URL to ask for the token, and how do I include the credentials with that via HTTP headers or in the URL?
Is there something I'm not aware of about this way of authenticating?
Comment: From what I understand, what you are describing isn't possible with the simple_oauth module.
Comment: Ya, it seems like it. I guess simple_oauth module is not sophisticated enough, yet!! If I'm not mistaken, you have to get the refresh token manually and then client has to keep sending it every time just before it expires to get the new one. I'm not an expert on the topic but I think this is useless if you want to build an industry standard app.
Comment: I developed some Android application for Drupal 7 in the past. What I had done is to authenticate with username and password (using RESTful endpoint - services), stored the cookie and re-used it in all subsequent requests. So that is one way to do it.
Answer: Moqbel,
Here is a Drupal 8 Android app code that uses Android accountManager to send user credentials and get the access token. https://github.com/onedrupal/One-Drupal-Android
Whan a token is expired, AccountManager can be used to get a fresh token.
https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java At the launch of the activity AccountManager.getAuthTokenByFeatures is called
mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

Here is the AccountAuthenticator https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java
authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);

It uses cookie auth by using endpoint /user/login?_format=json at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/provider/MyServerAuthenticator.java
But Android AccountManager also works with OAuth.
from https://developer.android.com/training/id-auth/authenticate

The only way to discover whether a token is expired or not is to
  contact the server, and it would be wasteful and expensive for
  AccountManager to continually go online to check the state of all of
  its tokens.
Because expired tokens are such a common occurrence, and fixing them
  is so easy, many applications just assume the token has expired before
  even asking for it. If renewing a token is a cheap operation for your
  server, you might prefer to call AccountManager.invalidateAuthToken()
  before the first call to AccountManager.getAuthToken(), and spare
  yourself the need to request an auth token twice.


The send function does not work in a custom form

Question: I have a module that creates a form in a block with a template.
But when I press the submit button, it does not execute the submitForm function.
Instead if in the template only {{form}} if you do.
To clarify, in the template the fields are customized and I call them: {{form.date}}, {{form.submit}}
/**
 * {@inheritdoc}
 */
public function getFormId() {
    return 'custom_form';
}

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

    $form['name'] = [
        '#type' => 'textfield',
        '#size' => 60,
        '#placeholder' => 'Votre nom',
        '#maxlength' => 128,
        '#required' => TRUE,
    ];

    $form['tel'] = [
        '#type' => 'number',
        '#default_value' => "",
        '#placeholder' => 'Votre numéro',
        '#size' => 20,
        '#maxlength' => 20,
    ];

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Réserver'),
        '#button_type' => 'primary',
    );

    return $form;
}

 /**
 * {@inheritdoc}
 */
 public function submitForm(array &$form, FormStateInterface $form_state) {

foreach ($form_state->getValues() as $key => $value) {
  drupal_set_message($key . ': ' . $value);
}
 }

Comment: We need to see your code to ba able to help you.
Comment: Update the question
Comment: How do you know submit is not executed? because you don't see the drupal set message? Sometimes is not realiable, can test in antoher way? using devel dd() function, for example.
Comment: Yes, please use debugging methods and not set message.
Answer: You have to write the submit handler for the form to save data.
  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Insert queries.

    $query = \Drupal::database()->insert('mymodule_table');
    $query->fields([
      'name' => $form_state->getValue('name'),
      'tel' => $form_state->getValue('tel'),
    ]);
    $query->execute();

  }

Comment: You also have to render all of the form elements, not just specific pieces of it.
Answer: I believe you do have to render with {{ form }} because it will render more than just your two form items. This is why the submit is not executing. If that is all you have in your twig, then it would sound like you are missing a form tag and hidden form elements.
Answer: If you don't render with {{ form }}, you have to make sure to add these elements to your twig:
{{ element.form_build_id }} {# required #}
{{ element.form_id }} {# required #}

as well as adding the  html manually and adding the appropriate attributes.  This gives you more flexility in your template.  But there are many advantages to just using {{ form }}, such as managing the elements entirely in your form class, rather than having to update two places.  But sometimes if your layout is really odd, it may make more sense to break the form elements up in the template.
Comment: My problem now is that  does not paint the attributes of the form, it's empty.
Comment: I already have those fields in place, and it stays the same. Does anybody have or know any example module in drupal 8?


Expanded notification

Question: I have a notification that i want to be displayed immediately after that´s created.
my code right now:
Intent myIntent = new Intent(WearRunActivity.this, ResultsActivity.class);
    myIntent.putExtra("distance", distance);
    myIntent.putExtra("time", chronometer.getText());
    myIntent.putExtra("pace", pace);
    myIntent.putExtra("speed", speedAc);
    myIntent.putExtra("lSteps", leftSteps);
    myIntent.putExtra("rSteps", rightSteps);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    //WearRunActivity.this.startActivityIfNeeded(myIntent, 1);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.card_icon)
                    .setContentTitle("REPORT")
                    .setContentText(chronometer.getText())
                    .setLargeIcon(BitmapFactory.decodeResource(
                            getResources(), R.drawable.card_icon))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent);

    notification_manager = NotificationManagerCompat.from(this);

    notification_manager.notify(1, notificationBuilder.build());

With this code, the notification is created but it is not displayed automatically on the screen. I need to swipe through all the pending notifications to search for it. What I want is that this notification is displayed on the screen automatically after it is created, any suggestions?
Answer: I foud a way!
When building the notification add the line .setOngoing(True) so when the notification is sent, it will be on top of all the pending notifications and will be displayed on the screen.
NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.card_icon)
                    .setContentTitle("Report")
                    .setContentText(chronometer.getText())
                    .setLargeIcon(BitmapFactory.decodeResource(
                            getResources(), R.drawable.card_background_blur))
                    .setAutoCancel(true)
                    .setOngoing(true)
                    .setContentIntent(pendingIntent);

Expanded notification


Sistema de transferência ( opções)

Question: Boa tarde!
Pessoal, sou iniciante e queria saber como faço pra simular uma transferência de Banco (Conta + Conta2), sendo "Conta2" uma classe criada fora da Classe "Conta".
Fiz o os métodos Sacar e Depositar dentro da Classe "Conta".
Meu código tá assim:
public class Conta {

String nome; String numero; double saldo;

public void Depositar(double NovoValor) {

if (NovoValor > 0) this.saldo = this.saldo + NovoValor; }

public void Sacar(double NovoSaque) {

if (this.saldo > NovoSaque) this.saldo = this.saldo - NovoSaque;

}

}

Comment: Como você está começando vou perguntar antes de dar minha resposta, tu já chegou a ler sobre métodos estáticos?
Comment: Ainda não, tô no 1° da facul, isso é um exercício e foi até aonde eu conseguir chegar com oque conheço até agora.
Answer: Você deve fazer uma função para realizar a transferência que terá como parâmetros: a conta destino e o valor, essa função vai chamar as duas outras funções que você já fez afinal, se pudermos reutilizar o código é melhor.
public void transferir(Conta destino, double valor){
    destino.Depositar(valor);
    this.Sacar(valor);
}

Sistema de transferência ( opções)


Selected value in ViewBag SelectList not working

Question: I'm trying to set the selected value for a dropdown menu in my controller and pass it to my view via ViewBag. When I debug, all the correct values are being passed to the controller and to the view as well, but when it actually renders on the page, the selected value is not set.
View

    Company

    @Html.DropDownList("CompanyID", (IEnumerable<SelectListItem>)ViewBag.CompanyID, "", new { @class = "required-validation" })
    @Html.ValidationMessageFor(model => model.CompanyID)

Controller
public ActionResult Edit(int? id) {
if (id == null) {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var sale = db.SalesOpportunities.Find(id);
if (sale == null) {
    return HttpNotFound();
}

ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "Name", sale.CompanyID);

var technicians = db.UserProfiles.Select(t => new {
    ID = t.ID,
    Name = t.FirstName + " " + t.LastName,
}).OrderBy(t => t.Name);

ViewBag.UserID = new SelectList(technicians, "ID", "Name", sale.UserID);

return View(sale);
}

Answer: The name of the field and the name of the variable in ViewBag for your choices cannot be the same. Change it from ViewBag.CompanyID to something like ViewBag.CompanyChoices and it will work.


Factory pattern with dependency injection, serviceProvider always return null

Question: I tried to follow the example from
https://chaitanyasuvarna.wordpress.com/2021/03/21/factory-pattern-di-in-net-core/
but i didn't use a classic console application, I created a .Net core service project in VS.
Please find below the files with their source code:
IShape.cs
public interface IShape
{
    public void GetInputValues();
    public void DisplaySurfaceArea();
    public void DisplayVolume();
}

Sphere.cs
public class Sphere : IShape
{
    public decimal Radius { get; set; }

    public void GetInputValues()
    {
        Console.WriteLine("Radius : ");
        Radius = decimal.Parse(Console.ReadLine());
    }

    public void DisplaySurfaceArea()
    {
        Console.WriteLine("Surface Area of the sphere is :" + (4 * 3.14m * Radius * Radius));
    }

    public void DisplayVolume()
    {
        Console.WriteLine("Volume of the sphere is :" + (4 / 3 * 3.14m * Radius * Radius * Radius));
    }
}

Cube.cs
public class Cube : IShape
{
    public decimal Side { get; set; }

    public void GetInputValues()
    {
        Console.WriteLine("Side : ");
        Side = decimal.Parse(Console.ReadLine());
    }

    public void DisplaySurfaceArea()
    {
        Console.WriteLine("Surface Area of the Cube is :" + (6 * Side * Side));
    }

    public void DisplayVolume()
    {
        Console.WriteLine("Volume of the Cube is :" + (Side * Side * Side));
    }
}

ShapeFactory.cs
public class ShapeFactory : IShapeFactory
{
    private readonly IServiceProvider serviceProvider;

    public ShapeFactory(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    public IShape GetShape(ShapeEnum shapeEnum)
    {
        switch (shapeEnum)
        {
            case ShapeEnum.Cube:
                return (IShape)this.serviceProvider.GetService(typeof(Cube));
            case ShapeEnum.Sphere:
                return (IShape)this.serviceProvider.GetService(typeof(Sphere));
            default:
            throw new ArgumentOutOfRangeException(nameof(shapeEnum), shapeEnum, $"Shape of {shapeEnum} is not supported.");
        }
    }
}

public interface IShapeFactory
{
    public IShape GetShape(ShapeEnum shapeEnum);
}

ShapeCalculationService.cs
public class ShapeCalculationService : IShapeCalculationService
{
    private readonly IShapeFactory _shapeFactory;
    private IShape _shape;

    public ShapeCalculationService(IShapeFactory shapeFactory)
    {
        this._shapeFactory = shapeFactory;
    }

    public void CalculateShapeMeasurements()
    {
        this._shape = GetShapeFromUser();
        this._shape.GetInputValues();
        this._shape.DisplaySurfaceArea();
        this._shape.DisplayVolume();
    }

    private IShape GetShapeFromUser()
    {
        Console.WriteLine("Enter the serial no. for the shape you want to choose :");
        Console.WriteLine("1. Cube");
        Console.WriteLine("2. Sphere");
        var serialNumber = int.Parse(Console.ReadLine());

        switch (serialNumber)
        {
            case 1:
                return _shapeFactory.GetShape(ShapeEnum.Cube);
            case 2:
                return _shapeFactory.GetShape(ShapeEnum.Sphere);
            default:
                throw new ArgumentOutOfRangeException("Invalid input.");
        }
    }
}

public interface IShapeCalculationService
{
    public void CalculateShapeMeasurements();
}

worker.cs
public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IShapeCalculationService shapeCalculationService;
    public Worker(ILogger<Worker> logger, IShapeCalculationService shapeCalculationService)
    {
        _logger = logger;
        this.shapeCalculationService = shapeCalculationService;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {

            shapeCalculationService.CalculateShapeMeasurements();
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

Program.cs
using TestFactory;

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext,services) =>
    {
        services.AddTransient<IShapeFactory, ShapeFactory>();
        services.AddTransient<IShapeCalculationService, ShapeCalculationService>();
        services.AddScoped<Sphere>().AddScoped<IShape, Sphere>(s=>s.GetService<Sphere>());
        services.AddScoped<Cube>().AddScoped<IShape, Cube>(s => s.GetService<Cube>()); ;

        services.AddHostedService<Worker>();
    })
    .Build();

await host.RunAsync();

While going through with the debugger, I found that
public IShape GetShape(ShapeEnum shapeEnum) always returns null.
Please can you advice what I am doing wrong, and how I can correct it and make the example work.
Answer: You can simplify your solution by using delegate in DI, like this:
{
    public delegate IShape ShapeResolver(int serialNumber);
}

then in program.cs:
services.AddScoped<Sphere>();
services.AddScoped<Cube>();

 services.AddTransient<ShapeResolver>(serviceProvider => key =>
            {
                switch (key)
                {
                    case 1:
                        return this.serviceProvider.GetRequiredService<Cube>();

                    case 2:
                        return this.serviceProvider.GetRequiredService<Sphere>();

                    default:
                        throw new KeyNotFoundException();
                }

ShapeCalculationService will look something like this:
public class ShapeCalculationService : IShapeCalculationService
{
    private readonly ShapeResolver _ShapeResolver;
    private IShape _shape;

    public ShapeCalculationService(ShapeResolver shapeResolver)
    {
        this._ShapeResolver= shapeResolver;
    }

    public void CalculateShapeMeasurements()
    {
        this._shape = GetShapeFromUser();
        this._shape.GetInputValues();
        this._shape.DisplaySurfaceArea();
        this._shape.DisplayVolume();
    }

    private IShape GetShapeFromUser()
    {
        Console.WriteLine("Enter the serial no. for the shape you want to choose :");
        Console.WriteLine("1. Cube");
        Console.WriteLine("2. Sphere");
        var serialNumber = int.Parse(Console.ReadLine());

        return _ShapeResolver(serialNumber);
    }
}

Answer: You registered and requested different types. Within your registration phase you make these calls to register your types by their interfaces:
services.AddScoped<Sphere>().AddScoped<IShape, Sphere>(s=>s.GetService<Sphere>());
services.AddScoped<Cube>().AddScoped<IShape, Cube>(s => s.GetService<Cube>());

Within your method later you are going to request this:
(IShape)this.serviceProvider.GetService(typeof(Cube))

As you can see, the type Cube is not registered within the DI Container, only its interface IShape. Also it seems you seem to mix up the things a little bit, cause the purpose of a registered factory is to support the DI framework to produce the desired concrete type. But your factory just forwards the calls to the container itself.
To make your code working you should in a first step register your Sphere and Cube as their explicit type within the DI like this:
services.AddScoped<Sphere>();
services.AddScoped<Cube>();

And within your factory you should call one of these:
(IShape)this.serviceProvider.GetRequiredService(typeof(Cube));
this.serviceProvider.GetRequiredService<Cube>();

In a next step take a closer look on how factories are implemented and how they  know which concrete type they have to return for a given interface or base type.
Update regarding scopes
I just seen now, that you registered your classes as scoped, but in your code you're going to ask the provider directly for an instance. This is the root provider that doesn't hold a scope. Instead you have to create a scope by calling .CreateScope() and from the returned scoped provider you can request an instance of your desired scoped classes. For further details take a look at the Microsoft documentation.
Comment: Hi,I added the services.AddScoped(); and services.AddScoped(); to the Program.cs, but the issue remains. The call this.serviceProvider.GetRequiredService(typeof(Cube)) is not working because it requires a cast to IShape
Comment: If you use the non-generic method with a type parameter, the return type is object and you have to cast it. If you use the generic method with the corresponding parameter the return type is of this type T and a cast shouldn't be necessary. Using the *Required* method prevents returning null and will throw an exception. If it doesn't work, it should probably give you a hint, why it doesn't return anything.


Prove that a polynomial is irreducible or the field contains a $p$th root

Question: An exercise from Lang.

Let $k$ be a field. Let $n$ be a nonnegative integer.
Consider the polynomial $x^{p^n}-a \in k[x]$.
Assume that $\text{char}(k) = p > 0$.
Prove that either the polynomial $x^{p^n}-a$ is irreducible over the field $k$ or there exists $b\in k$ such that $a = b^p$.

How to prove this statement? I am a little bit confused with this statement.
Comment: Related : http://math.stackexchange.com/questions/1376541/proving-that-tpr-a-is-irreducible-when-a-in-k-is-not-a-pth-power, http://math.stackexchange.com/questions/275052/irreducibility-of-xpr-a-if-a-is-not-a-p-th-power?rq=1
Answer: One side:
If $a=b^{p}$ for $b\in k$ then: $$x^{p^{n}}-a=x^{p^{n}}-b^{p}=\left(x^{p^{n-1}}-b\right)^{p}$$
showing that the polynomial is not irreducible.

Let $k^{\mathbf{a}}$ denote an algebraically closed fied that contains
$k$ and is algebraic over $k$.
Let it be that $\alpha\in k^{\mathbf{a}}$ is a root of $x^{p^{n}}-a$.
Then $\alpha^{p^{n}}-a=0$ so that $x^{p^{n}}-a=x^{p^{n}}-\alpha^{p^{n}}=\left(x-\alpha\right)^{p^{n}}$.
This reveals that polynomial $x^{p^{n}}-a$ has only one root in $k^{\mathbf{a}}$.

The other side:
For convenience define $f\left(x\right):=x^{p^{n}}-a$ and let $g\left(x\right)\in k\left[x\right]$
denote the minimal polynomial of $\alpha$.
Then $f\left(x\right)=g\left(x\right)^{m}h\left(x\right)$
for some positive integer $m$ and some $h\left(x\right)\in k\left[x\right]$.
Taking $m$ maximal $g\left(x\right)$ will not divide $h\left(x\right)$
so that $\alpha$ is not a root of $h\left(x\right)$. But $\alpha$
is the only candidate for being a root of $h\left(x\right)$ so we
conclude that $h\left(x\right)$ has no roots at all. This allows
the conclusion that: $$f\left(x\right)=g\left(x\right)^{m}$$ If $d$
denotes the degree of $g$ then $md=p^{n}$ showing that $m$ and
$d$ are both powers of $p$. So nonnegative integers $u,v$ exist
with $u+v=n$, $d=p^{u}$ and $m=p^{v}$. Then: $$x^{p^{u}}-\alpha^{p^{u}}=\left(x-\alpha\right)^{p^{u}}=g\left(x\right)\in k\left[X\right]$$
Proved is now that $\alpha^{p^{u}}\in k$.
If $f$ is not irreducible then $p^{v}=m>1$ so that $v\geq1$.
Defining $b:=\alpha^{p^{n-1}}=\left(\alpha^{p^{u}}\right)^{p^{v-1}}\in k$
we find:
$$a=\alpha^{p^{n}}=b^{p}$$
Answer: Rename the field $k$ as $K$. Rename the indeterminate $x$ as $X$. Thus we must prove that either the polynomial $X^{p^n}-a$ is irreducible over $K$ or $a$ is a $b$-th power.
In an extension field of $K$, if $b$ is a root of $X^{p^n}-a$, then $(X-b)^{p^n}=X^{p^n}-b^{p^n}
=X^{p^n}-a$. Therefore, any proper monic factor of $X^{p^n}-a$ is
$(X-b)^k$ where $0<k<p^n$. If $(X-b)^k$ has coefficients in $K$, then $b^k\in K$.
But as $b^{p^n}=a\in K$, then $b^g\in K$, where $g=\gcd(k,p^n)$. Then $g=p^m$
where $0\le m\le n-1$, and this implies $b^{p^{k-1}}\in K$, and that's a $p$-th
root of $a$.
Comment: This is great thanks. I never realized if it had a root then it would be the only root...
Very helpful.
Comment: @Angina Seng In the last line it should be $b^{p^{n-1}} \in K$ as $b^{p^{n-1}} =(b^{p^{m}})^{p^{n-m-1}}$.


Convert from Itext PDF byte array to multipage TIFF file

Question: I have a pdf file (obtained from a byte[] generated by iText) I need to send to a signature hardware.
Due some incompatibility with the java printer driver I can't send the PDF directly, so i need to convert it to images before. I've succeed converting each PDF page to a jpg file, but customer does not like solution cause signatures are not in all the document, only in individual pages.
As I've not found any free library, I decided to make it in four steps:
STEP1: generate PDF with itext and persist it.
FileOutputStream fos = new FileOutputStream("tempFile.pdf");
fos.write(myByteArray);
fos.close();
fos.flush();

STEP 2: convert from PDF multipaged to List<java.awt.Image>
List<Image> images = null;

Ghostscript.getInstance(); // create gs instance

PDFDocument lDocument = new PDFDocument();
lDocument.load(new File("tempFile.pdf"));

SimpleRenderer renderer = new SimpleRenderer();

renderer.setResolution(300);

try
{
    images = renderer.render(lDocument);
}
catch (RendererException | DocumentException e)
{
    e.printStackTrace();
}

Step 3: Now I iterate over List<java.awt.Image> to convert to an individual TIFF's.
    int filename = 1;

    TIFFEncodeParam params = new TIFFEncodeParam();

    Iterator<Image> imageIterator = images.iterator();

    while (imageIterator.hasNext()) {
        BufferedImage  image = (BufferedImage) imageIterator.next();

        FileOutputStream os = new FileOutputStream(/*outputDir + */ filename + ".tif");

        JAI.create("encode", image , os, "TIFF", params);

        filename ++;
    }

STEP 4: create multipaged TIFF from various individual TIFF files
BufferedImage image[] = new BufferedImage[paginas];
    for (int i = 0; i < paginas; i++) {
        SeekableStream ss = new FileSeekableStream((i + 1) + ".tif");
        ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
        PlanarImage pi = new NullOpImage(decoder.decodeAsRenderedImage(0),null,null,OpImage.OP_IO_BOUND);
        image[i] = pi.getAsBufferedImage();
        ss.close();
    }

    TIFFEncodeParam params = new TIFFEncodeParam();
    params.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
    OutputStream out = new FileOutputStream(nombre +".tif");
    ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
    List <BufferedImage>list = new ArrayList<BufferedImage>(image.length);

    for (int i = 1; i < image.length; i++) {
        list.add(image[i]);
    }

    params.setExtraImages(list.iterator());
    encoder.encode(image[0]);
    out.close();

    System.out.println("Done.");

DONE. Hope that helps for someone else with same problem.
Comment: @JordiCastilla *the device to sign is viewed by java / system as a printer* - hmmm, feels like a design that sounded good at the start but eventually turns out to be more a burden than a boon. Sigh, sorry.
Comment: Wouldn't it make more sense to sign the PDF as is and convert only for printing?
Comment: From what line do you get the exception? `ImageIO.read`? It seems that your PDFBox-exported JPEGs are either not found, or not readable. Does this happen for the first file in the loop, or at some (random?) point later? If so, try attaching a sample file that fails to be read. :-)
Comment: @mkl the device to sign is viewed by java / system as a printer.
Comment: @haraldK im getting the error in line `RenderedImage image = ImageIO.read(new File(file + ".jpg"));`
Comment: @haraldK ... solved, I edited question to help future OP
Comment: [Here](http://stackoverflow.com/questions/31973354/converting-pdf-to-multipage-tiff-group-4/32702373#32702373) you can find a simpler approach to convert PDF to multipage TIFF directly without the middle man.
Answer: I had same issue a while ago. I got lot of help from here:
Multiple page tif
Allso check:
JAI (Java Advance Image)
Here is the conde snippet to convert pdf pages to png images (using org.apache.pdfbox library):
    PDDocument document = null;
    document = PDDocument.load(pdf1);

    int pageNum = document.getNumberOfPages();

    PDFImageWriter writer = new PDFImageWriter();
    String filename = pdf1.getPath() + "-";
    filename = filename.replace(".pdf", "");
    writer.writeImage(document, "png", "", 1, Integer.MAX_VALUE, filename);

    document.close();

And after that i converted each PNG image to TIFF and then from multiple TIFF images to single multi paged TIFF.
Comment: I converted png to tiff using JAI (a free library from Sun). Here is an example: https://blog.idrsolutions.com/2009/06/saving-java-images-as-tifs-wth-jai/
Comment: Thanks! That helped, now I'm able to convert from various TIFF files to one multipaged TIFF... problem is now convert from PDF to TIFF...
Comment: I used itext to convert pdf pages to png and from png to tiff. Look at updated answer.
Comment: conversion from PDF to JPG/PNG is not a problem, the problem is the PNG/JPG/PDF to TIFF, cause TIFF seems to need additional librarys or so... did you succeed to convert PNG to TIFF in itext/pdfbox???
Comment: Accepted, your answer helped enough... :D
Comment: see more recent code here: https://stackoverflow.com/questions/23326562/convert-pdf-files-to-images-with-pdfbox


how to pass parameters to puppet modules?

Question: What is the best practice for configuration of puppet modules? I have puppet 2.7.11. I find this way quite messy, it looks like using global variables.
node default {
   $always_apt_update = true
   include apt
}

Should I create class which would inherit most of configuration from the original? The documentation seems to have too many versions and I'm not sure which one applies for me.
UPDATE:
when I try this:
  class { 'apt':
    always_update => 'true',
  }

I get an error:
Error 400 on SERVER: Invalid parameter always_update at /etc/puppet/manifests/nodes.pp:32

Answer: You should use Parametrized classes instead of global variables.
For example:
node default {
  class {'apt':
    always_update =>true
  }
}
class apt ($always_update = true ) {
  // code
}

node 'example.com' {
  class { bar: }
}

See puppet documentation for more information:

http://projects.puppetlabs.com/projects/1/wiki/Development_Language_Evolution#Parameterized+classes
http://docs.puppetlabs.com/guides/language_guide.html#parameterised-classes
Comment: yeah, that's what I was trying, but for 2.7 the syntax is slightly different: `class { 'apt': always_update => true }`
Comment: I've upgraded to puppet 3.1.0, if I you exactly your code I get this: `Could not parse for environment production: Syntax error at '='; expected '}'`. Without parameters it works, but does not solve anything.
Comment: edited post to reflect puppet 3 syntax
Comment: I had there also error in declaration of that class, now it finally works. thanks!
Answer: These answers seems a bit outdated, with new versions of puppet i.e 3.7.x, class parameters can be passed using Hiera.
Resource like class declaration is not considered best practice anymore.
Although the second answer does use Hiera, but it is using 'hiera' function explicitly, which is again a not so advisable practice.
The new solution would look something like this:
/etc/puppet/manifests/site.pp:
node default {
    include apt
}

/etc/puppet/modules/apt/manifests/init.pp:
class apt ($always_update = true ) {
  // code
}

/etc/puppet/hieradata/<filename>.yaml
apt::always_update: true

Hiera data yaml files can have different values of the parameter as required.
Comment: What would  the hiera file name be in this example case?
Answer: The recommended practice these days is to use Hiera.  It's built into 3.x, but in 2.7 you need to install it separately.
You can then grab data from Hiera in your manifest for the apt class:
$always_apt_update = hiera("always_apt_update")

With a Hiera config like this..
:hierarchy:
  - %{::clientcert}
  - common

..the node (pulled from the clientcert fact) will be used as higher precedence in the lookup than the common.yaml file.
So, with always_apt_update: false in node1.example.com.yaml and always_apt_update: true in common.yaml, node1 will end up with that variable set to false while other nodes will have it default to true.
Comment: Thanks, it looks interesting. Puppet is obviously going through rapid development and sometimes it's not clear what's the currently supported way.


Problema ao exibir array

Question: Estou com um problema na lógica para exibir os dados de um array.
É o seguinte:
Tenho uma função, que me retorna o resultado de cadastros por UF por dia. Nela passo 2 parâmetros, um array com as datas e um array com os estados.
Montando os parametros para passar para a funçao.
$uf = array('sp','rj');

$d1 = '2015-09-15';
$d2 = '2015-09-17';
$timestamp1 = strtotime( $d1 );
$timestamp2 = strtotime( $d2 );

while ( $timestamp1 <= $timestamp2 ) {
   $data_mod[] = date( 'Y-m-d', $timestamp1 ) . PHP_EOL; // data_mod vira um array com as data entre $d1 e $d2
   $timestamp1 += 86400;
}

Função:
function grafico_cadastro_por_dia($conexao,$uf,$data_mod){
$lista = array();
$qtd_dias = count($data_mod);
$qtd_uf = count($uf);

for($i = 0; $i <= $qtd_uf; $i++) {
if( $uf[$i] ) {  $where[] = " uf = '{$uf[$i]}'"; } //monto o implode para o array de UF
}

for($i = 0; $i <= $qtd_dias; $i++) {
if( $data_mod[$i] ) {  $where2[] = " dataCadastro = '{$data_mod[$i]}'"; } //monto o implode para o array de datas
}

$query = "SELECT dataCadastro,uf,sum(cadastros) FROM tblCadastros where (".implode( ' or ',$where2 ).") AND (".implode( ' or ',$where ).") group by 1,2";
   $sql = mysql_query($query,$conexao);
   while($row = mysql_fetch_assoc($sql)){
   $lista[] = $row;
 }
return $lista;
}

No retorno da função, eu recebo os seguintes dados.
$funcao = grafico_cadastro_por_dia($conexao,$uf,$data_mod);

for($i = 0; $i <= count($funcao); $i++){
  echo  '
';
 print_r($funcao[$i]);
}

Resultado:

Array ( [dataCadastro] => 2015-09-15 [uf] => SP [sum(cadastros)] => 36 )
Array ( [dataCadastro] => 2015-09-15 [uf] => RJ [sum(cadastros)] => 9 )
Array ( [dataCadastro] => 2015-09-16 [uf] => SP [sum(cadastros)] => 19 )
Array ( [dataCadastro] => 2015-09-16 [uf] => RJ [sum(cadastros)] => 8 )
Array ( [dataCadastro] => 2015-09-17 [uf] => SP [sum(cadastros)] => 14 )
Array ( [dataCadastro] => 2015-09-17 [uf] => rj [sum(cadastros)] => 2 )

Como podem ver  , a função retorna 2 vezes a data pois tem mais de um estado para exibir o valor.
Se eu passo 3 estados no array , ele exibiria 3 vezes a mesma data.
Até ai, tudo bem.
O problema começa agora , já que vou colocar esses resultados em um gráfico.
E não estou conseguindo imprimir os resultados na ordem que o gráfico pede.
Teria que exibir nessa ordem:
[$data, $total "uf SP" , $total "uf RJ"]
['2015-09-15', 36 , 9],// 36 é o valor de cadastro de SP no dia 15 e 9 o valor de cadastros de RJ no dia 15
['2015-09-16', 19 , 8],

e assim por diante.
Mas já rascunhei de tudo quanto é forma que consegui imaginar, mas não consegui exibir os dados dessa forma.
Alguém pode me ajudar?
Comment: Henrique, eu re-li umas 3 vezes, me desculpe. Talvez seja o cansaço mas não consegui absorver sua dúvida. Eu entendi referente a estrutura da array mas não entendi como deve ser o output. Por favor entente colocar mais códigos, você apenas disse a estrutura da array mas acredito estar faltando pouco de código, e seja especifico no output que deseja. Bom, me desculpe novamente.
Comment: Tem um problema na lógica mesmo. Acredito que a forma que você está fazendo não é muito indicada, outro detalhe, é que você pode pegar pelo alias: `sum(cadastros) as total_cadastros` : `$row["total_cadastros"]`. Esta saída que você está fazendo, dá pra fazer direto na query.
Comment: Estas datas vem do banco de dados? Ou simplesmente de um array()?
Comment: Como estou testando em local host , estou definindo as datas manualmente , mas quando passar para o servidor receberei elas via POST. @juniorb2ss , então , o resto do código seria minha função que  pega os dados no banco.
Comment: Dando um print_r na funcao , ele retorna assim : Array ( [0] => Array ( [dataCadastro] => 2015-09-15 [uf] => SP [sum(total)] => 36 ) [1] => Array ( [dataCadastro] => 2015-09-15 [uf] => RJ [sum(total)] => 9 ) [2] => Array ( [dataCadastro] => 2015-09-16 [uf] => SP [sum(total)] => 19 ) [3] => Array ( [dataCadastro] => 2015-09-16 [uf] => RJ [sum(total)] => 8 ) [4] => Array ( [dataCadastro] => 2015-09-17 [uf] => SP [sum(total)] => 14 ) [5] => Array ( [dataCadastro] => 2015-09-17 [uf] => rj [sum(total)] => 2 ) ).
Comment: Amigo, tem má formatação desse seu array. Ele esta formatado incorreto, vou tentar postar uma resposta.
Comment: Qual biblioteca para gerar gráfico você está tentando usar? Tem algum exemplo online? Para facilitar a leitura, você poderia trabalhar com uma matriz aninhada por interesse, EX: ['2015-09-15' => ['SP' => 10, 'RJ' => 15], '2015-09-16' => ['SP' => 3, 'RJ' => 11]]
Comment: Boa tarde, uso o Google charts. Estou montando um grafico de linhas, para saber os dias que teve mais cadastros no site.
Answer: Você esta percorrendo muitos arrays para no final montar uma query para pegar os valores por data dos cadastros feitos naquele UF, sendo que próprio SQL da ferramentas para isso.
Temos a função Between que é usada para comparações.
Neste exemplo irei mostrar como pegar todos os cadastros feitos entre um período de data e agrupar pela data do cadastro e uf.
Assim poderei retornar todos os cadastros feitos em x UF para Y dia, montando array que você precisa.
Nesta query irei utilizar o DATE_FORMAT do MySQL, pois vou partir do principio que seu campo dataCadastro tenha o horário do cadastro, se eu não formatar esta data irei agrupar os cadastros por dia/mês/ano hora:minuto:segundo que não é o que você precisa, você precisa apenas por dia/mês/ano.
Basta executar esta query invés desse código todo:
SELECT
DATE_FORMAT(`dataCadastro`, '%Y-%m-%d') AS `dataCadastro`,
uf,
SUM(cadastros) AS 'Cadastros'
FROM
  tblCadastros
WHERE
  dataCadastro BETWEEN 2015 - 09 - 15 AND 2015 - 09 - 17
GROUP BY DATE_FORMAT(`dataCadastro`, '%Y-%m-%d'), `uf`

Execute apenas esta query invés deste código todo que você fez. O resultado dessa você poderá montar um array dinâmico mais ou menos assim:
Array
(
    [2015-09-15] => Array
    (
        [SP] => 36
        [RJ] => 9
    )
)

Veja no ideone
Como ficaria final:
$query = 'SELECT DATE_FORMAT(`dataCadastro`, "%Y%m%d") as `dataCadastro`, uf, sum(cadastros) as Cadastros FROM tblCadastros where dataCadastro BETWEEN '. $d1 .' and '. $d2 .' GROUP BY `dataCadastro`, `uf`';
$sql = mysql_query($query,$conexao);

while($row = mysql_fetch_assoc($sql))
{
    $lista[$row['dataCadastro']] = [
        $row['uf'] => $row['Cadastros']
    ];
}

Dúvidas? Viu como reduziu todo esse seu código?
Dessa forma você tem um array montado com as informações que deseja para montar o gráfico, ai é só percorrer ele.
Edit
$lista = array();

while($row = mysql_fetch_assoc($sql))
{
   if(!isset($lista[$row['dataCadastro']]))
   {
    $lista[$row['dataCadastro']] = array(
        $row['uf'] => $row['Cadastros']
    );
   }
   else
   {
      $lista[$row['dataCadastro']] += array(
        $row['uf'] => $row['Cadastros']
      );
   }
}

Veja em funcionamento
Comment: Henrique, isso é erro de sintaxe. É só corrigir amigo. Qual versão do seu PHP? Não é suportado abrir array assim `[]` onde tiver você terá que trocar por `array()`
Comment: Obrigado pelo ajuda . Mas , deu o seguinte erro : Parse error: syntax error, unexpected '[' in F:\PROGRAMAS INSTALADOS\Ampps\www\testes\teste_loop\loop_data_uf\index.php on line 63. Conteudo da linha 63 :  $lista[$row['dataCadastro']] = [
        $row['uf'] => $row['Cadastros']
    ];  Desde ja , grato
Comment: junior , mais uma vez obrigado pela ajuda.Esta na versao 5.3 se nao me engano .Tentei dessa forma : $lista = array("data_cadastro" => $row['dataCadastro'],"dados" => array( "uf" => $row['uf'],"cadastros" => $row['cadastros'])); . Mas ao dar um print_r no retorno , ele só mostrou uma linha.
Comment: Pois você esta sobrescrevendo o array, Henrique. Veja minha resposta atualizada.
Comment: @HenriqueFelix veja a edição da resposta.
Comment: quase . Deu essa saida : Array ( [2015-09-15] => Array ( [SP] => 36 ) [2015-09-16] => Array ( [SP] => 19 ) [2015-09-17] => Array ( [SP] => 14 ) ) . No caso , não pegou o outro estado .
Comment: Henrique, por favor analise o código. Também não podemos dar de mão beijada. Por favor sinalize a resposta como correta e positive, com pequenos ajustes você faz o array que precisa.
Comment: Junior , deu certo. Não tinha visto seu ultimo Edit. Retorno: Array ( [2015-09-15] => Array ( [RJ] => 9 [SP] => 36 ). Muito obrigado pela paciencia e pela ajuda.
Comment: O importante não é só funcionar, é estudar a query, olha a diferença entre executar uma query do que 30 linhas de códigos que era o seu código, estude as funções utilizada, @HenriqueFelix
Comment: Eu reparei. O que pesou foi na hora de comparar a data , não sei o porque fiz daquele jeito, sendo que o betwen resolveria ,tornando o cod mais correto.Agora, vou dar uma estuda mais profunda nos array, pois me perdi um pouco de como fez. Mais uma vez , grato.

Problema ao exibir array


Remove exceeding more than n consecutive br-tags from running text

Question: I have some rich text input and want to allow only a maximum of two consecutive
 tags.
I found a partial good answer to my problem: XSLT: remove duplicate br-tags from running text
However I need to allow up to two consecutive
 tags. A more general question would be: how to allow a maximum of n consecutive
 tags?
Example input:

        Lorem ipsum...

        ..dolor sit

Needed output:

        Lorem ipsum...

        ..dolor sit

Example input 2:

        Lorem ipsum...

        lorem ...

        ..dolor sit

Needed output:

        Lorem ipsum...

        lorem ...

        ..dolor sit

Comment: I will add that the library I use for XSLT, Nokogiri, seems to support only XSLT 1.0 and XPath 1.0
Answer: try this one
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="br">
        <xsl:if test="not(preceding-sibling::node()
            [not(self::text() and normalize-space(.) = '')][2]
            [self::br])">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>

Comment: This doesn't work if there's text or other elements between the ``'s.
Comment: @Kimmy The OP expressly asks about "consecutive" `br` elements which I think means _adjacent_ consecutive elements. Elements between `br` elements are not an issue in my opinion.
Comment: I agree they shouldn't be an issue, but they *are* in your xsl. Try it!
Comment: The problem at hand is removing consecutive br elements. If there is text in between, there can be any number of br elements in my case. This version removes too many br elements
Answer: First, make sure you have XHTML, so
 instead of
! And then:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output encoding="UTF-8" method="xml" version="1.0" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="processing-instruction()">
        <xsl:copy/>
    </xsl:template>

    <xsl:template match="br">
        <xsl:if test="not(preceding-sibling::node()[local-name() or normalize-space()][1][local-name()='br']) or not(preceding-sibling::node()[local-name() or normalize-space()][2][local-name()='br'])">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Depending on how many
's following each other directly you want to allow, you can add more of the same, e.g. for the third one: or not(preceding-sibling::node()[local-name() or normalize-space()][3][local-name()='br']), 4th one or not(preceding-sibling::node()[local-name() or normalize-space()][4][local-name()='br']) etc.
Comment: No, Joel's solution doesn't work. In your input xml sample, try adding some text or any xml element between the first and the second ``, then you will see that this does not perform your expected behavior. So **if** you want a shorter solution that works, then accept GomX's approach!
Answer: Use the following code in your stylesheet:

   <xsl:variable name="brThreshold" select="2"/>

   <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="br[count(preceding-sibling::node()[not(self::text() and normalize-space(.) = '')][position() <= $brThreshold][self::br]) = $brThreshold]">

    </xsl:template>

Comment: Good one! Although it seems to require xslt 2.0!?
Comment: Looks neat. However, I was not able to apply this one. I had an error in the library I use. I use [http://www.nokogiri.org/ ] and it failed to compile the predicate. It seems it only supports XSLT 1.0 and XPath 1.0
Comment: I think it's because of the global variable `brThreshold`. If you leave it away and use `2`instead of `$brThreshold`, it should also work in xslt 1.0!


Why does omniauth-oauth2 strategy append /oauth/authorize to my site url?

Question: I am using the sample provided by omniauth-oauth2 to create a custom Oauth2 provider. This is fairly easy and I use option :client_options, {site: "https://sub.dom.is?id=myId"} for my issuer but when the redirection happens I get a 404 and when I check the URL I can see that is is actually https://sub.dom.is/oauth/authorize?id=myID and of course this is wrong since there has been added oauth/authorize to the URL..
does anyone know why? or who adds it and then how can I get rid of it?
Answer: I found the answer on anti-pattern.com ... when I provide only the site the omniauth-oauth2 will add oauth/authorize to it as a default. However, if I provided authorize_url like so option :client_options,{site:"https://www.dom.is",authorize_url:"https://sub.dom.is?id=myID"} the autorize_url is used when authorising the user.


How do you run a command prior to including a component Makefile?

Question: I am trying to create a subdirectory in my project (let's call it $PROJECT/child) that needs to pull in a Makefile (let's call it ../Makefile.inc) from its parent, $PROJECT/Makefile.inc. Later I want to copy $PROJECT/child somewhere else so it can run independently of $PROJECT.
There is a common Makefile that needs to be included in both projects and shipped when the subdirectory is copied, and I want it to be included in both cases. So I thought I would link it in during the child build, if it isn't found. (I don't want to just include ../Makefile.inc, because this will disappear when I copy the project, and I don't want the calling build system to be responsible for putting the Makefile.inc in place.)
With those constraints, here's a horrible hack that I've come up with to do this, within $PROJECT/child/Makefile:
HACK = $(shell test -f Makefile.inc || ln -f  ../Makefile.inc .)
include $(HACK)Makefile.inc

Notice the extra special duct tape on that second command. I have to actually include $(HACK) even though it's going to end up empty, so that the $(shell ...) will be evaluated. ;-)
Is there a cleaner way to make this happen?
Answer: Give a rule to build Makefile.inc. (make will complain that Makefile.inc doesn't exist when it parses the include line, but it will go on parsing the main makefile, apply any rule to build included files, and go back and re-parse the main makefile with the included files.)
include Makefile.inc
Makefile.inc:
        ln ../Makefile.inc $@

Comment: Beautiful! Thanks. I added a comment to make it clear to the casual observer what was happening.


Impact of data dimensionality on computation complexity of SVM?

Question: What is the impact of data dimensionality on computation complexity of SVM? I found on the literature that the complexity of SVM is $O(N^3)$, where $N$ is the number of training examples. If the number of dimension (e.g., $D$) does not impact the training time why it s better to reduce the dimensionality for training high-dimension dataset? Is it just to avoid overfitting?
BTW, I m using SVDD (support vector data description) from RRTools.
Answer: The O($N^3$) training complexity involves $n^2$ dot products and $n^3$ inverse of kernel matrix (A.Bordes et al Fast Kernel Classifiers with Online and Active Learning). However, it is also shown that the runtime of linear SVM optimization may decrease as the training size $N$ increases (Shai Shalev-Shwartz et al. SVM Optimization: Inverse Dependence on Training Set Size).
Mostly people view the training complexity independent of feature number, yet in SVM with RBF kernel, the training complexity is regarded as $O(dN^2)$ or $O(dN^3)$ ,where $d$ is the feature number (dimensionality)(Sreekanth Vempati et al.Generalized RBF feature maps for Efficient Detection).
While reducing the feature number might help in reducing the training complexity, the aim of feature selection is mainly to remove the additional features that may not help separate the classes in the feature space (sometimes may even at the risk of learning the noise in the data) (J. Weston et al Feature Selection for SVMs).
Comment: @lennon310 Almost all kernels evaluations are dependent on $d$ since they typically involve an inner product. This is true for all common kernels (linear, polynomial, sigmoid, RBF).
Comment: Thanks for your answer. So is that correct to say that  RBF is the only kernel that its complexity is effected by the number of features (d)?
Comment: To my knowledge it may be the only kernel that is d dependent


How do I view the maintenance page without putting the site in maintenance mode?

Question: I've just been asked by the stakeholder of a site I'm working on how he can view the maintenance page of his site so he can test links on it without putting the site in maintenance mode.
I'm going to suggest that we do this in a lower environment, since the info is the same but is there any way to do this?
Answer: By default there is no route to access the maintenance page via url. You can create a menu item and the corresponding page callback in your module :
// Access maintenance page regardless of the maintenance mode.
$items['maintenance'] = array(
  'title' => 'Maintenance',
  'page callback' => 'yourmodule_maintenance_page',
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK
);

yourmodule_maintenance_page () {
  // Just use the internal status code to make Drupal load the apropriate theme and template.
  return MENU_SITE_OFFLINE;
}

And that's all, go to /maintenance to see the page.
You may also want to override the 'maintenance_page' theme, have a look at :

the base preprocess function in includes/theme.maintenance.inc
base template file in modules\system\maintenance-page.tpl.php
Answer: Another way to do it is to add the following code to your settings.php file
if (isset($_GET['maintenance'])) {
   $conf['maintenance_mode'] = TRUE;
}

Then go-to 'your_domain/?maintenance=1' and you'll be in maintenance mode.
Comment: This works nicely. But IMHO it should only be used in development environments not in production.


Singing - effect of vowels on tuning and tonality

Question: I am a multi-instrumentalist and singer-songwriter. Singing for me has been a long road but recently I found out something very interesting.
I have a certain song that I am very fond of but I have struggled to make a recording that I am satisfied with. Basically it always sound a bit flat at certain points. I've tried bringing it down a tone (a bit of a pain as it has a guitar part that more or less needs open strings, so I tuned down to D) but really it wasn't much better.
I've done quite a bit of work on my voice and I know that I am not always flat, and the reason for this really eluded me. This week I had a bit of an epiphany.
I bought the whole thing UP a semitone, and voila! it sounds much better I think.
I worked on this with my singing teacher and we figured out in the end that it seemed to be about the vowel sounds that come out on certain notes that sit right in the middle of my vocal break. There are certain notes that have open vowels "ah" or "oh" in a descending line. By doing a lot of practice on vowel sounds through the break I found that those notes need to be a bit more in "head" voice but the ones before them more in "chest" (even though they are higher). It's really not comfortable to do that in the middle of a line that goes down, and the result is that the lower notes tend to come out a bit flat.
This really explains a lot to me. It also explains to me why the key is of such importance to a singer.
Can a singer eventually hope to attain true "12 key" technique as most instrumentalists can (of course some keys will always be a bit easier, but a competent musician could play a simple melody perfectly well in any key), or will this kind of thing always be a concern for a singer?
Comment: Given that a lot of instruments have a range of more than three octaves (guitars, trumpets, clarinets all more than that), but singers might have a comfortable range of less than three octaves, and songs generally don't have much more than an octave and a half, then yes, it should be possible to 'sing in all twelve keys'.
Comment: the range doesn't really have much bearing on this. The point is really about why transposing a certain phrase (and the words have a strong effect) can be a big deal for singers - something that it is often hard to explain to instrumentalists ... :-)
Comment: Totally agree. Always had problems singing certain words or sounds at the limit of my range, but not looked into the problem 'scientifically'. There are some songs I can't/ won't sing the harmony for as they're just on that edge. And it's particular words on particular notes rather than the actual notes with other words, as you say. So unless the co-singers change the key, that's how it is.
Comment: try singing through the vowels ( ee - eh - ah - oh - ooh ) on each semitone, especially through the break, and after a bit you start to realise what is going on. It's a kind of non-linear problem unlike other instruments.
Comment: What dmb said sounds like good advice. A good singer will know how to cross all the break-points in their voice.
Comment: @PeterJ - maybe not all the breakpoints. I've been singing for many decades, and there are some occasions where the only solution is to change key - or change harmony.
Comment: @Tim - Fair enough. My comment was too sweeping. .  .
Comment: @Tim That's where this is a bit of an open question for me. I guess it depends to some extent on style. It seems (to me) that the goal of "bel canto" study is to smooth out all these irregularities and make the voice as much an "instrument" as possible. But I wonder to what extent that is doable. In other genres of course, the natural irregularities of the voice are used as a stylistic feature. It's an interesting topic.
Answer: The keyword you are looking for is "vowel modification".  It is most important to soprano singers since their upper range has the most serious conflicts of the fundamental pitch with the individual vowel formants and so vowels need to be colored for a clear pitch and vowel combination, as far as possible.  While vowel modification is most important for soprano, other voice types may need a bit of adaption in certain ranges as well.
Comment: It's like you say! And that's why every singer and every choir leader in the warming ups for all voices are practicing a simple melody as i.e. *sofamiredo* on all vowels, starting by u, o, a, e, i and other exercises.
Comment: Do you mean that the sounds are made to come out differently? Examples, please.
Comment: yes, I came across this topic in my research. However I didn't really find a clear description of *how* to modify the vowels - perhaps that is something only discovered through practice. This is a pretty good explanation : http://www.singwise.com/cgi-bin/main.pl?section=articles&doc=VowelsFormantsAndModifications&page=3
Answer:
Can a singer eventually hope to attain true "12 key" technique as most instrumentalists can (of course some keys will always be a bit easier...)

I don't think this is the question of the keys but of the pitch and the range of your voice.
You'll have to train the vowels in all pitches and ranges (what you mean by "keys" and have to find out the best resonances with your teacher.
There are lots of exercises that you can find in books, in the net and together with your voice trainer.
Yes, you can hope.
http://www.singwise.com/cgi-bin/main.pl?section=articles&doc=VowelsFormantsAndModifications&page=3
The most simple exercise I used with choirs and singing classes:
singing the whole major scale down (or from the fifth to the root) always going a halftone up on the vowels: U (oo), O (oh), A (ah) than uo,

u
o
a
uo
uoa
i
ie
iea

also adding a consonant at the beginning like m, n, v, ng, will help to find and keep the best resonances.


Swift expression type is ambigious without more context

Question: Please consider following code:
 func checkIfNewVersionAvailable() -> (isNewAvailable : Bool, error : String?){

        DispatchQueue.global().async {
            do {
                let update = try self.isUpdateAvailable()
                DispatchQueue.main.async {
                    return (true, nil)
                }
            } catch {
                print(error)
                return (false, error)
            }
        }
    }

On line :  return (true, nil) compiler throw me an error : Expression type '(_, _)' is ambiguous without more context
What i'm doing wrong?
Comment: You cannot use the result of an asynchronous task as a return value of a function. That's impossible. And the parameter labels are useless in Swift 3+
Comment: You cannot *return on the main queue*, that does not make any sense, how would a call of this method logically happen?
Comment: @luk2302 thank you
Comment: @vadian thanks. What you mean - parameter labels are useless in Swift 3? You mean in tuples?
Comment: I mean omit the parameter labels in closures and return values like `-> (Bool, String?)` or `completion : (Bool, String?) -> ()`
Comment: @vadian ok, clear now for me, thanks :)
Answer: What you need is
func checkIfNewVersionAvailable(@escaping completion : ((isNewAvailable : Bool, error : String?) -> ())) {

        DispatchQueue.global().async {
            do {
                let update = try self.isUpdateAvailable()
                DispatchQueue.main.async {
                    completion(true,nil)
                }
            } catch {
                print(error)
                completion(false,error)
            }
        }
    }

Now issue :
DispatchQueue.main.async does not expects any return value and you are trying to return a tuple of type (bool,String) hence its mentioning the issue

thanks but i dont want to add closure, i want to return tuple.

You are executing  self.isUpdateAvailable asynchronously on a global queue with default priority. So the call to self.isUpdateAvailable is not synchronous where as your return statements are synchronous ones hence even if you manage to write return statement somehow you won't have proper values while returning because self.isUpdateAvailable might still be running or waiting to run when your return gets executed.
Comment: thanks but i dont want to add closure, i want to return tuple.
Comment: @EvgeniyKleban yes, you *want* / *have to* use a closure.


In (python) plotly how to start (0,0) after some padding as below

Question: How can we have (0,0) as below in plotly (python) in scatterplot using go.Scattergl().
How to have some padding before (0,0)?
Answer: You have to specify that the lower bound of the range of both axes is 0.
<code>import plotly.graph_objects as go
import numpy as np

x = np.array([1, 2, 3, 4, 5])
fig = go.Figure(data=go.Scatter(x=x, y=x**2))

fig.update_layout(yaxis_range=[0,4])
fig.update_layout(xaxis_range=[0,4])

fig.show()

</code>
Comment: Or else some negative value for the lower bound, if the padding should come before (0, 0).


How to upgrade already developed ASP.NET framework 3.5 project to 4.5?

Question: I have developed a web application project in asp.net 3.5 frame work(VS 2012). It's working fine in server side. Now I would like to upgrade its version to 4.5 to use the latest updates.  How can I upgrade it?  My friend told that, if I change the version I will lose my web.config file.
How can I upgrade the version without any side effects?
Comment: @ Patrick Hofman, When I change the version I lost some of my web config file contents
Answer: Just change the version of your project to .NET 4.5. I don't think there is a special migration path needed.
You won't lose your web.config file all of a sudden. You might need to do some migration of settings (just make a safe copy and see what you need to migrate), but they would most likely be quite easy and only applicable if you use specific parts of the framework for example or a different pipeline mode (but that is just specific to IIS, not your ASP.NET application).
Comment: Unfortunately there are [breaking changes](http://www.asp.net/whitepapers/aspnet4/breaking-changes).
Answer: There is a MSDN Article How to: Upgrade an ASP.NET Web Application to ASP.NET 4 which you can follow.
I think the magic word is "Visual Studio Conversion Wizard".


Does Simple Injector have a way to Register with an instance factory in combination with a TypeFactoryContext?

Question: I'm working on a legacy code base that seriously needs refactoring towards SOLID principles. We are adding the Simple Injector dependency injection container to the mix as a first step.
For one of the registrations I need something very much like the RegisterConditional example for Log4Net, i.e:
container.RegisterConditional(
    typeof(ILogger),
    c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
    Lifestyle.Singleton,
    c => true);

Difference is that I want to inject an instance returned by a factory method that takes the c.Consumer.ImplementationType as input:
container.Register???(
    typeof(ILogger),
    c => LoggerProvider.GetLogger(c.Consumer.ImplementationType),
    Lifestyle.Transient);

Can this be accomplished in Simple Injector?
I have read the answer to a similar question, but that does not suffice. The ImplementationType needs to be handed to the instance factory.
For the time being, I will implement a Logger<TParent> and use that in the RegisterConditional call:
public class Logger<TParent> : ILogger
{
    private readonly ILogger _decoratedLogger;

    public Logger()
    {
        _decoratedLogger = Logger.GetLogger(typeof(TParent));
    }
}

Comment: "We are adding the Simple Injector dependency injection container to the mix as a first step." You might want to start using a DI Container later on. See: https://stackoverflow.com/a/32033648/264697
Comment: Good point. We did consider going for Pure DI for a brief moment. However, the code base is used for multiple applications. Each requiring a composition root that would quickly impair maintainability.
Answer:
Can this be accomplished in Simple Injector?

Yes and no.

No, this isn't supported using the RegisterConditional and that's because Simple Injector tries to push you towards registering types, so it can verify and diagnose your object graph as much as possible. Preferred way is to create a proxy class much as is explained here. It basically explains your current solution, but has a Logger<T> that inherits from LogImp instead, since that leads to a simpler solution.
Yes, this is possible, but you'll have to revert to using a custom IDependencyInjectionBehavior as explained here (the example is for Serilog, but can be easily rewritten to log4net). The first method however is preferred if possible.
Comment: "but has a Logger that inherits from LogImp instead".
Ended up doing exactly that ;-)


Using word embeddings in text classifier

Question: I have a bunch of sentences that I want to do binary classification with SVM.
My sentences have varying lengths form 4 to 34. If I use word embeddings such as word2vec or skip gram to convert my words into word vectors, I would end up with matrices of very different sizes due to differences in sentence length.
What is the best way to get around that? I know that if I were to use a neural network classifier, I would just pad with zeroes and let the neural network figure out the features. But If I were to use a classical machine learning classification method, what is the best way to deal with sentences of varying lengths?
Answer: Have you checked doc2vec? Doc2vec returns a fixed representation for each document (sentence in your case), regardless of its length. Here is the original paper. There is also a Python implementation from the gensim package.
Another usual approach for text classification is to calculate the tf-idf matrix and use it as input to a classifier, in which case the columns of the matrix are the features. The tf-idf matrix represents the sentences in its rows and the unique terms (words) of all your sentences in its columns. Each element in the matrix is the tf-idf value of this sentence-term. You can find more information in the wiki page. scikit-learn has an implementation of tf-idf here.
Comment: Thank you for your answer! I have already tried Doc2Vec but the accuracy I get is not satisfactory. This is why I am trying other word embedding solutions.

tf.idf would be a count based approach. I want to try embeddings
Answer: For inputs of varying lengths I suggest to use an encoder/decoder architecture, such as an LSTM model. You can use pretrained encoders for example from the flair library https://github.com/zalandoresearch/flair .
Essentially you would be giving the model a sequence of words as input and it will generate a context vector (essentially the hidden layer of the LSTM). you can then use the context vector as input to a normal fully connected hidden layer and a softmax to do your classification. That's the theoretical setup. Whether that works or not remains to be explored :)


flutter js-interop streamcontroller not updating value from listprovider

Question: I want to send a UInt8list(3) from flutter to the js-side to use the data with WebMidi.
Starting from the element_embedding example i added some riverpod providers for the data.
    final listProvider3 = StateProvider<Uint8List>((_) {
           return Uint8List.fromList([144, 68, 70]); });  //Npte-on event

I have a table of 8*16 buttons and a listprovider for their states:
final listProvider1 = StateProvider<List<int>>((_) {
  return List.generate(8 * 16, (_) => 0);
});

another listprovider to hold the current stepnumber for each row of buttons:
 final steplistProvider = StateProvider<List<int>>((_) {
  return List.generate(8, (_) => 0);

I use a countdowntimer to update the steplistprovider every 250ms.
In the build method of _MyAppState I listen to steplistprovider:
    Widget build(BuildContext context) {
    ref.listen(steplistProvider, (previous, next) {
      final steps = ref.read(steplistProvider);
      final list1 = ref.read(listProvider1);
      final Uint8List listBytes = ref.read(listProvider3);

       for (int i = 0; i < 8; i++) {
        if (list1[steps[i] + i * 16] > 0) {  //Button selected?

          listBytes[0] = 144;
          listBytes[1] = 30 + i;  //Here i increment the value
          listBytes[2] = 70;
          ref.read(listProvider3.notifier).state = listBytes;

          sendToJs();  //call function in loop
          }}}

 @js.JSExport()
  void sendToJs()
{
         setState(() {

      final listBytes = ref.read(listProvider3);
      byteList = listBytes;
      _streamController.add(null);
    }
  }

From the loop I call sendToJs and add my bytelist to a _streamcontroller.
on the Js-side there is a callback when the streamcontroller emits:
demo-js-interop.js
  let updateState = function () {
      valueField.value = appState.mybuffer;  //the Uint8list from flutter
      myFunction(appState.mybuffer);
     };

    // Register a callback to update the HTML field from Flutter.
    appState.addHandler(updateState);

myFunction(appState.mybuffer); is a js-function where data is sent via WebMidi
In class _MyAppState I have:
var byteList = Uint8List(3);
@js.JSExport()
  void addHandler(void Function() handler) {
    _streamController.stream.listen((event) {
      handler();
    });
  }

  @js.JSExport()
  Uint8List get mybuffer => byteList;

Expected behaviour: Every 250 ms the steplistprovider is updated and in a loop in ref.listen(steplistprovider) i call the sendToJs function. In my Matrix of buttons if i select two buttons in the same column(step) i want to send out two diffrent Uint8List.
But with the Code above it sends out the same value twice. I think it's the streamcontroller sending the latest value twice.
If button 1 and button 8 are selected I would expect listBytes[1] to be  30 and 37 but it sends 37 two times.
It does send two events but with the same (higher) value.
the bug must be in the loop and the way _streamcontroller is used.
This really blocks me from continuing with my app.
Answer: I had to set sync field in streamcontroller.
final _streamController = StreamController<void>.broadcast(sync: true);


ASP.Net Gridview -> How to show collection of data inside one row of the GrdiView?

Question: <code>     I have a scenario where I will be showing a Customer data in a GridView. I have a Dictionary collection like this IDictionary<Customer, IList<CustomerOrder>>.
</code>
First Question Can I bind this dictionary to the ASP.Net GridView?
Now next question, I want to show following kind of UI i.e. Show multiple CustomerOrders in one row of Customer.
FName  LastName OrderNumber MarkOrderCompleted(RadioButton)
ABC    DEF      123          Radio Buttons Yes No
                345          Radio Buttons Yes No
                678          Radio Buttons Yes No
GHI    JKL      213          Radio Buttons Yes No
                546          Radio Buttons Yes No
                768          Radio Buttons Yes No
FName and LastName would be populated from Customer object inside the Dictionary and OrderNumber and MarkOrderCompleted would be populated from CustomerOrders.
Below all thre is a submit button, which saves the radion buton status values to the database  against the Order.
Immediate help would be really appreciated. Thanks in advance...
Answer: Do you have to have both Customer and CustomerOrder in the same Dictionary? I would have used a nested grid with two different collections. The nested grid uses the "DataKeyNames" attribute of the first grid as parameter. Example:
The Grid:
<code>   <asp:GridView ID="CustomerGrid" runat="server" EnableModelValidation="True"
        onrowdatabound="CustomerGrid_RowDataBound" DataKeyNames="CustomerId">
        <Columns>
            <asp:TemplateField HeaderText="Orders">
                <ItemTemplate>
                    <asp:GridView ID="OrderGrid" runat="server">
                    </asp:GridView>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</code>
Code behind:
<code>    List<Customer> CustomerList = new List<Customer>();
    List<Orders> Orders = new List<Orders>();

    protected void Page_Load(object sender, EventArgs e)
    {
        // Add some customers
        CustomerList.Add(new Customer() { CustomerId = 1, CompanyName = "TestCompany", FirstName = "John", LastName = "West" });
        CustomerList.Add(new Customer() { CustomerId = 2, CompanyName = "AnotherCompany", FirstName = "Alan", LastName = "East" });

        // Add some orders
        Orders.Add(new Orders() { CustomerId = 1, OrderId = 1, OrderDate = DateTime.Now, Sum = 300 });
        Orders.Add(new Orders() { CustomerId = 1, OrderId = 2, OrderDate = DateTime.Now, Sum = 600 });
        Orders.Add(new Orders() { CustomerId = 2, OrderId = 3, OrderDate = DateTime.Now, Sum = 2000 });
        Orders.Add(new Orders() { CustomerId = 2, OrderId = 4, OrderDate = DateTime.Now, Sum = 100 });

        // Bind customerlist to grid
        CustomerGrid.DataSource = CustomerList;
        CustomerGrid.DataBind();
    }

    protected void CustomerGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Get customer id for row
            int customerId = (int)CustomerGrid.DataKeys[e.Row.RowIndex].Value;

            // Get the nested grid control
            GridView OrderGrid = e.Row.FindControl("OrderGrid") as GridView;

            // Get orders for customer
            OrderGrid.DataSource = Orders.Where(o => o.CustomerId == customerId);
            OrderGrid.DataBind();
        }
    }
</code>
Comment: One thing i some one one can help. What if i have more than one columns in the innerGridView and the same has to be matched to the HeaderText of the parent GridView. How can this be achieved?
Comment: I have some problems understanding what you want to achieve. Could you give a practical example?
Comment: i got the solution that is for header column separate style needs to be written.


Delete all extended properties from a mailbox using EWS

Question: we are connecting to office 365 mailbox using EWS and creating extended properties on outgoing emails, and we have reached the limit on max number of extended properties can be created. We create the property while sending an email and use it after we send it. But we don't store the property Ids.
Is there an option to delete all or some of the properties without having the property id?
Or, can we get a list of properties or IDs of the properties?
Thanks in advance.
Answer: No you can't do that with EWS or MAPI,

we are connecting to office 365 mailbox using EWS and creating extended properties on outgoing emails, and we have reached the limit on max number of extended properties can be created.

You shouldn't get into this situation in the first place if you use Extended properties correctly. Eg your app shouldn't be creating random new extended properties, you should just use one property and then in the Value for that property store a Json string with the key/value combination you need. In that way you will never get to the point of named property exhaustion because you are only using one property that can have an infinite number of Key/Value pairs for whatever application you want.
Comment: This is Office365 and we are trying to talk to them. By this time, I was able to read the extended property of the emails from the Sent Items in Outlook using Outlook Spy. We are using that ID for now. Thanks for you help!
Comment: Hi Glen, you are absolutely right. We should not have created new properties each time, instead we should use the same ID for each of the emails. But, we have erroneously made this mess and fixed our code. But, the problem is we need to create one new property and we cannot because it already reached the max limit. We have also tried to read the item.extendedproperties of the sent emails but we don't see any property in the list. We could use one of the existing ID. Any suggestions?
Comment: If this is an onPrem server then you need to move the Mailbox to another database and use the DoNotPreserveMailboxSignature switch which will reset the Named properties https://blogs.technet.microsoft.com/exchange/2011/01/24/obviating-outlook-client-restarts-after-mailbox-moves/ . If its Office365 you need to talk to support as they will be only people that can resolve the issue for you.
Answer: This doc seems to suggest that deleting extended properties is possible, provided you have the right information to construct an ExtendedPropertyDefinition.
Comment: The only problem here is that I don't have the IDs of the properties and for that reason I cannot construct the ExtendedPropertyDefinition. Thanks, Richard.
Answer: I was able to read the extended property of the emails from the Sent Items in Outlook using Outlook Spy. We are using that ID for now. This is not an option to delete the properties from Office 365. But it gave me the ID of an existing property that we can use for the future emails.


Internet Sharing via router

Question: Question:
How to setup Internet Sharing among two computers (one Mac 10.5.6, one Ubuntu 9.10) via a router?
Situation:
The Mac is using AirPort (wireless interface) to connect to router as 192.168.1.101.
The Ubuntu is using an ethernet cable to connect to router as 192.168.1.104.
Visual:
Mac ))))))  Router ======= Ubuntu
Any ideas are greatly appreciated.
Thanks.
Comment: Is the router connected directly to the internet via a cable/DSL modem, or is something else going on?  What make/model is the router?
Answer: I like your visual. So, this is what you need:
<code>Mac )))))) Router ======= Ubuntu
              +
              |
              +---- Modem (ADSL/Cable/etc)---- (INTERNET)
</code>
You will need to configure your router to use the modem for Internet connections and it should do the rest of it automagically. The exact settings would depend on how you get your internet and the settings of your ISP. You will need that information before you configure your router.

Internet Sharing via router


Efficient way to find a T1 in T1[] by T2[] where T2[] is a property on T1?

Question: What is a fast way to find a product by properties like in the given example? I have a list of 3000 products, each of which has a list of 12 property objects as in the example. I need to be able to find products quickly using n number of properties.
public class Test
{
    public class ProductProperty
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public ProductProperty() { }
        public ProductProperty(string name, string value)
        {
            this.Name = name;
            this.Value = value;
        }
    }
    public class Product
    {
        public string ProductName { get; set; }
        public ProductProperty[] Properties { get; set; }
    }

    public static void Main(string[] args)
    {
        List<Product> models = new List<Product>()
        {
            new Product() { ProductName = "Test1", Properties = new ProductProperty[] { new ProductProperty("title", "car"), new ProductProperty("length", "5") } },
            new Product() { ProductName = "Test1", Properties = new ProductProperty[] { new ProductProperty("title", "car"), new ProductProperty("length", "7") } },
            new Product() { ProductName = "Test1", Properties = new ProductProperty[] { new ProductProperty("title", "ship"), new ProductProperty("length", "9") } },
        };

        var findByProps = new ProductProperty[] { new ProductProperty("title", "car"), new ProductProperty("length", "7") };

        // var product = find Product that has title=car and length=7

    }
}

Answer: If you override the Equals method inside ProductProperty:
public override bool Equals(object o) => o is ProductProperty p && p.Name == Name && p.Value== Value;

it's easier to compare ProductProperty  with each other (you could also implement IEquatable). (NB, the syntax above is not supported by older Visual studios, but can easily be rewritten if needed)
Once overridden, any default method can be used such as Contains:
var product = models.FirstOrDefault(m=> findByProps.All(m.Properties.Contains));

Comment: If it is only one time action `FirstOrDefault` will work. If you want to do that several times I suggest to sort your collection and use binary search.
Comment: Yep, it is the same, but without the extra lambda. The `Contains` method of the Properties array instance is passed directly to the `All` (extension) method, so it can be called directly by each iteration inside `All`
Comment: That's interesting! Care to elaborate on "m=> findByProps.All(m.Properties.Contains)"?What is passed as a param into Contains? Each of the elements in findByProps? Is it same as to write "m=> findByProps.All(prop => m.Properties.Contains(prop))"?


How many combinations exist?

Question: How many combinations exist between this range of lowercase hex values: b000000000000000 to bfffffffffffffff?
If it was just 0000000000000000 to ffffffffffffffff, then it would be $16^{16}$,right?
My thought would be $16^{16}-16^{15}$, but I do not know if that is correct?
Comment: No, it is not.  You can just ignore the leading b's.  Consider in decimal how many numbers between 200 and 299.  The leading 2's do not matter.  You also need to define whether you count either or both ends for there to be an answer.
Answer: You are looking for the amount of combinations that exist for a word of $15$ letters with an alphabet of $16$ letters. If we calculate $\left(BFFFFFFFFFFFFFFF\right)_{16} - \left(B000000000000000\right)_{16}$ = $\left(FFFFFFFFFFFFFFF\right)_{16}$ one can see that the leading B wont change the amount of combinations. If we now convert this number into decimal form we get: $\left(FFFFFFFFFFFFFFF\right)_{16} = \left(1\;152\;921\;504\;606\;846\;975\right)_{10}$. This is the maximum number we can display; Including the Zero there has to be $\left(1\;152\;921\;504\;606\;846\;976\right)_{10}$ combinations which is equal to your Base $B = 16$ to the power of the amount of letters $L = 15$:
$$B^L = 16^{15} = \left(1\;152\;921\;504\;606\;846\;976\right)_{10}$$

How many combinations exist?


Do I really play this entire passage with my hands crossed? (Ludwig Schunke, Piano Sonata, Op. 3, Movement 2)

Question: I've listened to Ludwig Schunke's Piano Sonata, Op. 3 before, and my favourite movement is its second movement (a scherzo), so I got the sheet music and tried to play it. It was surprisingly easy and, partially as a result, very fun!
I was perplexed by large swathes of the score implying that I should play them with my hands crossed:

I thankfully get to stop playing with my hands possibly crossed at the start of the last line/system above, but that's 11 straight measures of piano music that might be better played with the right hand playing the lower staff and the left hand playing the upper staff.
The second movement, according to http://ks.petruccimusiclibrary.org/files/imglnks/usimg/3/31/IMSLP187196-PMLP321465-Schuncke_op.03_Klaviersonate.pdf, even sometimes assigns the 16th-note runs to the lower staff instead of the upper staff.
So, am I better off playing this and similar passages with my hands crossed or with my right hand playing the lower staff and my left hand playing the upper staff? My left hand can pull off its 16th-note runs.
Answer: I'd say that provided you can play the semiquavers/16ths in your left hand smoothly, and keep them running smoothly in that 3rd system's 1st bar as you pass them from your left hand to your right, go for it.
There are several moments in piano works, I've found, where the notation suggests cross hands, but you can avoid it by suitably assigning notes to hands.
I wonder sometimes if some pianist/composers deliberately wrote crossed-hands passages to enable the performer to show off. (Scarlatti was one for this is some of his early sonatas.)
Comment: show off! piano artists in the circus, that's it ;)
Answer: The start of the movement has some hand crossings that are explicitly marked with "s" and "d" (sinistra and destra) which are repeated later on.
Looking at the bars after the hand crossing, the each hand continues to play the same note patterns, but uncrossed.
So it is clear enough what the composer intended. If you can produce the same result without crossing hands, that's fine - but it's probably easier to get the intended result with crossed hands than without. Since your left hand is the mirror image of your right, the "built-in" phrasing and dynamics caused by changes in hand position etc will occur in different places using different hands to play the same notes.
Comment: For the matter, in my first playthrough, I actually didn't play any passages with my hands crossed.
Answer: Always play the way that is better, convenient and more comfortable to you. Everything else is chewing gum for the brain or as Rosie says: show off.
btw: Cross crawl is not just nonsense! Look at Mozart playing piano in the movie Amadeus. It is good training to integrate the working of both brain hemispheres:
Practical Guide to Natural Vision Improvemen
Comment: Perhaps I have misunderstood you but I believe that they are written to be played with just one hand.  They are often performed by two handed pianists using just one hand.
Comment: Always?  Some fairly difficult keyboard pieces are written for just one hand and it would be easier to play them using two hands, but you would never consider doing that would you?
Comment: Of course I would. They are not written in purpose to be played with one hand, they have been written for  pianists who had lost one arm in the war. But what I often use to do is play  a one hand reduction of e.g. a two- part invention. This helps me better understanding the counterpoint of this music ...
Comment: @JimM Your example qualifies as an exception imo. Since such pieces were written for pianists who lost an arm in the war, by playing the pieces with one hand only, the two-armed pianist feels, at least in part, the struggle the one-armed pianists had to go through.