text:
Q: Trigger validations in real-time with jquery.validate I'm using to jquery.validate to validate my forms.
The first-time validation only happens when I focusout the input.
If I come back to the same input already validated once, it validates as a write, in real-time.
I have to focusout the input or submit it once to get real-time validations. Is this a bug or a configuration issue?
My validate.js file:
https://gist.github.com/4445364
Is there a way to get this behaviour as default?

A:
"Is this a bug or a configuration issue?"

It's a configuration issue.  See below.

"I have to 'focusout' the input or submit it once to get real-time validations.  Is there a way to get this behaviour as default?"

This is already the default behavior.  See this simple jsFiddle demo.  Just start typing in any field and you'll immediately see a message in real-time as you type.
http://jsfiddle.net/RXrKU/
jQuery:
$(document).ready(function() {
    $('form').validate({
        rules: {
            field: {
                required: true,
                minlength: 5
            }
        }
    });
});

HTML:
<form>
     <input type="text" name="field" />
     <input type="submit" />
</form>

A: I think you can call $('form').validate().form() to get this behaviour


text:
Q: Keyboard starts as English even being configured for Spanish Upon Ubuntu's installation I configured the keyboard to be Spanish.  I think it worked fine for a while but after sometime, and maybe some updates, every time I start Ubuntu it is set to English even though it shows as Spanish at the task-bar.  Once I click on the already ES-Spanish option, it works as it should be.
cat /etc/default/keyboard

XKBMODEL="pc105"
XKBLAYOUT="es"
XKBVARIANT=""
XKBOPTIONS=""

Please let me know what could I check.

A: You could try checking the Keyboard Layout Chart to make sure that the key configuration matches up with your physical keyboard. Or, if your physical keyboard isn't a spanish keyboard, you can change the settings to English (International) which will still allow you to type accented characters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dúvida com dados hierárquicos Fala galera , tudo bem ?
Estou com um problema já tem uns dias , no sistema eu preciso controlar a exibição de alguns dados, eu tenho um cadastro de função , setor e empregado, ligados entre sim. Nessa regra de negocio, o Usuário pode montar seu setor e logo sua hierarquia de forma dinâmica , sendo assim , os Usuários só podem ver os dados deles e se eles forem responsareis por alguém, esse responsável pode ver os dados do seu subordinado e os dados do subordinado do seu subordinado e por ai vai.
Nessa tabela acima consigo saber quem é responsável por quem e assim consigo ter uma linha hierárquica.
Meu problema está em conseguir fazer essa escala , saber quem é responsável de quem e se essa pessoa que é subordinada é responsável por alguém tb , assim o primeiro responsável pode ver os dados do segundo responsável e ver os dados so subordinado desse responsavel. Alguém  sabe de um modo de fazer isso? E se assim é a melhor maneira de armazenar os responsáveis (Hierarquia)
OBS: na coluna responsavel_titular e responsavel_subordinado são os códigos do empregado.


text:
Q: Return multiple columns / a dataframe in Deedle based on row-wise mapping I want to look at each row in a frame and construct multiple columns for a new frame based on values in that row.
The final result should be a frame that has the columns of the original frame plus the new columns.
I have a solution but I wonder if there is a better one. I think the best way to explain the desired behavior is with an example. I'm using Deedle's titanic data set:
#r @"F:\aolney\research_projects\braintrust\code\QualtricsToR\packages\Deedle.1.2.3\lib\net40\Deedle.dll";;
#r @"F:\aolney\research_projects\braintrust\code\QualtricsToR\packages\FSharp.Charting.0.90.12\lib\net40\FSharp.Charting.dll";;
#r @"F:\aolney\research_projects\braintrust\code\QualtricsToR\packages\FSharp.Data.2.2.2\lib\net40\FSharp.Data.dll";;
open System
open FSharp.Data
open Deedle
open FSharp.Charting;;
#load @"F:\aolney\research_projects\braintrust\code\QualtricsToR\packages\FSharp.Charting.0.90.12\FSharp.Charting.fsx";;
#load @"F:\aolney\research_projects\braintrust\code\QualtricsToR\packages\Deedle.1.2.3\Deedle.fsx";;

let titanic = Frame.ReadCsv(@"C:\Users\aolne_000\Downloads\titanic.csv");;

This is what that frame looks like:
val titanic : Frame<int,string> =

       PassengerId Survived Pclass Name                                                Sex    Age       SibSp Parch Ticket           Fare    Cabin Embarked
0   -> 1           False    3      Braund, Mr. Owen Harris                             male   22        1     0     A/5 21171        7.25          S
1   -> 2           True     1      Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38        1     0     PC 17599         71.2833 C85   C

My approach grabs each row, uses some selection logic, and then returns a new row value as a dictionary. Then I use Deedle's expansion operation to convert the values in this dictionary to new columns.
titanic?test <- titanic |> Frame.mapRowValues( fun x -> if x.GetAs<int>("Pclass") > 1 then dict ["A", 1; "B", 2] else dict ["A", 2 ; "B", 1] );;
titanic |> Frame.expandCols ["test"];;

This gives the following new frame:
       PassengerId Survived Pclass Name                                                Sex    Age       SibSp Parch Ticket           Fare    Cabin Embarked test.A test.B
0   -> 1           False    3      Braund, Mr. Owen Harris                             male   22        1     0     A/5 21171        7.25          S        1      2
1   -> 2           True     1      Cumings, Mrs. John Bradley (Florence Briggs Thayer) female 38        1     0     PC 17599         71.2833 C85   C        2      1

Note the last two columns are test.A and test.B. Effectively this approach creates a new frame (A and B) and then joins the frame to the existing frame.
This is fine for my use case but it is probably confusing for others to read. Also it forces the prefix, e.g. "test", on the final columns which isn't highly desirable.
Is there a way to append the new values to the end of the row series represented in the code above by x?

A: I find your approach quite elegant and clever. Because the new series shares the index with the original frame, it is also going to be pretty fast. So, I think your solution may actually be better than the alternative option (but I have not measured this).
Anyway, the other option would be to return new rows from your Frame.mapRowValues call - so for each row, we return the original row together with the additional columns.
titanic
|> Frame.mapRowValues(fun x ->
  let add =
    if x.GetAs<int>("Pclass") > 1 then series ["A", box 1; "B", box 2]
    else series ["A", box 2 ; "B", box 1]
  Series.merge x add)
|> Frame.ofRows


text:
Q: Как сложить результаты двух таблиц? Есть две таблицы:
CREATE TABLE [ostatky] (
  [id] INTEGER PRIMARY KEY,
  [d] INTEGER,
  [m] VARCHAR(20),
  [y] INTEGER,
  [point] VARCHAR(80),
  [predprijatie] VARCHAR(80),
  [ostatok] CURRENCY);

CREATE TABLE [main] (
  [id] INTEGER PRIMARY KEY,
  [d] INTEGER,
  [m] VARCHAR(20),
  [y] INTEGER,
  [point] VARCHAR(80),
  [predprijatie] VARCHAR(80),
  [prihod] CURRENCY,
  [rashod] CURRENCY);

Надо получить результат сложения [ostatok] первой таблицы и [prihod] второй таблицы и от этого отнять [rashod] второй таблицы...ну...как то так SUM(ostatok)+SUM(prihod)-SUM(rashod). Как это сделать?


text:
Q: Using href in jquery with get method i´m learning jquery and i have a question.
On html, when i want to pass variables by get, i write:
$subject=$_GET['subject'];

$id_user=$_GET['id_user'];

$id_pupil=$_GET['id_pupil'];

Add

But i want to do it on Jquery. My idea is:
I have this part of code:
while ($row = mysql_fetch_array($result))
{
    echo "
<form action='update_marks.php' method='post'>
        <input type='text' name='mark' value='".$row['mark']."'>
        ".$row['date']."
        <input type='submit' value='Update'>
        <input type='hidden' name='id_mark' id='id_mark' value='".$row['id_mark']."'>
        <input type='hidden' name='subject' id='subject' value='".$subject."'>
        <input type='hidden' name='id_user' id='id_user' value='".$id_user."'>
        <input type='hidden' name='id_pupil' id='id_pupil' value='".$id_pupil."'>
        </form>

";
    echo "
";

}
echo "
";
echo "<input type='button' id='add' value='Add row' />";

