text:
Q: Box plots from dataset with metadata in one column and data in another How can I instruct pgfplots to generate a boxplot from a dataset with an identifier in one column (Label in the example below) and the data in another column (Value in the example below)? I would like the plot to be similar to the first plot, but without having to manually create a separate dataset for each value of the Label.
Example data:
\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usepgfplotslibrary{statistics}

\usepackage{pgfplotstable}

\pgfplotstableset{%
    columns/Label/.style={string type},
}
\pgfplotstablenew[%
        create on use/Label/.style={create col/set={A}},
        create on use/Value/.style={create col/expr={rand}},
        columns={Label,Value}
]{10}\Asamples
\pgfplotstablenew[%
        create on use/Label/.style={create col/set={B}},
        create on use/Value/.style={create col/expr={rand}},
        columns={Label,Value}
]{10}\Bsamples
\pgfplotstablenew[%
    create on use/Label/.style={copy column from table={\Asamples}{Label}},
    create on use/Value/.style={copy column from table={\Asamples}{Value}},
    columns={Label,Value}
]{10}\ABsamples
\pgfplotstablevertcat{\ABsamples}{\Bsamples}%

\begin{document}

% Works fine
\begin{tikzpicture}
    \begin{axis}[
        ytick={1,2},
        yticklabels={Group A, Group B},
    ]
        \addplot[boxplot] table[y=Value] \Asamples;
        \addplot[boxplot] table[y=Value] \Bsamples;
    \end{axis}
\end{tikzpicture}

% Does not work as intended
% The plot should be similar to the above
% with one box for A and one for B
\begin{tikzpicture}
    \begin{axis}[
        ytick={1,2},
        yticklabels={Group A, Group B},
    ]
        \addplot[boxplot] table[x=Label,y=Value] \ABsamples;
    \end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Remove old data from S3 based on last modified timestamp I am working on a project dealing with images. It stores all the images in Amazon S3 and do some editing and then store that edited images again in S3 and then use the S3 urls.
Now, there are lot of images (>100000) and I need to query on what images were modified an year back so that I can save on my s3 cost by removing those images.

A: Lifecycle Rules are the S3 Feature that helps you transition objects automatically to either cheaper storage classes or delete them after a certain period of time.
You can create these on the bucket for specific prefixes and then choose an action for the objects that match the prefix. These actions will be applied to the objects x amount of time after they have been created/modified based on your configuration.
Be aware that this happens asynchronously and not immediately, but usually within 48 hours if I recall correctly. Lifecycle rules have the benefit of being free.
Here's some more information:

*

*Managing your storage lifecycle

*Lifecycle configuration elements

A: You can specify lifecycle transitions and delete or move less frequently used objects/images to low cost storage. Please read https://docs.aws.amazon.com/AmazonS3/latest/userguide/lifecycle-transition-general-considerations.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: TemplateSyntaxError during Template rendering Python/Django beginner here - I get this error:

Reverse for 'topic' with arguments '('',)' and keyword arguments '{}'
  not found. 1 pattern(s) tried: ['topics/(?P\d+)/$']

when trying to load my template.
This is my template:
{% extends "learning_logs/base.html" %}

{% block content %}

Topics

{% for topic in topics %}

    {{ topic }}

{% empty %}

No topics for now

{% endfor %}

{% endblock content %}

This is my views.py
from django.shortcuts import render
from .models import Topic

# Create your views here.
def index(request):
    '''Home page for learning log'''
    return render(request, 'learning_logs/index.html')

def topics(request):
    '''Show all topics'''
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    '''Show a single topic and all its entries'''
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

I have been on this a while now, read some previous answers here, but they all had to do with auth/login not working. Also tried removing the '' after the url as some answers suggested but it didnt work. I am using Python Crash Course: A Hands-On, Project-Based Introduction to Programming for my tutorials.
Any help will be appreciated.
Finally, this is my urls.py code
    from django.conf.urls import url
    from . import views
urlpatterns = [
    # Home page
    url(r'^$', views.index, name='index'),
    url(r'^topics/$', views.topics, name='topics'),
    url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic'),

A: According to the error, there was an argument passed into the url tag, but it was empty:

Reverse for 'topic' with arguments '('',)'...

That's because of the topic_id variable, it is not defined. You should use topic.id instead:
{{ topic }}


text:
Q: How Do I Remove Emoji and Special Characters Using Vim? I have a large text document 1Gig+ and I am trying to import the data into a MYSQL database. Now I go through the process and I receive the following Error
OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x91\\xBD T...' for column 'copyright' at row 24")

Now from what I can gather this is an emoji that is present in the values. With the file size being so big I am using VIM to actually open the document for editing, the problem is however that when I search for the above values I can't find them anywhere in the text document.
Am I doing something wrong or is there a better approach?
Thanks

A: you can do it simple with sed
The sample will change your code to :-)
sed 's/\\\\xF0\\\\x9F\\\\x91\\\\xBD/:-)/g' yourfile.txt > newfile.txt

and this will change all 4 Byte Codes
sed 's/\\\\x[0-9A-F][0-9A-F]\\\\x[0-9A-F][0-9A-F]\\\\x[0-9A-F][0-9A-F]\\\\x[0-9A-F][0-9A-F]/:-)/g' x.txt


text:
Q: How can I see the `qsub` command used to submit a job? I have a job running in a remote cluster. Is there a way to see what qsub command was used (the options and so on) to start the job?

A: Do a 'qstat -f [job number]' and look for 'submit_args'.


text:
Q: Flask url_for passing arguments error while extracting returns values from a form So I have implemented this code:
from flask import Flask, render_template,redirect,url_for
from flask.globals import request
from task2_code import predict_num_new_cases as p

app=Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/Task1')
def Task1():
    return render_template('Task 1.html')

@app.route('/Task2', methods=['GET','POST'])
def Task2():
    render_template('Task 2.html')
    if request.method=='POST' or request.method=='GET':
        nvax=request.form.get('nvax')
        po=request.form.get('pop')
        co=request.form.get('c')
        return redirect(url_for('display',novax=nvax,pop=po,country=co))
    else:
        return render_template('Task 2.html')

@app.route('/pdfview1')
def pdffor1():
    return render_template

@app.route('/Task 2/display')
def display(novax,pop,country):
    predicted=p(novax,pop,country)
    return render_template('display.html',predicted)

@app.route('/bibliography')
def bibliography():
    render_template('bibliography.html')

'''def functionultimate(no_cases,population):
    #calculate stuff
    return #a string value that can be concatenated into task 2'''

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

but it raises the following error:
TypeError: display() missing 3 required positional arguments: 'novax', 'pop', and 'country'

My goal is to pass in arguments into the display function such that it invokes another function from task2_code and displays the result in display.html
How else do I pass in arguments for the display function?

A: The parameters are being passed in via the request, so you will have to extract them from the request. Try something like this.
@app.route('/Task 2/display')
def display():
    novax = request.args.get('novax')
    pop = request.args.get('pop')
    country = request.args.get('country')
    predicted=p(novax,pop,country)
    return render_template('display.html',predicted)

How can I pass arguments into redirect(url_for()) of Flask?


text:
Q: aria-expanded does not switch to true on clicking , so dropdown is not working The powerOffn image is a dropdown which will shows sign out on clicking. But the dropdown is not working.
I am using Bootstrap4. The aria-expanded does not switch to true on clicking.
I have tried adding aria-haspopup="true" aria-expanded="false" but does not work.
I also tried adding id and aria-labelledby as suggested in another post. What changes should I make?

          Sign out

    ```


text:
Q: AJAX example not working locally I copied the example from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first and saved it locally to test.html on my computer. Yes I did make an ajax_info.txt file too, but when I click the button nothing happens, and on w3schools works fine. Any ideas?
Here is the copied code:

Let AJAX change this text

<button type="button" onclick="loadXMLDoc()">Change Content</button>

A: Is your machine \ environment setup to serve that text file over HTTP i.e. when you press the button the client - i.e. your browser will do a GET HTTP to a server i.e. you localmachine running a web server (iis/apache etc) or remote box if configured

A: Does your ajax_info.txt file have the contents of:

AJAX is not a new programming language.

AJAX is a technique for creating fast and dynamic web pages.

There is no space in
 and
. I put it in just for formatting purpuses.
Side note: when you learn the fundamentals of ajax, you will find it much easier to work with jQuery's versions of it. Much simpler!!!!


text:
Q: How to get multiple values from multiple select drop down in angular 6? My code is given below,
<select multiple [(ngModel)]="myModelProperty" name="category" (change)="catFilter($event.target.value);hName($event.target.value);" class="form-control">
        <option>Select Cat</option>
        <ng-container *ngFor="let type of cat">
            <ng-container *ngIf="type.Record.Pre!=undefined">
            <ng-container *ngIf="type.Record.prefname">
            <option [value]="type.Record.pre">{{type.Record.prefname}}</option>
            <ng-container *ngFor="let e of cat">
            <ng-container *ngIf="e!=type">
                <ng-container *ngIf="e.Record.Pre == type.Record.Pre">
                <option [value]="type.Record.subcat">   {{ e.Record.subcat }}</option>
                </ng-container>
            </ng-container>
           </ng-container>
           </ng-container>
           </ng-container>
           </ng-container>
    </select>

And in my ts file,
   catFilter(selectedCat:string){
      this.selectedCat = selectedCat;
   }

I want to choose multiple values & get the selected values from the dropdown. Can anybody please tell me how to do this in angular 6? I have followed many links, But they have shown me how to get a value of a single option. But I need to get values of multiple options.

A: First
You wrote a wrong Object key in <option [value]="type.Record.pre">{{type.Record.prefname}}</option>
as you see [value]="type.Record.pre" should be [value]="type.Record.Pre"
Second
[(ngModel)] is a two way data binding that means when you set the default selection from Component's TS File and can get selected values directly from <select></select>
i tired to follow your data model and came with this result
https://stackblitz.com/edit/angular-isquyp?file=src%2Fapp%2Fapp.component.html


text:
Q: How to Change Vector Datasource in QGIS 3.2.0? QGIS 2.18 has a very good function Change Vector Datasource:

In QGIS 3.2.0 there is Update SQL layer but it doesn't work like Change Vector Datasource. When I open it, select and do update, it acts in the way shown below on screenshots.
Please help how to change vector datasource as easy as in 2.18.

A: Update: changeDataSource plugin has been updated for QGIS 3.x.

A: In qgis 2 this functionality was not native but came from a plugin (changeDataSource), it seem this plugin has not been ported to qgis 3. You could try to contact the plugin creator to made this happen (by sponsoring the upgrade or helping with the migration...)
You could also propose for this fonctionality to be added in qgis core (again more likely to happen and/or quicker if you sponsor it or contribute)


text:
Q: Can this Ruby error be caught with NeoVim/ALE/RuboCop/Syntastic? I'm new to Ruby and doing some experimenting with NeoVim/ALE which I'm also new to. I'm coming from Perl using the syntastic plugin and I'm trying to figure out how to best set up NeoVim/ALE/RuboCop. I've never used a delinter before.
My confusion stems from this bit of code:
#!/usr/bin/env ruby

r = Array() # Improper array initialization, should be Array.new()
puts r

When run, I get:
Traceback (most recent call last):
        1: from /Users/me/ruby/workshop/dink.rb:3:in `<main>'
