text:
Q: Как реализовать решение задачи ЕГЭ на C++? Возник такой вопрос: как реализовать решение следующей задачи на C++? Вводятся число N - количество строк. В каждой из N строк через пробел вводятся 4 значения: название АЗС (не более 20 символов), название улицы (не более 20 символов), марка бензина (92, 95, 98), цена за бензин этой марки (число от 1000 до 3000). Программа должна выводить три числа через пробел - количество АЗС, на которых бензин каждой марки продаётся дешевле всего. На Паскале решение этой задачи выглядит так:
var min, ans: array[92..98] of integer; // Массивы для минимальной цены и для количества АЗС
    c: char; // "Мусорная" переменная для ввода названия АЗС и улицы
    i, k, N, b: integer;

begin

   for i:=92 to 98 do begin // Заполнение массивов
      min[i]:=3001; // Максимальная цена за бензин = 3000, поэтому заполняем массив 3001
      ans[i]:=0; // Счётчик количества АЗС
   end;

   readln(N); // Ввод количества АЗС

   for i:=1 to N do begin

      repeat // Ввод названия АЗС до тех пор, пока не будет введён пробел
         read(c);
      until c=' ';

      repeat // Ввод улицы до тех пор, пока не будет введён пробел
         read(c);
      until c = ' ';

      readln(k, b); // Ввод марки бензина и его цены

      if b<min[k] then begin // Если цена меньше минимума за эту марку
         min[k] := b; // Минимум = цена
         ans[k] := 1; //  Количество АЗС = 1
      end else if min[k] = b then // Если минимум = цене
         ans[k] := ans[k] + 1; // Количество АЗС +1
   end;

   writeln (ans[92], ' ', ans[95], ' ', ans[98]); // Вывод количеств АЗС с наиболее низкими ценами каждой марки

end.

Суть в том, что название АЗС и название улицы для ответа по сути не нужны. В связи с этим логичнее было бы записывать их в отдельную переменную, которая с каждой новой введённой буквой будет перезаписываться, до тех пор, пока не будет введён пробел (пробел = конец ввода слова). Попытался сделать так же на C++, но понял, что cin >> не учитывает пробелы. Потом попытался сделать то же самое с cin.get(), но столкнулся с проблемой, что он учитывает ещё и символ новой строки и поэтому работает неправильно. cin.getline() на сколько я понял работает только со строками, и поэтому с переменной это сделать не получится. Подскажите, как вообще можно реализовать решение этой задачи на C++, желательно используя переменную для лишней информации, а не строку (хотелось бы, чтобы программа занимала как можно меньше памяти). Спасибо.

A: #include <iostream>
#include <cstdlib>

/*
 * Вводятся число N - количество строк.
 * В каждой из N строк через пробел вводятся 4 значения:
 * название АЗС (не более 20 символов),
 * название улицы (не более 20 символов),
 * марка бензина (92, 95, 98),
 * цена за бензин этой марки (число от 1000 до 3000).
 *
 * Программа должна выводить три числа через пробел -
 * количество АЗС, на которых бензин каждой марки продаётся дешевле всего.
 */

using namespace std;

struct GasStation{
    char* stationName = new char[20];
    char* streetName = new char[20];
    int mark;
    int price;

public: GasStation(char* _stationName, char* _streetName, int _mark, int _price){
        stationName = _stationName;
        streetName = _streetName;
        if (_mark == 92 || _mark == 95 || _mark == 98)
            mark = _mark;

        if (_price >= 1000 && _price <= 3000)
            price = _price;
    }

};

struct MinPriceCount{
    int minPrice92 = 0;
    int minPrice95 = 0;
    int minPrice98 = 0;

public: MinPriceCount(int min92, int min95, int min98){
        minPrice92 = min92;
        minPrice95 = min95;
        minPrice98 = min98;
    }
};

MinPriceCount searchMinPrice(int amount);
void printMinPrice(MinPriceCount minPr);

int main() {
    cout << "Enter amount gas station: ";
    int amount;
    cin >> amount;
    printMinPrice(searchMinPrice(amount));
    system("pause");
    return 0;
}

MinPriceCount searchMinPrice(int amount){
    char* stationName = new char[20];
    char* streetName = new char[20];
    int mark;
    int price;

    int minPrice92 = 3000;
    int minPrice95 = 3000;
    int minPrice98 = 3000;

    int countMinPrice92 = 0;
    int countMinPrice95 = 0;
    int countMinPrice98 = 0;

    for (int i = 0; i < amount; ++i) {

        cout << "Enter name of gas station, street, mark and price: ";
        cin >> stationName >> streetName >> mark >> price;
        GasStation gasStation(stationName, streetName, mark, price);

        if (gasStation.mark == 92 && gasStation.price < minPrice92){
            minPrice92 = gasStation.price;
            countMinPrice92 = 1;
        }

        else if (gasStation.mark == 92 && gasStation.price == minPrice92)
            countMinPrice92++;

        if (gasStation.mark == 95 && gasStation.price < minPrice95){
            minPrice95 = gasStation.price;
            countMinPrice95 = 1;
        }

        else if (gasStation.mark == 95 && gasStation.price == minPrice95)
            countMinPrice95++;

        if (gasStation.mark == 98 && gasStation.price < minPrice98){
            minPrice98 = gasStation.price;
            countMinPrice98 = 1;
        }

        else if (gasStation.mark == 98 && gasStation.price == minPrice98)
            countMinPrice98++;
    }
    MinPriceCount minPrice(countMinPrice92, countMinPrice95, countMinPrice98);

    return minPrice;
}

void printMinPrice(MinPriceCount minPr){
    cout << minPr.minPrice92 << " " << minPr.minPrice95 << " " << minPr.minPrice98 << "\n";
}

A: Не знаю, разрешается ли на ЕГЭ С++11
#include <array>
#include <algorithm>
#include <iostream>
#include <map>

using namespace std;

int main(){
    size_t n;
    cin >> n;

    array<int, 3> ms = {92, 95, 98};
    map<int, int> min_p, ans;

    transform(ms.begin(), ms.end(), inserter(min_p, min_p.end()),
        [](int m){ return make_pair(m, numeric_limits<int>::max()); });
    transform(ms.begin(), ms.end(), inserter(ans, ans.end()),
        [](int m){ return make_pair(m, 0); });

    for(size_t i = 0; i < n; ++i){
        string nil;
        int m, p;
        cin >> nil >> nil >> m >> p;

        if(p < min_p[m]){
            min_p[m] = p;
            ans[m] = 1;
        } else if(p == min_p[m]){
            ++ans[m];
        }
    }

    for(auto& pair: ans){
        cout << pair.second << " ";
    }

    return 0;
}