And i would like to add rows in the table on Jquery:
$(document).ready(function(){
    var subj=$('#subject').val();
    var id_us=$('#id_user').val();
    var id_pup=$('#id_pupil').val();

    $("#add").on('click', function(){
        $('#table > tbody:last').after("
<input type='text' name='mark' value=''>		Add row
");

});

A: I think I understand what you're trying to do. In javascript strings and concatenation are a little different.
Try changing this line:
$('#table > tbody:last').after("
<input type='text' name='mark' value=''>		Add row
");

To:
$('#table > tbody:last').after("
<input type='text' name='mark' value=''>		Add row
");


text:
Q: Link without jumping to top of page I have the following link on my website:

    Next Step

It works fine, however, would it be possible to change it so that when the link is clicked and the new page is opened it does not automatically scroll to the top of the page? i.e. the new page is in the same position as the previous page was?

A: Yes, if you read about Internal links.

A: Yes it is possible using HTML tags.
You should be using anchors.
You can have named anchors to jump to.
here

You can jump to named anchors by using there names after a #.
http://somedns.com/index.php#jumphere

more info
Named anchors are no longer supported in HTML5 - use id instead in HTML5 pages.


text:
Q: Is there another way to restrict SSH user other than chroot jail? I need to create a safe environment for a foreign SSH user that has to have very restricted access to our server. That is:

*

*can only execute commands that are allowed

*can only use specific software that is allowed

*must not be allowed to see/modify/remove folders and files outside of his/her root filesystem under any circumstances

I have tried using chroot jail before using the jailkit tool for a smaller project that did not need as much customization and it worked fine, but this project is much bigger and requires a lot more customization in terms of allowed software and commands.
The requirements for the safe environment are:

*

*the ability to use basic commands such as ls, cd, grep etc.

*the ability to run dotnet scripts

*the ability to utilize running RabbitMQ broker (the broker is running OUTSIDE of the environment)

*the ability to utilize running PostgreSQL database (the database is running OUTSIDE of the environment)

I have heard about multistrap or debootstrap but I am not sure whether these are adequate tools for solving my problem.
The servers are running on Debian OS v. 9 and 10. All the required software is installed in the root filesystem and is running fine. All I need is for the restricted user to be able to utilize it without being able to damage/corrupt the root filesystem.
My questions are:

*

*Are there any other useful (better) tools that I have not mentioned that could solve my problem?

*Are there any useful guides for the software I have mentioned that could solve my problem?

A: In case somebody is facing the same problem. I solved it using Docker container with separate SSH server and all required software installed on it.


text:
Q: IDE for HTML / CSS / Java Script w/ Live View Port I have been searching around. This is perhaps more a nuance than anything. When I do jQuery or other UI work I like seeing my changes immediately. Adobe Dreamweavers live view port does this, not extremely well, but it does it. Kompozer has a view port but its not live and no JS or actions. Does anybody know of an IDE out there besides DW that has this feature? Linux is preferred but would like to know of anything.
As a note of interest I recently discovered Wakanda http://wakanda.org

A: I know this post is over a year old, but I thought I'd throw this out if you are interested.  Adobe is developing a product now that may fit what you are looking for.  If you have the creative cloud, there is a preview of the program.  It is called Edge Code in the creative cloud, but it is being developed as a standalone, open source, platform independent code editor as well.  I'm not sure why, but outside of the creative cloud, it is called Brackets.  It doesn't do a live view in the program itself, but it does automatically open the document in Chrome, and updates as you make changes.  The really interesting thing is that the program itself is written in html, css, and JS, so that it should be easy to customize to your liking.  It is currently in beta, and can be downloaded at

A: It might not be exactly what you are looking for (does not support javascript), but dabblet is a great tool for writing html+css and watching the preview live as-you-type in the browser.
dabblet live editor

A: I have been recently love struck by Sublime Text 2. After trying many IDE's it is the one that impresses me the most.
I was watching a tutorial by Paul Irish on Web Development workflows for 2013 (video only partially relevant), where he describes a plugin that he uses to avoid having to hit F5 to refresh the browser. Instead it is updated every time he saves a file.
Sublime Text 2 has been rising in popularity and my understanding is that it will work very well in Linux. The plugin is called LiveReload ($10).
It will require research, but is likely well worth it. Link

A: Stylizer is a nice app for CSS live edition.

A: I made my own open source coding playground called kodeWeave (which saves and retrieves your weaves as a Github Gist). It's available for Windows, Linux, Mac OS X, Android and Online (I also plan on releasing it for iOS and Windows Phone too).

Some other good coding playgrounds to tryout are CodePen, CSSDeck, Plunker, JSBin, jsFiddle, Liveweave.
There is also Brackets which is an open source project created by Adobe (It's basically the open source version of Edge Code). The nice thing about Brackets is it runs off it's own server locally on your device so if you're using a library like JSZip it works right away. In addition whenever you save a change made in a file in Brackets your app will reload in Chrome's Debugger (launched from Brackets) So debugging is very fast and easy, not to mention there's lots of plugins that are made to increase productivity. It's really tremendous!

There's also the Cloud9IDE.

I'm sure you already know this but the Chrome Developer Tools has this capability as well.


text:
Q: How can I specify the discrete values that I want to plot on the x-axis (matplotlib, boxplot)? I'm using boxplot in matplotlib (Python) to create box plots, I'm creating many graphs with different dates.  On the x axis the data is discrete.
The values on the x axis in seconds are 0.25, 0.5, 1, 2, 5 .... 28800.  These values were arbitrarily chosen (they are sampling periods).  On some graphs one or two values are missing because the data wasn't available. On these graphs the x axis resizes itself to spread out the other values.
I would like all the graphs to have the same values at the same place on the x axis (it doesn't matter if the x axis shows a value but there is no data plotted on the graph)
Could someone tell me if there is a way to specify the x axis values?  Or another way to keep the same values in the same place.
The relevant section of code is as follows:

for i, group in myDataframe.groupby("Date"):
    graphFilename = (basename+'_' + str(i) + '.png')
    plt.figure(graphFilename)
    group.boxplot(by=["SamplePeriod_seconds"], sym='g+') ## colour = 'blue'
    plt.grid(True)
    axes = plt.gca()
    axes.set_ylim([0,30000])
    plt.ylabel('Average distance (m)', fontsize =8)
    plt.xlabel('GPS sample interval (s)', fontsize=8)
    plt.tick_params(axis='x', which='major', labelsize=8)
    plt.tick_params(axis='y', which='major', labelsize=8)
    plt.xticks(rotation=90)
    plt.title(str(i) + ' - ' + 'Average distance travelled by cattle over 24  hour period', fontsize=9)
    plt.suptitle('')
    plt.savefig(graphFilename)
    plt.close()

Any help appreciated, I will continue googling... .thanks :)

A: if you try somehting like this:
plt.xticks(np.arange(x.min(), x.max(), 5))

where x is your array of x values, and 5 the steps you take along the axis.
Same applies for the y axis with yticks. Hope it helps! :)
EDIT:
I have removed the instances that i did not have, but the following code should give you a grid to plot onto:
import matplotlib.pyplot as plt
import numpy as np

plt.grid(True)
axes = plt.gca()
axes.set_ylim([0, 30000])
plt.ylabel('Average distance (m)', fontsize=8)
plt.xlabel('GPS sample interval (s)', fontsize=8)
plt.tick_params(axis='x', which='major', labelsize=8)
plt.tick_params(axis='y', which='major', labelsize=8)
plt.xticks(rotation=90)
plt.suptitle('')
my_xticks =[0.25,0.5,1,2,5,10,20,30,60,120,300,600,1200,1800,2400,3000,3600,7200,10800, 14400,18000,21600,25200,28800]
x = np.array(np.arange(0, len(my_xticks), 1))

plt.xticks(x, my_ticks)
plt.show()

Try plugging in your values on top of this :)

A: By default, boxplot simply plots the available data to successive positions on the axes. Missing data are left out, simply because the boxplot doesn't know they are missing. However, the positions of the boxes can be set manually using the positions argument.
The following example does this and thereby produces plots of equal extents even when values are missing.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

basename = __file__+"_plot"
Nd = 4 # four different dates
Ns = 5 # five second intervals
N = 80 # each 80 values
date = []
seconds = []
avgdist = []
# fill lists
for i in range(Nd):
    # for each date, select a random SamplePeriod to be not part of the dataframe
    w = np.random.randint(0,5)
    for j in range(Ns):
        if j!=w:
            av = np.random.poisson(1.36+j/10., N)*4000+1000
            avgdist.append(av)
            seconds.append([j]*N)
            date.append([i]*N)

date = np.array(date).flatten()
seconds = np.array(seconds).flatten()
avgdist = np.array(avgdist).flatten()
#put data into DataFrame
myDataframe = pd.DataFrame({"Date" : date, "SamplePeriod_seconds" : seconds, "avgdist" : avgdist})
# obtain a list of all possible Sampleperiods
globalunique = np.sort(myDataframe["SamplePeriod_seconds"].unique())

for i, group in myDataframe.groupby("Date"):

    graphFilename = (basename+'_' + str(i) + '.png')
    fig = plt.figure(graphFilename, figsize=(6,3))
    axes = fig.add_subplot(111)
    plt.grid(True)

    # omit the `dates` column
    dfgroup = group[["SamplePeriod_seconds", "avgdist"]]
    # obtain a list of Sampleperiods for this date
    unique = np.sort(dfgroup["SamplePeriod_seconds"].unique())
    # plot the boxes to the axes, one for each sample periods in dfgroup
    # set the boxes' positions to the values in unique
    dfgroup.boxplot(by=["SamplePeriod_seconds"], sym='g+', positions=unique, ax=axes)

    # set xticks to the unique positions, where boxes are
    axes.set_xticks(unique)
    # make sure all plots share the same extent.
    axes.set_xlim([-0.5,globalunique[-1]+0.5])
    axes.set_ylim([0,30000])

    plt.ylabel('Average distance (m)', fontsize =8)
    plt.xlabel('GPS sample interval (s)', fontsize=8)
    plt.tick_params(axis='x', which='major', labelsize=8)
    plt.tick_params(axis='y', which='major', labelsize=8)
    plt.xticks(rotation=90)
    plt.suptitle(str(i) + ' - ' + 'Average distance travelled by cattle over 24  hour period', fontsize=9)
    plt.title("")
    plt.savefig(graphFilename)
    plt.close()

This will still work, if the values in the SamplePeriod_seconds columnare non-equally spaced, but of course if they are extremely different, this will not produce nice results, because the bars will overlapp:

This however is not a problem with plotting itself. And for further help, one would need to know how you expect the graph to look like at the end.

A: Thank you everyone very much for the help, using your answers I got it working with the following code. (I realize it can probably be improved but happy that it works I can look at the data now :) )
valuesShouldPlot = ['0.25','0.5','1.0','2.0','5.0','10.0','20.0','30.0','60.0','120.0','300.0','600.0','1200.0','1800.0','2400.0','3000.0','3600.0','7200.0','10800.0','14400.0','18000.0','21600.0','25200.0','28800.0']

for xDate, group in myDataframe.groupby("Date"):            ## for each date

    graphFilename = (basename+'_' + str(xDate) + '.png')    ## make up a suitable filename for the graph

    plt.figure(graphFilename)

    group.boxplot(by=["SamplePeriod_seconds"], sym='g+', return_type='both')  ## create box plot, (boxplots are placed in default positions)

    ## get information on where the boxplots were placed by looking at the values on the x-axis
    axes = plt.gca()
    checkXticks= axes.get_xticks()
    numOfValuesPlotted =len(checkXticks)            ## check how many boxplots were actually plotted by counting the labels printed on the x-axis
    lengthValuesShouldPlot = len(valuesShouldPlot)  ## (check how many boxplots should have been created if no data was missing)

    if (numOfValuesPlotted < valuesShouldPlot): ## if number of values actually plotted is less than the maximum possible it means some values are missing
                                                ## if that occurs then want to move the plots across accordingly to leave gaps where the missing values should go

        labels = [item.get_text() for item in axes.get_xticklabels()]

        i=0                 ## counter to increment through the entire list of x values that should exist if no data was missing.
        j=0                 ## counter to increment through the list of x labels that were originally plotted (some labels may be missing, want to check what's missing)

        positionOfBoxesList =[] ## create a list which will eventually contain the positions on the x-axis where boxplots should be drawn

        while ( j < numOfValuesPlotted): ## look at each value in turn in the list of x-axis labels (on the graph plotted earlier)

            if (labels[j] == valuesShouldPlot[i]):  ## if the value on the x axis matches the value in the list of 'valuesShouldPlot'
                positionOfBoxesList.append(i)       ## then record that position as a suitable position to put a boxplot
                j = j+1
                i = i+1

            else :                                  ## if they don't match (there must be a value missing) skip the value and look at the next one

                print("\n******** missing value ************")
                print("Date:"),
                print(xDate),
                print(", Position:"),
                print(i),
                print(":"),
                print(valuesShouldPlot[i])
                i=i+1

        plt.close()     ## close the original plot (the one that didn't leave gaps for missing data)
        group.boxplot(by=["SamplePeriod_seconds"], sym='g+', return_type='both', positions=positionOfBoxesList) ## replot with boxes in correct positions

    ## format graph to make it look better
    plt.ylabel('Average distance (m)', fontsize =8)
    plt.xlabel('GPS sample interval (s)', fontsize=8)
    plt.tick_params(axis='x', which='major', labelsize=8)
    plt.tick_params(axis='y', which='major', labelsize=8)
    plt.xticks(rotation=90)
    plt.title(str(xDate) + ' - ' + 'Average distance travelled by cattle over 24 hour period', fontsize=9) ## put the title above the first subplot (ie. at the top of the page)
    plt.suptitle('')
    axes = plt.gca()
    axes.set_ylim([0,30000])

    ## save and close
    plt.savefig(graphFilename)
    plt.close()


text:
Q: Django unit testing: AttributeError: 'WSGIRequest' object has no attribute 'user' When running the tests i get outputted following error:
user = self.request.user
AttributeError: 'WSGIRequest' object has no attribute 'user'
I have tried switching from MIDDLEWARE to MIDDLEWARE_CLASSES and vice versa. Currently, I'm running Django 2.1.
Also, I have tried switching middleware positions and it didn't help.
settings.py
MIDDLEWARE = (
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.auth.middleware.SessionAuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # to serve static files
)

test_views.py
from django.test import (TestCase,
                     RequestFactory
                     )
from mixer.backend.django import mixer

from .. import views
from accounts.models import User

class TestHomeView(TestCase):
    def test_anonymous(self):
        req = RequestFactory().get("/")
        resp = views.HomeView.as_view()(req)
        self.assertEquals(resp.status_code, 200,
                          "Should be callable by anyone")

    def test_auth_user(self):
        req = RequestFactory().get("/")
        req.user = mixer.blend("accounts.User")
        resp = views.HomeView.as_view()(req)
        self.assertTrue("dashboard" in resp.url,
                        "Should redirect authenticated user to /dashboard/")

error output
user = self.request.user
AttributeError: 'WSGIRequest' object has no attribute 'user'

A: In the first test test_anonymous, you are not actually setting the user. As per documentation https://docs.djangoproject.com/en/2.1/topics/testing/advanced/#the-request-factory, the middleware are not executed if you use RequestFactory and you have to set the user explicitly. So if you want to test again AnonymousUser, you should set request.user = AnonymousUser(). If you don't do this, the request object will not have the user attribute, and thus the error.


text:
Q: SQL Server - SELECT TOP 5 rows for each FK I've got the following query, that looks up the TOP 5 Products matching the search. Each Product is associated with a Shop

SELECT     TOP 5 * FROM     Products
  p, Shops s WHERE    p.ShopId =
  s.ShopId AND    p.ProductName LIKE
  '%christmas%'

I need to extend this so that it returns me the TOP 5 Products in each Shop.
Could anyone let me know how the query could be modified to achieve this? - i.e. choose the TOP 5 products matching "%christmas%" in each shop (rather than the current which shows the TOP 5 products matching "%chrismas%" across all shops).

A: Try this:
select * from (
    select *, rn = row_number() over (partition by s.ShopId order by p.ProductName)
    from Products p, Shops s
    where p.ShopId = s.ShopId AND p.ProductName LIKE '%christmas%'
) a where a.rn <= 5

A: Here is a great solution I just found.
Select the TOP n Rows For Each Group
Arnie Rowland, March 13, 2008
There are Multiple Rows for Each Category, and there is a desire to
SELECT ONLY the TOP two (2) Rows per Category by Price.
For example, from the following data:
RowID    Category    ID  Description     Price
1    Pot     A1  Small Saucepan  21.50
2    Pot     A2  1 Qt Saucepan   29.95
3    Pot     A3  1.5 Qt Saucepan     33.95
4    Pot     A4  Double Boiler   39.50
5    Pot     A5  Stewpot     49.50
6    Pot     A6  Pressure Cooker     79.95
7    Pan     B1  8" Pie  6.95
8    Pan     B2  8" Sq Cake  7.50
9    Pan     B3  Bundt Cake  12.50
10   Pan     B4  9x12 Brownie    7.95
11   Bowl    C1  Lg Mixing   27.50
12   Bowl    C2  Sm Mixing   17.50
13   Tools   T1  14" Spatula     9.95

The desired output is:
RowID    Category    ID  Description     Price
11   Bowl    C1  Lg Mixing   27.50
12   Bowl    C2  Sm Mixing   17.50
9    Pan     B3  Bundt Cake  12.50
10   Pan     B4  9x12 Brownie    7.95
6    Pot     A6  Pressure Cooker     79.95
5    Pot     A5  Stewpot     49.50
13   Tools   T1  14" Spatula     9.95

There are several methods to accomplish the desired output.
This demonstration provides a Solution for SQL Server 2005 / SQL Server 2008 ,
and then a Solution for SQL Server 2000.
Create Sample Data for Both Solutions
-- Suppress data loading messages
SET NOCOUNT ON

-- Create Sample Data using a Table Varable
DECLARE @MyTable table
   (  RowID         int   IDENTITY,
      Category      varchar(5),
      [ID]          varchar(5),
      [Description] varchar(25),
      Price         decimal(10,2)
   )

-- Load Sample Data

INSERT INTO @MyTable VALUES ( 'Pot', 'A1', 'Small Saucepan', 21.50 )
INSERT INTO @MyTable VALUES ( 'Pot', 'A2', '1 Qt Saucepan', 29.95 )
INSERT INTO @MyTable VALUES ( 'Pot', 'A3', '1.5 Qt Saucepan', 33.95 )
INSERT INTO @MyTable VALUES ( 'Pot', 'A4', 'Double Boiler', 39.50 )
INSERT INTO @MyTable VALUES ( 'Pot', 'A5', 'Stewpot', 49.50 )
INSERT INTO @MyTable VALUES ( 'Pot', 'A6', 'Pressure Cooker', 79.95 )
INSERT INTO @MyTable VALUES ( 'Pan', 'B1', '8"" Pie', 6.95 )
INSERT INTO @MyTable VALUES ( 'Pan', 'B2', '8"" Sq Cake', 7.50 )
INSERT INTO @MyTable VALUES ( 'Pan', 'B3', 'Bundt Cake', 12.50 )
INSERT INTO @MyTable VALUES ( 'Pan', 'B4', '9x12 Brownie', 7.95 )
INSERT INTO @MyTable VALUES ( 'Bowl', 'C1', 'Lg Mixing', 27.50 )
INSERT INTO @MyTable VALUES ( 'Bowl', 'C2', 'Sm Mixing', 17.50 )
INSERT INTO @MyTable VALUES ( 'Tools', 'T1', '14"" Spatula', 9.95 )
Return to Top

SQL Server 2005 / SQL Server 2008 Solution
--Query to Retrieve Desired Data
SELECT
   RowID,
   Category,
   [ID],
   [Description],
   Price
FROM (SELECT
         ROW_NUMBER() OVER ( PARTITION BY Category ORDER BY Price DESC ) AS 'RowNumber',
         RowID,
         Category,
         [ID],
         [Description],
         Price
      FROM @MyTable
      ) dt
WHERE RowNumber <= 2

-- Results
RowID Category  ID Description     Price
11    Bowl      C1 Lg Mixing       27.50
12    Bowl      C2 Sm Mixing       17.50
9     Pan       B3 Bundt Cake      12.50
10    Pan       B4 9x12 Brownie    7.95
6     Pot       A6 Pressure Cooker 79.95
5     Pot       A5 Stewpot         49.50
13    Tools     T1 14" Spatula     9.95
Return to Top

SQL Server 2005 / SQL Server 2008 Solution using a CTE
(Added by: Jacob Sebastian)
-- Define a CTE with the name "dt"
;WITH dt AS (
     SELECT
         ROW_NUMBER() OVER ( PARTITION BY Category ORDER BY Price DESC ) AS 'RowNumber',
         RowID,
         Category,
         [ID],
         [Description],
         Price
      FROM @MyTable
)
-- and select the data from the CTE
SELECT
   RowID,
   Category,
   [ID],
   [Description],
   Price
FROM dt
WHERE RowNumber <= 2

-- Results
RowID Category  ID Description     Price
11    Bowl      C1 Lg Mixing       27.50
12    Bowl      C2 Sm Mixing       17.50
9     Pan       B3 Bundt Cake      12.50
10    Pan       B4 9x12 Brownie    7.95
6     Pot       A6 Pressure Cooker 79.95
5     Pot       A5 Stewpot         49.50
13    Tools     T1 14" Spatula     9.95
Return to Top

SQL 2000 Solution
--Query to Retrieve Desired Data
SELECT DISTINCT
   RowID,
   Category,
   [ID],
   [Description],
   Price
FROM @MyTable t1
WHERE RowID IN (SELECT TOP 2
                   RowID
                FROM @MyTable t2
                WHERE t2.Category = t1.Category
                ORDER BY Price DESC
               )
ORDER BY
   Category,
   Price DESC

-- Results
RowID Category  ID Description     Price
11    Bowl      C1 Lg Mixing       27.50
12    Bowl      C2 Sm Mixing       17.50
9     Pan       B3 Bundt Cake      12.50
10    Pan       B4 9x12 Brownie    7.95
6     Pot       A6 Pressure Cooker 79.95
5     Pot       A5 Stewpot         49.50
13    Tools     T1 14" Spatula     9.95

From: Select the TOP n Rows For Each Group

A: You're actually missing an ORDER BY to make the TOP meaningful, or any solution based on ROW_NUMBER which requires an ORDER BY.
SELECT
    *
FROM
    Shops s
CROSS APPLY (
    SELECT TOP 5
        *
    FROM
        Products p
    WHERE
        p.ShopId = s.ShopId AND p.ProductName LIKE '%christmas%'
    ORDER BY --added on edit
        ???
) X

A: Try this
SELECT DISTINCT
        A.Product_Group_code
        ,B.Sub_Product_Group_code
        ,A.Product_code
        ,A.Product_name
FROM dbo.A A
    LEFT JOIN dbo.B B
        ON A.Product_code = B.Product_code
WHERE  B.Product_code IN
                (
                    SELECT TOP 5 E.Product_code
                    FROM dbo.A D
                        LEFT JOIN dbo.B E
                            ON D.Product_code = E.Product_code
                    WHERE E.Sub_Product_Group_code = B.Sub_Product_Group_code
                )
        AND B.Sub_Product_Group_code IS NOT NULL
ORDER BY B.Sub_Product_Group_code,A.Product_name


text:
Q: Close all Responsive-accordion Tabs on small screen? (Foundation 6.3) So I'm having a really hard time figuring out why I can't collapse my accordion tabs using the Foundation 6.3 responsive tabs (https://foundation.zurb.com/sites/docs/responsive-accordion-tabs.html). I am trying to use their javascript reference to implment: (https://foundation.zurb.com/sites/docs/accordion.html#up).
This only seams to work for the accordion but not responsive accordions tabs.
Code Pen to demonstrate:https://codepen.io/jinch/pen/RQxQNG
//This code only collapses the "Reugular Accordion" and NOT a responsive Accordion?
$('#regulare-accordion').foundation('up', $('#regulare-accordion .accordion-content'));

//This code does not working for the the "Responsive Accordion Tab"?
$('#responsive-tab-accordion').foundation('up', $('#responsive-tab-accordion .accordion-content'));

Does anyone know of a reason or solution if using the responsive tabs? I need to close all on small screens if possible.

A: So far the responsive tab accordion component does not implement the methods of the used plugins.
You can either collapse them with CSS or clonse the methods of the accordion plugin and execute their code.
See https://github.com/zurb/foundation-sites/pull/10961 which is not yet implemented.


text:
Q: Olympiad Inequality AM-GM (easy) Prove that
$(1 + x + y)^2 + (1 + y + z)^2 + (1 + z + x)^2 ≤ 3(x + y + z)^2$, with equality if and only if $x = y = z = 1$ ($xyz \ge 1$) ($x,y,z$ positive reals)
This simplifies to
$x^2 + y^2 + z^2 + 4(xy + yz + zx) - 4(x + y + z) \geq 3$
I am looking for a proof using AM-GM preferably.

A: $$x^2 + y^2 + z^2 + 4(xy + yz + zx) - 4(x + y + z) =(x+y+z-2)^2-4+2(xy + yz + zx)$$
Now, by AM-GM:
$$x+y+z\ge3\sqrt[3]{xyz}\ge3\tag{1}$$
$$xy+yz+zx\ge3\sqrt[3]{x^2y^2z^2}\ge3\tag{2}$$
which pretty much settles the matter:
$$\underbrace{(x+y+z-2)^2}_{\ge1}-4+2(\;\underbrace{xy + yz + zx}_{\ge3}\;)\ge1-4+6=3$$


text:
Q: need explanation of postfix log send status someone sent me an email but I didn't receive it this is what was in their log.  Can't seem to find the documentation / explanation of the message
status=sent (250 2.7.0 Ok, discarded, id=24684-20 - BANNED: Index)

I did find the RFC explanation of the DSN=2.7.0 but can't figure the remainder of the message.

A: Sounds like whoever is responsible for managing your mailbox has chosen to accept responsibility for delivering a message and then not or not immediately delivered it, though the wording points to the former.
Ask your postmaster to explain - you won't find much more standardized information on this, because accepting then not delivering is non-standard behaviour, not typically appropriate for user mailboxes.
The standard expected behaviour is typically this:

When the receiver-SMTP accepts a piece of mail (by sending a "250 OK"
message in response to DATA), it is accepting responsibility for
delivering or relaying the message.  It must take this responsibility
seriously. -- rfc5321#section-6.1

In an ideal world, mail administrators who chose to deviate from this expectation will ensure that the status message clearly spells out the problem to help with remediation in case it affects more than just the intended mail flows. E.g. if the action was meant to deal with a runaway process on the sending side, it should say something like  "discarded message matching recently received message-id from IP XYZ".


text:
Q: Are there any plugin for vim to format javascript like formatting in Visual Studio? I like the formatting style of javascript in Visual Studio. ( Press Ctrl+K, Ctrl+D )
Are there any plugin which can do the same thing?

A: Some suggestions here: How can I format JS code in Vim?
jsbeautyfy is here: jsbeautify


text:
Q: Root partition encrypted with LUKS and Yubikey to Decrypt (problems with initramfs) I am working on a Raspberry Pi 3B v1.2, and I have already encrypted my root partition of the OS with LUKS.
The problem is that I would like to decrypt it or have the appropriate password to decrypt it using a Yubikey and use a challenge password at boot time.
I've being searching on Internet a lot about how to do it but everything I have found is that there is a bug that in new distros' systemd do not recognize the /etc/crypttab keyscript option (which refers to a bash script) that would create that challenge-password situation at a boot time and as a result, get the password to decrypt the root partition.
Every time I boot up the raspberry, appears one question that asks for the password (I think it is the askpass script that generates it, but I am not really sure about it) but the thing is that is not what it is expected to be. I don't know if the bug is fixed yet or not and if it is, I would really appreciate an answer on where is it and how to fix it.
By the way, I also try to use at kernel command line the cryptopts option to decrypt it with the script in bash I mentioned before, but nothing. The password needed is already saved in the yubikey and the yubikey is also configured to work on the challenge-response situation.
Also, every time I made a change on initramfs I use both sudo update-initramfs -u and sudo update-initramfs -c -k, which I know that these last one is not really recommended.
On the other hand, I've also read that there is a conflict between initramfs and the initramfs that systemd generates by itself. Something like, even if you specified to use the /etc/crypttab keyscript option it won't read it. By the way, I am using a Raspberry Pi OS, the one that offers their webpage: "Raspberry Pi OS with desktop and recommended software", debian version 11 (bullseye).


text:
Q: JSFiddle not downloading online images I am trying to download a dog image from an online source and insert it in the navigation logo.
The image link is - http://postimg.org/image/46j7vuv49/
And the JSFiddle link with no image is, http://jsfiddle.net/9zLj60bg/

Why isn't the dog image shown inside the header, when I run it?

A: Put the correct (direct) src path:
http://s12.postimg.org/5lkskkw7h/dog.png
An updated example:
http://jsfiddle.net/9zLj60bg/1/

instead of


text:
Q: ovirt iso upload not visible in webgui I recently set up an ovirt host with an self hosted engine. I use nfs shares as a storage backend (freenas). The setup went through perfectly and I was able to access the webgui. Everything seems to work fine, except the iso upload.
After uploading an iso (debian-8.4.0-amd64-netinst.iso) using the ovirt-iso-uploader I wanted to setup a VM. Sadly, I was not able to choose an iso to attach (Attach CD). Also the image tab under the iso storage shows "No items to display" even after pressing the refresh button.
After rebooting the engine, putting the iso domain to maintenance, detach, attach again, enable and upload an other image, I got the same result.

After searching a bit the logs, I could find the following in vdsm.log:
jsonrpc.Executor/1::INFO::2016-08-16 09:12:51,066::logUtils::51::dispatcher::(wrapper) Run and protect: getFileStats, Return response: {'fileStats': {u'debian-8.2.0-amd64-netinst.iso': {'status': 469, 'ctime': '1471271972.0', 'size': '258998272'}, u'debian-8.4.0-amd64-netinst.iso': {'status': 469, 'ctime': '1471263076.0', 'size': '258998272'}}}
This appears each time I try to list the images in the webgui.
I can also find the mounted path and files on the hypervisor:
-rw-r-----. 1 root root 258998272 Aug 15 14:11 /rhev/data-center/mnt/hades.gwitter.ch:_mnt_Master_iso/a93e3450-42e1-494b-a3bc-12756f16ed29/images/11111111-1111-1111-1111-111111111111/debian-8.4.0-amd64-netinst.iso
I really do not know, if I am hitting a bug or if I just missed something.
Additional infos:
I used centos7 as abase os and the package ovirt-engine-appliance-3.6-20160623.1.el7.centos.noarch to install the engine.
The iso domain was created during the hosted-egine setup on the same nfs host as the hosted-engine is placed.
oVirt Engine Version: 3.6.6.2-1.el7.centos

A: I just found my issue!The iso images folder needs to be owned by 36:36 (user vdsm group kvm).
Just use chown on your nfs server to adjust your permissions:
chown -R 36:36 a93e3450-42e1-494b-a3bc-12756f16ed29/images/11111111-1111-1111-1111-111111111111
Also newly uploaded images will be shown in the webgui now.


text:
Q: Store 2000 images I am implementing a web application which uses React as front end and Asp.net as backend. I have around 2000 images that has to be used in the web application. What will be best way to store these images ?

A: The best way is never store any media yourself.
Since serving any image/video content relies heavily on your network/bandwidth, it is not always stable and vulnerable to the slightest DDoS attack. Let alone that the security of your server may not be enough to protect your data.
I would highly recommend you to lookup some CDN, or Content Delivery Network, provider, such as AWS and GCD. You may also set up access right and serve criteria to better protect your data in these providers.
Reference:Why Use CDN's for Your Website & Image Hosting
Edit: I just noticed that you have tagged your question with azure-storage, which is also a great option for serving media over the internet.


text:
Q: Android Studio - How to handle error regarding xml files A few days ago, I started learning Kotlin language and i'm currently struggling with an issue with Android Studio. I have an XML file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <Folder title="title">
        <Album title="author">
            <Song title="title" author="author">lyrics</Song>
        </Album>
    </Folder>
</resources>

And when I try to run the project, I get the following error:
Can't determine type for tag '<resources>
    <Fold title="title">
        <Album title="author">
            <Song title="title" author="author">lyrics</Song>
        </Album>
    </Fold>
</resources>'

The xml file is in res/values/
Do you know a way to solve this issue? (and above all, what does it mean?)


text:
Q: eBay API Grant Application Access return URL contains empty 'ebaytkn' parameter I need some help. When I click the "I agree" button on the "Grant Application Access Page" it returns to the predefined return url just fine which is https://localhost/app/return.
My problem is the query string that eBay sends to that return url
?ebaytkn=&tknexp=1970-01-01+00%3A00%3A00&username=testuser_USERNAME

The parameter ebaytkn is completely empty and I cannot understand whats causing this issue at all.
Someone help.
Thanks,
Grady

A: If your eBay token return method is FetchToken (the recommended method), then this shouldn't matter. When you get to your accept page all you have to do is make a FetchToken call with the same Session Id that you used to generate the url. This is all documented in the eBay dev docs here.


text:
Q: Navigable clojure stacktraces with emacs, nREPL, and clojure.test I'm using emacs with nREPL via cider, and I've got a suite of clojure.test-based tests that I run to see when I've broken things (which is a lot as I'm fairly new to clojure.) I've tried two methods to run these tests - first by invoked the external "lein test" command and second by using clojure-test - and both work but neither gives completely satisfactory results. What I want is to be able to "navigate" the results of the tests, i.e. click on failures and stacktraces to go to the sources of failure.
I've poked around a bit with clojure-stacktrace-mode, but, while fairly impressive, that only seems to apply to stacktraces generated in the nREPL buffer.
So my question is: is there a way to get the behavior I want? Or maybe another way to get equivalent functionality? I feel like all the parts are there, but that I'm putting them together incorrectly.


text:
Q: Prevent Firefox from stealing FirefoxESR events? tl;dr: How to run both Firefox(79 as of now), and FirefoxESR(68) at the same time, and have FirefoxESR to be the default OS browser, where all external URL cliks get open at?
For a long time, at my work computer, I have used Firefox for work and another browser for personal links (previously Opera, lately Chrome).
Recently I've decided to use FirefoxESR for work, and Firefox for personal links.
All seem to work fine. I still have to binaries. Two icons (with different icons since ESR uses the old one). Profiles are completely separate. etc.
The only Problem is the that Firefox(latest) keeps stealing OS events from FirefoxESR, and I want ESR, i.e. my work browser, to be the default.
I want to keep FirefoxESR as my default OS browser. On the OSX prefences window I have already set ESR instead of latest:

If only one Firefox is open, it will get all the external URL clicks. If both are open (doesn't mater which was open last, or which had focus last) external URL clicks will open a new tab on latest Firefox (the non default one!).
Already disabled the "set this browser as the default" on both browsers, and hoped the OS setting would prevail. No. Still get links on the wrong Firefox.
Is there any hope for this?
Here's the running processes I see. They show distinct profiles and processes and originating binaries just fine.
$ ps aux | grep Firefox
USER               PID  %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND
user          12406   0.0  1.1  8871828 382536   ??  S     3:50PM   0:11.91 /Applications/FirefoxESR.app/Contents/MacOS/plugin-container.app/Contents/MacOS/plugin-container -childID 71 -isForBrowser -prefsLen 13552 -prefMapSize 185407 -sbStartup -sbAppPath /Applications/FirefoxESR.app -sbLevel 3 -sbAllowAudio -sbAllowWindowServer -parentBuildID 20200720181548 -greomni /Applications/FirefoxESR.app/Contents/Resources/omni.ja -appomni /Applications/FirefoxESR.app/Contents/Resources/browser/omni.ja -appdir /Applications/FirefoxESR.app/Contents/Resources/browser -profile /Users/user/Library/Application Support/Firefox/Profiles/b0s2tzpe.default-esr 1513 gecko-crash-server-pipe.1513 org.mozilla.machname.550427022 tab
user          12400   0.0  0.9  8765320 295044   ??  S     3:50PM   0:23.96 /Applications/FirefoxESR.app/Contents/MacOS/plugin-container.app/Contents/MacOS/plugin-container -childID 70 -isForBrowser -prefsLen 13552 -prefMapSize 185407 -sbStartup -sbAppPath /Applications/FirefoxESR.app -sbLevel 3 -sbAllowAudio -sbAllowWindowServer -parentBuildID 20200720181548 -greomni /Applications/FirefoxESR.app/Contents/Resources/omni.ja -appomni /Applications/FirefoxESR.app/Contents/Resources/browser/omni.ja -appdir /Applications/FirefoxESR.app/Contents/Resources/browser -profile /Users/user/Library/Application Support/Firefox/Profiles/b0s2tzpe.default-esr 1513 gecko-crash-server-pipe.1513 org.mozilla.machname.478282958 tab
user          12320   0.0  0.2  8472860  57360   ??  S     3:42PM   0:00.38 /Applications/Firefox.app/Contents/MacOS/plugin-container.app/Contents/MacOS/plugin-container -childID 15 -isForBrowser -prefsLen 8089 -prefMapSize 224843 -sbStartup -sbAppPath /Applications/Firefox.app -sbLevel 3 -sbAllowAudio -sbAllowWindowServer -parentBuildID 20200720193547 -appdir /Applications/Firefox.app/Contents/Resources/browser -profile /Users/user/Library/Application Support/Firefox/Profiles/027dcedw.default-release 11340 gecko-crash-server-pipe.11340 org.mozilla.machname.1180584643 tab
user          12309   0.0  0.3  8545064 105792   ??  S     3:41PM   0:01.16 /Applications/Firefox.app/Contents/MacOS/plugin-container.app/Contents/MacOS/plugin-container -childID 14 -isForBrowser -prefsLen 8114 -prefMapSize 224843 -sbStartup -sbAppPath /Applications/Firefox.app -sbLevel 3 -sbAllowAudio -sbAllowWindowServer -parentBuildID 20200720193547 -appdir /Applications/Firefox.app/Contents/Resources/browser -profile /Users/user/Library/Application Support/Firefox/Profiles/027dcedw.default-release 11340 gecko-crash-server-pipe.11340 org.mozilla.machname.1651746662 tab

--
edit: trying to understand OSX launchservice
$ osascript -e 'id of app "Firefox"'
org.mozilla.firefox
$ osascript -e 'id of app "FirefoxESR"'
org.mozilla.firefox

Guess despite the OS seeing two distinct apps on the default browser dialog, it then proceeds to threat both as the same because they share the same ID.
I am assuming the nonESR version is picked because launchservice decides by picking the first on the list?

A: This doesn't have to do with firefox. The OS is sending the event to the wrong instance. i've opened a question centered on OSX OSX: control which of two applications with same id will be selected by launchservice?


text:
Q: apt update hangs - error message in Ubuntu 16.04 I cannot update Ubuntu 16.04 due to the following error:
Could not get lock /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/

How should I proceed in trying to update?


text:
Q: Programmatically edit EdgeCollider2D vertices Is there a way to programmatically edit the vertices of EdgeCollider2D in Unity2D? Like programmatically edit each vertex and it's location.

A: Yes, you can edit them using EdgeCollider2D.points array.


text:
Q: Custom li value sort I found the following script to start a custom sort, but it works with "category-class" and not with li value.
I was unsuccessful to modify this script, maybe someone can help me?
The script:

download

video

product

any

(function($) {

$.fn.reOrder = function(array) {
  return this.each(function() {

    if (array) {
      for(var i=0; i < array.length; i++)
        array[i] = $('li[category="' + array[i] + '"]');

      $(this).empty();

      for(var i=0; i < array.length; i++)
        $(this).append(array[i]);
    }
  });
}
})(jQuery);

var category_sort_order = ['any', 'product', 'download', 'video'];
$('#input').reOrder(category_sort_order);

What I need (no category, just li value):

download

video

product

any

Note:
Its important to me that I can indicate the sort values (no alphabet sort).

A: for html you mentioned

download

video

product

any

you can simply update your script to select li based on it's html instead of category like shown below
(function($) {

$.fn.reOrder = function(array) {
  return this.each(function() {

    if (array) {
      for(var i=0; i < array.length; i++)
        array[i] = $('li:contains('+array[i]+')');

      $(this).empty();

      for(var i=0; i < array.length; i++)
        $(this).append(array[i]);
    }
  });
}
})(jQuery);

var category_sort_order = ['any','product', 'download', 'video'];
$('#input').reOrder(category_sort_order);

that will work


text:
Q: How to solve flavor "normal" has no flavor dimension in Android studio 3.0? While I was opening an google project called iosched, the gradle building was failed and kept warning me something about flavor. I tried to solve it follow some suggestions online but it turned out to warn me this. What should I do?? My Android studio version is 3.0 btw.

A: In the build.gradle of app module you must define flavorDimensions which is from Android studio 3.0. so do something like :
android {
    flavorDimensions "example"
}
and inside ProductFlavors on same module use it as:
productFlavors {
a {
dimension "example"
}
b{dimension "example"
}
here a and b are the types of product flavors.
For more information refer to this link Configure Build Variants

A: I got this error (and several others) after importing a project from version control via Bitbucket hyperlink.
Once imported, close the project and re-import it using File > New > Import Project. After that  everything built correctly.
(My productFlavors were already defined properly)
Meta:
Android Studio 3.5
Build #AI-191.8026.42.35.5791312, built on August 8, 2019
JRE: 1.8.0_202-release-1483-b49-5587405 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Gradle 3.4.0


text:
Q: Python Receive HTTP file via POST I'm trying to create a Python web server that can receive files. So someone can vist the website, click the upload button on the form, then the file will be sent to the server and stored locally on the server.
Here is the contents of index.html
<form enctype="multipart/form-data" action="" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="8000000" />
    <input name="uploadedfile" type="file" />

    <input type="submit" value="Upload File" />
</form>

Contents of Server.py
import socket

class server():
    def __init__(self):
        self.host_ip = socket.gethostbyname(socket.gethostname())
        self.host_port = 81
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.data_recv_size = 1024

    def get_data(self, conn):
        """ gets the data from client """
        data = b""
        while b"\r\n\r\n" not in data:
            data += conn.recv(self.data_recv_size)
        return data

    def server(self):
        """ main method starts the server """
        print(f"[+] Server started listening on port {self.host_port}!")
        print(f"[+] Server Ip: {self.host_ip}")
        self.s.bind((self.host_ip, self.host_port))
        self.s.listen()

        while True:
            conn, addr = self.s.accept()
            with conn:
                data = self.get_data(conn)

                # GET request
                if data[0:5] == b"GET /":
                    index = open("index.html", "rb").read()
                    conn.sendall(b"HTTP/1.0 200 OK\nContent-Type: text/html\n\n" + index)
                    print("[+] Responded to GET request")

                # POST request
                elif data[0:4] == b"POST":
                    with open("output.txt", "ab") as file:
                        file.write(data)
                        print(f"{len(data)} bytes received from post!")
                        conn.sendall(b"HTTP/1.0 200 OK\r\nContent-Type: text/html")

s = server()
s.server()

The GET part of the server works correctly, when I visit the website the index.html file is display in my web browser and I can see the file upload form.
EDIT: I updated the form to max file size 8 million name="MAX_FILE_SIZE" value="8000000", The POST response the server receives is much bigger (I updated it below), but it still doesn't look like it contains the file contents.
POST / HTTP/1.1
Host: 169.254.126.211:81
Connection: keep-alive
Content-Length: 2857323
Cache-Control: max-age=0
Origin: http://169.254.126.211:81
Upgrade-Insecure-Requests: 1
DNT: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryjbf7KaGShYBQ75wT
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://169.254.126.211:81/
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,ru;q=0.7

------WebKitFormBoundaryjbf7KaGShYBQ75wT
Content-Disposition: form-data; name="MAX_FILE_SIZE"

8000000
------WebKitFormBoundaryjbf7KaGShYBQ75wT
Content-Disposition: form-data; name="uploadedfile"; filename="IMG_20210131_165637.jpg"
Content-Type: image/jpeg

ÿØÿá"ÙExif  MM *         @
°         ö       ¶       ¾POST / HTTP/1.1
Host: 169.254.126.211:81
Connection: keep-alive
Content-Length: 2857323
Cache-Control: max-age=0
Origin: http://169.254.126.211:81
Upgrade-Insecure-Requests: 1
DNT: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryjbf7KaGShYBQ75wT
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://169.254.126.211:81/
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,ru;q=0.7

Screenshot showing the output in Python IDLE when I run the script.

Edit: It only says 1024 bytes received from post!, so it looks like the full file isn't being sent.
How do I sent a file from a web browser via POST, and receive the file on the server?

A: In get_data() you check while b"\r\n\r\n" not in data: so you read only head with headers but not body with posted file.
You have to get value from header Content-Length and use it to read rest of data - body.
But your recv(1024) may already read some part of body and it can make problem. You should read byte-after-byte (recv(1)) until you get b"\r\n\r\n" and later use Content-Length to read rest of data.

Minimal working code with HTML in code so everyone can simply copy and run it.
import socket

class Server():  # PEP8: `CamelCaseName` for classes

    def __init__(self):
        #self.host_ip = socket.gethostbyname(socket.gethostname())
        self.host_ip = '0.0.0.0'  # universal IP for server - to connect from other computers
        self.host_port = 8000  # 81 was restricted on my computer

        #self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s = socket.socket()  # default values are `socket.AF_INET, socket.SOCK_STREAM`
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # solution for '[Error 89] Address already in use'. Use before bind()

        self.data_recv_size = 1024

    def get_head(self, conn):
        """ gets headers from client """
        data = b""
        while not data.endswith(b"\r\n\r\n"):
            data += conn.recv(1)
        return data

    def get_body(self, conn, size):
        """ gets the data from client """
        data = b""
        while b"\r\n\r\n" not in data:
            data += conn.recv(self.data_recv_size)
        return data

    def run(self):
        """ main method starts the server """
        print(f"[+] Server: http://{self.host_ip}:{self.host_port}")
        self.s.bind((self.host_ip, self.host_port))
        self.s.listen()
        try:
            while True:
                conn, addr = self.s.accept()
                with conn:
                    head = self.get_head(conn)

                    # todo: parse headers
                    lines = head.strip().splitlines()
                    request = lines[0]
                    headers = lines[1:]
                    headers = list(line.split(b': ') for line in headers)
                    #print(headers)
                    headers = dict(headers)
                    for key, value in headers.items():
                        print(f'{key.decode()}: {value.decode()}')

                    # GET request
                    if request[0:5] == b"GET /":
                        #html = open("index.html", "rb").read()

                        html = '''<form enctype="multipart/form-data" action="" method="POST">
                                    <input type="hidden" name="MAX_FILE_SIZE" value="8000000" />
                                    <input name="uploadedfile" type="file" />

                                    <input type="submit" value="Upload File" />
                                </form>'''

                        conn.sendall(b"HTTP/1.0 200 OK\nContent-Type: text/html\n\n" + html.encode())
                        print("[+] Responded to GET request")

                    # POST request
                    elif request[0:4] == b"POST":
                        size = int(headers[b'Content-Length'].decode())
                        body = self.get_body(conn, size)
                        with open("output.txt", "ab") as file:
                            file.write(head)
                            file.write(body)
                        total_size = len(head)+len(body)
                        print(f"{total_size} bytes received from POST")
                        html = f"OK: {total_size} bytes"
                        conn.sendall(b"HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" + html.encode())
                        print("[+] Responded to POST request")

        except KeyboardInterrupt:
            print("[+] Stopped by Ctrl+C")
        finally:
            self.s.close()

# --- main ---

s = Server()
s.run()

BTW:
I display http://0.0.0.0:8000 in console because in some consoles you can click on URL to open it in browser.
I use universal address 0.0.0.0 so it can recive connections from all NIC (Network Internet Controller/Card?) which means LAN cable, WiFi and other connections at the same time.
PEP 8 -- Style Guide for Python Code

EDIT:
It can be much simpler with Flask
I use form for uploading 3 files at once.
import os
from flask import Flask, request

# create folder for uploaded data
FOLDER = 'uploaded'
os.makedirs(FOLDER, exist_ok=True)

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():

    if request.method == 'GET':
        return '''<form enctype="multipart/form-data" action="" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="8000000" />
    <input name="uploadedfile1" type="file" />

    <input name="uploadedfile2" type="file" />

    <input name="uploadedfile3" type="file" />

    <input type="submit" value="Upload File" />
</form>'''

    if request.method == 'POST':
        for field, data in request.files.items():
            print('field:', field)
            print('filename:', data.filename)
            if data.filename:
                data.save(os.path.join(FOLDER, data.filename))
        return "OK"

if __name__ == '__main__':
    app.run(port=80)

A: With the help of furas answer, trial an error, and lots of research online. I was able to create a web server that works. I'm going to post the completed script here, as it will be of use to other people in the future who stumbles across this question, and are also trying to create a file upload server as well.
import socket, re

class Server():
    def __init__(self):
        self.host_ip = "localhost"
        self.host_port = 81
        self.s = socket.socket()
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.data_recv_size = 1024
        self.form = b"""<form enctype="multipart/form-data" action="" method="POST">
                <input type="hidden" name="MAX_FILE_SIZE" value="8000000" />
                <input name="uploadedfile" type="file" />

                <input type="submit" value="Upload File" />
            </form>"""

    def get_data(self, conn):
        data = b""
        while True:
            chunk = conn.recv(self.data_recv_size)
            if len(chunk) < self.data_recv_size:
                return data + chunk
            else:
                data += chunk

    def save_file(self, packet):
        name = re.compile(b'name="uploadedfile"; filename="(.+)"').search(packet).group(1)
        data = re.compile(b"WebKitFormBoundary((\n|.)*)Content-Type.+\n.+?\n((\n|.)*)([\-]+WebKitFormBoundary)?")
        with open(name, "wb") as file:
            file.write(data.search(packet).group(3))

    def run(self):
        print(f"[+] Server: http://{self.host_ip}:{self.host_port}")
        self.s.bind((self.host_ip, self.host_port))
        self.s.listen()

        while True:
            conn,addr = self.s.accept()
            request = self.get_data(conn)

            # GET request
            if request[0:5] == b"GET /":
                conn.sendall(b"HTTP/1.0 200 OK\nContent-Type: text/html\n\n"+self.form)
                print("[+] Responded to GET request!")

            # POST request
            elif request[0:4] == b"POST":
                packet = self.get_data(conn)
                self.save_file(packet)
                ok_reponse = b"Successfully upload %d bytes to the server!" % len(packet)
                conn.sendall(b"HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n"+ok_reponse)
                print(f"[+] {len(packet)} bytes received from POST!")

s = Server()
s.run()

Here is a screenshot showing the script running

Here is a screenshot of the directory with the image file saved, after it was uploaded via the server.

So it all seems to be working OK now.


text:
Q: magento 2 remove leading zeros from order number everywhere In magento 2 i want to remove leading zeros from the order numbers.
Order Number looks like:  0000012351
i want order number to look like 12351 without any leading zero.
How can i modify it?


text:
Q: Curly brackets catching many lines in tables I have the following table
\begin{center}
\begin{tabular}{ |p{3cm}||p{3cm}|p{3cm}|
\hline
 \multicolumn{3}{|c|}{Bosonic spectrum of type IIA and IIB theories} \\
 \hline
 Sector& IIA & IIB\\
 \hline
  NS-NS  & graviton  $g_{\mu \nu}$   & graviton $g_{\mu \nu}$ \\
NS-NS &  dilaton $\phi$  & dilaton $\phi$\\ \hline
R-R & 1-form  $C_1$& (axion)0-form $C_0$\\
R-R   &3-form $C_3$ & 2-form $C_2$ \\
R-R &    & (self-dual) 4-form $C_4$\\
 \hline
\end{tabular}
\end{center}

which I do not know how to make it appear (how do I Latex in this forum?). I would like to do something so that the first column which has these NS-NS and R-R entries to be such that there is only one entry since the first three columns correspond all to NS-NS and the last three all correspond to R-$. That is I would like the first entry of the first column for the first three lines to be something like R{ (so the curly bracket to include all first three columns) and similarly for the last three ones.
How could I do this?

A: Something like this?

\documentclass{article}

\usepackage{multirow}
\usepackage{array}
\usepackage{mathtools}

\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}p{#1}}

\begin{document}
\begin{center}
\begin{tabular}{ |R{2cm}||p{3cm}|p{3cm}|}
\hline
\multicolumn{3}{|c|}{Bosonic spectrum of type IIA and IIB theories} \\
\hline
Sector& IIA & IIB\\
\hline
\multirow{2}{*}{NS-NS $\begin{dcases*} \\ \\ \end{dcases*}$}  & graviton  $g_{\mu \nu}$   & graviton $g_{\mu \nu}$ \\
&  dilaton $\phi$  & dilaton $\phi$\\[1.5ex]
\hline
\multirow{4}{*}{R-R $\begin{dcases} \\ \\ \\ \end{dcases}$} & 1-form  $C_1$& (axion)0-form $C_0$\\
&3-form $C_3$ & 2-form $C_2$ \\
&    & (self-dual) 4-form $C_4$\\
 \hline
\end{tabular}
\end{center}

\end{document}

A: Here is a solution with {NiceTabular} of nicematrix.
\documentclass{article}

\usepackage{nicematrix}

\begin{document}

\begin{center}
\begin{NiceTabular}{ |p{3cm}||p{3cm}|p{3cm}|}
\hline
 \Block{1-3}{Bosonic spectrum of type IIA and IIB theories} \\
 \hline
 Sector& IIA & IIB\\
 \hline
\Block{2-1}{NS-NS}  & graviton  $g_{\mu \nu}$   & graviton $g_{\mu \nu}$ \\
         &  dilaton $\phi$  & dilaton $\phi$\\ \hline
\Block{3-1}{R-R}& 1-form  $C_1$& (axion)0-form $C_0$\\
& 3-form $C_3$ & 2-form $C_2$ \\
&               & (self-dual) 4-form $C_4$\\
 \hline
\CodeAfter
   \SubMatrix{\{}{3-2}{4-2}{.}[xshift=8mm,extra-height=-1.5mm]
   \SubMatrix{\{}{5-2}{7-2}{.}[xshift=8mm,extra-height=-1mm]
\end{NiceTabular}
\end{center}

\end{document}

You need several compilations (because nicematrix uses PGF/Tikz under the hood).


text:
Q: custom substr php With the following string:
$string='some text <photo id="id#" /> some text';

Make a substr that if the end of its string is a part of
<photo id="id#" />

then apply an extra chunk to complete
"<photo id="id#" />"

Example:
substr($string,0,15);

result is:
some text <phot

If this happens I need to end up with:
some text <photo id="id#" />

He, can't find the way of doing this. by the way id# is a random numeric value whose length won't exceed 3 chars. If regex is necessary to come up with a function.

A: See this:-
output:-

<?php

$str= 'some text <photo id="#xx"/> some test';
$parts = preg_split('~(</?[\w][^>]*>)~', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($parts);
echo htmlentities($parts[1]);

$str_new= 'some text <photo id="#xx"></photo> some test';
$parts_new = preg_split('~(</?[\w][^>]*>)~', $str_new, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($parts_new);
echo htmlentities($parts_new[1]);
echo htmlentities($parts_new[2]);

?>

A: No need to use regex, just use the PHP string functions:
$string = 'some text <photo id="id#" /> some text';
$newString = substr($string, 0, strpos($string, '>') + 1);


text:
Q: Pairs of cards from 1,2,...,n arranged according to rules on pairwise separation - is it possible for various n?
A deck of $2n+1$ cards consists of a joker and, for each number between $1$ and $n$ inclusive, two cards marked with that number. The $2n + 1$ cards are placed in a row, with the joker in the middle. For each $k$ with $1\le  k\le n$, the two cards numbered $k$ have exactly $k−1$ cards between them. Determine all the values of $n$ not exceeding 10 for which this arrangement is possible. For which values of $n$ is it impossible?

The problem is from the 1992 Canada National Olympiad. I can show by parity arguments that the arrangement is impossible for some $n$. This approach is inconclusive for other values, though.

Numbering positions from $0$ at the left, the joker occupies position $n$ and the rightmost card occupies position $2n$.
Then the sum of positions is given by:
$$S_n = -n + \sum_{k=0}^{2n}{k} = -n + \frac{2n(2n+1)}{2} = 2n^2 \tag{1}$$
Now let the leftmost card of each pair of $k$ be at position $\alpha_k$. Then the rightmost card in the pair is at $\alpha_k + k$, so we have:
$$S_n = \sum_{k=1}^{n}{(2\alpha_k + k)} = \frac{n(n+1)}{2}+2\sum_{k=1}^{n}{\alpha_k}$$
Letting the sum of $\alpha$ values be $A$, then we have:
$$S_n = 2A + \frac{n(n+1)}{2} \tag{2}$$
By (1), $S_n$ is even for all $n$, and by (2) $S_n$ is even only if and only if  the second term is even, so we deduce that the arrangement of cards is only possible if $\frac{n(n+1)}{2}$ is even.
This immediately rules out $n=1,2,5,6,9,10$.
For $n=3$, a possible arrangement is:
$$\begin{array}{ccccccc} 1&1&3&\bigstar&2&3&2 \end{array}$$
while for $n=4$, a possible arrangement is:
$$\begin{array}{ccc} 1&1&3&4&\bigstar&3&2&4&2 \end{array}$$
I am not sure how to resolve the question of whether there is a viable arrangement for $n=7$ or for $n=8$.

A: Possible arrangement for $n=7$:$$\begin{array}{ccc} 1&1&2&5&2&6&7&\bigstar&5&3&4&6&3&7&4 \end{array}$$
Possible arrangement for $n=8$:$$\begin{array}{ccc} 1&1&2&4&2&7&8&4&\bigstar&6&3&5&7&3&8&6&5 \end{array}$$


text:
Q: Study convergence in distribution of $T_{n}(x)=\frac{|x|^{\frac{1}{n}-1}}{2n}$ I have a problems in distribution theory but I don't know if my step correct!
Study the convergent of $T_{n}$ in $D'(\mathbb{R})$
Where :
$$T_{n}(x)=\frac{|x|^{\frac{1}{n}-1}}{2n}$$
$$k\in \mathbb{N}~,~ x\in \mathbb{R^{*}}$$
My try :
Its clearly that : $T_{n}\in L^{1}_{\text{loc}}(\mathbb{R^{*}})$ so :
$\langle T_{n} ,\varphi \rangle =\int_{\mathbb{R}}T_{n}(x)\varphi(x)dx$
And we have $\varphi\in D'(\mathbb{R})\implies \exists a>0 ~\text{supp}\varphi \subset [a,a]$ so :
$\langle T_{n} ,\varphi \rangle =\int_{|x|≤a}T_{n}(x)\varphi(x)dx≤\frac{a^{\frac{1}{n}-1}}{2n}\int_{|x|≤a}\varphi (x)dx$ and this go to $0$ because $\int_{|x|≤a}\varphi (x)dx<\infty $
Also here we say convergence in
$D'(\mathbb{R^{*}}) ~\text{or} ~D'(\mathbb{R})$ ? Also $\varphi \in D(\mathbb{R}) ~\text{or}~D(\mathbb{R^{*}})$
In finally thank you to every teachers see my problems
I'm greatful

Thanks!

A: I get that $T_n \to \delta$:
$$
\left< T_{n}, \varphi \right>
= \int_{-\infty}^{\infty} \frac{|x|^{\frac{1}{n}-1}}{2n} \, \varphi(x) \, dx
= \int_{0}^{\infty} \frac{x^{\frac{1}{n}-1}}{2n} \, (\varphi(x) + \varphi(-x)) \, dx
= \{ x = y^n \} \\
= \int_{0}^{\infty} \frac{\varphi(y^n) + \varphi(-y^n)}{2} \, dy
= \int_{0}^{1} \frac{\varphi(y^n) + \varphi(-y^n)}{2} \, dy
+ \int_{1}^{\infty} \frac{\varphi(y^n) + \varphi(-y^n)}{2} \, dy \\
\to \int_{0}^{1} \varphi(0) \, dy
+ \int_{1}^{\infty} \underbrace{\varphi(\infty)}_{=0} \, dy
= \varphi(0)
= \left< \delta, \varphi \right>
.
$$
This is a bit sloppy. Some more work might be needed to justify the limits better.


text:
Q: Opening IDLE from Terminal I'm new to programming and to be more specific, Python. I was going through the installation process from Robert Sedgewick's Introduction to Programming in Python website until right before the section "Downloading and Installing the Booksite Library". My problem occurred with:

In the Terminal window issue the command idleX.Y (for example, idle2.7). If an IDLE window appears, then you have installed IDLE properly. Close the IDLE window.

As I was installing Python 2.7, I attempted to use the command idle2.7, but I received the following response. As far as I can tell, I followed all of the directions provided by Mr. Sedgewick's website and I have already verified that Python was being installed as version 2.7.10. After looking for answers online, I found a similar one here on Stack Overflow. Unfortunately, the potential solutions listed for that question didn't help resolve my issue. At this point, I should mention that I am trying this on a MacBook Pro (2015 model) running the latest version of OS X (El Capitan).
Thanks for your help!

A: For 2.7, the following, where 'python' is 'whatever string needed to start 2.7' (perhaps 'python', perhaps 'python2'), should work on any OS:
python -m idlelib.idle

For 3.x, .idle can be omitted.  In *nix (but not on Windows), python should probably be replaced by python3.  The usability of shortcut scripts such as 'idle2.7' depends on the script being both present and on the executable path.  That, in turn, depends on the specific installers.  In the last year, Python core developers have veered away from the use of a multiplicity of short-cut scripts, which are not dependable, toward python -m module, which is dependable as long as one can start a particular version of Python. On Windows and, I believe on Mac, after using the PSF installers, python can be replaced by py -x or py -x.y if one has multiple python installations.


text:
Q: Запрос копирования данных с условием Есть таблицы content и contentvalues. Необходимо скопировать данные из одной таблицы в другую. БД одна, но столбцы разные.
Нужно из таблицы content, строки, ID которых равны content_id в таблице contentvalues, скопировать поле content.longtitle в поле contentvalues.value. Изменять только строки, tmplvarid которых равен 13.
Делал так, но выдает ошибку:
update contentvalues, content
set contentvalues.value=content.longtitle
where contentvalues.tmplvarid=13;

A: merge into contentvalues cval using content src
on (cval.content_id = src.id)
when matched then
    update set cval.value = src.longtitle
    where cval.tmplvarid = 13
;

Можете добавить - when not matched then insert ..., если подозреваете, что строчкa ещё не существует.


text:
Q: ViewDidAppear/ViewWillAppear not being called I have a ViewController that adds to other subviews which have subclassed uiviewControllers
so Its like this:
mainViewController
       |
  v---------v
subVC1   subVC2

And neither subVC1 or subVC2 have the viewDidAppear/viewWillAppear fired on them?
The main view controller is creating in the app delegate and it view added there as well to the window.
Here is an xcode project to show my problem: http://www.qfpost.com/download.do?get=92f03538907e72665ea794d98ff8392b

A: I had a look at your code.
So the problem is that viewWillAppear/viewDidAppear get called when the view is added to the Window, not to one of it's subview.
You might want to use viewDidLoad for that.

A: Firstly, are you sure you actually need to be doing what you're doing with this hierarchy of UIViewControllers? Why can't your MainViewController deal with the views that your subVC1 and subVC2 are responsible for?
Second, your viewWillAppear/viewDidAppear will get called when YOU write the code to call them from your MainViewController. Without knowing anything else about your design it's not really possible to advise on when you should call them, but if the sub-controllers' views are to be always visible when the 'main' view is visible, then it probably makes sense to call them from the viewWillAppear/viewDidAppear methods of your mainViewController.


text:
Q: How do I access logged in user in prisma and apollo graphql? Here is my code. I'm trying to learn graphql and prisma, and I want to access the user that is logged in, and display their name in the header. However I'm having trouble accessing the data. It says it's undefined, as you can see in the details below. I'm also not sure how to test this in the playground, or if I should use the auth token for this.
schema.graphql:
type Query {
  info: String!
  userlist: [User!]!
  me: User
}

type Mutation {
  signup(email: String!, password: String!, name: String!): AuthPayload
  login(email: String!, password: String!): AuthPayload
}

type AuthPayload {
  token: String
  user: User
}

type User {
  id: ID!
  name: String!
  email: String!
}

Query.js:
const { getUserId } = require("../utils");

function userlist(parent, args, context) {
  return context.prisma.user.findMany();
}

function me(parent, args, context) {
  const id = getUserId(context);
  return context.prisma.user({ id });
}

module.exports = {
  userlist,
  me,
};

Header.js:
import React from "react";
import { Link, useNavigate } from "react-router-dom";
import { AUTH_TOKEN } from "../constants";
import { useQuery, gql } from "@apollo/client";

const ME_QUERY = gql`
  {
    me {
      id
      name
    }
  }
`;

const Header = () => {
  const navigate = useNavigate();
  //const { data } = useQuery(ME_QUERY);
  console.log(data);
  const authToken = localStorage.getItem(AUTH_TOKEN);
  return (

        <Link to="/" className="no-underline black">

Example Site

        </Link>
        <Link to="/" className="ml1 no-underline black">
          home
        </Link>
        {/*
Hello {data && <>{data.me}</>}
 */}

        {authToken ? (

 {
              localStorage.removeItem(AUTH_TOKEN);
              navigate(`/`);
              window.location.reload();
            }}
          >
            logout

        ) : (
          <Link to="/login" className="ml1 no-underline black">
            login
          </Link>
        )}

  );
};

export default Header;

console.log(data); gives me undefined. I'm a total beginner so hopefully this is a quick solution. I can give any more background as requested. Thank you.


text:
Q: How can an EJB parallelize a long, CPU intensive process? The application has a CPU intensive long process that currently runs on one server (an EJB method) serially when the client requests it.
It's theoretically possible (from a conceptual point of view) to split that process in N chunks and execute them in parallel, as long as the output of all parallel jobs can be collected and joined together before  sending it back to the client that initiated the process. I'd like to use this parallelization to optimize performance.
How can I implement this parallelization with EJBs? I know that we should not create threads in a EJB method. Instead, we should publish messages (one per job) to be consumed by message driven beans (MDBs). But then it would not be a synchronous call anymore. And being synchronous seems to be a requirement in this case since I need to collect the output of all jobs before sending it back to the client.
Is there a solution for this?

A: This particular question has come up on multiple occasions and I will summarize that there are several possible solutions, only 1 of which I would recommend.
Use a WorkManager from the commonj API.  It allows for managed threads in a Java EE container and is specifically designed to fit your use case.  If you are using WebSphere or WebLogic, these API's are already available in your server.  For others your will have to put a third party solution in yourself.
WorkManager info
Related questions
Why Spawning threads is discouraged

A: An EJB is a ultimately a transactional component for a client-server system providing request/reply semantics.  If you find yourself in the position that you need to pigeonhole a long-running transaction within the bounds of a request/reply cycle, then somewhere your system architect(ure) has taken the wrong turn.
The situation you describe is cleanly and correctly handled by an event based architecture with a messaging back end.  Initial event initiates the process (which can then be trivially parallelized by having the workers subscribe to the event topic) and the aggregating process itself raises an event on its completion.  You can still squeeze these sequence within the bounds of a request/reply cycle, but you will by necessity violate the letter and spirit of the Java EE system architecture specs.

A: Back to the Future - Java EE 7 has lot more Concurrency support via ManagedThreadFactory, ManagedExecutor service etc (JSR 236: Concurrency Utilities for Java EE) with which you can create your own 'managed'Threads .It is no longer a taboo in EE AS supporting it (Wildfly ?) via usining the ManagedThread* API's
More details
https://jcp.org/aboutJava/communityprocess/ec-public/materials/2013-01-1516/JSR236-EC-F2F-Jan2013.pdf
http://docs.oracle.com/javaee/7/tutorial/doc/concurrency-utilities002.htm

A: There are all sorts of ways to do this.
One, you can use an EJB Timer to create a run-once process that will start immediately. This is a good technique to spawn processes in the background. A EJB Timer is associated with a specific Session Bean implementation. You can either add an EJB Timer to every Session Bean that you want to be able to do this, or you can have a single Session Bean that can then call your application logic through some dispatch mechanism.
For me, I pass a serializable blob of parameters along with a class name that meets a specific interface to a generic Session Bean that then executes the class. This way I can easily background most anything.
One caveat about the EJB Timer is that EJB Timers are persistent. Once you create an EJB Timer is stays in the container until its job is finished or canceled. The gotcha on this is that if you have a long running process, and the server goes down, when it restarts the process will continue and pick back up. Mind this can be a good thing, but only if your process is prepared to be restarted. But if your have a simple process iterating through "10,000 items", if the server goes down on item 9,999, when it comes back up you can easily see it simply starting over at item 1. It's all workable, just a caveat to be aware of.
Another way to background something is you can use a JMS queue. Put a message on the queue, and the handler runs aysnchronously from the rest of your application.
The clever part here, and something I has also done leveraging the work with the Timer Bean, is you can control how many "jobs" will run based on how many MDB instances you configure the system to have.
So, for the specific task of running a process in multiple, parallel chunks, I take the task, break it up in to "pieces", and then send each piece on the Message Queue, where the MDBs execute them. If I allow 10 instances of the MDB, I can have 10 "parts" of any task running simultaneously.
This actually works surprisingly well. There's a little overhead it splitting the process up and routing it through the JMS queue, but that's all basically "start up time". Once it gets going, you get a real benefit.
Another benefit of using the Message Queue is you can have your actual long running processes executing on a separate machine, or you can readily create a cluster of machines to handle these processes. Yet, the interface is the same, and the code doesn't know the difference.
I've found once you've relegated a long running process to the background, you can pay the price of having less-that-instant access to that process. That is, there's no reason to monitor the executing classes themselves directly, just have them publish interesting information and statistic to the database, or JMX, or whatever rather than having something that can monitor the object directly because it shares the same memory space.
I was easily able to set up a framework that lets task run either on the EJB Timer or on the MDB scatter queue, the tasks are the same, and I could monitor their progress, stop them, etc.
You could combine the scatter technique to create several EJB Timer jobs. One of the free advantages of the MDB is it acts as a thread pool which can throttle your jobs (so you don't suddenly saturate your system with too many background processes). You get this "for free" just by leveraging the EJB management features in the container.
Finally, Java EE 6 has a new "asynchronous" (or something) qualifier for Session Bean methods. I do not know the details on how this works, as I've yet to play with a new Java EE 6 container. But I imagine you're probably not going to want to change containers just for this facility.

A: I once participated in a project where EJB transactions ran for up to 5 hours at a time. Aargh!
This same application also had a BEA specialist consultant who approved that they started additional threads from the transactions. While it's disrecommended in the specs and elsewhere, it doesn't automatically result in failure. You need to be aware that your extra threads are outside the container's control and thus if something goes wrong it's your fault. But if you can assure that the number of threads started in the worst case doesn't exceed reasonable limits, and that they all terminate cleanly within reasonable time, then it is quite possible to work like this. In fact, in your case it sounds like the almost-only solution.
There are some slightly esoteric solutions possible where your EJB app reaches out to another app for a service, which then does the multithreading in itself before returning to the EJB caller. But this is essentially just shifting the problem around.
You may, however, consider a thread pooling solution to keep an upper limit on the number of threads spawned. If you have too many threads your application will behave horribly.

A: You've analyzed the situation quite well, and no, there is not patern for this that match the EJB model.
Creating threads is mainly forbidden because it bypass the app. server thread management strategy and also because of the transactions.
I worked on a project with similar requireements and I decided to spawn additional threads (going against the sepc then). The operation to parallelized was read-only, so it worked regarding the transaction (the thread would basically have not transaction associated to them).  I also knew that I wouldn't spawn too many threads per EJB calls, so the number of threads was not an issue. But if your threads are supposed to modify data, then you break the transactional model of the EJB seriously. But if your operation in pure computing, that might be ok.
Hope it helps...


text:
Q: why we are checking it if(instance == null){ instance =this;} in this code? public class Gamemanager : MonoBehaviour
{

  public static Gamemanager instance;
  [SerializeField]
  private void Awake(){

    if(instance == null) // if instance is not initilized then instance is equal to class
      instance =this;
  }

}//classs

A: Basically we want to make sure that the static (!) "instance" variable will always hold the reference to the same instance of the Gamemanager no matter what, even if for some reason, multiple instances of Gamemanager are created.
As it has been mentioned above, this is also called "Singleton pattern".


text:
Q: Angular 9: deActivate guard and session timeout I am having an angular app and spring boot in the backend using BasicAuth for my authentication.
When the session on the server runs out I am getting a 401 and in the httpInterceptor I am then redirecting to the logout page.
On some components I have a form and when the user has not saved the changes, there is a canDeactive guard with a modal pop-up, warning the user of the unsaved changes.
The problem is now, when the session is invalid, the guard fires (since the angular app does not know yet of the invalid session) and I am stuck on the pop-up.
My goal would be to check if the session is valid, before the guard is fired (or evaluate in the guard itself, if the session is valid).
My idea was to call a isAuthenticated function in the backend and in the guard navigate to logout, on a 401 and else show the dialog, but since the call is async it won´t work and I did not figure out how to do it.
component.ts
createChangeGuard() {
    setTimeout(() => {
      this.myObjectOrig$ = new BehaviorSubject(this.bookingForm.value).asObservable();
      this.isDirty$ = this.bookingForm.valueChanges.pipe(dirtyCheck(this.myObjectOrig$));
      this.myObjectOrig$.pipe(untilDestroyed(this)).subscribe(state => { this.bookingForm.patchValue(state, { emitEvent: false }); });
    }, 1000);
  }

dirty-check component
export interface DirtyComponent {
  isDirty$: Observable<boolean>;
  // isPrinting: boolean;
  hasValidSession$: Observable<boolean>;
}

export function dirtyCheck<U>( source: Observable<U> ) {
  let subscription: Subscription;
  let isDirty = false;
  return function <T>( valueChanges: Observable<T> ): Observable<boolean> {

    const isDirty$ = combineLatest(
      [source,
      valueChanges]
    ).pipe(
      debounceTime(300),
      map(( [a, b] ) => { return isDirty = isEqual(a, b) === false;
      }),
      finalize(() => subscription.unsubscribe()),
      startWith(false),
      shareReplay({ bufferSize: 1, refCount: true }),
    );

    subscription = fromEvent(window, 'beforeunload').subscribe(event => {
        isDirty && (event.returnValue = false) && event.preventDefault();
    });
    return isDirty$;
  };
}

deactivate Guard
export class DirtyCheckGuard implements CanDeactivate<DirtyComponent> {
   ....

    constructor( private modalService: NzModalService,
                 .....
                  ) {
    }

    contentNormal = 'Die Änderungen wurden nicht gespeichert. Wollen Sie wirklich die Seite verlassen?';
    contentPrint = 'Die Änderungen wurden noch nicht gespeichert. Trotzdem drucken?';
    canDeactivate( component: DirtyComponent, currentRoute: ActivatedRouteSnapshot ): Observable<boolean> | boolean {
      let formIsDirty = false;
      ...some logic to set formIsDirty...
      return component.isDirty$.pipe(switchMap(dirty => {
        let navigate;
        if ( (dirty === false && !formIsDirty ) ) {
          // update status to status before the booking went into edit mode since no change was made
            this.checkPage(currentRoute.data.origin);
          return of(true);
        } else if (dirty === true || (dirty === false && formIsDirty)) {
        return this.modalService.create({
          nzTitle: 'Not saved',
          nzContent: content,
          nzFooter: [
            {
              label: 'Abbrechen',
              onClick: () => {navigate = false; this.modalService.closeAll(); }
            },
            {
              label: confirmText,
              type: 'primary',
              onClick: () => { navigate = true; this.checkPage(currentRoute.data.origin); this.modalService.closeAll(); }
            }
          ]
        }).afterClose.pipe(map(() => navigate ));

      }}), take(1));
    }
  }

interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     const requestRoute = this.router.url;
       return next.handle(request).pipe(retry(1), catchError((error: HttpErrorResponse) => {
         // this.errorCount = true;|| this.authenticationService.isLoggedIn() === false
         if (error.status === 401 ) {
             this.authenticationService.logout(requestRoute);
           }
         if (error.error instanceof ErrorEvent) {
               // A client-side or network error occurred. Handle it accordingly.
               console.error('An error occurred:', error.error.message);
             } else {
               console.error('An error occurred:', error);
               // The backend returned an unsuccessful response code.
               // The response body may contain clues as to what went wrong,
               if (error.error !== null){
                   this.showErrorNotification(error.status, error.error?.errorCode, error.error?.errorText);
                   console.error(`Backend returned code ${error.status}, body was: ${error.error?.errorText}}`);
                 }
             }
         return throwError(error.error);
       })
       );

authentication service
async isAuthenticated(){
    const serverUrl = this.baseURL + 'isValidSession';
    const response = await this.http.get(serverUrl, httpOptions).toPromise();
    return response.toString();
 }

A: If you have to validate session on each canActivate. You need to have a api for that.
lets say you have that api in AuthService
async isSessionValid() {
   var res = await this.http.get('url').toPromise();
   return res;
}

then use this promise returned as first statement of guard using same await strategy. if this returns true proceed furter, if this returns false return false from guard.


text:
Q: -D option to define parameter is not working in MAVEN 3 but working in MAVEN 2 We upgrade our project to from Maven 2 to Maven 3. We had a parameter for version of the project and provide the value in maven goal. After upgrade to Maven 3, its not working.
Instead of providing -D tried --define option too, still its not able to recognize. Tried the -DnewVersion with versions:set, but it does not work when i have the complete goal. I need to run the maven goal twice. Think link https://www.youtube.com/watch?v=vJzZvBVd18w was helpful, but do not solve the purpose.
<groupId>alex.test</groupId>
  <artifactId>test1</artifactId>
  <version>${rel.version}</version>
  <name>Test1</name>
  <packaging>pom</packaging>

Maven 2, following mvn command worked
mvn clean install -Drel.version=1.0.1
Same command failed in Maven 3 stating the following error
"'version' contains an expression but should be a constant. @ alex.test:test1:${rel.version}"
As project has dependencies I tried the following
Parent Pom
<groupId>alex.test</groupId>
  <artifactId>test1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>Test1</name>
  <properties>
    <child1.version>1.0-SNAPSHOT</child1.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
     <groupId>test</groupId>
     <artifactId>child1</artifactId>
     <version>${child1.version}</version>
      </dependency>
    <dependencies>
  </dependencyManagement>

  <modules>
    <module>../child1</module>
  </modules>

Child Pom
<parent>
    <groupId>alex.test</groupId>
    <artifactId>child1</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <artifactId>child1</artifactId>
  <name>child1</name>

while executing following command on parent project
mvn versions:update-properties versions:set -DnewVersion=3.0-SNAPSHOT
It updated the pom.xml in both Parent and Child modules,
But following command failed with error
mvn versions:update-properties versions:set -DnewVersion=3.0-SNAPSHOT clean install
Error:
The project alex.test:child1:[unknown-version] (C:\Maven_Test\Test_Program\child1\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for alex.test:child1:[unknown-version]: Could not find artifact alex.test:test1:pom:3.0.2-SNAPSHOT

*

*Why -D parameter not working on version tag in Maven 3.

*In terms of complex multinode project how to create the artifact versioning and can we handle it in maven goal ?


text:
Q: Why do I get an error message using "sudo apt-get update"? I get this error message while trying to update from the terminal:
Reading package lists... Done
W: The repository 'http://ppa.launchpad.net/ffmulticonverter/stable/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/ffmulticonverter/stable/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.

It is referring to a specific app, but the whole update is rendered useless (I guess due to this error).
Any ideas what's going on and why I can't update my OS? The graphical update won't work either.

A: This PPA doesn't have a release for Xenial, the latest version this repository supports is Utopic.
This article may help:
http://www.ubuntumaniac.com/2015/12/install-ff-multi-converter-172-on.html

A: This is due to the reason that the PPA does not have a Xenial release, as seen in screenshot below. PPA Link

If you need to get rid of this error, remove the PPA from software sources and then do a repo update.