/Users/me/ruby/workshop/dink.rb:3:in `Array': wrong number of arguments (given
0, expected 1) (ArgumentError)

RuboCop didn't catch this error. I turned syntastic on and it didn't catch the error either. I assume because it's a runtime error and not a compile time error like I thought it would be. Running ruby -c on the script yields no errors either. But perhaps I'm wrong and aren't using the syntax checking tools properly. Can someone please confirm that this is indeed a runtime error and that it's impossible to catch before executing the script?
I have a second question as well: Do I need syntastic with Ruby? Does it do anything more that RuboCop doesn't?
Thanks.

A: Both tools are correct, because there is the Array() method defined in Kernel.
That means this is not a syntax but a runtime error because that method expects at least one argument.
From the docs:

Array(arg) → array
Returns arg as an Array.
First tries to call to_ary on arg, then to_a. If arg does not respond to to_ary or to_a, returns an Array of length 1 containing arg.


text:
Q: what is the purpose of protected variable and method in java I am new to Java, could you please tell me -
"what is the purpose of the protected variable and method in Java".
Thanks in advance.
JP.

A: Take a look at the docs
The following table shows the access to members permitted by each modifier.
Access Levels
Modifier    Class  Package  Subclass  World
public      Y      Y        Y         Y
protected   Y      Y        Y         N
no modifier Y      Y        N         N
private     Y      N        N         N

So, protected elements in a Java application will be accessible form subclasses, class itself AND classes in the same package!, knowing this, you should use protected when some methods or attributes of one class needs to be shared around.

*

*If you don't want any leaking of internal state, then declaring all your member variables private is the way to go.

*If you don't really care that subclasses can access internal state, then protected is good enough.


text:
Q: Is it possible to open Facebook share dialog (in Facebook app) from mobile web? We have similar functionality for Twitter -- linking to "twitter://post?message=Hello" will open the Twitter app (if installed). Is there a similar way to invoke in-facebook-app share dialog via "fb://"?
The reason we'd like to use "fb://" over "http://facebook.com?sharer.php?u=" is UX. From their phones, most FB and Twitter users use the native apps (not the mobile web versions) so their apps are logged in and their browsers are not. The "twitter://post" link works beautifully for Twitter, but we can't figure out if something similar is possible with Facebook (we tried most of what's on http://wiki.akosma.com/IPhone_URL_Schemes#Facebook but no dice. Even the actual share button invokes the fb web version, not the app). Suggestions?
Thanks.


text:
Q: Windows 8.1, XAML binding listview but not showing the first item Below is my code
    <ListView ScrollViewer.VerticalScrollMode="Disabled" ScrollViewer.VerticalScrollBarVisibility="Hidden" HorizontalAlignment="Stretch" VerticalContentAlignment="Stretch" VerticalAlignment="Stretch" SelectionMode="None" Grid.Row="3" Grid.ColumnSpan="3" CanReorderItems="False" CanDragItems="False" IsRightTapEnabled="False" IsItemClickEnabled="True" BorderBrush="White" Background="White" ItemClick="lvGroupInfoCVS_ItemClick"  RequestedTheme="Light" FontFamily="Helvetica" x:Name="lvGroupInfoCVS" ItemsSource="{Binding Source={StaticResource MyCollection}}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Width="{Binding ElementName=lvGroupInfoCVS, Path=ActualWidth}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4*"/>
                            <ColumnDefinition Width="1*"/>
                            <ColumnDefinition  Width="1*"/>
                        </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" FontFamily="Helvetica" Grid.Column="0" Text="{Binding Name}" Foreground="DarkGray" FontSize="23" HorizontalAlignment="Left"/>
                    <TextBlock Grid.Row="0"  FontFamily="Helvetica" Grid.Column="1" Text="{Binding EventDate}" Foreground="DarkGray" FontSize="23" HorizontalAlignment="Center"/>
                    <TextBlock Grid.Column="2" FontFamily="Helvetica" Grid.Row="0"  Text="{Binding StartTime}" Foreground="DarkGray" FontSize="23" HorizontalAlignment="Center"/>
                    </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

All my data shows up properly but my first item is blank, although it is clickable. I tried changing the width and height but I still have the same issue
Environment: Windows 8.1, XAML, C#
I tried looking into the other similar stackoverflow questions but had no luck

A: I had the same problem and I just fixed it!
Both of us tried to set Grid Width by binding to ListView.ActualWidth, but it's not working until first element will be rendered, so first elemnt always have 0 Width :(
To solve this, please do this (based on this answer by @Kievic

Setting the ListView.ItemContainerStyle with a
  HorizontalContentAlignment setter makes the trick.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</ListView.ItemContainerStyle>

A: You can do:
<ListView SelectedIndex="0">

If you want it to select the first item in the list on load.


text:
Q: Copying directories and incrementing name I have a folder "named training01". I Want to run a script that copies the directory and its contents 12 times so I have "training01, training02, ..., training13". It must be really simple but I'm noob to bash scripts. Thanks in advance :)

A: #!/bin/bash
i=2

    while [ $i -le 13 ]
     do
      if [i -le 9]; then
       cp training01 "training0$i"
      else
       cp training01 "training$i"
      fi

     i=`expr $i+1`
     done

A: Try something like:
#!/bin/bash

org="training01"
base=$(echo "$org" | sed -e 's/[0-9]//g')
for ((i=2; i<=13; i++)); do
    dest=$(printf "%s%02d" "$base" $i)
    cp -a "$org" "$dest"
done

A: My final solution was this:
for i in $(seq -f "%02g" 1 13)
  do
    cp -r "../path/to/file" "target/directory/training$i"
  done

Thanks to everyone who contributed :)


text:
Q: How to create page content from a taxonomy using DRUPAL I'm pretty new using Drupal, and I have a doubt.
I have a category with some categories inside: Services (main category) that has child categories (books, newspapers, letters).
Each child category has an image, a title and a short description for it. I created a taxonomy, called Services, and I added the child categories as terms. (I don't know if this is the correct way for doing this. Any suggestion will be accepted and thanked).
Now I want on home page to show something like this:

So, I want a grid view of my sub-categories on my home page with the image and the title, and when I click it, go to the sub category and show its content.
Sorry for not being more specific, but I'm really newby...

A: If I understand you correctly, your vocabulary looks like this:
[Category]
- Sub-category 1
 - term 1
 - term 2
- Sub-category 2
 - term 3
 - term 4
- Sub-category 3
 - term 5
etc.

and while you create your terms you also add a description for each sub-category term.
So, to output only first-level terms (sub-categories) you should create a page/block with Views module.
While creating a new View, be careful to choose Show: Taxonomy terms above the "Adding new view" form and select your vocabulary.
Then, in order to output only level-1 terms, you should add relations - press Advanced/ Relationships and choose Taxonomy term: Parent term. Then add new Filter criteria - Taxonomy term: Parent term with Relationship set to Parent and Operator set to Is empty (NULL)
To add description simply add new field - Taxonomy term: Term description.
All other customization (wrap title in  tags, output fields as table/grid and so on) are also available in views.
I've not tried to add an img to terms so far, but I guess there are to ways to accomplish that: via CSS (by adding 'background:' property) or by using some modules such as Taxonomy Image.
PS
If it matters, all above is about Drupal 7, and I'm not absolutely sure will it work on Drupal 6 or not.


text:
Q: Question about hint from Folland's exercise 2.5.50 This question is related to the exercise that was mentioned in this post, and is primarily about the hint provided to prove $G_{f} = \{(x,y)\in X\times[0,\infty]:y\leq f(x)\}$ is measurable. The solutions I have seen follow the hint, but I am wondering if it is possible to note that since $h(y) = -y$ is Borel measurable, and since it is known that $f\in L^{+}$, can we instead just use the fact that function measurability is closed under addition to show $G_{f}$ is measurable, or is this not correct in this instance? In other words, can we use
$$f\in L^{+}, \hspace{1mm} h\in \mathcal{B}\implies g(x,y) = f(x) + h(y) = f(x) + (-y) = f(x) - y$$
to show that $G_{f}$ is measurable, or does this not actually show that $g$ is measurable? I understand what to do with the hint provided by Folland, but I am not sure if it is acceptable to alternatively use the previously mentioned approach as shown above.
Any help is appreciated.

A: Yes you can. You have to be careful with $\infty - \infty$, but defining $\infty - \infty$ you can show that sums of extended real valued measurable functions are measurable. There are related exercises about this measurability of extended real valued functions in Folland's book.


text:
Q: Call WebApi with JWT Token from Blazor WebAssembly I am getting an unexpected Unauthorized response from an Api when using JWT in Blazor WebAssembly.  Note, I am not trying to secure anything on the WebAssembly client; just the API endpoint.  I have deliberately left out expiry validation.
Server
appsettings.json
{
  "JwtSecurity": {
    "Key": "RANDOM_KEY_MUST_NOT_BE_SHARED",
    "Issuer": "https://localhost",
    "Audience": "https://localhost",
    "ExpiryDays": 1
  }
}

Program.cs
// Service registration
builder.Services
    .AddAuthentication(auth =>
    {
        auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["JwtSecurity:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["JwtSecurity:Audience"],
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSecurity:Key"])),
            RequireExpirationTime = false,
            ValidateLifetime = false
        };
    });

// Configure the HTTP request pipeline.

// SignalR Compression
app.UseResponseCompression();

if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

// Logs the received token
app.UseJwtTokenHandler();

//explicitly only use blazor when the path doesn't start with api
app.MapWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api"), blazor =>
{

    blazor.UseBlazorFrameworkFiles();
    blazor.UseStaticFiles();

    blazor.UseRouting();

    blazor.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<Cosmos.App.Server.Hubs.TillSiteHub>("/tradingsessionhub");
        endpoints.MapFallbackToFile("index.html");
    });
});

//explicitly map api endpoints only when path starts with api
app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), api =>
{
    api.UseStaticFiles();
    api.UseRequestLogging();

    api.UseRouting();
    api.UseAuthentication();
    api.UseAuthorization();
    // HAVE ALSO TRIED
    // api.UseAuthentication();
    // api.UseRouting();
    // api.UseAuthorization();

    api.UseErrorHandling();

    api.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
});

app.Run();

*

*This link suggests UseRouting should come before
UseAuthentication and UseAuthorisation.

*This link suggests UseRouting should come between them.

Have tried both to no avail.
Token Generation on Login
Helper Class
public class JwtHelper
{
    public static JwtSecurityToken GetJwtToken(
        string username,
        string signingKey,
        string issuer,
        string audience,
        TimeSpan expiration,
        Claim[] additionalClaims = null)
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub,username),
            // this guarantees the token is unique
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        if (additionalClaims is object)
        {
            var claimList = new List<Claim>(claims);
            claimList.AddRange(additionalClaims);
            claims = claimList.ToArray();
        }

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        return new JwtSecurityToken(
            issuer: issuer,
            audience: audience,
            expires: DateTime.UtcNow.Add(expiration),
            claims: claims,
            signingCredentials: creds
        );
    }
}

Controller Method for Login
    Guid userGid = await loginManager.LoginAsync(request.Email!, request.Password!);

    if (userGid == default)
    {
        return base.NotFound();
    }

    List<Claim> claims = new List<Claim>();
    claims.Add(new Claim(ClaimTypes.NameIdentifier, userGid.ToString()));
    claims.Add(new Claim(ClaimTypes.Name, userGid.ToString()));

    string key = configuration["JwtSecurity:Key"];
    string issuer = configuration["JwtSecurity:Issuer"];
    string audience = configuration["JwtSecurity:Audience"];
    string expiryDays = configuration["JwtSecurity:ExpiryDays"];
    TimeSpan expiry = TimeSpan.FromDays(Convert.ToInt32(expiryDays));

    var token = JwtHelper.GetJwtToken(
        userGid.ToString(),
        key,
        issuer,
        audience,
        expiry,
        claims.ToArray());

    LoginResponse response = new(new JwtSecurityTokenHandler().WriteToken(token));

    return base.Ok(response);

The token string response is stored in Local Storage.
Client
Adding header to Http Client
// GetTokenAsync retrieve the string from Local Storage
_httpClient.DefaultRequestHeaders.Authorization =
    new System.Net.Http.Headers.AuthenticationHeaderValue(
        "bearer",
        (await _accessControlStateManager.GetTokenAsync())!.Write());

Server Logging of Received Token by middleware
public class JwtTokenHandlerMiddleware
{
    readonly RequestDelegate _next;
    readonly ILogger _logger;

    public JwtTokenHandlerMiddleware(
        RequestDelegate next,
        ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger(typeof(JwtTokenHandlerMiddleware).FullName!);
    }

    public async Task Invoke(HttpContext context)
    {
        JwtSecurityToken? jwt = context.GetJwtTokenFromAuthorizationHeader();

        if (jwt != null)
        {
            _logger.LogInformation("Request received with token: {uri}", context.Request.GetDisplayUrl());
            _logger.LogInformation("Token: {token}", jwt.Write());

        }
        else
        {
            _logger.LogInformation("Request received from ANONYMOUS: {uri}", context.Request.GetDisplayUrl());
        }

        await _next(context);
    }
}

        public static JwtSecurityToken? GetJwtTokenFromAuthorizationHeader(this HttpContext httpContext)
        {
            string text = httpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            if (string.IsNullOrWhiteSpace(text))
            {
                return null;
            }

            return new JwtSecurityTokenHandler().ReadJwtToken(text);
        }

*

*I have confirmed from the logs that the JWT is being received

*Using jwt.io I can confirm that the token logged in the request middleware can be read

jwt.io output

Given all of the above, it seems that:

*

*I am generating JWT correcly.

*JWT is being stored and retrieved correctly from Local Storage

*JWT is being received in the Authorization header in the request

*The controller is secured at Controller level using Authorize
attribute (no roles mentioned)

But still I get Unauthorized.
Any advice?
Attempts to Isolate
Disable validation parameters
Tried:
options.TokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuer = false,
    ValidateAudience = false,
    ValidateIssuerSigningKey = false,
    RequireExpirationTime = false,
    ValidateLifetime = false
};

And added simple test controller:
using Microsoft.AspNetCore.Authorization;

namespace Cosmos.App.Server.Controllers;
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class TestController : ControllerBase
{
    [HttpGet]
    [Route("test")]
    public async Task<IActionResult> TestAsync()
    {
        await Task.Delay(1);

        return Ok("Hello");
    }
}

But same issue.

A: Found it!
The issue was that I was caching the returned string from login as a Token so I could quickly access claims in the client (whilst saving the string received from login in LocalStorage).
Then, when putting the token on the HttpClient, if I had a cached token, I was writing it out to string to populate the Authorization on the Http Request.
The problem is that the string received from the initial login, e.g.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5NGU2YWZhNy00NGYwLTRlNTUtODgxMy0xMTRmNGY1OWE2NzIiLCJqdGkiOiI2MWYwYTRiMi0wNjQwLTRiMjgtYmM2Mi0zMDZlYTVmYmJiM2UiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6Ijk0ZTZhZmE3LTQ0ZjAtNGU1NS04ODEzLTExNGY0ZjU5YTY3MiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiI5NGU2YWZhNy00NGYwLTRlNTUtODgxMy0xMTRmNGY1OWE2NzIiLCJleHAiOjE2NjM5NjEwMjMsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0IiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3QifQ.5l9LRYIx3wXruW7BMa1DDbEoltVgP6Fbfkc2O03XAAY
was truncated when reading back into a token for caching.  It appears to have truncated what I presume is the signing key.  The following was missing:
5l9LRYIx3wXruW7BMa1DDbEoltVgP6Fbfkc2O03XAAY
This meant I had the full string stored in local storage but a cached token without the signing key.
When then used the cached token to write to string for the authorization header I got:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5NGU2YWZhNy00NGYwLTRlNTUtODgxMy0xMTRmNGY1OWE2NzIiLCJqdGkiOiI2MWYwYTRiMi0wNjQwLTRiMjgtYmM2Mi0zMDZlYTVmYmJiM2UiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6Ijk0ZTZhZmE3LTQ0ZjAtNGU1NS04ODEzLTExNGY0ZjU5YTY3MiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiI5NGU2YWZhNy00NGYwLTRlNTUtODgxMy0xMTRmNGY1OWE2NzIiLCJleHAiOjE2NjM5NjEwMjMsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0IiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3QifQ.
without the suffix of the signing key.
This meant that the validation of that string failed authorization on the server, even though jwt.io would happily read it.
Using the full string that I'd stored in Local Storage instead of a 'written' string from the cached token solved the problem.


text: Q: Supercritical and subcritical Hopf bifurcation While studying the bifurcations for two dimensional dynamic systems, I came across the subcritical and supercritical Hopf bifurcation. I know that the subcriticâl involves a limit cycle around a stable equilibrium and the supercritical one around an unstable equilibrium. But is there an easier way to recognize which one of the two Hopf bifurcations there is? E.g. by looking at the eigenvalues?


text:
Q: mfc accelerators Ctrl + doesn't work I have mfc application where I defined keyboard ACCELERATORS
It works fine when I use alphanumeric characters, but I want to define an accelerators that zoomin/zoomout while pressing on the keys +/-
so I defined it as the following and it works fine
 ID1 ACCELERATORS DISCARDABLE
 {
   "+",  ID_ZOOMIN ,  ,ASCII, NOINVERT
   "-",   ID_ZOOMIN ,ASCII, NOINVERT
 }

Now I added a text box that can accept "+/-" as charcters but pressing on them now function as zoomin/zoomout and the characters "+/-" are not typed
so I changed my implementation to have the "zoomin/zoomout" functionality only works while the control button is pressed
 ID1 ACCELERATORS DISCARDABLE
 {
   "+",  ID_ZOOMIN ,  ,ASCII, CONTROL, NOINVERT
   "-",   ID_ZOOMIN ,ASCII, CONTROL, NOINVERT
 }

but still pressing +/- or Ctrl + +/Ctrl + -" function as "zoomin/zoomout" and the +/- characters are not typed
Note: changing ASCII to VIRTKEY doesn't solve the problem
Any ideas??

A: I've just tested with my Windows laptop. It seems ASCII accelerators don't support the CONTROL modifier.
Use VIRTKEY instead.
 ID1 ACCELERATORS DISCARDABLE
 {
   107,  ID_ZOOMIN,  VIRTKEY, CONTROL, NOINVERT
   109,  ID_ZOOMOUT,  VIRTKEY, CONTROL, NOINVERT
 }

Or specify VK_ADD for +, VK_SUBTRACT for -.
Windows Virtual-Key Codes


text:
Q: How can I enter Greek numerals based on obsolete letters {Ϛ΄, Ϟ΄, Ϡ΄}? These three letters, now otherwise obsolete in the Greek language, still have usage in the Greek numeral system:

*

*6 = Ϛ΄ (stigma)

*90 = Ϟ΄ (qoppa)

*900 = Ϡ΄ (sampi)

Aside from copy-pasting, how can I input these symbols using the Greek Input Source?

A: Have you checked the Greek Polytonic input source provided by Apple on the option and option-shift levels?
Otherwise the usual way to enter archaic characters is via the character viewer.
If you need them often, you can make a text replacement entry in system preferences > keyboard > text > replace with.
If Greek Polytonic doesn't have everything you need, you can make a custom layout with Ukelele.


text:
Q: React router not rendering components? I'm trying to render out new components without showing the original home component. I separated my components and now when I try to render them out it doesn't display.
class App extends Component {
render() {
return (

      <Route exact={true} path="/" component={Home} />

);
}
}

Here is my home component that is supposed to render the About component and Pages component, but currently when I click it it doesn't display anything.
const Home = () => (

Home page

<Link to="/about">About</Link>

<Link to="/pages">Page with Subpages</Link>

        <Route path="/about" component={About} />
        <Route path="/pages" component={Pages} />

)

My About component:
const About = () => (

About page

)

My pages component:
const Pages = ({ match }) => (

Page with Subpages

<Link to={`${match.url}/subpage1`}>Subpage 1</Link>

<Link to={`${match.url}/subpage2`}>Subpage 2</Link>

<Link to={`${match.url}/subpage3`}>Subpage 3</Link>

    <Route path={`${match.url}/subpage1`} component={Subpage1}/>
    <Route path={`${match.url}/subpage2`} component={Subpage2}/>
    <Route path={`${match.url}/subpage3`} component={Subpage3}/>

)

A: I think, you should delete exact from <Route path="/" component={Home} />, because in your case you place About and Pages component under Home, so when you go to /about url, there is no Home component anymore, because you put exact there, so you  see a blank screen;
class App extends React.Component {
  render() {
    return (

        <Route path="/" component={Home} />

  );
  }
}

Full working example here: https://codesandbox.io/s/mjr8xypp4x

A: You must have forgot to add <Router> component as of <BrowserRouter> which has to be embeded as main component in class Component where main Route is defined,
Here's the solution -
import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

class Appz extends React.Component {
    render() {
      return (
        <Router>

<Link to="/about">Home</Link>

            <Route path="/" component={Home} />

        </Router>
      );
    }
}

const Home = () => (

Home page

<Link to="/about">About</Link>

<Link to="/pages">Page with Subpages</Link>

      <Route path="/about" component={About} />
      <Route path="/pages" component={Pages} />

)

const About = () => (

About page

)

const Pages = ({ match }) => (

Page with Subpages

<Link to={`${match.url}/subpage1`}>Subpage 1</Link>

<Link to={`${match.url}/subpage2`}>Subpage 2</Link>

<Link to={`${match.url}/subpage3`}>Subpage 3</Link>

)

export default Appz;

Working example - https://codesandbox.io/s/kxmj48p14v


text:
Q: How to check for staleness of data in Combine with Timers I am converting some code into Combine in order to get familiar with it. I am doing fine with the easy stuff, but here it gets a little trickier. I am trying to report to the user when incoming GPS data is accurate and also whether it's stale.
So I have
let locationPublisher = PassthroughSubject<CLLocation,Never>()
private var cancellableSet: Set<AnyCancellable> = []
var status:GPSStatus = .red //enum

and in init I have
locationPublisher
        .map(gpsStatus(from:)) //maps CLLocation to GPSStatus enum
        .assign(to: \.gpsStatus, on: self)
        .store(in: &cancellableSet)

locationPublisher.sink() { [weak self] location in
        self?.statusTimer?.invalidate()
        self?.setStatusTimer()
}
    .store(in: &cancellableSet)

setStatusTimer()

Here is the setStatusTimer function
func setStatusTimer () {
    statusTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false)   {@MainActor _ in
          self.updateGPSStatus(.red)
    }
}

Is there a more "Combine" way of doing this? I know there are Timer.TimerPublishers, but I'm not sure how to incorporate them?
My tendency is to think there is some kind of combineLatest with one input being the gps status publisher and the other one being some kind go publisher that fires if the upstream pub hasn't fired for x seconds.
Thanks!

A: This is a bit tricky.  You don't need a TimerPublisher but you can use the timeout operator. The tricky part is that timeout will create a publisher that stops publishing when it times out.  The question is "how do you start again".  To do that, you can use the catch operator.
The solution looks like this:
import UIKit
import Combine

enum GPSStatus {
    // Karma Chameleon...
    case red
    case gold
    case green
}

func gpsStatus(from location: String) -> GPSStatus {
    switch location {
    case "ok":
        return .green

    default:
        return .gold

    }
}

class UnnamedLocationThingy {
    let locationPublisher = PassthroughSubject<String,Never>()
    var gpsStatus:GPSStatus = .red {
        didSet { print("set the new value to \(String(describing: gpsStatus))") }
    }

    private enum LocationError: Error {
        case timeout
    }

    private var statusProvider: AnyCancellable?
    init() {
        statusProvider = makeStatusProvider()
            .assign(to: \.gpsStatus, on: self)
    }

    func makeStatusProvider() -> AnyPublisher<GPSStatus, Never> {
        return locationPublisher
            .map(gpsStatus(from:)) //maps CLLocation to GPSStatus enum
            .setFailureType(to: LocationError.self)
            .timeout(.seconds(2), scheduler: DispatchQueue.main) {
                return LocationError.timeout
            }
            .catch { _ in
                self.gpsStatus = .red;
                return self.makeStatusProvider()
            }.eraseToAnyPublisher()
    }
}

let thingy = UnnamedLocationThingy();
Task {
    for delay in [1, 1, 1, 3, 1, 1, 3, 1] {
        try await Task.sleep(for: .seconds(delay))
        thingy.locationPublisher.send("ok")
    }
}

The heart of it is the makeStatusProvider function.  This function creates a publisher that will convert published locations to GPSStatus values as long as they come in in a time limit.  But if one doesn't come fast enough, it times out.  I set up the timeout operator with a customError: handler so that it doesn't just terminate the publisher, but sends an error.  I can catch that error in the catch operator and substitute a new publisher to replace the old one.  The new publisher I substitute is a brand new publisher created by makeStatusProvider which, as we've just seen is a publisher that converts published locations into GPSStatus values until it hits a timeout...
It's a form of recursion.
I've decorated your code with enough stuff to make a Playground and added a bit of code at the end to exercise the functionality.


text:
Q: How do I access an individual 'type' inside std::list< std::list< type > > I am creating a function that recursively finds structs within structs.
I create a list < list <struct> > and then I call a function that finds the first list <struct> and pushes it to the back of a list. I need to iterate through that list of structs and look for more structs within.
Here is my code, this may make things more clear.
std::list<std::list<iof_chunk>>     read_ALLChunks  (iof_chunk* reading_material)
{
    std::list< std::list<iof_chunk> > ALL_CHUNKS;
    std::list< std::list<iof_chunk> >::iterator iter;

    if ( ((*reading_material).header.BASEID_Code != 'BODY') && (checkfor_header( &(*reading_material).data[20] )) )
    {
        ALL_CHUNKS.push_back( read_subChunks(reading_material) );
        for( int i = 0; i < ALL_CHUNKS.size; ++i)
        {

        }
    }
}

My Question about the code above: How do I access an iof_chunk in ALL_CHUNKS

A: You can use iterator in this way:
std::list< std::list<iof_chunk> > ALL_CHUNKS;
std::list< std::list<iof_chunk> >::iterator i = ALL_CHUNKS.begin();
std::list<iof_chunk> one_chunk;

for(; i != ALL_CHUNKS.end(); ++i) {
  *i = one_chunk;
  /* it's just an example */
}

edit
std::list< std::list<iof_chunk> > ALL_CHUNKS;
std::list< std::list<iof_chunk> >::iterator i = ALL_CHUNKS.begin();

for(; i != ALL_CHUNKS.end(); ++i) {
  std::list<iof_chunk> i-th_chunkList = *i;
  std::list<iof_chunk>::iterator j = *i.begin();
  for(; j != *i.end(); ++j) {
    /* do your operation with *j that is an iof_chunk object */
  }
}

A: First of all this statement is invalid because there is no identifier that is being declared.
std::list< std::list<iof_chunk> >::iterator;

As for your question then you can use the following construction
for ( iof_chunk &chunk : ALL_CHUNKS.back() )
{
   // do something
}

A: A rather easy way to do this is with the auto keyword, like so..
auto iter = myList.begin();

This is equivalent to..
std::list< std::list<T> >::iterator iter = myList.begin();

The thing to remember is that every level of list you add will add a corresponding iterator between you and the type T
So for example, if we have two lists ie. std::list<std::list<T>> we'll need to use two iterators to get to any T values.
std::list<std::list<T>> myList;
auto iter1 = myList.begin();
auto iter2 = iter1->begin();
T value = *iter2; //assuming iter2 != iter1->end()

So for a moderately more complex example, with a more useful bit of code supporting it, take the following..
//list x 4
std::list< std::list< std::list< std::list<T> > > > myCrazyList;
for(auto iter1 = myCrazyList.begin(); iter1 != myCrazyList.end(); ++iter1){
    for(auto iter2 = iter1->begin(); iter2 != iter1->end(); ++iter2){
        for(auto iter3 = iter2->begin(); iter3 != iter2->end(); ++iter3){
            for(auto iter4 = iter3->begin(); iter4 != iter3->end(); ++iter4){
                T& value = *iter4;
                //do stuff to your T
            }
        }
    }
}

As you can see auto can be instrumental in keeping sane when dealing with long types like this. iter4 would be equivalent to std::list<T>::iterator but iter1 on the other hand has all 4 std::list in the type-name.


text:
Q: Bootstrap glyphicon not centred with text I'm creating a form and am trying to do validation on my bootstrap form, using bootstrap components. I'm using a c# class library to do my server side validation, and then use the c# code-behind to validate the styles when the form meets a validation condition. I use a panel to hold my form control as such:
<asp:Panel ID="TeacherNamePanel" CssClass="form-group" runat="server">
                    <asp:TextBox ID="tbTeacherName" CssClass="form-control input-lg" placeholder="Teacher-in-charge" runat="server"></asp:TextBox>
</asp:Panel>

and in the code-behind to validate the style:
if (teacherName.Length == 0)
{
      TeacherNamePanel.CssClass = "form-group has-error has-feedback";
      Label span = new Label();
      span.CssClass = "glyphicon glyphicon-remove form-control-feedback";
      span.Attributes["style"] = "vertical-align:middle";
      TeacherNamePanel.Controls.Add(span);
}
else
      TeacherNamePanel.CssClass = "form-group";

However, my glyphicon is not centred in my form's input control, it's too low. Anyway to rectify this problem? Tried to change the positioning for "top" in the css for .has-feedback .form-control-feedback but to no avail.

A: Just a couple of ways to achieve what your after.

*

*Use different syntax:

span.Attributes["style"] = "vertical-align:middle";
to
span.Attributes.Add("vertical-align", "middle");

*Add a css class and apply it to label with the CssClass property. For instance:

This goes in your css file
 .centerAlign {vertical-align: middle;}

then the following should work
span.CssClass = "centerAlign";

and will generate:
your text

A: Try using !important to force the attribute to override predefined ones like so:
span{vertical-align:middle!important;}

A: Solved! I copied the following css from bootstrap.css
.has-feedback .form-control-feedback {
position: absolute;
top: 25px;
right: 0;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
}

and pasted it in my own stylesheet and adjusted top and right to fit my input box. Thanks for your help and advice guys!


text:
Q: MediaPlayer returning wrong mouse position I've run into a strange problem with the MediaPlayer component
that appears to be a bug with either the API or Delphi.
I display the video directly on the Form2 canvas and allow
the user to zoom and drag the video within the window.
I use the Form2.MouseDown and MouseUp events to drag.
The drag was behaving erratically and I traced the problem
to inconsistent use of the window coordinates in the events.
An MPG or WMV video (compressed) will report the MouseDown
coordinates relative to the video, but the MouseUp relative
to the form.  An AVI video (uncompressed) will report both
relative to the form.
I'm using Delphi XE3 with Windows 7.
Has anyone else encountered this anomaly, and how can I
get consistent X,Y coordinates?
Added 7/20:
I don't know what MCVE means, but I added some code in case someone
wants to try and duplicate the problem.
Label1 & Label2 report the mouse coordinates, and if the video is moved
out of the (0,0) position then the coordinates will jump as the mouse
crosses into or out of the video.  It should not do that, it should
always report coordinates relative to the window, not the video.
FormMouseUp will always report relative to the window.
FormMouseDown and FormMouseMove jump back and forth.
procedure TForm1.MFLoadFileClick(Sender: TObject);
begin
  MediaPlayer1.Open;
  MediaPlayer1.Display := Form2;
end;

procedure TForm2.FormMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  Label1.Caption := IntToStr(X); {diag}
  Label2.Caption := IntToStr(Y); {diag}
  VidLoc := Form1.MediaPlayer1.DisplayRect;
  mX := X;   mY := Y;
  MouseDown := True;
end;

procedure TForm2.FormMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
  Label1.Caption := IntToStr(X); {diag}
  Label2.Caption := IntToStr(Y); {diag}
end;

procedure TForm2.FormMouseUp(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var  VL : tRect;
begin
  Label1.Caption := IntToStr(X); {diag}
  Label2.Caption := IntToStr(Y); {diag}
  if (MouseDown and Form1.Loaded) then begin
    VL := VidLoc;
    VL.Left := VidLoc.Left - mX + X;
    VL.Top  := VidLoc.Top  - mY + Y;
    Form1.MediaPlayer1.DisplayRect := VL;
    Form1.MediaPlayer1.Step;
  end;
  MouseDown := False;
end;

A: Oddly enough, moving the video in a panel doesn't work, but moving the panel did.
I didn't want to do that because it requires keeping track of too many objects, but it'll have to do.
Moving the panel uses the same code as above, but with other assorted properties.


text:
Q: How many different possible simple graphs are there with vertex set V of n elements Is V is a set with n elements, how many different simple, undirected graphs are there with vertex set V?

A: See http://oeis.org/A000088. This is the sequence which gives the number of isomorphism classes of simple graphs on n vertices, also called the number of graphs on n unlabeled nodes.  You will also find a lot of relevant references here.

A: If you consider isomorphic graphs different, then obviously the answer is $2^{n\choose 2}$. Most graphs have no nontrivial automorphisms, so up to isomorphism the number of different graphs is asymptotically $2^{n\choose 2}/n!$. This goes back to a famous method of Pólya (1937), see this paper for more information. You can find Pólya's original paper here.


text:
Q: Deflate module not working in .htaccess I have deflate module enabled but when I put my code in .htaccess, it is not working. On various websites I have tested and it shows me to enable gzip compression. Below is the code for deflate:
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE image/x-icon
    AddOutputFilterByType DEFLATE image/svg+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/x-font
    AddOutputFilterByType DEFLATE application/x-font-truetype
    AddOutputFilterByType DEFLATE application/x-font-ttf
    AddOutputFilterByType DEFLATE application/x-font-otf
    AddOutputFilterByType DEFLATE application/x-font-opentype
    AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
    AddOutputFilterByType DEFLATE font/ttf
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/opentype

    # For Olders Browsers Which Can't Handle Compression
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>

When I enable deflate in terminal, this is the message that I get:
sudo a2enmod deflate

Considering dependency filter for deflate:
  Module filter already enabled
  Module deflate already enabled


text:
Q: How to create a table inside of a procedure in Oracle? I want to create a table inside of a procedure. I tried to put the create query in a string then execute immediate the string. For example:
create or replace procedure hr.temp is
   var1 varchar2(4000);
begin
   var1:='create table hr.temp(
          id number)';
   execute immediate var1;
end temp;

But when I execute this procedure I get the error:

ORA-00911: invalid character
ORA-06512: at "SYS.TEMP", line 6
.
.
.

Is there any way I can do this?

A: Try this. It should work...
create or replace procedure hr.temp is
   var1 varchar2(4000);
BEGIN
   var1:='create table hr.temp2(
          id number)';
   EXECUTE IMMEDIATE var1;
end temp;

A: the answer of m.r 'a_horse_with_no_name' is right. The first point is I should not create a table in sys schema.
The second point is in a dynamic sql I should not use ; character in dynamic sql.


text:
Q: How to generalize the momentum reversal operator? In non-relativistic quantum mechanics, in position space, the complex conjugate operator $C$ flips the sign of the momentum operator, $CpC=-p$ (and thus also flips the sign of the orbital angular momentum).
The operator $T=C$ is usually called the time reversal operator, but this only works in certain cases. For example, it does not work in the presence of spins  (where $T=Ci\sigma_y$). So $C$ may not always be called the (full) time reversal operator.
Would it be safe to say that $C$ is the momentum reversal operator? I think this holds always. Also, does $C$ do anything else that is not associated to momentum directly? Is the general behavior of $C$ well-studied? References would be much appreciated.
Edit: after writing this, I realized that it also flips the sign of $i\partial_t$ (some kind of energy reversal?), but I am not sure how helpful it can be to talk of non-stationary states (or of relativistic quantum mechanics).
Edit: I now realize that this question is ill defined, I did not want people to focus on the basis issue. A better question would be to ask specifically how to generalize the $C$ operator to other basis in relation to time and momentum.

A: The "complex conjugation" operator is basis dependent and so ill defined.
A vector  that has real components in one basis may be have  complex components in another. For example the $x\leftrightarrow p$ change-of-basis formula for the components is
$$
\tilde \psi(p) = \langle p|\psi\rangle = \int dx \langle p|x\rangle\langle x|\psi\rangle= \int dx e^{ipx}\psi(x)
$$
and the $i$ in $e^{-ipx}$ means that a state $|\psi\rangle$ that has real components $\psi(x)=\langle x|\psi\rangle$ in the $|x\rangle$ basis can have complex components  $\tilde \psi(p)=\langle p|\psi\rangle$ in the $|p\rangle$ basis.
Correspondingly
the $\hat p$ opertor acts  as  $-i\partial _x$ in the $|x\rangle$  basis and so flips sign under congugation, while $\hat x$ which acts by multiplication by the real number $x$ does not. But in the $|p\rangle$ basis $\hat p$ is just multiplication by the real number $p$ while $\hat x$ acts as $i\partial_p$, so the "flips" are reversed.
As consequence of this, "complex conjugation" can only be defined as an operator if you also specify a set of basis vectors that are declared "real"
Thus, when defining antilinear operators such as time reversal it is dangerous  to  factor the operator as "$T=Ci\sigma_y$" -- although this is common practice. It is confusing because this formula  is only correct when acting on states in the $\sigma_x$-diagonal or $\sigma_x$-diagonal bases which  are connected by change-of-basis matrices with real entries. If you have need to use a different spin basis, say the general ${\bf n}\cdot {\boldsymbol \sigma}$-diagonal basis, the formula for $T$ is different.


text:
Q: Python Django sqlite connection I would like to create a simple dynamic Sudoku game. Idea is to create new "puzzle" every hour then put it to database and let users solve it. Each solve attempt is compared with database for verification. For that purpose I would like to create python script that generates puzzle and puts it to the database. My database set in models looks like this:
from django.db import models

class user(models.Model):
    name = models.CharField(max_length=30)
    password = models.CharField(max_length=30)
    time_registered=models.DateTimeField()
    time_uploaded=models.DateTimeField()
    points=models.IntegerField()
    saved_sudoku=models.CommaSeparatedIntegerField(max_length=81)
    solved=models.BooleanField()

    def __str__(self):
        return self.name

class server_sudoku(models.Model):
    time_uploaded=models.DateTimeField()
    generated_sudoku=models.CommaSeparatedIntegerField(max_length=81)

Now, when I use :
name1=request.POST["name"]
pass1=request.POST["password"]
newuser=user(name=name1,password=pass1,time_registered=datetime.datetime.now(),time_uploaded=datetime.datetime.now(),points=0,saved_sudoku="",solved=False)
newuser.save()

in views.py it creates new user. So to verify my idea I created application "generate_sudoku.py". To test its connection to database I just try to add user. Code looks as follows:
#!/usr/bin/env python
from db_interface.models import user

import random
import datetime

newuser=user(name="name", password="pass", time_registered=datetime.datetime.now() ,time_uploaded=datetime.datetime.now(), points=0, saved_sudoku="", solved=False)
newuser.save()

This simple app gives me this error:
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Hope I made it clear, I would like to run this application by windows scheduler so that it is automatically run every hour...

A: Use a custom manage.py command.

A: First link on google : http://eliasbland.wordpress.com/2010/01/25/importerror-settings-cannot-be-imported-because-environment-variable-django_settings_module-is-undefined/ ;)
This works for me (in a lambda script, not _ _init _ _.py file) :
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.contrib.auth.models import User #import django stuff after
print User.objects.all()


text:
Q: Probabilty using indicator
Suppose that there are $K$ types of butterflies in a forest. A scientist goes to the forest and captures $n$ butterflies. Suppose that each type of butterfly is independently captured with probability $\frac1k$, and let $X=\{1,2,3,\dots,K\}$ be the number of distinct types of butterflies captured. For example, if $K = 3$, $n = 5$ and the caught butterfly types are AABAB then $X = 2$. Calculate $\operatorname E(X)$ and $\operatorname{Var}(X)$.

How can I set up the indicator variable?
I have tried: Let $I=1$, then if the $i$th type of butterfly was caught, since $X = I_1+\dots+I_n$ $E(X) =\frac nk$. Is that right?


text:
Q: Implementing Custom Controller Factory involving multiple Assemblies Currently, we are trying to implement a custom Controller Factory in our API to determine the correct controller to be used depending on an identifier token that is passed in to our API. The way this project is setup is that each different company (there are only about 5) has its own assembly which contains custom Controllers that has the Action Methods needed to execute whatever action someone is attempting to do. One of the requirements I've been sent is that the controllers must be named the same in these assemblies. So you could have, for example, four different Controllers each in a different assembly all named CustomerController. These four controllers all contain Action Methods named the same as well but the implementation within them is completely different.
When using our custom Controller Factory, we're using Reflection to pull and create an instance of the correct controller type based off of which Assembly should be targeted. I've debugged this and confirmed that the correct Controller is being returned as a result.
The issue occurring happens during the Action Method call. Even though our Controller Factory is returning the correct controller for our request, it seems that MVC has possibly pre-loaded every controller from these assemblies and is still looking at these as a possible direction. The exact error we're getting on the Action Method getting called is: The current request is ambiguous between the following action methods
Is there any way to tell MVC to ignore the other controllers that were not returned in the request of the controller factory so it will know not to attempt to look at the other controllers that do not seem to be loaded? What is the point of a ControllerFactory if MVC is just going to check all the other controllers for an Action Method match? There must be something I'm missing here.
The only other solution I've found to work around this is adding a ActionMethodSelector attribute to all of the Action Methods involved. However, this makes the solution pretty brittle when looking forward and considering that every single Action Method would need to have the same attribute repeated across them.
Looking forward to any advice or knowledge on why MVC is behaving this way when I have implemented a custom Controller Factory that should be deciding which Controller is chosen for using an Action Method. Thanks in advance!

A: We found the solution. The Controller Factory was working as intended. The issue was actually in our routing. Before implementing this solution, we had tagged our Action Methods with the Route attribute. So, for example, for every Controller in the different assemblies we had

[Route("Customer/Lookup/{name}")]
public ActionResult LookupByName(string name)
{
    // Custom code content here
}

It turns out that specifying a Route attribute on these ActionMethods takes precedence over the chosen controller and all controllers that have a match with the currently requested controller/action are called anyway. Our solution was to remove this attribute and put what was needed in the RouteConfig.cs file so it is loaded dynamically and full control is returned to our custom Controller Factory to decide which Controller specifically to use for the chosen ActionMethod.

routes.MapRoute(
    name: "CustomerLookup",
    url: "customer/lookup/{name}",
    defaults: new { controller = "Customer", action = "LookupByName", name = UrlParameter.Optional }
);


text:
Q: Multi-label clustering I have a question regarding a task that I am trying to solve. The data that I have are characterisation data,
meaning that I have a label (PASS/FAIL) for every single datapoint.
So my data matrix, is of n rows and m columns and the target variables are again a matrix of
n rows and m columns composed of binary values (0s and 1s).
My task is to apply clustering and partition all these datapoints into two clusters, one being for PASS
datapoints and the other for FAIL datapoints. I wasn't able to find an algorithm that can solve
this type of 'multi-label' problem with clustering.
I tried to implement algorithms like k-means but while tuning the number of clusters to initialise
I get k=6 which doesn't really make sense. In the data, outliers are already dropped and they
are normalised as well.
I have a large amount of features on my data matrix (eg. >3000) and I tried to apply
dimensionality reduction methods like PCA to at least drop the features that are more
irrelevant than the rest. But I am not sure if this would be applicable in my case when
I have a binary matrix as target variables.
Is there a specific algorithm that can solve this type of problem and if so, what is the
necessary pre-processing I should be doing before applying it?


text:
Q: Google App Engine: BadQueryError: Parse Error: Expected no additional symbols at symbol GROUP I have a Google App Engine datastore NDB model
class Track(ndb.Model):
    datetime = ndb.DateTimeProperty(indexed=True, required=True)
    title = ndb.StringProperty(indexed=True, required=True)
    artist = ndb.StringProperty(indexed=True, required=True)

and I wish to group matching tracks by title and artist that are played at different datetimes using the GROUP BY GQL clause. I am not sure why this GQL query isn't working:
qry = ndb.gql("SELECT * FROM Track GROUP BY title, artist")

which returns the error BadQueryError: Parse Error: Expected no additional symbols at symbol GROUP while the following works fine
qry = ndb.gql("SELECT DISTINCT title, artist FROM Track")

The BadQueryError: Parse Error: Expected no additional symbols at symbol X error also occurs when I place some arbitrary clause X into the query, suggesting that GQL doesn't support the GROUP BY GQL clause (like older answers here suggest) even though it exists in the documentation.

A: GROUP BY is not supported in GQL by App Engine Datastore, so you will have to do order by and then post filter in your app.
The documentation you link is for v1beta2 for Google Cloud Datastore (the standalone version). For App Engine Datastore, read here instead for GQL


text:
Q: Difference operator between a List and a Set Is there an operator to remove elements from a List based on the content of a Set?
What I want to do is already possible by doing this:
words = ["hello", "you", "how", "are", "you", "today", "hello"]
my_set = {"you", "are"}

new_list = [w for w in words if w not in my_set]
# ["hello", "how", "today", "hello"]

What bothers me with this list comprehension is that for huge collections, it looks less effective to me than the - operator that can be used between two sets. Because in the list comprehension, the iteration happens in Python, whereas with the operator, the iteration happens in C and is more low-level, hence faster.
So is there some way of computing a difference between a List and a Set in a shorter/cleaner/more efficient way than using a list comprehension, like for example:
# I know this is not possible, but does something approaching exist?
new_list = words - my_set

TL;DR
I'm looking for a way to remove all element presents in a Set from a List, that is either:

*

*cleaner (with a built-in perhaps)

*and/or more efficient

than what I know can be done with list comprehensions.

A: Unfortunately, the only answer for this is: No, there is no built-in way, implemented in native code, for this kind of operation.

What bothers me with this list comprehension is that for huge collections, it looks less effective to me than the - operator that can be used between two sets.

I think what's important here is the "looks" part. Yes, list comprehensions run more within Python than a set difference, but I assume that most of your application actually runs within Python (otherwise you should probably be programming in C instead). So you should consider whether it really matters much. Iterating over a list is fast in Python, and a membership test on a set is also super fast (constant time, and implemented in native code). And if you look at list comprehensions, they are also very fast. So it probably won't matter much.

Because in the list comprehension, the iteration happens in Python, whereas with the operator, the iteration happens in C and is more low-level, hence faster.

It is true that native operations are faster, but they are also more specialized, limited and allow for less flexibility. For sets, a difference is pretty easy. The set difference is a mathematical concept and is very clearly defined.
But when talking about a "list difference" or a "list and set difference" (or more generalized "list and iterable difference"?) it becomes a lot more unclear. There are a lot open questions:

*

*How are duplicates handled? If there are two X in the original list and only one X in the subtrahend, should both X disappear from the list? Should only one disappear? If so, which one, and why?

*How is order handled? Should the order be kept as in the original list? Does the order of the elements in the subtrahend have any impact?

*What if we want to subtract members based on some other condition than equality? For sets, it's clear that they always work on the equality (and hash value) of the members. Lists don't, so lists are by design a lot more flexible. With list comprehensions, we can easily have any kind of condition to remove elements from a list; with a "list difference" we would be restricted to equality, and that might actually be a rare situation if you think about it.
It's maybe more likely to use a set if you need to calculate differences (or even some ordered set). And for filtering lists, it might also be a rare case that you want to end up with a filtered list, so it might be more common to use a generator expression (or the Python 3 filter() function) and work with that later without having to create that filtered list in memory.
What I'm trying to say is that the use case for a list difference is not as clear as a set difference. And if there was a use case, it might be a very rare use case. And in general, I don't think it's worth to add complexity to the Python implementation for this. Especially when the in-Python alternative, e.g. a list comprehension, is as fast as it already is.

A: First things first, are you prematurely worrying about an optimisation problem that isn't really an issue? I have to to have lists with at least 10,000,000 elements before I even get into the range of this operation taking 1/10ths of a second.
If you're working with large data sets then you may find it advantageous to move to using numpy.
import random
import timeit

r = range(10000000)

setup = """
import numpy as np
l = list({!r})
s = set(l)
to_remove = {!r}
n = np.array(l)
n_remove = np.array(list(to_remove))
""".format(r, set(random.sample(r, 3)))

list_filter = "[x for x in l if x not in to_remove]"
set_filter = "s - to_remove"
np_filter = "n[np.in1d(n, n_remove, invert=True)]"

n = 1
l_time = timeit.timeit(list_filter, setup, number=n)
print("lists:", l_time)
s_time = timeit.timeit(set_filter, setup, number=n)
print("sets:", s_time)
n_time = timeit.timeit(np_filter, setup, number=n)
print("numpy:", n_time)

returns the following results -- with numpy an order of magnitude faster than using sets.
lists: 0.8743789765043315
sets: 0.20703006886620656
numpy: 0.06197169088128707

A: I agree with poke. Here is my reasoning:
The easiest way to do it would be using a filter:
words = ["hello", "you", "how", "are", "you", "today", "hello"]
my_set = {"you", "are"}

new_list = filter(lambda w: w not in my_set, words)

And using Dunes solution, I get these times:
lists:  0.87401028
sets:   0.55103887
numpy:  0.16134396
filter: 0.00000886 WOW beats numpy by various orders of magnitude !!!

But wait, we are making a flawed comparison because we are comparing the time of making a list strictly (comprehension and set difference) vs. lazily (numpy and filter).
If I run Dunes solution but producing the actual lists, I get:
lists:  0.86804159
sets:   0.56945663
numpy:  1.19315723
filter: 1.68792561

Now numpy is slightly more efficient than using a simple filter, but both are not better than the list comprehension, which was the first and more intuitive solution.
I would definitely use a filter over the comprehension, except if I need to use the filtered list more than once (although I could tee it).


text:
Q: Can I set InputType to "textCapSentences" Delphi XE5 I need to capitalize first letter In sentences then user typing string in Edit like I can do it in Eclipse : "android:inputType="textCapSentences"
How can I do it in XE5?
Or may be some other way to change Shift status on virtual keyboard in XE5?

A: The textCapSentences Corresponds to the TYPE_TEXT_FLAG_CAP_SENTENCES
 constant which is part of the TextView Android Class. This class is wrapped by the Androidapi.JNI.Widget.JTextView interface but this is not used directly by the Firemonkey TEdit controls, instead Firemonkey uses a proxy class called JFMXTextEditorProxy. so in theory you must access the proxy class linked to the EditControl to set the  value TYPE_TEXT_FLAG_CAP_SENTENCES using the setEnterAction method. unfortunately the instance to this proxy class is encapsuled in the TTextServiceAndroid class which is defined in the implementation part of the FMX.Platform.Android unit, so can't be accessed. So the only option which come to my mind is use the OnKeyDown event like :
This will Capitalize the first letter of the EditText and any after a space character.
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
  Shift: TShiftState);
begin
  if  (TEdit(Sender).Text.Length=0) or ((TEdit(Sender).Text.Length>0) and  TEdit(Sender).Text.EndsWith(' ')) then
     KeyChar:=UpCase(KeyChar);
end;


text:
Q: Visual Studio 2013 ASP.Net Publish ConnexionString When i publish my ASP.Net project (ftp method), web.config does not contain connexionstring section.
Do you know how i can do to make ASP.Net upload connexionstrings on production web.config ?
Or should i do this by hand ?

A: Here is url for web.config transformation.
http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/web-config-transformations


text:
Q: LINQ query to room bookings hi everyone i want to get all the rooms that are available from the database. Below is the table structure:
Table Room:
CREATE TABLE [dbo].[Room] (
    [ID]            INT           IDENTITY (1, 1) NOT NULL,
    [Title]         NVARCHAR (50) NOT NULL,

    PRIMARY KEY CLUSTERED ([ID] ASC),
);

Table Booking:
CREATE TABLE [dbo].[Booking] (
    [ID]               INT            IDENTITY (1, 1) NOT NULL,
    [RoomID]           INT            NOT NULL,
    [DateFrom]         DATETIME       NOT NULL,
    [DateTo]           DATETIME       NOT NULL,

    PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [FK_Booking_Room] FOREIGN KEY ([RoomID]) REFERENCES [dbo].[Room] ([ID]),

);

This is what i have done till now and it is not right.
var a = _RoomService.GetRooms()
 .Where(a => a.ID <> (_BookingService.GetBookings()
 .Where((b => b.DateFrom > thisDate.DateFrom ||
              b.DateFrom < thisDate.DateFrom &&
              b.DateTo > thisDate.DateTo ||
              b.DateTo < thisDate.DateTo))
 .ToList());

I want to get all the rooms that are available when a user chose a From Date and To Date. Thank you in anticipation.
EDIT
here is what i achieved but still no results..
var roomsBooked = from b in _BookingService.GetBookings()
                               where (b.DateFrom <= thisDate.DateFrom) && (b.DateTo >= thisDate.DateFrom) ||
                               (b.DateFrom <= thisDate.DateTo) && (b.DateTo <= thisDate.DateTo) ||
                               (b.DateFrom >= thisDate.DateFrom) && (b.DateTo >= thisDate.DateTo)
                               select b;

var availableRooms = _RoomService.GetRooms().Where(a => roomsBooked.Any(b => b.RoomID != a.ID));

Anyone who can help is welcome. i have been trying since yesterday:( Thank you

A: var bookings = _BookingService.GetBookings()
        .Where((b => b.DateFrom > thisDate.DateFrom ||
               b.DateFrom < thisDate.DateFrom
                     && b.DateTo > thisDate.DateTo
                          || b.DateTo < thisDate.DateTo);

var a = _RoomService.GetRooms().Where(a => !bookings.Any(b=>b.RoomID == a.ID)).ToList());

A: Here is a sample I have put together for you.  It is exactly the same as @AD.Net asnwer, except that mine is written in LINQ. I have placed this is in a console application for you, that you can test and play around with if interested, just copy and paste.
Here is the code:
class Program
{
    public DateTime DateFrom { get; set; }
    public DateTime DateTo { get; set; }

    static void Main(string[] args)
    {
        Program p = new Program();
    }

    public Program()
    {
        var _BookingService = new List<Booking>()
        {
            new Booking() { ID = 100, RoomID = 1, DateFrom = new DateTime(2016, 5, 15), DateTo = new DateTime(2016, 5, 17)},
            new Booking() { ID = 200, RoomID = 2, DateFrom = new DateTime(2016, 5, 20), DateTo = new DateTime(2016, 5, 25) }
        };

        this.DateFrom = new DateTime(2016, 5, 14);
        this.DateTo = new DateTime(2016, 5, 27);

        var roomsBooked = from b in _BookingService
                          where
                                  ((this.DateFrom >= b.DateFrom) && (this.DateFrom <= b.DateTo)) ||
                                  ((this.DateTo >= b.DateFrom) && (this.DateTo <= b.DateTo)) ||
                                  ((this.DateFrom <= b.DateFrom) && (this.DateTo >= b.DateFrom) && (this.DateTo <= b.DateTo)) ||
                                  ((this.DateFrom >= b.DateFrom) && (this.DateFrom <= b.DateTo) && (this.DateTo >= b.DateTo)) ||
                                  ((this.DateFrom <= b.DateFrom) && (this.DateTo >= b.DateTo))
                            select b;

        var availableRooms = GetRooms().Where(r => !roomsBooked.Any(b => b.RoomID == r.ID));

        foreach (var room in availableRooms)
            Console.WriteLine($"{room.Title}");

        Console.ReadKey();

    }

    public List<Room> GetRooms()
    {
        return new List<Room>()
        {
            new Room() { ID = 1, Title = "Room 1" },
            new Room() { ID = 2, Title = "Room 3" }
        };
    }
}

public class Room
{
    public int ID { get; set; }
    public string Title { get; set; }

}
public class Booking
{
    public int ID { get; set; }
    public int RoomID { get; set; }
    public DateTime DateFrom { get; set; }
    public DateTime DateTo { get; set; }
}

The juicy part, that you are interested in, is this piece of code:
var roomsBooked = from b in _BookingService
                          where
                                  ((this.DateFrom >= b.DateFrom) && (this.DateFrom <= b.DateTo)) ||
                                  ((this.DateTo >= b.DateFrom) && (this.DateTo <= b.DateTo)) ||
                                  ((this.DateFrom <= b.DateFrom) && (this.DateTo >= b.DateFrom) && (this.DateTo <= b.DateTo)) ||
                                  ((this.DateFrom >= b.DateFrom) && (this.DateFrom <= b.DateTo) && (this.DateTo >= b.DateTo)) ||
                                  ((this.DateFrom <= b.DateFrom) && (this.DateTo >= b.DateTo))
                            select b;

        var availableRooms = GetRooms().Where(r => !roomsBooked.Any(b => b.RoomID == r.ID));

The above code first selects all the rooms that are booked and places them in the roomsBooked collection.  There after, I call the GetRooms() function, that will get all the rooms in your "Database". I then do a where() to filter out all the rooms from the GetRooms() that are not currently in the roomsBooked list/collection. I hope this makes some sense


text:
Q: Maximizing the efficiency of a simple algorithm in MATLAB So here is what I'm trying to do in MATLAB:
I have an array of n, 2D images.  I need to go through pixel by pixel, and find which picture has the brightest pixel at each point, then store the index of that image in another array at that point.
As in, if I have three pictures (n=1,2,3) and picture 2 has the brightest pixel at [1,1], then the value of max_pixels[1,1] would be 2, the index of the picture with that brightest pixel.
I know how to do this with for loops,
    %not my actual code:
    max_pixels = zeroes(x_max, y_max)
    for i:x_max
      for j:y_max
        [~ , max_pixels(i, j)] = max(pic_arr(i, j))
      end
    end

But my question is, can it be done faster with some of the special functionality in MATLAB?  I have heard that MATLAB isn't too friendly when it comes to nested loops, and the functionality of : should be used wherever possible.  Is there any way to get this more efficient?
-PK

A: You can use max(...) with a dimension specified to get the maximum along the 3rd dimension.
 [max_picture, indexOfMax] = max(pic_arr,[],3)

A: You can get the matrix of maximum values in this way, using memory instead of high performance of processor:
a = [1 2 3];
b = [3 4 2];
c = [0 4 1];
[max_matrix, index_max] = arrayfun(@(x,y,z) max([x y z]), a,b,c);

a,b,c can be matrices also.
It returns the matrix with max values and the matrix of indexes (in which matrix is found each max value).


text:
Q: Converting a string "10.214.239" to integer I have some strings of the format "10.214.239" that I want to convert to an integer. Some of the strings are only thousands, and thus only contain 1 dot, but some are millions, and thus contain 2 dots. Is there a simple way to solve this?

A: int  i, len;
int result=0;

len = strlen(num);

for(i=0; i<len; i++){
    if(num[i] >= '0' && num[i] <= '9' )
        result=(result*10)+(num[i]-'0')
}

printf("%d", result);

A: You roughly need this:
int main()
{
  const char num[] = "12.345.66";
  char buffer[100];

  // copy string to buffer skipping dots
  char c;
  int j = 0;
  for (int i = 0; c = num[i]; i++)
  {
    if (c != '.')
      buffer[j++] = c;
  }

  // put the NUL strig terminator
  buffer[j] = 0;

  // convert string stripped of dots to long
  long number = strtol(buffer, NULL, 10);

}

Disclaimer: this is non error checking, quickly written code that shouldn't be used as it stands here, but it just should give you an idea of what you need to do.

A: Simple solution:
int i,ans=0;
for(i=0;num[i];i++)
   if(num[i]!='.') ans=ans*10+num[i]-'0';

printf("%d",ans);

A: Just go through each character, and use isdigit() from <ctype.h>to determine if characters are numbers. Something like this would work:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void) {
    const char *test = "10.214.239";
    const char neg = '-';
    long number = 0;

    for (size_t i = 0; test[i] != '\0'; i++) {
        if (isdigit(test[i])) {
            number *= 10;
            number += test[i] - '0';
        }
    }

    /* if first character is a dash, make sure the converted number is negative */
    if (test[0] == neg) {
        number *= -1;
    }

    printf("number = %ld\n", number);

    return 0;
}

A: A different approach from all the other answers so far would be utilise the standard library functions designed to handle manipulate/handle strings. For example, this could be done with sscanf:
#include <stdio.h>

int main(void) {
    const char *test = "10.214.239";
    int vals[3] = {0, 0, 0};

    const int n = sscanf(test, "%i.%i.%i", &vals[0], &vals[1], &vals[2]);
    const int exponent = n < sizeof(vals)/sizeof(int) ? 1: 1E3;
    long number = vals[0]*1E3*exponent + vals[1]*exponent + vals[2]);

    printf("%ld\n", number);

    return 0;
}

Or, alternatively, you could use strtok to split the string and atol to convert each substring to a number:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  char *test = "10.214.239";
  char *tok = test;
  const int exponent = 1e3;
  long ans = 0;

  while ((tok = strtok(tok, ".")) != NULL) {
    ans = ans*exponent + atol(tok);
    tok = NULL;
  }

  printf("%ld\n", ans);
  return 0;
}


text:
Q: c# - How to create Generic T from objectName? I have created a FetchData method which returns IList<object> and it takes objectName(string) as parameter(name of the object of which we want to return List).
Task<IList<object>> FetchData(string processGuiId, string objectName);

I am calling a Gateway method from FetchData(string processGuiId, string objectName) to get data from source.
_gateway.ReadByQueryAsync<T>();

How can I get T from objectName for ReadByQueryAsync method?

A: You can't "create Generic T from objectName" but you can construct generic method from type.
I think you are looking for MethodInfo.MakeGenericMethod usage would be like this:
// somehow get fully qualified name from objectName
vat type = Type.GetType("fully qualified name");
var mi = _gateway.GetType().GetMethod("ReadByQueryAsync").MakeGenericMethod(type);

And call, for example:
mi.Invoke(_gateway, null)

or build a lambda with expression trees and cache it.
Example with Enumerable.First():
var mi = typeof(Enumerable)
    // cause multiple "First" methods
    .GetMethods()
    .Where(mi => mi.Name == "First" && mi.GetParameters().Length == 1)
    .First();
var type = Type.GetType("System.Int32");
var constructed = mi.MakeGenericMethod(type);
var obj = new[] { 1, 2 };
// you will have another order of parameters in Invoke if ReadByQueryAsync is instance method
var x = constructed.Invoke(
    null, // null cause First is extension method, should be obj if instance
    new[] { obj } // should be null for parameterless instance method
    ); // x = 1


text:
Q: Prestashop 1.5.6.2 adding product in ajax stopped working my client is using prestashop 1.5.6.2 and products are added trough ajax-cart.js file that is sending correct POST to cart controller with id of product qty in params:
controller  cart
add 1
ajax    true
qty 1
id_product  92
token   4c30038914336909b4bab857c7ce7a1b

In response I get Status 200 and properly formated JSON that should contain all of added products and add it to cart right? Just the thing is, that JSON is empty no matter what product I try to add. It looks something like this:
products    []
discounts   []
shippingCost    0,00 zł
shippingCostFloat   0
wrappingCost    0,00 zł
nbTotalProducts 0
total   0,00 zł
productTotal    0,00 zł
hasError    false

I've look through the files, but not found any weird stuff in functions, there are no js errors or 500 code. Does anyone know anything how to fix that?
EDIT:
I've found out that guest_id always equals 0 no matter when loged or not.


text:
Q: Limit the ngFor loop to two iterations How to limit the ngFor loop to only 2 iterations?
I want there to be only 2 'chat-window' tags that can be displayed.

    <chat-window
            *ngFor="let box of windows; let i = index"
            [box]="box">
    </chat-window>

A: Seems a duplicate of Angular 2: how to apply limit to *ngFor?
You can use Array.slice(...) do something like that if you don't want to use <template>:

    <chat-window
            *ngFor="let box of (windows ? windows.slice(0,2): []); let i = index"
            [box]="box">
    </chat-window>

EDIT : show the last two boxes (eg.: if 3 or more boxes):
You simply have to enhance a bit the Array.slice(...) parameters to make them more dynamic. This way, you'll always show the two latest boxes.

    <chat-window
            *ngFor="let box of (windows ? windows.slice(windows.length-2,2): []); let i = index"
            [box]="box">
    </chat-window>

For example, if you have 4 boxes in windows, it will be the same that:

    <chat-window
            *ngFor="let box of (windows ? windows.slice(2,2): []); let i = index"
            [box]="box">
    </chat-window>

A: You could also try to keep your template clean of slicing and prepare the data in the component itself:
public get windows(): Window[] {
    return this.windows.slice(0,2);
}

or give the getter method another name, if you don't want to mix it up with existing getters in your component.

A:
Simple soultion:

    <div *ngIf="i<2">
        {{tran.id}}

A:

    <template *ngFor="let box of windows; let i = index">
        <chat-window [box]="box" *ngIf="i < 2">
        </chat-window>
    </template>


text:
Q: Adding Text before pagination link segment of codeigniter hi i just want to ask about codeigniter pagination link.
this my controller :
    $configp['base_url'] = base_url().'post';
    $configp['total_rows'] = $this->db->where('status',0)->get('room_post')->num_rows();
    $configp['per_page'] =5;
    $configp['uri_segment'] = 2;

    $this->pagination->initialize($configp);

    $data['pendinglink'] = $this->pagination->create_links();

i want to add text before the segment of pagination example if i create this link it will generate this link
1
2
>

i want to add "pendingpost" before "5" of "http://localhost/istay/post/5" so it will have a result of "http://localhost/istay/post/pendingpost/5"
i search about it and i find out about "config['first_url']" but i don't fully understand it and i think it will only modify first url of the link. i hope someone can help. thx.

A: change from
$configp['base_url'] = base_url().'post';

to
$configp['base_url'] = base_url().'post/pendingpost';


text:
Q: is there a way to avoid calling nextval() if the insert fails in PostgreSQL? In a PostgreSQL database I have a table with a primary key and another field which needs to be unique.
  CREATE TABLE users (
    id      INTEGER PRIMARY KEY DEFAULT nextval('groups_id_seq'::regclass),
    name    VARCHAR(255) UNIQUE NOT NULL
  );

  INSERT users (name) VALUES ('foo');
  INSERT users (name) VALUES ('foo');
  INSERT users (name) VALUES ('bar');

The second insert fails but the sequence groups_id_seq is already incremented so when 'bar' is added it leaves a gap in the id numbers.
Is there a way to tell PostgreSQL to fetch the next value only if other constraints are met or should I check first using SELECT if the name is not duplicate? This still would not guarantee the lack of gaps but at least it would reduce their number to the rare cases when there is another process trying to insert the same name at the same time

A: If you need gapless sequences - there are ways to do it, but it's not trivial, and definitely much slower.
Also - if you worry about "using too many ids" - just define id as bigserial.

A: It is possible, though cumbersome, to do this.  As bortzmeyer says, it's dangerous to rely on values from sequences being contiguous, so it's best to just leave things as they are if you can.
If you can't:
Every access to the table that could cause a row to have a certain name (that is, every INSERT to that table, and if you allow it (though it's poor practice) every UPDATE that could change the name field) must do so inside a transaction that locks soemthing first.  The simplest and least performant option is to simply lock the entire table using LOCK users IN EXCLUSIVE MODE (adding the last 3 words permits concurrent read access by other processes, which is safe).
However that is a very coarse lock that will slow performance if there are many concurrent modifications to users; a better option would be locking a single, corresponding row in another table that must already exist.  This row can be locked with SELECT ... FOR UPDATE.  This makes sense only when working with a "child" table that has a FK dependency on another "parent" table.
For example, imagine for the time being that we are actually trying to safely create new orders for a customer, and that these orders somehow have identifying 'names'.  (I know, poor example...)  orders has a FK dependency on customers.  Then to prevent ever creating two orders with the same name for a given customer, you could do the following:
BEGIN;

-- Customer 'jbloggs' must exist for this to work.
SELECT 1 FROM customers
WHERE id = 'jbloggs'
FOR UPDATE

-- Provided every attempt to create an order performs the above step first,
-- at this point, we will have exclusive access to all orders for jbloggs.
SELECT 1 FROM orders
WHERE id = 'jbloggs'
AND order_name = 'foo'

-- Determine if the preceding query returned a row or not.
-- If it did not:
INSERT orders (id, name) VALUES ('jbloggs', 'foo');

-- Regardless, end the transaction:
END;

Note that it is not sufficient to simply lock the corresponding row in users with SELECT ... FOR UPDATE -- if the row does not already exist, several concurrent processes may simultaneously report that the row does not exist, and then attempt simultaneous insertions, resulting in failed transactions and thus sequence gaps.
Either locking scheme will work; what's important is that anyone trying to create a row with the same name must attempt to lock the same object.

A: I don't think so: a basic feature of sequences is that gaps are possible (think of two concurrent transactions, with one performing a ROLLBACK). You should ignore gaps. Why are they a problem in your case?


text:
Q: Azure SQL - Correct way to create a contained database user in a non-contained azure sql database We have multiple non-contained Azure sql databases.  We plan to create contained database users in each of them.  These users are for SQL Authentication.  My question:  Do these users have to be created in the master database?
Thank you in advance!
Here are the steps I tried:
Scenario 1 where the user is created BUT failed to sign into the server using SSMS.

*

*In the application database
CREATE USER someContainedDBUser WITH PASSWORD = 'somepwd';

*In the application database, grant roles

*Attempt to sign in with SSMS ( failure)
Scenario 2 where the user is created and can sign into the server using SSMS.

*

*In master database,
CREATE USER someContainedDBUser WITH PASSWORD = 'somepwd';

*In the application database,
CREATE USER someContainedDBUser WITH PASSWORD = 'somepwd';

*In the application database, grant roles

*Attempt to sign in with SSMS ( success)

A: You don't have to create them in master also.  You do have to specify the database you want to connect to via the Options section in SSMS, eg


text:
Q: Determine controllability with big A matrix in linear system On the linear system below:
\begin{aligned}
\dot{x} &= Ax + Bu \\
\end{aligned}
where
$$ A = \begin{bmatrix}
    1       & 0 &0 &-1  \\
    0      & 1 &2 &-1  \\
1       & -2 &1 &0  \\
-1       & 0 &0 &2  \\
\end{bmatrix}
$$
and
$$ B = \begin{bmatrix}
    0  \\
0 \\
1\\
0\\
\end{bmatrix}
$$
is there a quick way to check whether it's controllable or not? I know the textbook way by creating the matrix:
$$ M = \begin{bmatrix}
    B &AB & A^2B &A^3B
\end{bmatrix}
$$
and then finding out if $$ \det{M}$$ is zero or not, but is there any (linear algebra) trick I am missing where the conclusion could be made more easily?
hint: It's not controllable

A: When the eigenvalues of $A$ are given or can relatively easily be obtained one could use the Hautus lemma, which for controllability states that
$$
\text{rank}\begin{bmatrix} \lambda\,I - A & B \end{bmatrix} = n,\,\forall\,\lambda\in\mathbb{C},
$$
or equivalently for all $\lambda$ equal to one of the eigenvalues of $A$.
However, in this case the controllability matrix is probably the easiest route. It can be noted that $M$ can be calculate iteratively (it is not required to calculate the powers of $A$). Namely
$$
M = \begin{bmatrix} L_1 & \cdots & L_n \end{bmatrix},
$$
with $L_1 = B$ and $L_{i+1} = A\,L_i$.
Calculating the controllability matrix in your case yields
$$
M =
\begin{bmatrix}
0 & 0 & 0 & 0 \\
0 & 2 & 4 & -2 \\
1 & 1 & -3 & -11 \\
0 & 0 & 0 & 0
\end{bmatrix},
$$
which contains two rows of all zeros. However, the rank of a (square) matrix always is reduced by one if it has a row (or column) of all zeros, thus in this case $M$ can't be full rank.

A: What you could reason is that the $B$ matrix only 'supplies' terms from the 3rd column in the $A$ matrix. Going one step further, the $AB$ term has only nonzero terms on the 2nd and third row (which is trivial to see). As the first and last row of $A$ have zeros in the second and third column, the $A^iB$th term can never have terms in its first or second row. This reasoning of course only holds for this example, but the idea behind it can be used to quickly see if a controllability (or observability) matrix has full rank (I used this for tests on the subject at uni).


text:
Q: How to load a class based on exact sub-classes? I have Section class that has list of ContentItems. ContentItem has a number of subclasses like TextContentItem, ImageContentItem, etc. All of them are mapped to database (using class and subclass Maps).
I need to have an ability to retrieve Section instance with the populated exact subclass instances of ContentItem.

A: Use the IEnumerable<T> extension method OfType<T> to filter the collection:
var filter = section.ContentItems.OfType<TextContentItem>();

If your collection is very large and you want to avoid loading all of the content items, then I would populate a data transfer object (DTO) comprised of the Section class and a collection of the desired content items. I would not advise partially loading the collection in the domain model.


text:
Q: are or have the same price and different designs? I am going to make up two sentences below.

*

*All the different computers in this section are or have the same price.

*These watches have or are different designs.

I have heard people use either choice when I shop in stores.
Which one is actually correct - are or have?

A: Both solutions are possible in the first sentence. Both of them mean the same thing.

*

*All the different computers in this section are/have the same price.

However, with the second sentence it is grammatically correct to add the preposition "of" after are:

*

*These watches are of/have different designs.

It just happens that the word you picked for this example, "designs", has multiple meanings.  "Design" can refer to either the scheme for how the components of the watch will work, or a decorative pattern applied to the watch.  So if it is used with have, the meaning of the sentence would depend on the context. If are of is used, it could have only the first meaning.


text:
Q: Ubuntu screen keeps freezing randomly I'm a relevantly new user to Ubuntu (I've been using it for about eight months). My pc has 2GB of RAM, and an NVIDIA C61[GeForce 7025 / nForce 630a] graphics card. When I first installed Ubuntu, I single booted Ubuntu 16.04 LTS on it. But I kept having this problem, where the screen kept freezing randomly every once in a while, as shown in the picture below (PC shown in image is not mine. Although, the problem is the exact same)

I factory reset my pc, and dual booted Windows 7 and Ubuntu 14.04 LTS (Because my mother uses the same pc, and she doesn't know how to use Ubuntu). I had the same problem again, although, the problem wouldn't occur when I ran Ubuntu in failsafe graphics mode (This wouldn't work on 16.04. It'd just show a black screen)
Two days ago, I switched to Ubuntu GNOME 16.10. The problem occurs much more rarely now, but it still happens. I went to software updates, additional drivers, and switched to nvidia 304.135. This helped, but everytime I reboot the pc, it'll just show a blank screen with my files on the screen. Nothing is clickable. I can't even open a terminal. The only fix I've been able to find for that, is to purge the nvidia drivers, and switch back to xorg. I've searched all over the Internet for a solution, but I still haven't found one for 8 months. I love Ubuntu, and I don't ever want to switch back to Windows. I would be immensely grateful if someone would be able to find a solution for this.