text:
Q: Как правильно фиксить баги? При разработке часто приходится фиксить баги в проекте.
Я делаю это следующим образом:
создаю ветку bugfix/* от мастера, после фикса бага, делаю git push origin HEAD, далее в guthub создаю pull-request и происходит слияние с мастером.
После чего, снова переключаюсь на мастер - git checkout -, и пишу git pull origin master чтобы у меня появились изменения.
Правильно ли так делать? Или есть другие способы ?
Может вместо git pull надо merge локально?

A: Ну можно всё и из командной строки делать
$ git pull
$ git checkout -b task_branch
...
$ git add path/to/file0
$ git rm path/to/file1
$ git mv path/to/file2 path/to/file3
...
$ git commit -am 'Changes'
$ git pull
$ git push
$ git checkout master
$ git merge task_branch
$ git push

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plot coordinates don't mach with *jpg image coordinates I've like to create a box coordinates for one ellipse object in a jpg image using original plot coordinates created using ggplot2 package. In my example:
#Packages
library(ggplot2)
library(ggforce)
library(raster)

#Create a ellipse using ggplot2
ell.sim<-ggplot() +
  geom_ellipse(aes(x0 = 200, y0 = 200, a = 150, b = 50, angle = 0), fill="black") +
  coord_fixed(xlim=c(0,1000),ylim=c(0,1000))
ell.sim2 <- ell.sim + theme_void()
plot(ell.sim2)

#Save in JPG format with 96 DPI
ggsave(
  filename="ellipse_test.jpg",
  plot = ell.sim2,
  width = 10,
  height = 10,
  dpi = 96)

#Open jpg created with raster
img <- stack("ellipse_test.jpg")
plotRGB(img)
#

#Extract the ellipse limits for the box coordinate creation
ell.sim.coords <- ggplot_build(ell.sim2)
x1<-(min(ell.sim.coords$data[[1]]$x))
x2<-(max(ell.sim.coords$data[[1]]$x))
y1<-(min(ell.sim.coords$data[[1]]$y))
y2<-(max(ell.sim.coords$data[[1]]$y))
bbx<-c(x1,x1,x2,x2,x1)
bby<-c(y1,y2,y2,y1,y1)
lines(bbx,bby,col="red")
#

But If I look at the image plot below I see that the ellipse in the jpg image and box coordinates doesn't match:

And if I try to multiply or divide the x and y coordinates by the width and height of the image the box coordinates are not plotted.
Please, any tips?
Thanks

A: You have to force the origin to (0,0) in ggplot.
Try This:
ell.sim<-ggplot() +
  geom_ellipse(aes(x0 = 200, y0 = 200, a = 150, b = 50, angle = 0), fill="black") +
  coord_fixed(xlim=c(0,1000),ylim=c(0,1000)) +
  scale_y_continuous(expand = c(0, 0)) +scale_x_continuous(expand = c(0, 0))

ell.sim2 <- ell.sim + theme_void()
plot(ell.sim2)

Also, you need to change the dpi accordingly
ggsave(
  filename="ellipse_test.jpg",
  plot = ell.sim2,
  width = 10,
  height = 10,
  dpi = 100)

img <- stack("ellipse_test.jpg")
plotRGB(img)

ell.sim.coords <- ggplot_build(ell.sim2)
x1<-(min(ell.sim.coords$data[[1]]$x))
x2<-(max(ell.sim.coords$data[[1]]$x))
y1<-(min(ell.sim.coords$data[[1]]$y))
y2<-(max(ell.sim.coords$data[[1]]$y))
bbx<-c(x1,x1,x2,x2,x1)
bby<-c(y1,y2,y2,y1,y1)
lines(bbx,bby,col="red")


text:
Q: python pandas multi index how to move rows down? Hey I am trying to make a dataframe ready for exportation into latex and I can't figure out how to change the order of my dataframe manually, i can sort it etc, but i can't get it to show the specific order i require:
    Hyper-parameter                  H-parameter values
CNN activation function          relu                         0.018254  0.018359
                                 tanh                         0.018249  0.018348
CNN filter layers                16                                NaN  0.018353
                                 32                                NaN  0.018338
                                 64                                NaN  0.018368
Feature collections              daytime                      0.017845  0.017947
                                 daytime + sensors            0.020593  0.020344
                                 daytime + wind + irradiance  0.017080  0.017311
                                 daytime + wind + sensors     0.019660  0.019819
                                 irradiance                   0.017133  0.017413
                                 pressure and humidity        0.017735  0.017828
                                 rain                         0.017983  0.017953
                                 sensors                      0.020103  0.020075
                                 temperature                  0.018081  0.017964
                                 univariate                   0.017827  0.017747
                                 wind                         0.017216  0.017571
                                 wind + irradiance            0.016605  0.017027
                                 wind + sensors               0.019407  0.019594
LSTM activation function         relu                         0.018299       NaN
                                 tanh                         0.018204       NaN
LSTM history vector length       60                           0.018246       NaN
                                 80                           0.018253       NaN
                                 100                          0.018255       NaN
Learning rate                    0.0001                       0.018424  0.018496
                                 0.0005                       0.018156  0.018259
                                 0.001                        0.018174  0.018305
MaxPooling layer size            3                            0.018212  0.018300
                                 5                            0.018230  0.018378
                                 7                            0.018313  0.018381
Second CNN kernel                False                             NaN  0.018407
                                 True                              NaN  0.018300
Second set of cnn+pooling layers False                             NaN  0.018333
                                 True                              NaN  0.018374

This is my dataframe, I would really like to have control over the order of the Hyper parameters. For example I would like to move CNN activation function and CNN filter layers down below Feature collections. Any idea on how to accomplish this would be great.
for reference, here is a toy example:
df = pd.DataFrame({"a": [1, 2, 3, 4, 5, 6]}, index=['A', 'b', 'C', 'd', 'e', 'f'])
arrays = [[1, 1, 2, 2, 3, 3], ['red', 'blue', 'red', 'blue', 'red', 'blue']]
df.index = pd.MultiIndex.from_arrays(arrays, names=('number', 'color')
df

              a
number color
1      red    1
       blue   2
2      red    3
       blue   4
3      red    5
       blue   6

How to move the contents of "number' 2 to the top?

A: Nevermind, After more than an hour of searching i made this post, and 10 minutes later i found the answer. using the example at the bottom of my question:
df.reindex([2,1,3], level=0)
df

              a
number color
2      red    3
       blue   4
1      red    1
       blue   2
3      red    5
       blue   6


text:
Q: groupby in pandas messes with row indexes I have a pandas df with three columns, purchase_day, customer_name, products_purchased.
I want to return an array of number of days that each customer visited the store. So I used
gpd = df.groupby(by=['customer_name', 'purchase_day']).count()

which returns a table that looks like:

Unfortunately with this returned table, I can't run groupby on it because of the unusual format (where customer_name and purchase_days aren't in the first row but in the second).
Any tips so that I can count the number of purchase_days each customer visited the store?

A: What you need to do is resetting the index.
Since you apply .groupby the dataframe with multiple columns,
the dataframe returned would have a MultiIndex.
gpd = df.groupby(by=['customer_name', 'purchase_day']).count().reset_index()
Also you can still apply .groupby with multiindexed dataframe.
In the documentation of method pandas.DataFrame.groupby,
there is a para level which you can use to set multiindices as groupby columns.
There is a SO thread on this that you can check out here.


text:
Q: PHP, fopen() can't create new file out of the site's root directory I'm trying a demo provided by PHP and MySQL Web Development 5th Edition .
Here is my code
    $outPut="test";
    $fp=fopen("$documentRoot/../orders/orders.txt", 'ab');
    fwrite($fp,$outPut);

The new file should be created in www/wwwroot/orders, but no new files, and no errors.
I'm on nginx1.20.1, PHP7.4, Debian 10.
The permission of orders/ folder is 775, owner is www. I have tried 777 but it still doesn't work.


text:
Q: $.fn.modal is not defined; for bootbox I have included bootbox with "npm install bootbox --save", also included in angular.json
"scripts": [
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js",
              "./node_modules/bootbox/bootbox.js"
            ]

I have tried to use it in a component
bootbox.confirm("This is the default confirm!", function (result) {
            if (result) {
                this.router.navigateByUrl('login');
            }
        });

It gives error $.fn.modal is not defined; please double check you have included the Bootstrap JavaScript library. See http://getbootstrap.com/javascript/ for more details.
But it works fine when checked with console apart from UI is not good..
Kindly help

A: I solved this issue by wrapping the JS in this block of code:
$(document).ready(function () {
     bootbox.alert("Hello world!");
});

This ensures that the code begins to run only once the page has fully loaded.
This is the best practice in any case, not only when you encounter Bootbox issues.

A: Removing the node_modules folder inside the bootbox folder helped resolve this same issue for me.  After removing, rebuild your bundle.  May not work for all cases but it's worth a try.

A: For me I had to add this dependency to the requirejs config.js file.
If you are not be using requirejs it could still be a dependency issue.
shim: {
    bootstrap: {
        deps: ['jquery']
    },
    bootbox: {
        deps: ['bootstrap']
    } .....


text:
Q: How can I add up the values from the Stacked Bar and output them to the label above the bar, Apache ECharts Currently it looks like this:

I want to add the values in one column and display them above the bar so that it looks like this:

You must use the Apache Echarts library.
export let getSum = function(data, obj, str) {
  data.forEach(el => {
    if (el.period === obj.name && el.name === str) {
      let sum = obj.data + el.value;
      return sum;
    };
  });
}

I tried to use this function, I wanted to go through our data array, get the elements if they are in the same column.


text:
Q: Image max-width (non floated) use space next to floated div? The site I'm working on will display lengthy articles on screen. The site is responsive so everything you see on screen will re-size and re-flow to accommodate different screens. Previously we had a two column layout where the articles would be in the left floated div. And a side bar of shorter content would be in the right hand floated div.
It was decided that since the right hand content was so short there was lots of wasted white space beneath it. I was asked to try and incorporate the right hand column into the left hand div so the text would wrap around it.
That part was pretty easy, I just floated the now embedded right hand column into the article and the written text wrapped around it.
See this JSFiddle:
http://jsfiddle.net/TheMonkxx/2aucA/1/
Here is the HTML for the page:

Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas vitae nunc arcu. Cras tortor velit, consectetur
quis consectetur vel, ultrices eu nisl. Pellentesque convallis orci ligula,
id pharetra mauris. Vestibulum eleifend, turpis eget commodo dapibus, diam

magna nunc auctor elit, nec molestie libero quam quis mi. Donec interdum
velit non arcu sollicitudin eu ullamcorper lectus venenatis. Vivamus at
lacus magna. Proin in diam semper urna fermentum molestie sit amet sit
amet augue. Nulla sit amet massa eu risus laoreet laoreet eget sed erat.
Aliquam quis enim in odio porta consequat. Ut egestas urna et erat iaculis
et aliquam libero auctor.

Here is the CSS
.parent {
 border: 1px solid green;
 width: 200px;
 float: right;
}

.right_content {
 width: 25%;
 height: 150px;
 float: right;
 background-color: red;
 margin: 0 0 7px 7px;
}

The problem comes in when I try to add images to the article content. Since the site is responsive, I want the images to have max-width: 100% applied. However when I do that the images go 100% of the parent container and push any written content beneath the images gets pushed after the right hand column. See this fiddle:
http://jsfiddle.net/TheMonkxx/2a66J/
Here is the updated HTML for the page:

Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas vitae nunc arcu. Cras tortor velit, consectetur
quis consectetur vel, ultrices eu nisl. Pellentesque convallis orci ligula,
id pharetra mauris. Vestibulum eleifend, turpis eget commodo dapibus, diam

magna nunc auctor elit, nec molestie libero quam quis mi. Donec interdum
velit non arcu sollicitudin eu ullamcorper lectus venenatis. Vivamus at
lacus magna. Proin in diam semper urna fermentum molestie sit amet sit
amet augue. Nulla sit amet massa eu risus laoreet laoreet eget sed erat.
Aliquam quis enim in odio porta consequat. Ut egestas urna et erat iaculis
et aliquam libero auctor.

And the updated CSS:
img {
  max-width:100%;
}
.parent {
   border: 1px solid green;
   width: 200px;
   float: right;
}
.right_content {
   width: 25%;
   height: 150px;
   float: right;
   background-color: red;
   margin: 0 0 7px 7px;
}

Giving the image a pre-defined width fixes the layout but it causes problems for the responsive nature of the site. I also will have some articles which have images at various places in the copy, so I can't always predict an image will be beside the right hand column.
Any ideas or suggestions how I can get the desired layout and keep the responsive aspect working? Thanks!

A: Although this is old, I've just figured out a good and simple solution using jQuery.

CSS Part
First we need to set all the images to be small so they can fit next to the floating div. let's say 75%;
.parent img {
  max-width:100%;
  width: 75%;
}

jQuery Part
Then we want to reset the width of all images below the floating div:
jQuery(document).ready(function(){
        var h = jQuery(".right_content").height(); //get floating div height (let's say it's dynamic).

        jQuery('.parent img').each(function(){ //loop through all images in content
            jQuery(this).removeAttr('style') //remove any disturbing inline styles. optional.
            var p = jQuery(this).position(); //get each .wp-caption position
            var top = p.top; //top position
            if(top > h){ //if img is below the floating div
                jQuery(this).css("width", "initial") //change img width to original (or anything you like)
            }
        });
});

hope it help somehow.

A: Without a script with which to do some calculations, you might have to settle for smaller images.
http://jsfiddle.net/2a66J/2/
img {
    max-width:72%;
    float: left;
}

Technically, your site isn't "responsive". It's "fluid". If it was responsive you could set fixed max-widths based on viewport size and have 100% image width for all scenarios. The minor drawback is that you aren't usually using 100% of the available viewport width for your page with a responsive design.

A: One way to look at this, however it is not very efficient and be very bloated if you are working with lots of images.
If what you posted on jsFiddle is all that you have to work with, then my suggestion is to add a  around said article image.  You will then constraint this  to a percentage and either float it left or right with a secondary class.
HTML

CSS
.article_image{
 width: 50%;
}
.article_image_flleft{
 float: left;
}

Fiddle:
http://jsfiddle.net/D8ELj/1/
As isherwood points out, setting various viewports at be more beneficial in the long run.


text:
Q: add write access to user ubuntu - shared folder cifs-utils I have folder in /media on ubuntu - shared from windows via fstab and cifs-utils. Can I share this folder to other user: "miki" (not root)
root@localhost:/media#
drwxr-xrwx  4 root    root 4096 Nov 15 12:21 .
drwxr-xr-x 23 root    root 4096 Nov 14 06:34 ..
drwxr-xr-x  2 padm    root    0 Nov 15 09:34 Archive
drwxr-xrwx  2 root    root 4096 Feb 25  2019 kekik

I have try with:
root@localhost:~# sudo chmod -R 757 /media/Archive/

but get:
chmod: changing permissions of '/media/Archive/': Permission denied

A: Find a solution:
need to modify /etc/fstab by changing:
//windowsServer/Archive /media/Archive  cifs  username=wundowsuser,password=somepass,uid=1000,iocharset=iso8859-1,rw,file_mode=0777,dir_mode=0777,vers=1.0  0  0

and change group of folder (must umont it first!)
sudo umount -l /media/Archive
sudo chown miki:miki /media/Archive/


text:
Q: Shader's layout position versus accessor id of GLTF file I am using three.js with Webgl2 to show a gltf file I made for GIS purpose.
I need a custom vertex attribute as gltf allows that.
The shader compiles OK in GLSL 300 es
The thematics are in vertex attribute buffer interleaved with the position.
Everything draw ok. But now I want to use the thematic data .
If I define the layout at location 2  like the accessors
layout(location=2) in  uint thematic;

Everything still draw ok if I dont use the variable. But if I do,
I got error like this
[.WebGL-000000000BAE32A0] GL_INVALID_OPERATION: Vertex shader input type does not match the type of the bound vertex attribute.
What is the right way to declare the layout for a custom vertex attribute??
Finally I decide to use a prdefined attribute, namely COLOR_0, and it works.
Here is the primitive declaration in the gltf and the accessor
{ "attributes" : {
   "POSITION" : 1 ,
  "COLOR_0":2 },
{
 "bufferView" : 1,
 "byteOffset" : 12,
 "componentType" : 5121,
 "count" : 16263,
 "type" : "VEC3",
 "normalized" :  true
}
Component Type 5121 stand for unsigned byte (should be normalized)
Populating with random color I got that image

But This is just à workaround and a bad one using 32 bits where I need only 4. I need 16 bits for record gid and the rest for outline and bacground styling
Does any one know how To teach 3js's gltfLoader and shader compiler to expose custom vertex attributes so we can reference and use it normaly?
======================================================
Following ScieCode's suggestion I sent a report to 3js forum and Michael Herzog told me that glVertexAttribIPointer is not yet supported but he will work on it.
3JS Add support for integer attributes with WebGL2


text:
Q: Disclosure button for displaying more text in a table view So i have created a custom cell with IB and source files associated which is put in my table view. The cell in my table view display text which doesn't fit entirely. What i want is to add a disclosure button in my cells which when is touch up display the rest of the text of the cell in for example two lines or by adjusting the text in the cell. But i really do not know how to do.
So if you have any clue, link or code it would be really nice thanks to all.

A: Have you tried setting the subclassed cell's accessoryType or accessoryView property? When touched, perhaps the -tableView:accessoryButtonTappedForRowWithIndexPath: method could be used to trigger some animation on the content of the custom cell's contentView.


text:
Q: Determine the interface which was used for booting via PXE I have a linux machine which was booted via PXE.
Can I determine the network interface which was used for booting?

A: If assume you're using PXELINUX.
There's a flag IPAPPEND; if you set it to 2, it should cause PXELINUX to append a parameter BOOTIF=<hardware-address-of-boot-interface> to your kernel command line. Then you've got the MAC address, which you can use to identify the used interface.
http://www.syslinux.org/wiki/index.php/SYSLINUX#IPAPPEND_flag_val_.5BPXELINUX_only.5D

A: I have used PXELINUX with IPAPPEND=2 for years. But I recently had to switch to EFI PXE boot, where most people seem to prefer GRUB to PXELINUX.
The GRUB EFI PXE bootloader defines a $net_default_mac variable that contains the MAC address of the boot interface. You can use this to add the MAC address to your kernel command line, but it differs from the PXELINUX IPAPPEND=2 value in two ways:

*

*It does not include the hardware type prefix byte (01 = Ethernet)

*It uses colons to separate octets instead of dashes (e.g. ba:98:76:54:32:10 instead of 01-ba-98-76-54-32-10)

We have some scripts that expect the PXELINUX BOOTIF format, so I wanted to replicate that in the GRUB configuration.
Unfortunately, GRUB's text manipulation functions seem to be nearly non-existent. I would up using the regexp command like so:
set dd="[0-9a-f][0-9a-f]"

regexp --set 1:o1 --set 2:o2 --set 3:o3 --set 4:o4 --set 5:o5 --set 6:o6 \
    ($dd):($dd):($dd):($dd):($dd):($dd) \
    $net_default_mac

set hwaddr="01-$o1-$o2-$o3-$o4-$o5-$o6"

menuentry  'My Linux' --class fedora --class gnu-linux --class gnu --class os {
   linuxefi my-kernel-image BOOTIF=$hwaddr
   initrdefi my-initramfs.img
}


text:
Q: Hwo to fix error in WordPress Trying to get property 'ID' of non-object in functions.php I created a custom functionality in WooCommerce and it is about the filtering. If you choose any filter from the sidebar of the eshop and then browse to a single product page you'll have navigation arrows based on your previous selection filtering. It works fine but only in a specific product i get the error
Notice: Trying to get property 'ID' of non-object in functions.php on line 355
function filter_single_post_pagination($output, $format, $link, $post){
    $variable = $_GET;

    if (count($variable) == 0) {
        $url       = get_permalink($post->ID);
        if (isset($post->ID)) {
            if('previous_post_link' === current_filter()){
                return "→";
            } else {
                return "←";
            }
        }
    }

    else {
        $pids = array();
        $product_ids = "";
        foreach ($variable as $key => $value) {
            $product_ids .= $key."&";
            array_push($pids, $key);
        }

        global $product;
        $id = $product->get_id();
        $key_val = array_search($id,$pids);
        $custom_link = "?".$product_ids;

        if (isset($pids[$key_val+1])) {
            if('previous_post_link' === current_filter()){
                $rel  = 'next';
                $next_url       = get_permalink($pids[$key_val+1]);
                return "→";
            }
        }

        if (isset($pids[$key_val-1])) {
            if('next_post_link' === current_filter()){
                $rel  = 'prev';
                $previous_url   = get_permalink($pids[$key_val-1]);
                return "←";
            }
        }
    }
}


text:
Q: Companies and addresses MySQL I've got a database with 2 tables.

*

*companies

*addresses

These are my tables.
Adresses

*

*adress_id

*adress_adress

*adress_adressnumber

*adress_zipcode

*adress_city

*adress_postbus

*adress_country

*adress_building

*adress_unit

Companies

*

*company_id

*company_name

*company_adress_id

*company_postadress_id

A company can have a address but maby different postal address. I want to join these addresses in 1 query but when i join them only 1 address is shown because i think they're overlapping.
What can i do make this work? I'm really struggling.
Thanks in advance.
SELECT * FROM companies as c JOIN adresses as a ON c.company_adress_id = a.adress_id JOIN adresses as postaddress ON c.company_postadress_id = postaddress.adress_id

A:             -- ----------------------------
            -- Table structure for adresses
            -- ----------------------------
            DROP TABLE IF EXISTS `adresses`;
            CREATE TABLE `adresses` (
            `adress_id` int(11) NOT NULL AUTO_INCREMENT,
            `adress_adress` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
            `adress_adressnumber` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
            `adress_zipcode` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
            `adress_city` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
            `adress_postbus` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
            `adress_country` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
            `adress_building` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
            `adress_unit` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
            `company_id` int(11) DEFAULT NULL,
            `addresss_role` tinyint(4) DEFAULT NULL COMMENT 'Role 1 for company may be and 2 for comapny postal, feel free',
            PRIMARY KEY (`adress_id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

            -- ----------------------------
            -- Records of adresses
            -- ----------------------------
            INSERT INTO `adresses` VALUES ('1', '1324234', '', '', '', null, '', null, null, '1', '2');
            INSERT INTO `adresses` VALUES ('2', '67856785678', '', '', '', null, '', null, null, '1', '1');

            -- ----------------------------
            -- Table structure for companies
            -- ----------------------------
            DROP TABLE IF EXISTS `companies`;
            CREATE TABLE `companies` (
            `company_id` int(11) NOT NULL AUTO_INCREMENT,
            `company_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
            `company_adress_id` int(11) NOT NULL,
            `company_postadress_id` int(11) NOT NULL,
            PRIMARY KEY (`company_id`),
            KEY `company_adress_id` (`company_adress_id`,`company_postadress_id`),
            KEY `company_adress_id_2` (`company_adress_id`,`company_postadress_id`),
            KEY `company_postadress_id` (`company_postadress_id`),
            CONSTRAINT `address` FOREIGN KEY (`company_adress_id`) REFERENCES `adresses` (`adress_id`) ON DELETE CASCADE ON UPDATE CASCADE,
            CONSTRAINT `postal_address` FOREIGN KEY (`company_postadress_id`) REFERENCES `adresses` (`adress_id`) ON DELETE CASCADE ON UPDATE CASCADE
            ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

            -- ----------------------------
            -- Records of companies
            -- ----------------------------
            INSERT INTO `companies` VALUES ('1', 'sdfgsdf', '1', '2');

A: Best solution. Thanks to @Marshall Matters
SELECT
c.*,
a1.adress_adress AS company_adress_adress,
a1.adress_adressnumber as company_adress_adressnumber,
a1.adress_zipcode as company_adress_adress_zipcode,
a1.adress_zipcode as company_adress_adress_city,

a2.adress_adress AS postal_adress_adress,
a2.adress_adressnumber as postal_adress_adressnumber,
a2.adress_zipcode as postal_adress_adress_zipcode
a2.adress_zipcode as postal_adress_adress_city

FROM
companies c
INNER JOIN adresses a1 ON c.company_id = a1.company_id
AND a1.addresss_role = 1
INNER JOIN adresses a2 ON c.company_id = a2.company_id
AND a2.addresss_role = 2


text:
Q: UBUNTTU 19.04 Not Shuting down I upgraded my Lenovo laptop from UBUNTU 18.04 to 19.04 and now it freezes at a blinking cursor mode after shutting down. I can shut down my laptop only by holding power key few seconds. I followed some instructions proposed for UBUNTU 18.04 but they didn't work here. Please help me if you can.

A: You can investigate an issue by reading systemd-logs:
journalctl --since today

Please, find the shutdown logs and put here.


text:
Q: EchoNest API Search for song by ID I am using Echo nest to make a new web app.  Firstly, I'm searching for a song by song title and artist.  This returns what I'm looking for.  One of the items I want back is the song id, which I get.
Now, I want to be able to search for that exact song later with the song ID, but the search provided on their API site does not search for what I'm looking for.
If you do a search for "Radioactive" by Imagine Dragons, you'll get this as the search: http://developer.echonest.com/api/v4/song/search?api_key=KEY&results=20&sort=song_hotttnesss-desc&title=radioactive&artist=imagine%20dragons
Great, I'm able to get some call backs.  The song I'm looking for has the ID of SOJGTBJ143947F080F.
I'm going to save this into a database to callback later.  But when I try to search for the song using the echo nest song search, I get nothing back:
http://developer.echonest.com/api/v4/track/profile?api_key=KEY&id=SOJGTBJ143947F080F
Now, where is my problem here?  Am I using the wrong search API?  am I not looking at the right ID?  Not sure where to go from here.

A: I found my answer for any one looking for the same thing.  You'll need to look into the "Profile" part of the API.
My lookup URL is now:
http://developer.echonest.com/api/v4/song/profile?api_key=KEY&format=json&id=SOJGTBJ143947F080F
This finds the one and only song I was looking for.


text:
Q: Check if a string contains only given characters I'm wondering if there is more elegant way to check if the string (str = 'abcccbbaabcbca') contains only 'a','b' or 'c' than iterating over it :
for i in str:
   if i in ['a','b','c']:
      pass
   else :
      print('wrong character')

A: You could use any with a generator expression:
if any(c not in 'abc' for c in _str):  # Don't use str as a name.
    print('Wrong character')

A: Convert both strings to sets and check if they are equal. If yes, your string contains a AND b AND c:
valid = set(your_string) == set('abc')...

Use issubset to check if it contains ANY of a, b, c:
valid = set(your_string) <= set('abc')

or
valid = set(your_string).issubset('abc')

Subtract the sets to find out invalid characters:
bad_chars = set('abcXYcba') - set('abc') # set(X,Y)

A: Using regular expressions:
import re
if re.search('[^abc]', string):
    print('wrong character')

A: Feel free to mock, since this jumps directly to a regular expression, but test for matching against "^[abc]+$"
re.match('^[abc]+$', 'string')

A: You can also use string.translate:
import string

s = 'abcccbbaabcbca'
# translate character to empty ""
t = string.maketrans("","")

# if non-abc character is found s.translate will become the bad characters
if s.translate(t, 'abc'):
    print ('wrong character')

Updated
As also pointed out from @PadraicCunningham
# for one off usage, you can skip making a translation table.
if s.translate(None, 'abc'):
…


text:
Q: How do I implement OAuth implicit flow in a SPA? My web application is set up as follows:

*

*A resource server with APIs (uses Spring Security)

*An authorization server (Spring Security OAuth) which hosts the login form page

*An SPA client (Angular 6 / routing / angular-oauth-oidc library)

*I'm using the Implicit flow

I'm trying to figure out the best way to implement the login flow.  As I have it now, when the user attempts to access a protected route and does not have a token, he is redirected to the auth server's login form (via a guard).  If login is successful, the browser then redirects back to the angular app's protected route.  The guard allows access since the user now has a token.
The issue is that I'm trying to figure out is that my angular app twice: once before I'm logged in, and again after.  Modern browsers will cache the actual SPA resources (.js, .html, .css. etc), so there isn't another hit to the server.  But Angular apps take a non-trivial time to load, and in this flow, the SPA loads twice.
Is there a way that I can do this such that the Angular app only loads once?

A: You could use a popup window, as cgTag suggested, but popups are problematic on small devices and from my experience, people usually don't like them even on desktop computers. You cannot use an iframe, since the user should see the URL and certificate of the auth server.
I think the best way to solve the problem is to optimize your SPA to load faster. You need it for the first page load anyway. There are several ways to speed up the loading - ahead-of-time (AOT) compilation, tree-shaking, lazy loading, server-side pre-rendering and such. If you use Angular CLI, it has built in support for some of them, so it's easy to try and see whether they bring some improvements.


text:
Q: Db4o - how to rename a field in one step? As I've read in db4o documentation (.net version), I supposed that to rename a field in a class I would have to add the following to my code (and renaming the actual field in the class, of course):
IEmbeddedConfiguration configuration = Db4oEmbedded.NewConfiguration();
configuration.Common.ObjectClass("Namespace.ClassName, AssemblyName").
   ObjectField("fieldname").Rename("newfieldname");

And then leave this code there. But I tested this and it didn't work (the objects in the database would not load the renamed field). What did work was to follow the instructions in this page, which are

*

*Configure the renaming

*Open the db with the configuration created in 1

*Close db

*Change the field name in the code

*Now when opening the db again DO NOT CONFIGURE THE RENAME.

This seems a bit odd to me. My program needs to run once with just the rename call, and the run without the rename call but with the actual field renamed. The question is: is there a way to do an effective rename in just one step?
The steps that worked may mean a little extra effort, for example, in the process of updating an embedded (mobile) application - before installing the new version (refactored) on client, it would be necessary to run the rename call once. Is there a way to avoid it? Am I missing something or is there other way to rename a fiel in a db4o database?

A: I also had no luck with renaming in the configuration, but I found the following way that works well:
static void RenameFields() {
    using (IObjectContainer db = Db4oEmbedded.OpenFile("mydb.db4o")) {
        db.Ext().StoredClass(typeof(MyType)).GetStoredFields().Single(f => f.GetName() == "<ID>k__BackingField").Rename("<Id>k__BackingField");
    }
}

MyType can also be specified using the fully qualified class name as given by the function below, which lists all stored classes and field names. You will notice that private fields generated by auto properties are of the form <PropertyName>k__BackingField, for example <Id>k__BackingField for a property named Id.
static void ShowClassNamesAndFields() {
    using (IObjectContainer db = Db4oEmbedded.OpenFile("mydb.db4o")) {
        var dbClasses = db.Ext().StoredClasses();
        foreach (var dbClass in dbClasses) {
            Debug.Print(dbClass.GetName());
            foreach (var dbField in dbClass.GetStoredFields()) {
                Debug.Print("    " + dbField.GetName());
            }
        }
    }
}


text:
Q: Bundling server side code with webpack 2 I'm trying to bundle server side code with target: node but the code isn't transpiled (I see the source code in the build file) and there is the entry file only without any imported modules in it.
// webpack.config.server.dev.babel.js
import path from 'path'
const SRC = path.resolve(__dirname, '../server')
const BUILD = path.resolve(__dirname, '../build/')

const babelConfig = {
  babelrc: false,
  presets: [['env', {
    targets: { node: 'current' },
    modules: false,
    //useBuiltIns: true
  }], 'react']
}

export default {
  context: SRC,
  entry: './',
  output: {
    path: BUILD,
    filename: 'server.bundle.js'
  },
  target: 'node',
  module: {
    noParse: /node_modules/,
    rules: [{
      test: /\.jsx?$/,
      use: {
        loader: 'babel-loader',
        options: babelConfig
      }
    }, {
      test: /\.css$/,
      use: [
        'style-loader',
        {
          loader: 'css-loader/locals',
          options: {
            modules: true,
            localIdentName: '[folder]__[local]--[hash:base64:5]',
            camelCase: true
          }
        }
      ]
    }]
  },
  devtool: 'source-map',
  performance: { hints: false },
  resolve: {
    modules: ['node_modules', 'shared'],
    extensions: ['.js', '.jsx', '.json']
  }
}

What am I doing wrong?

A: config.module.noParse = true caused the behavior.


text:
Q: Reading a file in unix I am completely new to Unix. I want to access my friends file whose ls -l gives:
-r--r----- 1 root filename

Note that I am not the root user and just a normal user. My question is how to read this file?
I tried to change the ownership by using chown and change the permission using chmod but it gives Operation not permitted.
Outputs of variuos commands :
$ ls -l
total 4
-r--r----- 1 root abacus 373 Nov 12 19:19 abacus
$ groups
Wayne
$ cat abacus
abacus: Permission Denied

A: You cannot change the ownership of the file because you are not the superuser (root), and you do not already own the file.  If you could change the ownership/permissions on files you do not own, it would completely nullify the whole purpose of the permissions/ownership mechanism, which is computer security.
If you were operating a multiuser system, would you want your users to be able to muck about with files they do not own?  Would you like other users to modify your files without your permission?

A: Based on the information given, it looks like you won't be able to read the file. The owner is root, and the group abacus; the file is set to be readable only by the owner and group. And it looks like you are not in the group; you are only in the group Wayne.
Unless your friend was asking you to try hacking his system (for instance, if he had left the /etc/group file world writeable, so you could add yourself to the abacus group), then you should not be able to read that file.


text:
Q: how to draw guide lines on a gnuplot generated cdf? At work have a set of floating point values that I sort and compute a CDF for and plot within gnuplot.  I'd like to draw a line showing where the 80% and 90% thresholds of the CDF are, i.e. a line coming in from the left @ the 0.8 y tic mark, touching the graph and then dropping down to whatever that value might be.  This is to help guide the viewers eye.
The data is generated automatically and I make multiple plots so I don't want to have to hand craft these lines each time.
It's trivial to draw a horizontal arrow going completely across the plot at the 0.8 and 0.9 y-value points, but I don't understand how to determine where the vertical line should be drawn.
Here is a q/a wrt drawing arrows: Gnuplot: Vertical lines at specific positions, but the positions are known a priori.
Here is some sample data (my work machine is not internet accessible so sharing is hard)
  X                Y
 5.0   |         0.143
 8.0   |         0.288
16.0   |         0.429
25.0   |         0.714
39.0   |         0.857
47.0   |         1.000

Any ideas?

A: Here is my take (using percentile ranks), which only assumes a univariate series of measurement is available (your column headed X). You may want to tweak it a little to work with your pre-computed cumulative frequencies, but that's not really difficult.
# generate some artificial data
reset
set sample 200
set table 'rnd.dat'
plot invnorm(rand(0))
unset table

# display the CDF
unset key
set yrange [0:1]
perc80=system("cat rnd.dat | sed '1,4d' | awk '{print $2}' | sort -n | \
          awk 'BEGIN{i=0} {s[i]=$1; i++;} END{print s[int(NR*0.8-0.5)]}'")
set arrow from perc80,0 to perc80,0.8 nohead lt 2 lw 2
set arrow from graph(0,0),0.8 to perc80,0.8 nohead lt 2 lw 2
plot 'rnd.dat' using 2:(1./200.) smooth cumulative

This yields the following output:

You can add as many percentile values as you want, of course; you just have to define a new variable, e.g. perc90, as well as ask for two other arrow commands, and replace every occurrence of 0.8 (ah... the joy of magic numbers!) by the desired one (in this case, 0.9).
Some explanations about the above code:

*

*I generated an artificial dataset which was saved on disk.

*The 80th percentile is compute using awk, but before that we need to

*

*remove the header generated by table (first four lines); (we could ask awk to start at the 5th lines, but let's go with that.)

*keep only the second column;

*sort the entries.

*The awk command to compute the 80th percentile requires truncation, which is done as suggested here. (In R, I would simply use a function like trunc(rank(x))/length(x) to get the percentile ranks.)

If you want to give R a shot, you can safely replace that long series of sed/awk commands with a call to R like
Rscript -e 'x=read.table("~/rnd.dat")[,2]; sort(x)[trunc(length(x)*.8)]'

assuming rnd.dat is in your home directory.

Sidenote: And if you can live without gnuplot, here are some R commands to do that kind of graphics (even not using the quantile function):
x <- rnorm(200)
xs <- sort(x)
xf <- (1:length(xs))/length(xs)
plot(xs, xf, xlab="X", ylab="Cumulative frequency")
## quick outline of the 80th percentile rank
perc80 <- xs[trunc(length(x)*.8)]
abline(h=.8, v=perc80)
## alternative solution
plot(ecdf(x))
segments(par("usr")[1], .8, perc80, .8)
segments(perc80, par("usr")[3], perc80, .8)

A: You can use awk to calculate the line at a given value.
Example
If you have a data file Data.csv like so:
0     1
1     4
2     9
3    16
4    25
5    36
6    49
7    64
8    81
9   100

you can plot it with
plot "Data.csv" u 1:2 w l

Now if you want to draw a line at 90% of the maximal value of the second column (in this case 90) run an awk script. Its purpose is to identify the minimum and maximum x-value and the 90% value of the maximal y-value. It could look something like this:
awk '
{
if(x_min == "") {x_min = x_max = $1; y_max = $2};
if($1 > x_max) {x_max = $1};
if($1 < x_min) {x_min = $1};
if(y_max < $2) {y_max = $2}}
END {
print x_min, y_max * 0.9;
print x_max, y_max * 0.9
}' Data.csv

Basically what it does is the following:

*

*Check if x_min exists and if it does not set x_min, x_max and y_max to the first or second column of Data.csv.

*Check if the current first column is larger than the current x_min, if that is the case, set x_min to the value of the current first column.

*Do the equivalent for x_max and y_max (Note: we only need the maximum of the second column and not the minimum)

*After we looped through our data file print the result like so:
x_min y_max * 0.9
x_max y_max * 0.9

In order to make this work in gnuplot we append our script from above like so:
plot "Data.csv" u 1:2 w l, \
     "< awk '{if(x_min == \"\") {x_min = x_max = $1; y_max = $2}; if($1 > x_max) {x_max = $1}; if($1 < x_min) {x_min = $1}; if(y_max < $2) {y_max = $2}} END {print x_min, y_max * 0.9; print x_max, y_max * 0.9}' Data.csv" u 1:2 w l

Note the \" in the gnuplot script. The " need to be escaped for gnuplot not to stumble over them...
After all you should end up with a plot like this:

The green line marks the 90% value of the maximal y-value.


text:
Q: Schema for hierarchical data Schema of the tables that maintain hierarchical data:
Category table:
|   ID  |   Label |

Mapping table:
|   ID  |  ItemID   | ParentID  |

One of the requirements is to be able to map and construct a category tree similar to below:
Root
|
|---Wood (0)
|   |---Foundations (2)
|       |---Root Systems (4)
|           |---Closed Systems (5)
|
|---ETC (1)
|   |---Foundations (2)
|       |---Technology
|           |---Support
|       |---Root Systems (4)
|           |---Open Systems (6)

As you can see Foundations (2) can be a child of Wood (0) and ETC (1). I store this structure as below in the mapping table
|   ID  |  ItemID   | ParentID  |
|    1  |  2        | 0         |
|    2  |  2        | 1         |

I am in a conundrum. When constructing tree, how can I properly categorize Foundations as two different nodes one under Wood and one under ETC. Also, Foundations can have different or same children depending on the data. Note that Root Systems has Open Systems (6) as the child but Root Systems under Foundations has Closed Systems (5) as the child. Based on the current schema if I construct tree, it would look like this which is wrong:
Root
    |
    |---Wood (0)
    |   |---Foundations (2)
    |       |---Root Systems (4)
    |           |---Closed Systems (5)
    |           |---Open Systems (6)

    |
    |---ETC (1)
    |   |---Foundations (2)
    |       |---Technology
    |           |---Support

What changes should I make to the schema to accommodate my requirements? Is it really a hierarchical data?
=====================================
Rephrasing my question:
I need to be able to create schema for a tree which is represented as follows:

Root1
|---    Foundations
|---    --- Root Foundations
|---    --- --- Caps
|---    --- Primary Foundations
|---    --- --- Beams
|---    --- Retaining Walls
|---    Down Systems
|---
|---
Root2
|---    Foundations
|---    --- Root Foundations
|---    --- Retaining Walls
|---    --- --- Piles

I came up with below schema to store above hierarchical data:
CATEGORY Table
id  label
1   Root1
2   Root2
3   Foundations
4   Down Systems
5   Root Foundations
6   Primary Foundations
7   Retaining Walls
8   Caps
9   Beams
10  Piles

MAPPING Table
id  itemid  parentid
1   1   null
2   2   1
3   4   1
4   3   2
5   4   2
6   5   3
7   6   3
8   7   3
9   5   3
10  7   3
11  8   5
12  9   6
13  10  7

But I don't know how to write a query using common table expression or any other constructs to return the data in such a way that I can construct the tree. How can I modify my schema to be able to generate a tree in the above format?

A: The following example demonstrates how to use a single table to represent multiple trees of categories. Note that while the hierarchies are accurately represented in the output that the order of categories in the second tree differs from the OP's example due to a rearrangement of the table rows of sample data. If the order is important then it will have to be specified explicitly, i.e. either based on the existing data (e.g. alphabetical by Label) or by the addition of another column to the Categories table to specify the order within a level of a tree.
To see the example in action: dbfiddle.
-- Sample data.
declare @Categories as Table
  ( CategoryId Int Identity, Label NVarChar(50), ParentCategoryId Int NULL );

insert into @Categories ( Label, ParentCategoryId ) values
  -- First tree.
  --   Rows in order of the categories within the tree.
  ( 'Root1', NULL ),
  ( 'Foundations', 1 ),
  ( 'Root Foundations', 2 ),
  ( 'Caps', 3 ),
  ( 'Primary Foundations', 2 ),
  ( 'Beams', 5 ),
  ( 'Retaining Walls', 2 ),
  ( 'Down Systems', 1 ),
  -- Second tree.
  --   Rows out-of-order to show that the hierarchy is not dependent on   CategoryId   order.
  ( 'Piles', 10 ),
  ( 'Retaining Walls', 13 ),
  ( 'Root Foundations', 13 ),
  ( 'Root2', NULL ),
  ( 'Foundations', 12 );

select * from @Categories;

And the good part:
-- Walk through the hierarchy.
with Trees as (
  -- Start from the roots, i.e. categories with no parents.
  select CategoryId, Label, ParentCategoryId,
    -- Assemble the path of categories as we go so that we can order the results rationally.
    Cast( '/' + Cast( CategoryId as VarChar(10) ) + '/' as HierarchyId ) as Path
    from @Categories
      where ParentCategoryId is NULL
  union all
  -- Add each level of children.
  select Child.CategoryId, Child.Label, Child.ParentCategoryId,
    Cast( Parent.Path.ToString() + Cast( Child.Categoryid as VarChar(10) ) + '/' as HierarchyId )
    from Trees as Parent inner join
      @Categories as Child on Child.ParentCategoryId = Parent.CategoryId
  )
  -- Display the result.
  select CategoryId, Replicate( '|---', Path.GetLevel() - 1 ) + Label as Label, ParentCategoryId,
    Path.GetLevel() as Depth, Path
    from Trees
    order by Path;

Aside: Notice that well chosen column and table alias names make it much easier to understand code like ... from Trees as Parent inner join @Categories as Child on Child.ParentCategoryId = Parent.CategoryId.


text:
Q: I can save the image, but it's black I am using a nice tool called cropit and built a little application: You can check it out here
Now I tried to save the image instead of opening it in a new windows. I used this:
JQUERY:
$('.export').click(function() {
    var imageData = $('#image-cropper').cropit('export');
    $.post('upload.php', { imageData: imageData }, function() {
      alert("success");
    })
});

PHP:
$imageData = $_POST['imageData'];
$decoded = urldecode($imageData);
$exp = explode(',', $decoded);
$base64 = array_pop($exp);
$data = base64_decode($base64);
$file = 'data.png';
file_put_contents($file, $data);

In result I get a PNG file in my directory, which does not get an error when I open (I can zoom and do stuff), but it is blank. How do I make the image appear in the file?


text:
Q: reshape long to wide aggregated by multiple variables while keeping the original repeated rows I have this question that might be a reshaping or a merging problem.
id = c(rep(1,5), rep(2,5))
type = factor(c(1L, 1L, 2L, 2L, 2L,  2L, 2L, 1L, 1L, 1L),
              labels = c('pay','inv'))
lett = c('a', 'b', 'a_inv','a_inv', 'b_inv', 'c', 'c', 'd', 'd', NA)
numb = c(30, 30, -10, -20, -30, -20, -20,  20, 20, NA)
abs_numb = abs(numb)

test = data.frame(id, type, lett, numb, abs_numb)
test

   id type  lett numb abs_numb
1   1  pay     a   30       30
2   1  pay     b   30       30
3   1  inv a_inv  -10       10
4   1  inv a_inv  -20       20
5   1  inv b_inv  -30       30
6   2  inv     c  -20       20
7   2  inv     c  -20       20
8   2  pay     d   20       20
9   2  pay     d   20       20
10  2  pay  <NA>   NA       NA

I would like to reshape this long table into a wide table, aggregated by id, abs_numb and separated by type. Something like this:
  id abs_numb numb_inv numb_pay  lett_pay  lett_inv
  1       30  -30         30        b         b_inv
  1       10  -10         NA        NA        a_inv
  1       20  -20         NA        NA        a_inv
  1       30   NA         30        a         NA
  2       20  -20         20        d         c
  2       20  -20         20        d         c
  2       NA   NA         NA        <NA>      <NA>

I have two repeated rows in the data set (id == 2, abs_numb == 20), if I aggregate on this it will just return one line. But I need to keep both in the wide dataset for counting purposes. If I first split the dataset based on type == pay and type == inv and then merge on id and abs_numb, it will return four lines, when I only need two.
My dataset is kind of big, so I wonder if there's an efficient way to achieve this.
Thank you in advance!


text:
Q: Неправильная powershell/cmd команда Файл не компилируется когда делаю через ide. Но когда я вручную открываю powershell и пишу команду(из Arguments), то все отлично срабатывает.
public void CreateTest(string filePath, int a, int b)
        {

            var pc = new Process
            {
                StartInfo =
                {
                    Verb = "runas",
                    Arguments = $"dotnet \"C:\\Program Files\\dotnet\\sdk\\6.0.300\\Roslyn\\bincore\\csc.dll\" -r:\"C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\6.0.5\\System.Private.CoreLib.dll\" -r:\"C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\6.0.5\\System.Console.dll\" -r:\"C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\6.0.5\\System.Runtime.dll\" -r:\"C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\6.0.5\\System.Runtime.InteropServices.RuntimeInformation.dll\" {filePath}.cs",
                    FileName = "powershell",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                }
            };

            pc.Start();
            string stdoutx = pc.StandardOutput.ReadToEnd();
            string stderrx = pc.StandardError.ReadToEnd();
            pc.WaitForExit();

            Console.WriteLine("Exit code : {0}", pc.ExitCode);
            Console.WriteLine("Stdout : {0}", stdoutx);
            Console.WriteLine("Stderr : {0}", stderrx);
}

Вот такая ошибка:

A: Вероятно, нужно эскейпить строку дважды, но зачем вам здесь вообще PowerShell? Если с запуском обычный cmd справится? Да даже если в лоб запустить dotnet - тоже прокатит.
Verb = "runas",
Arguments = $@"""C:\Program Files\dotnet\sdk\6.0.300\Roslyn\bincore\csc.dll"" -r:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.5\System.Private.CoreLib.dll"" -r:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.5\System.Console.dll"" -r:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.5\System.Runtime.dll"" -r:""C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.5\System.Runtime.InteropServices.RuntimeInformation.dll"" ""{filePath}.cs""",
FileName = "dotnet",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true


text:
Q: Nuxt 3 package import specifier "#internal/nitro" is not defined I tried installing the new version of Nuxt.js with command:
npx nuxi init nuxt-app

Then tried just run and project in Nuxt 3 works fine. But when I tried run this command:
npm run generate

Get this error message:

ERROR  [nuxt] [request error] Package import specifier
"#internal/nitro" is not defined in package
C:\Users\Andreas\Projects\nuxt3-app\package.json imported from
C:\Users\Andreas\Projects\nuxt3-app.nuxt\dist\server\server.mjs   at
new NodeError (node:internal/errors:371:5)   at throwImportNotDefined
(node:internal/modules/esm/resolve:442:9)   at packageImportsResolve
(node:internal/modules/esm/resolve:819:3)   at moduleResolve
(node:internal/modules/esm/resolve:973:21)   at defaultResolve
(node:internal/modules/esm/resolve:1080:11)   at ESMLoader.resolve
(node:internal/modules/esm/loader:530:30)   at ESMLoader.getModuleJob
(node:internal/modules/esm/loader:251:18)   at ModuleWrap.
(node:internal/modules/esm/module_job:79:40)   at link
(node:internal/modules/esm/module_job:78:36)

My package.json source code:
{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
  "devDependencies": {
    "nuxt": "3.0.0-rc.1"
  }
}

*

*Node version: 16.14.1

*NPM version: 8.5.0

A: (Irrelevant solution, as this issue was in an RC version. Only leaving this solution for archive purposes. If you are using Nuxt and encounter this error, chances likely that this is not the correct solution. Please find another one)
-- Original comment --
I randomly fixed this issue by setting
// nuxt.config.ts

  ssr: false

Hope its the case for you too.

With client side rendering only there is no server-side rendering. Client side rendering means rendering the content in the browser using JavaScript. Instead of getting all of the content from the HTML we just get a basic HTML document with a JavaScript file that will then render the rest of the site using the browser. For client side rendering set ssr to false.

Link to configuration-ssr documentation
Link to rendering-modes documentation


text:
Q: after android 13 in samsung one ui 5 update device's data/data not display in Android Studio Device File Explorer i update my samsung mobile to one ui 5 android 13 after that i can't access my mobile's data/data folder in Android Studio`
how to access now ?


text:
Q: Display one by one text in textview every 10 seconds I want to display one by one some text which is named A,B,C,D in textview every 10 seconds (A-B-C-D-A-B-C-D...).
Can everyone give me some code?

A: seeking for code without any try is no a good habit. Anyways I am giving you a hint, try ureself. There are several other options. Here are some
Option 1:
put the texts in a array of string, use a timer to show the text one by one from the array every 10 seconds. when you reach the end of the array again show the first text.
Option 2:
as FoamyGuy suggeted. use [TextView.postDelayed][2] method to perform your task. In the runnable in postDelayed use the postDelayed method call recursively.
Option 3:
use different thread to perform your time counting then when triggered show the text using runOnUIThread.
So from these options (and may be other options too) I think it is better for you to learn and choose  your option.
[2]: http://developer.android.com/reference/android/view/View.html#postDelayed(java.lang.Runnable, long)


text:
Q: Copy PDF file to iBooks library I'm developing a sample app that user can read pdf file, pdf files in my app bundle and i use web view to read these files. Now i want to add a button that allow user click to and copy pdf file to iBooks library, that means when user perform this action, after that, when user opens iBooks app, this PDF file is already available in library of iBooks. Any idea for this problem, plz helps me, thanks alot.
PS: i want to make as this link, but i dont want open pdf file immediately in iBooks when user click button, i just want when user open ibooks after that anytime, user can see this pdf book in book shelf

A: There is not an API available for directly adding content to iBooks, unfortunately.
How it works is your app uses a UIDocumentInteractionController to present the user with the ability to open the PDF in an application that supports the file type that you specify to the controller.  One of those apps would be iBooks, if it is installed on the user's device.
Additional Resources:

*

*UIDocumentInteractionController sample application from developer.apple.com

*UIDocumentInteractionController Class Reference


text:
Q: Style is not binding in css i am trying to bind style in my css style using below format but its not working and i am learner for web development can some one help me please what is mistack?
css
.block-header.row.sample h1{
        color: aqua;
    }

html

Pending Approvals

A: Your style rule is wrong, it should be: .block-header .row.sample h1 instead of .block-header.row.sample h1. When you have a style for an element that's a descendant of another one (in your case .row.sample is a child of .block-header) you should have the parent first, followed by a space (or > if it's a direct child) and then the descendant element, just like you're doing with the h1...
You can see it works with that simple change:

.block-header .row.sample h1{
        color: aqua;
}

Pending Approvals

You can read more about selectors in mdn.

A: The problem in your rule is that there are no spaces between your classes, which makes the selector any h1 element with the parent having classes block-header, row, and sample.
You would need to put spaces so that the selector knows these elements are nested inside each other:
.block-header .row.sample h1 {
    color: aqua;
}

Learn more about how these selectors work from this FreeCodeCamp guide.


text:
Q: CSS Filter not working on body in Chrome & Firefox I want to create a chrome extension that does some filtering for color blindness testing and wanted to use css/svg filters but have a problem with filters not affecting body background.
Any suggestions?
Link to codepen (test in Chrome) or see screenshots below:
http://codepen.io/larsenwork/pen/oZvdzX/?editors=1100

html {
 filter: grayscale(100%);
}

body, div {
 background-color: cyan;
}

/* Codepen style (ignore) */
* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

body {
 min-height: 100vh;
 padding: calc(3vh + 3vw);
 display: flex;
 flex-direction: column;
 align-items: flex-start;
 font-family: sans-serif;
 font-weight: 700;
 font-size: calc(3vh + 3vw);
 line-height: 1.3;
}

div {
 margin: 0 calc(-.5vh - .5vw);
 padding: 0 calc(.5vh + .5vw);
}

small {
 font-size: .6em;
 margin-top: 2em;
}

pre {
 font-weight: normal;
}
In Chrome: Why is the body bg not gray

When this is?

Same result (i.e. not applied to body) with e.g.
filter: hue-rotate(90deg);
or
filter: url("#grayscale");

<svg version='1.1' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='saturate' values='0'/></filter></svg>

Chrome + Firefox:

Safari:

A: So I found a solution (not happy with it) but setting a background property like background-color: magenta; or background-image: url(""); on the html fixes the issue in chrome and Firefox
Link to working version:
http://codepen.io/larsenwork/pen/mWbjJY?editors=1100
html {
    filter: grayscale(100%);
    background-color: magenta;
}

body, div {
    background-color: cyan;
}


text:
Q: What is Azure storage blob IP range for white listing I am trying to find the IP range for Azure storage blob. I have a storage blob. I cannot white-list domain name so I am looking for IP range for this. My blob is in USWEST region.
Could someone advice?

A: Microsoft provides IP address ranges in bulk for Compute, SQl and Storage, however you have a choice to whitelist only those IP for USWEST region.
As of now, you can't simply whitelist IP for Azure Blob Storage.
https://www.microsoft.com/en-us/download/details.aspx?id=41653


text:
Q: How to prevent the page contextual filter to be appended to the page url when using contextual filters in drupal? I have a page that has both a contextual filter and an exposed filter. My Problem lies in the fact that If I access the page through myview/12 (where 12 is my contextual filter) and then use the on-page exposed filter to filter out the result , the value 12 would still be appended to the page and it would limit my results within the contextual filter value... Is there a way to remove the contextual filter value when using an exposed filter?
Thanks!

A: You can give a try to the Views Filter Harmonizer module. This module solves the problem when having views with contextual filter and exposed filters at the same tima and you can configure it to make them work independantly.

A: I don't think so. Because the page results is being filtered by the contextual filter before the exposed filters.
Why do you use "myview/12"?! Why don't only use "myview" without anything passed as  contextual filter ?
UPDATE:
To exclude the contextual filter from the URL, you need to change the the form's redirect attribute by applying hook_form_alter().
To do so you need to follow the following steps:

*

*find the form id.

*Change your module weight in "system" table. (Because views' weight defaults to 10, your module needs to have a heavier weight to make sure it affects the form generated by views)

*change the the form redirect attribute. $form['#redirect'] = 'myview';

Tell me if it worked.
Muhammad.

A: Provide a validation criteria, that fails if there is some exposed filter in the url, and select to display all values if the validation criteria fails.


text:
Q: Prove $\liminf\limits_{n\to\infty} F(x_n)\le F(x)$
Suppose $F$ is a nondecreasing and right continuous function, and the sequence $\{x_n\}_{n\geq1}$ converges to $x$. Then $\liminf\limits_{n\to\infty}F(x_n)\leq F(x)$.

How can I prove this?

A: Hints:

*

*For every $z\gt F(x)$, there exists $y\gt x$ such that $F(u)\leqslant z$ for every $u\leqslant y$.

*Since $x_n\to x$, $x_n\leqslant y$ for every $n$ large enough.

*Hence...

Edit:
... $F(x_n)\leqslant F(y)\leqslant z$ for every $n$ large enough. In particular, $\limsup\limits_{n\to\infty}F(x_n)\leqslant z$. This is valid for every $z\gt F(x)$, hence...

A: HINT: Let $\sigma_R=\langle x_{n_k}:k\in\Bbb N\rangle$ be the subsequence of terms greater than or equal to $x$, and let $\sigma_L=\langle x_{m_k}:k\in\Bbb N\rangle$ be the subsequence of terms less than $x$.

*

*If either subsequence is finite, it can be ignored.

*If $\sigma_R$ is infinite, $\lim\limits_{k\to\infty}F(x_{n_k})=F(x)$.

*For each $k\in\Bbb N$, $F(x_{m_k})\le F(x)$.

*If both subsequences are infinite, $\liminf_k x_k=\min\{\liminf\sigma_L,\liminf\sigma_R\}$.


text:
Q: PHP errors parsing Realurl config file I have installed the typo3 rearurl extension in Typo3. If I copy to the default manual config location typo3conf/realurl_conf.php a configuration file with for example:
<?PHP
   $TYPO3_CONF_VARS['EXTCONF']['realurl'] = array(
      '_DEFAULT' => array(

      ),
   );
?>

I getting PHP errors like below?
Parse error: syntax error, unexpected '$TYPO3_CONF_VARS' (T_VARIABLE) in /home/extension/public_html/typo3conf/realurl_conf.php on line 1

A: Use this instead
<?PHP
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'] = array(
   '_DEFAULT' => array(

   ),
);
?>

In newer version there are some problems with $TYPO3_CONF_VARS vs $GLOBALS['TYPO3_CONF_VARS'] the last one works always.


text:
Q: Xcode 9 Bug: Cannot find cdtool After installing Xcode 9 beta, Xcode 8 gives me an error when compiling a project:

Cannot find cdtool at '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents/cdtool': Cannot find a simulator runtime for platform <DVTPlatform:0x7fd67af0a930:'com.apple.platform.iphonesimulator':<DVTFilePath:0x7fd67af0a7c0:'/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform'>>.

I suspect Xcode 9 modified some shared state with Xcode 8 (set a path, overwrote a file, etc.). But I've tried deleting and both Xcodes to no avail.
The project uses Core Data and it's clearly failing when trying to compile the xcdatamodel.
I can still compile and run under Xcode 9.

A: Didn't work for me because I also have a Watch app and got the error on the Watch SDK.
I ended up deleting both Xcode 8 and 9 Beta, deleting /Library/Developer and ~/Library/Developer. Then reinstalled Xcode 8 and it worked.

A: An Apple engineer reached out about this...
Those of you with cdtool errors in Xcode 8, I suspect you installed the iOS 10.3 Simulator runtime from Xcode 9. It was discovered this week that this causes a problem with cdtool in Xcode 8.3.
You can work around that by moving iOS 10.3.simruntime aside and restarting CoreSimulatorService (source):
sudo mkdir /Library/Developer/CoreSimulator/Profiles/Runtimes/Backup

sudo mv /Library/Developer/CoreSimulator/Profiles/Runtimes/{,Backup/}iOS\ 10.3.simruntime

sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService

Then restart Xcode, Simulator, etc. Those of you that deleted CoreSimulator.framework and thus cannot run Xcode.app any more can reinstall CoreSimulator.framework with:
installer -pkg /Applications/Xcode-beta.app/Contents/Resources/Packages/XcodeSystemResources.pkg -target /

A: You can also remove the 10.3 folder from
/Library/Developer/CoreSimulator/Profiles/Runtimes
Restart Xcode in order to take effect (may not be needed).

A: I agree with this answer. In addition I first removed all existing(took backup) Xcode version from machine.Then kept xcode 8.3.3 in Application folder. Made the project to open with default Xcode 8.3.2. Problem got resolved.
The problem came when I updated Xcode 9 beta to 9.2.


text:
Q: Comparing multiple xmls using for-each I need to create report by comparing multiple xmls. There is base.xml and multiple chunked xmls. Actually these chunked xmls are transformed subset of base.xml.
My folder structure.
 Folder A - base.xml
 Folder B - metadata.xml(all the references to chuncked maintained here)
 Folder chunked - a.xml, b.xml, c.xml

Base.xml
<SchoolRoster>
<department>
    <name>Science</name>
    <location>LON</location>
    <Student>
        <rollNum>001</rollNum>
        <name>John</name>
        <age>14</age>
        <course>
            <refnum>A1</refnum>
            <math>A</math>
            <english>B</english>
            <metas>
                <meta>
                    <name>x</name>
                    <value>0</value>
                </meta>
                <meta>
                    <name>y</name>
                    <value>1</value>
                </meta>
                <meta>
                    <name>z</name>
                    <value>1</value>
                </meta>
            </metas>
        </course>
        <course>
            <refnum>B1</refnum>
            <government>A+</government>
            <math>A</math>
            <english>B</english>
        </course>
    </Student>
    <Student>
        <rollNum>002</rollNum>
        <name>Tom</name>
        <age>13</age>
        <course>
            <refnum>C1</refnum>
            <gym>A</gym>
            <geography>incomplete</geography>
            <metas>
                <meta>
                    <name>x</name>
                    <value>2</value>
                </meta>
                <meta>
                    <name>y</name>
                    <value>1</value>
                </meta>
            </metas>
        </course>
    </Student>
</department>
<department>
    <name>History</name>
    <location>OXE</location>
    <Student>
        <rollNum>001</rollNum>
        <name>John</name>
        <age>14</age>
        <course>
            <refnum>A1</refnum>
            <math>A</math>
            <english>B</english>
            <metas>
                <meta>
                    <name>x</name>
                    <value>0</value>
                </meta>
                <meta>
                    <name>y</name>
                    <value>1</value>
                </meta>
            </metas>
        </course>
        <course>
            <refnum>B1</refnum>
            <government>A+</government>
            <math>A</math>
            <english>B</english>
        </course>
    </Student>
    <Student>
        <rollNum>006</rollNum>
        <name>Harry</name>
        <age>13</age>
        <course>
            <gym>A</gym>
            <geography>incomplete</geography>
            <metas>
                <meta>
                    <name>x</name>
                    <value>2</value>
                </meta>
                <meta>
                    <name>y</name>
                    <value>1</value>
                </meta>
            </metas>
        </course>
    </Student>
</department>

Metadata.xml
<metadata>
<studentgroup category="science">
    <reference href="chunked/a.xml"/>
    <reference href="chunked/b.xml"/>
</studentgroup>
<studentgroup category="history">
    <reference href="chunked/a.xml"/>
    <reference href="chunked/c.xml"/>
</studentgroup>

a.xml
 <learner>
<ref>001</ref>
<name>John</name>
<age>14</age>
<course>
    <refnum>A1</refnum>
    <math>B</math>
    <english>B</english>
    <metas>
        <info>
            <name>x</name>
            <value>0</value>
        </info>
        <info>
            <name>y</name>
            <value>1</value>
        </info>
    </metas>
</course>
<course>
    <refnum>B1</refnum>
    <government>A+</government>
    <math>A</math>
    <english>B</english>
</course>

b.xml
 <learner>
<ref>002</ref>
<name>Tom</name>
<age>13</age>
<course>
    <refnum>C1</refnum>
    <gym>A</gym>
    <geography>incomplete</geography>
    <metas>
        <info>
            <name>x</name>
            <value>2</value>
        </info>
        <info>
            <name>y</name>
            <value>1</value>
        </info>
    </metas>
</course>

c.xml
<learner>
<ref>006</ref>
<name>Harry</name>
<age>13</age>
<course>
    <gym>A</gym>
    <geography>incomplete</geography>
    <metas>
        <info>
            <name>x</name>
            <value>2</value>
        </info>
        <info>
            <name>y</name>
            <value>1</value>
        </info>
    </metas>
</course>

Required Output:(not able to place HTML code)
        Department Name     Science
        Department Location LON
        Roll Number         oo1
        ---------------------------------------------------------
                                Base XML   Chucked XML      Equal?
        Name                        John        John        Yes
        Age                         14          14          Yes
        Course A1
                Math                A           B           No
                English             B           B           Yes
                Meta x
                        name        x           x           Yes
                        value       0           o           Yes
                Meta y
                        name        y           y           Yes
                        value       1           1           Yes
        Course B1
                Government          A+          A+          Yes
                Math                A           A           Yes
                English             B           B           Yes
        ---------------------------------------------------------
        Department Name         Science
        Department Location     LON
        Roll Number             oo2
        ---------------------------------------------------------
                                Base XML   Chucked XML      Equal?
        Name                        Tom         Tomcat      No
        Age                         13          13          Yes
        Course C1
                gym                 A           A           Yes
                geography   incomplete          incomplete  Yes
                Meta x
                        name        x           x           Yes
                        value       2           2           Yes
                Meta y
                        name        y           y           Yes
                        value       1           1           Yes
                Meta z
                        name        z           NA          NO
                        value       1           NA          NO
        ---------------------------------------------------------

I am trying following but not sure how to do multiple for-each loop:
 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:output method="html"/>
<xsl:template match="/">

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

</xsl:template>
<xsl:template match="department">
    <xsl:variable name="depName">
        <xsl:value-of select="name"/>
    </xsl:variable>
    <xsl:variable name="depLocation">
        <xsl:value-of select="location"/>
    </xsl:variable>

            Department Name

                <xsl:value-of select="$depName"/>

            Department Location

                <xsl:value-of select="$depLocation"/>

        <xsl:for-each select="Student">
            <xsl:variable name="rollNum" select="rollNum"/>
            <xsl:variable name="metaXML"
                select="document('metadata.xml')/metadata/studentgroup[@category='science']/reference/@href"/>
            <xsl:variable name="chuckedXML"/>

                Roll Number

                    <xsl:value-of select="rollNum"/>

                    <xsl:value-of select="$metaXML"/>

                Base XML
                Chuncked XML
                Equal?

        </xsl:for-each>

</xsl:template>

<xsl:template match="text()"/>

I am trying here:

*

*for each 'department/name' in base.xml match the right metadata/studentgroup/@category in metadata.xml.

*for each department/student/@rollNum match with chucked file 'metadata/studentgroupp[@category]/reference' find the matching chunked xml 'learner/ref'.

*compare the values.

*similarly loop through 'metas/meta' tags where 'name' should be unique identifier.

A: Here is some unpolished attempt to solve that, unfortunately the input samples have elements in different order (age, name vs. name, age) so it is not possible to simply compare based on position and furthermore the element names partly differ (meta versus info) so for those elements you need extra templates.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:param name="meta-uri" as="xs:string" select="'test2016032202.xml'"/>
    <xsl:param name="meta-doc" as="document-node()" select="doc($meta-uri)"/>

    <xsl:key name="cat" match="metadata/studentgroup" use="@category"/>
    <xsl:key name="stud" match="learner" use="ref"/>

    <xsl:key name="meta-compare" match="learner/course/metas/info" use="name"/>

    <xsl:output method="html" indent="yes"/>

    <xsl:template match="/">

                <title>Test</title>

                <xsl:apply-templates/>

    </xsl:template>

    <xsl:template match="department">

                    Department Name

                        <xsl:value-of select="name"/>

                    Department Location

                        <xsl:value-of select="location"/>

                <xsl:for-each select="Student">
                    <xsl:variable name="student" select="."/>
                    <xsl:variable name="student-chunk"
                        select="
                            for $ref-doc in document(key('cat', lower-case(../name), $meta-doc)/reference/@href)
                            return
                                key('stud', rollNum, $ref-doc)"/>

                        Roll Number

                            <xsl:value-of select="rollNum"/>

                        Base XML
                        Chuncked XML
                        Equal?

                    <xsl:apply-templates select="* except rollNum">
                        <xsl:with-param name="compare-parent" select="$student-chunk"/>
                    </xsl:apply-templates>

                </xsl:for-each>

    </xsl:template>

    <xsl:template match="Student//*[*]">
        <xsl:param name="compare-parent"/>
        <xsl:variable name="pos" as="xs:integer">
            <xsl:number/>
        </xsl:variable>
        <xsl:variable name="element-to-compare" select="$compare-parent/*[node-name(.) eq node-name(current())][$pos]"/>

                <xsl:value-of select="local-name()"/>

        <xsl:apply-templates select="*">
            <xsl:with-param name="compare-parent" select="$element-to-compare"></xsl:with-param>
        </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="Student//*[not(*)]">
        <xsl:param name="compare-parent"/>
        <xsl:variable name="pos" as="xs:integer">
            <xsl:number/>
        </xsl:variable>
        <xsl:variable name="element-to-compare"
            select="$compare-parent/*[node-name(.) eq node-name(current())][$pos]"/>

                <xsl:value-of select="local-name()"/>

                <xsl:value-of select="."/>

                <xsl:value-of select="$element-to-compare"/>

                <xsl:value-of select=". = $element-to-compare"/>

    </xsl:template>

    <xsl:template match="Student/course/metas/meta" priority="5">
        <xsl:param name="compare-parent"/>
        <xsl:variable name="element-to-compare" select="key('meta-compare', name, $compare-parent)"/>

                <xsl:value-of select="name"/>

                <xsl:value-of select="value"/>

                <xsl:value-of select="$element-to-compare/value"/>

                <xsl:value-of select="value = $element-to-compare/value"/>

    </xsl:template>

</xsl:stylesheet>


text:
Q: Is there any way to define a programming function not mathematic one? I want to define a programming function, as I understood in Mathematica we can define it as Module. Is there any way to pack this code in a Module and call it n time to plot n time m v , Y
like in range 1,n?
I just want to compare the results for different n.
Remove["Global`*"]
Clear["Global`*"]
n = 5;
y = Sum[x^i*a[i], {i, 2, n}];
th = D[y, x];
M = EI*D[y, {x, 2}];
V = EI*D[y, {x, 3}];
PE = EI/2*Integrate[(D[y, {x, 2}])^2, {x, 0, L}] -
   Integrate[q*(x/L)*y, {x, 0, L}];
Eq = Table[D[PE, a[i]], {i, 1, n}];
sol = Solve[Eq == 0, Array[a, n]]
Y = y /. sol
th /. sol
Eq /. sol;
m = FullSimplify[M /. sol[[1]]]
v = FullSimplify[V /. sol[[1]]]
EI = 100;
q = -1;
L = 10;
Plot[{m}, {x, 0, L}, AxesLabel -> {"x (m)", "M (N.m.)"},
 PlotLegends -> {Style[" M", Bold, 12]}]
Plot[{v}, {x, 0, L}, AxesLabel -> {"x (m)", "V (N/m^2.)"},
 PlotLegends -> {Style[" V", Bold, 12]}]
Plot[{Y}, {x, 0, L}, AxesLabel -> {"x (m)", "Y (m)"},
 PlotLegends -> {Style[" Y", Bold, 12]}]

A: To define a function you should clarify what you want as the input and output. As an alternative, you can use Manipulate
Clear["Global`*"]

EI = 100;
q = -1;
L = 10;

Manipulate[
  y = Sum[x^i*a[i], {i, 2, n}];
  th = D[y, x];
  M = EI*D[y, {x, 2}];
  V = EI*D[y, {x, 3}];
  PE = EI/2*Integrate[(D[y, {x, 2}])^2, {x, 0, L}] -
    Integrate[q*(x/L)*y, {x, 0, L}];
  Eq = Table[D[PE, a[i]], {i, 1, n}];
  sol = Solve[Eq == 0, Array[a, n]];
  Y = y /. sol;
  th /. sol;
  Eq /. sol;
  m = FullSimplify[M /. sol[[1]]];
  v = FullSimplify[V /. sol[[1]]];
  Column[{
    StringForm["M = ``", m],
    StringForm["V = ``", v],
    StringForm["Y = ``", Y[[1]]],
    Plot[Evaluate[Tooltip /@ {m, v, Y}], {x, 0, L},
     AxesLabel -> {Style["x (m)", 12, Bold], None},
     PlotLegends -> Placed[
       (Style[#, 12, Bold] & /@ {"M (N.m.)", "V (N/m^2)", "Y (m)"}),
       {0.7, 0.35}],
     ImageSize -> Medium]}],
  {{n, 5, Style["n", 12, Bold]}, 3, 6, 1, Appearance -> "Labeled"}] //
Quiet


text:
Q: What is a good tool or software for generating curved lines for Latex graphics? For example, I want to generate the following images,

or

I am using LaTexdraw at the moment but it seems to be very bad at generating curves. What would be a good choice for generating these curves for Latex graphics?

A: Inkscape is a great program for vector graphics.
It allows to embed latex equations (Extensions > Render > Mathematics > Pdflatex).

The images are .svg so you need to use \includesvg to embed them in your tex document. Rendering quality is optimal, much better than in the above .png export.
The only drawback is that generated elements are not linked to the source latex code. You can install the textext extension if working with long or complicated equations.

A: This is a starting for you. IMHO, Asymptote's paths can be managed in clearer
and easier way (try TikZ to compare!)

//http://asymptote.ualberta.ca/
unitsize(1cm);
pair A=(0,0), B=(3,0);
real h=4;
path p= A .. controls A+dir(55) and B+1.5*dir(-120) .. B;
path q=shift(0,h)*reverse(p);
filldraw(p--relpoint(q,0)--q--cycle,pink,blue);
shipout(bbox(5mm));


text:
Q: error on line 1 at column 3: xmlParsePI : no target name I need to generate a dynamic xml for the cms, products, images and categories pages of my online store. Here I show you the 3 files I use. The first one is the file funciones.php:
<?php
function devolver_url ($v,$i,$tipo=1)
   {
   foreach ($v as $linea)
     {
     $b=explode ("#",$linea);
     if ($b[1]==$i)
       $retorno=$b[2];
     }
  return $retorno;
 }
function devolver_url_productos ($v,$i)
   {
   foreach ($v as $linea)
    {
    $b=explode ("#",$linea);
    if ($b[1]==$i)
      $retorno=$b[2]."/".$b[4]."-".$b[3].".html";
    }
 return $retorno;
 }
function consultar_bd($consulta)
   {
   $bd="XXXXXXX";
   $clave="XXXXXXXXX";
   $host="localhost:3306";
   $conexion = mysql_connect($host, $user, $clave);
   mysql_select_db($bd, $conexion);
   $resultado = mysql_query($consulta, $conexion) or die(mysql_error());
   return $resultado;
   }

function quitar_tildes($cadena)
{
$no_permitidas= array ("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","À","Ã","Ì","Ò","Ù","Ù","à ","è","ì","ò","ù","ç","Ç","â","ê","î","ô","û","Â","Ê","ÃŽ","Ô","Û","ü","ö","Ö","ï","ä","«","Ò","Ã","Ä","Ë");
$permitidas= array ("a","e","i","o","u","A","E","I","O","U","n","N","A","E","I","O","U","a","e","i","o","u","c","C","a","e","i","o","u","A","E","I","O","U","u","o","O","i","a","e","U","I","A","E");
$texto = str_replace($no_permitidas, $permitidas ,$cadena);
return $texto;
}?>

File funciones_cms.php :
<?php
    include ("funciones.php");
    function poner_url_cms ($v)
       {
       $dominio="https://www.mobiliariocomercialmaniquies.com/";
       $l=array("nada","en","fr","es","de","it","ca");
       foreach ($v as $a)
          {
          $b=explode ("#",$a);
          echo '
                <url>
                <loc>'.$dominio.$l[$b[1]].'/content/'.$b[0].'-'.$b[2].'</loc>
                ';
          for ($i=1;$i<7;$i++)
             {
             if ($i<>$b[1])
                {
                echo '<xhtml:link
                rel="alternate"
                ';
                echo 'hreflang="'.$l[$i].'"
                ';
                echo 'href="'.$dominio.$l[$i].'/content/'.$b[0].'-'.devolver_url($v,$i,1).'"
                />';
                }
             }
            echo '</url>
            ';
          }
       }
    function generar_sitemap()
       {
       $consulta= "SELECT id_lang, id_cms,link_rewrite FROM ps_cms_lang";
       $resultado = consultar_bd($consulta);
       $filas = mysql_num_rows($resultado);
       $cms=0;
       if ($filas > 0)
       {
       while ($r= mysql_fetch_assoc($resultado))
       {
          if ( ($r['link_rewrite']<>"") && ($r['id_lang']<7) )
             {
               if ($r['id_cms']==$cms)
                   {
                   $v[]=$cms."#".$r['id_lang']."#".$r['link_rewrite'];
                   }
               else
                   {
                   if ($cms==0)
                      {
                      unset($v);
                      $cms=$r['id_cms'];
                      $v[0]=$cms."#".$r['id_lang']."#".$r['link_rewrite'];
                      }
                   else
                      {
                      poner_url_cms($v);
                      unset($v);
                      $cms=$r['id_cms'];
                      $v[0]=$cms."#".$r['id_lang']."#".$r['link_rewrite'];
                      }
                   }
             }
          }
       poner_url_cms($v);
       }
    }
    ?>

And finally i need to make the file cms.xml but it does not work:
    <?
    header("Content-Type: text/xml;charset=iso-8859-1");
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    include ("../funciones/funciones_cms.php");
    include ("../funciones/funciones.php");
    ?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <?php echo generar_sitemap() ?>
    </urlset>

I need to generate a dynamic xml for the cms, products, images and categories pages of my online store. Could you help me please?

A: *

*Your 'cms.xml' is not parsed by the webserver as PHP

*The HTTP client recieves the PHP source

*The PHP source is not valid XML

*The XML parser in the client throws an error

If you name the file cms.xml the webserver will not execute it as PHP (at least not without special configuration). That means that the PHP source will be send to the HTTP client. This includes the <? that starts your PHP source at the top of the file.
<? in XML is used for processing instructions (short PI), but they require a target name like <?xml-stylesheet ...?>


text:
Q: Store the output of the Python matplotlib function of pcolormesh and reconstruct it I am gonna apply Short Time Fourier Transform on this signal and plot the results using pcolormesh function. Then, I want to use Inverse Short Time Fourier Transform to reconstruct the signal. My question is how to use the output of the pcolormesh as input for signal.istft(Zxx) to get the signal back. In short this is what I want to do:
f, t, Zxx = signal.stft(sig, fs=250, nperseg=64)
mesh=plt.pcolormesh(t, f, np.abs(Zxx))
plt.axis('off')
plt.show()

which outputs this image. Then, apply the inverse Fourier Transform to reconstruct the signal:
_, xrec = signal.istft(mesh, fs=250)

Actually, I am not sure if the mesh input for the above function is the right way to do or not? And how I can get the correct input for the signal.istft(Zxx) instead of Zxx?
Thanks for your help.


text:
Q: web application, need to determine if a USB device is connected to the client computer I have a intranet web application that uses a signature pad to save the signatures of users.  I would like to display the signature control only when the sign pad is connected to the computer.
I have tried query against Win32_SystemDriver and Win32_USBController using ManagementObjectCollection but this will bring the server information.
I declare the control dynamically based on values in a parameter table. So the control is added to the form only if the parameter is needed. Now, if the parameter (signature) is required but the user does not have the signature pad, then I don't want the control to be added in the form.
There are ways to query against the device using the control, but I will have the control displayed in my form... I don't what to display it if not connected.

A: Perhaps with Flash you could try to get a hold of the USB connection... I don't really think you'll succeed, but it's worth a try.
Otherwise, probably not doable.


text:
Q: Direct sum of two modules Suppose that $M, N, P$ are right $R$-modules, where $R$ is a ring with unity, such that $M=N\oplus P$. Suppose that there exist two non-zero submodules $A,B\subseteq M$ with $A \cap B = 0$ and $A\cong B$. Is it possible to construct two non-zero submodules $A^{\prime}, B^{\prime} \subseteq N$ with $A^{\prime} \cap B^{\prime} = 0$ and $A^{\prime} \cong B^{\prime}$ ?!. I thought that $\pi_N(A)$ and $\pi_N(B)$, where $\pi_N: N\oplus P \to N$ is the canonical projection, would be the target submodules but, unfortunately, they do not satisfy the required criteria.
Thanks in advance. I appreciate any help.


text:
Q: Clicking ListView item and displaying its database contents in another activity i'm making a simple notes app which allows users to save data to a firebase database, ive then retrieve this data in a separate activity in a ListView and made each item within this ListView clickable. Would anyone be able to assist me in loading this data back into the original activity (with edit texts where we originally wrote this data).

A: You are making a mistake while putting data to your new intent
You need to replace
DatabaseReference putData = FirebaseDatabase.getInstance().getReference("ProgressReports/" + uid + "/" + id.get(i));
            Intent intent = new Intent(list_view.this, ProgressReports.class);
            String title = String.valueOf(putData.child("title"));
            String content = String.valueOf(putData.child("content"));
            intent().putExtra("titleTest", String.valueOf(title));
            intent().putExtra("contentTest", String.valueOf(content));
            startActivity(intent);

With
DatabaseReference putData = FirebaseDatabase.getInstance().getReference("ProgressReports/" + uid + "/" + id.get(i));
        Intent intent = new Intent(list_view.this, ProgressReports.class);
        String title = putData.child("title").getValue(String.class);
        String content = putData.child("content").getValue(String.class);
        intent.putExtra("titleTest", title);
        intent.putExtra("contentTest", content);
        startActivity(intent);


text:
Q: How to avoid PG::NumericValueOutOfRange when using sum function I have method like this:
  def self.weighted_average(column)
    sql = "SUM(#{column} * market_cap) / SUM(market_cap) as weighted_average"
    Company.select(sql).to_a.first.weighted_average
  end

When the column is a decimal, it returns a value without problem.
But when the column is integer, the method ends up with a PG::NumericValueOutOfRange error.
Should I change column type integer to decimal, or is there a way to get the result of sum without changing column type?

A: You can always make float from your integer.
  def self.weighted_average(column)
    column = column.to_f
    sql = "SUM(#{column} * market_cap) / SUM(market_cap) as weighted_average"
    Company.select(sql).to_a.first.weighted_average
  end

A: I would suggest you to change the datatype to decimal. Because, when SUM gets PG::NumericValueOutOfRange, it means that your datatype is not sufficient. It will lead to gracefully handle this scenario, instead of a workaround.

A: You can cast your value to alway be a decimal value, thus no need to change the column type:
sql = "SUM(#{column} * CAST(market_cap as decimal(53,8))) / SUM(CAST(market_cap as decimal(53,8))) as weighted_average"

P.S. I would go with changing the column type - it is consistent then.

A: Postgres documentation says this about SUM() return type:

bigint for smallint or int arguments, numeric for bigint arguments,
  otherwise the same as the argument data type

This means that you will somehow need to change datatype that you pass to SUM. It can be one of the following:

*

*Alter table to change column datatype.

*Cast column to other datatype in your method.

*Create a view that casts all integer columns to numeric and use that in your method.

A: You are trying to place a decimal value into a integer parameter. Unless you use the ABS() value that will not be possible, unless you are 100% sure that the % value will always be 0.
Use type Float or function ABS() if you HAVE to have an INT

A: Yo could try casting column to decimal
sql = "SUM(CAST(#{column}) AS DECIMAL * market_cap) / SUM(market_cap) as weighted_average"