text:
Q: Ruby - cant divide with fixnum values I need to calculate some % values by dividing two separate counts. I got the counts value which is class is fixnum. But while i am going to divide them, it showing me 0 whatever the count value is ,
<% dueTask = 12 %>
<% aT = 16 %>
<%= (dueTask/aT)*.to_f %>

Here Last result showing 0.

A: You can use two different lines in order to get the actual value.
    <% dueTask = 12 %>
    <% aT = 16 %>
    <% result = dueTask/aT.to_f %>
    <%= result %>

In IRB you can get the value by checking this:
dueTask = 12
aT = 16
dueTask/aT.to_f

but this technique might not work when you have to show the result in HTML. the variables are of Fixnum type (you can check it by the following command in IRB shell)
dueTask.class

Output will be
#=> Fixnum

A: You should convert them to float before division:
(dueTask.to_f/aT.to_f)

otherwise you'll get only integer part of the division, which is 0 in this case.

A: The way you did it the division is done with to integer, so the result is an integer. Even if you convert it to a float you just convert the result (0 in this case).
So you need to convert at least one of the two integers into a float:
<% dueTask = 12 %>
<% aT = 16 %>
<%= (dueTask.to_f/aT) %>

A: Right now you are getting the right answer to that division 0, because you are dividing 2 numbers that act as integer, and therefore you will get an integer answer.
To get a decimal answer from the division you need to convert them to float and then do the division.
dueTask.to_f/aT.to_f

Your code will end up like this:
<% dueTask = 12 %>
<% aT = 16 %>
<%= (dueTask.to_f/aT.to_f) %>


text:
Q: C using a file as an argument The problem I am having is that whenever I run the code I get the Null value for myfile before I even get to pass the file name as the argument into the program and i'm not sure why any help is much appreciated.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    FILE* myFile; // file pointer
    myFile = fopen(argv[1] , "r"); //open file
    if(myFile==NULL)
    {
        printf("Can't Open FIle.\n"); // if file doesn't exist then exit
        exit(0);
    }

    int A[10000]={0};
    int B[10000]={0};
    double C[10000]={0};
    int N,M;
    int i=0;

    fscanf (myFile, "%d", &N); //input N from file
    printf("%d\n",N);
    if(N>100)
    {
        exit(0); // if N>100 then exit
    }
    while (!feof (myFile)) // loop until file pointer reaches to the end of file
    {
        fscanf (myFile, "%d", &A[i]); //input source
        fscanf (myFile, "%d", &B[i]); // input destination
        fscanf (myFile, "%lf", &C[i]); // input time
        i++;
    }
    fclose (myFile); //close file

    M=i; // number of lines = M

    for (i = 0; i < M; i++)
    {
        if(A[i]==0) //end of output
            break;
        else
        {
            printf("%d %d %lf:\n",A[i],B[i],C[i]); //print source, destination and time
            if(A[i]>=1&&A[i]<=N)
            {
                if(B[i]>=1&&B[i]<=N)
                {
                    if(A[i]==B[i])
                    {
                        printf("Error:Source city is the same as destination city.\n"); //same source and destination error:condition
                    }
                    else
                    {
                        if(C[i]<0)
                        {
                            printf("Error:Invalid Time.\n"); //invalid time
                        }
                        else
                        {
                            //
                        }
                    }
                }
                else
                {
                    printf("Error: Invalid destination city.\n"); //invalid destination condition
                }
            }
            else
            {
                printf("Error: Invalid source city.\n"); //invalid source condition
            }
        }
    }

    return 0;
}

A: If you don't pass a file name as an argument to the program, the contents of argv[1] are undefined.
Since anything could be there in argv[1] when the program attempts to open the file, the most probable thing is that there is no file with that name, and hence fopen() returns NULL.
You should not try to access command line arguments without checking that they were supplied, for that check argc, if you just expect 1 argument, then a simple check would be
char filename[256]; /* the size should be reasonable
                     * can be PATH_MAX or MAX_PATH,
                     * depending on whether it's Windows
                     * or not
                     */
if (argc < 2)
 {
    size_t length;

    fprintf(stdout, "Error: %s program expects one argument\n", argv[0]);
    fprintf(stdout, "Please input the file name: ");
    if (fgets(filename, sizeof(filename), stdin) == NULL)
     {
        fprintf(stdout, "Error: unexpected error\n");
        return -1;
     }
    length = strlen(filename);
    if (length == 0)
     {
        fprintf(stdout, "Error: the provided file name is invalid.\n");
        return -1;
     }
    if (filename[length - 1] == '\n')
        filename[length - 1] = 0;
 }
else
    strcpy(filename, argv[1]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get selected item in react-native-modal-selector react-native-modal-selector has the getSelectedItem()(for
 getting the currently selected item) but when I'm using this method it's not working, it's not giving me any selected item.
code:
<ModalSelector
                                selectStyle={{ borderWidth: 0 }}
                                selectTextStyle={{ color: '#ffffff' }}
                                data={this.filterData()}
                                visible={this.state.visible}
                                optionTextStyle={{ fontSize: 20 }}
                                labelExtractor={(item) => item.categoryName}
                                initValue="Choose Category"
                                supportedOrientations={[ 'landscape' ]}
                                accessible={true}
                                getSelectedItem={(item)=> console.log(item)}
                                keyExtractor={(item) => item.categoryId}
                                closeOnChange={false}
                                backdropPressToClose={true}

         />

A: Get currently selected value of from array using the below code.
<ModalSelector
     data={data}
     initValue="Select something yummy!"
     supportedOrientations={['landscape']}
     accessible={true}
     scrollViewAccessibilityLabel={'Scrollable options'}
     cancelButtonAccessibilityLabel={'Cancel Button'}
     onChange={(option)=>{ this.setState({textInputValue:option.label})}}>

getSelectedItem(): get current selected item, updated by onChange() event only.
so that's the reason you are not getting currently selected value.
Hope it helps to you.


text:
Q: How can I target specific slides with custom CSS in ioslide presentation? Reading this introductory text, I thought it is straightforward to color the body or bullet points on a specific slide green. I created my own css file containing the following lines:
body p {
 font-size: 24px;
 font-family: Frutiger Light;
 color: orange;
}

li {
 font-family: Frutiger Light;
 font-size: 20px;
 color: green;
}

.change {
 color: green;
}

and referred to the css-class change by adding {.change} to my header in the rmarkdown file. However, this is completely ignored. I am lost and would very much appreciate a hint in how to solve this.
Here is a simple reproducible example. Please make sure that the css is located in the same folder than the rmd.

A: This really depends on what exactly would you like to style. The ioslides manage the "content"** of each slide with an
 that is given an id with the name of the slide. For example, if you do in your R Markdown file:
## Introduction

* Bullet 1
* Bullet 2

This will (after knit) render into a html similar to:
<hgroup>
Introduction
 </hgroup>

Bullet 1

Bullet 2

This means you can use your .css to target the
 bullets on that slide like so - very silly example, but you immediately see if you got it right (proper doc on this here):
#introduction ul li {
    font-size: 50px;
}

** I said content there vaguely, as the management of the entire <slide> is done via classes such as "current" which is variable and makes it more difficult to target a specific slide
EDIT: If you really want, you can also include the css directly in the .Rmd, using the example above you could do in your .Rmd:

## Introduction

* Bullet 1
* Bullet 2


text:
Q: Api response is null when consumed, with django and vue Im using my api from the rest framework, when I got to the URL from the api it shows's it correct. But when I consume it the response seems to be null.
Im hosting both project (front vuejs and back django) in diferents ports (8080 and 8000, respectively). CORS are allowed.
I've tried with another tools like fetch or jquery and seems to be the same.
Js:
export class APIService {
    contructor() {}

    get_user_id(){
        const url = `http://localhost:8000/api/v1/user-id/`;
        return axios.get(url).then(function (response) {
            console.log(response); // For testing
            return response.data;
        });
    }
}

Django api view, for that url:
class UserIdLoggedView(APIView):
    def get(self, request):
        user = request.user
        return Response({
            'id': user.id,
        })

For this case I didn't need a serializer.
This is how the django rest shows it:
    {    HTTP 200 OK
    Allow: GET, HEAD, OPTIONS
    Content-Type: application/json
    Vary: Accept

    {
        "id": 1
    }

And this is the output of the response from the console (just the data part)
data:
   id: null

Instead of return id=1 as expected it return null.

A: why are you using two return statements in get_user_id? You hit the first return statement and it doesn't wait for the promise to be fulfilled. Basically, you send the get request but don't wait for the response. Also, I would recommend creating a base instance of axios as a vue plugin.


text:
Q: Given $v_1(t) = 1 + t, v_2(t) = t + 2t^2$ and $v_3(t) = 1 - t^2$, check that the set {$v_1(t), v_2(t), v_3(t)$} is a basis of the vector space ...
Given $v_1(t) = 1 + t, v_2(t) = t + 2t^2$ and $v_3(t) = 1 - t^2$, check that the
set {$v_1(t), v_2(t), v_3(t)$} is a basis of the vector space $\mathbb R_2[x]$ of real polynomials of degree less than or equal to two and with real coefficients.

My attempt
$\alpha v_1 + \beta v_2 + \gamma v_3 = 0 = \alpha (1,1,0)+ \beta (0,1,2) + \gamma (1, 0, -1) = 0$
$\alpha + \gamma = 0$
$\alpha + \beta = 0$
$2 \beta - \gamma = 0$
$\alpha = 0, \beta = 0, \gamma = 0$
So it is linear independent.
Now I need to check if $v_1,v_2,v_3$ generates all $R_2[x] $
$ax^0 + bx^1 + cx^2 = \alpha v_1 + \beta v_2 + \gamma v_3 = $
$\alpha + \gamma = a$
$\alpha + \beta = b$
$2 \beta - \gamma = c$
is this correct?
Thanks.

A: As @whoisit told you, you have not completed the proof.
You need to solve $\begin{cases} \alpha+\gamma=\color{Red} a \\ \alpha+\beta=\color{Red} b\\ 2\beta-\gamma=\color{Red} c\end{cases}$ for any vector $x\mapsto {\color{Red} a}\times1+{\color{Red} b}x+{\color{Red} c}x^2$. You will find $\begin{cases} \alpha=-{\color{Red} a}+2{\color{Red} b}-\color{Red} c \\ \beta={\color{Red} a}-{\color{Red} b}+\color{Red} c\\ \gamma={\color{Red} c}-2{\color{Red} b}+2\color{Red} a\end{cases}$.
For example, with $v:x\mapsto {\color{Red} 7}\times1{\color{Red} {-3}}x+{\color{Red} 4}x^2, v=-17v_1+14v_2+24v_3$.


text:
Q: How to prevent summernote from popping open all modals? On rendering summer note all modals appear open with the help modal at the top most of the stack. I am unable to close any of them. Not using bower or anything else. A simple application hosted with bottle python. No JS errors. From element inspector if I check the rendering is correct and functional too.
The stacked up modals that appear on rendering:

Just this from JS console : NO OEMBED

A: As it turns out, the bootstrap version of my template is old (2.3.2). I just added a "display:none" on the modal class of the css and then the behavior is fine.
The pop ups behave open and correctly after this.


text:
Q: How to write the open api spec for the response object where the property is a value? This is the response Object I am getting:
{
    "data": {

        "19fba609-f306-5a4a-962f-758c4ec1b510": [

            {

                "t": "2022-05-10T09:31:44.175104298Z",

                "v": 3

            },

            {

                "t": "2022-05-12T19:42:47.384567752Z",

                "v": 4

            }

        ]

    }
}

This is the spec I can come up with:
data:
  type: object
  properties:
    deviceId:
      type: array
      items:
        type: object
        properties:
          t:
            type: string
            description: Timestamp of point value
          v:
            type: string
            description: Point value

I am getting the value of deviceId.What do I write in the spec in place of deviceId?
I cannot change the api response in any way.


text:
Q: How to do a 301 redirect in Magento 1.7.0.2? We recently change our old Eshop from aspx technology to Magento 1.7.0.2
My old urls are like
http://www.demostore.nl/Contact.aspx

http://www.demostore.nl/category1.aspx

and now in magento are like
http://www.demostore.nl/contacts

http://www.demostore.nl/products-category1

Could you give me some example of what and how to include all my old urls with a 301 redirect to the new Magento site? I assume it will be inside htaccess but I dont know how exactly to do that?

A: Put this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

# catehory1.aspx => products-category1
RewriteRule ^(category[^.]*)\.aspx$ /products-$1 [L,R=301,NC]

# contact.aspx => contacts
RewriteCond %{REQUEST_URI} !^/category [NC]
RewriteRule ^(.+?)\.aspx$ /$1s [L,R=301,NC]


text:
Q: Python with VS2012 I just start with NLTK ,when i try to instal NLTK with python in the VS2012 IDE
first i run:
import nltk
nltk.download()

It runs correctly.Then I try:
from nltk.book import *

It gives me:
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.1\visualstudio_py_util.py", line 1
06, in exec_file
    exec_code(code, file, global_variables)
  File "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.1\visualstudio_py_util.py", line 8
1, in exec_code
    code_obj = compile(code, file, 'exec')
  File "C:\Users\Toshiba\Documents\Visual Studio 2012\Projects\Helloworld\Hellow
orld\module2.py", line 2
    NLTK_DADA ="E:\NLtk\nltk_data"
              ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in positio
n 2-3: malformed \N character escape
Press any key to continue . . .

A: The error itself says it all:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in positio
n 2-3: malformed \N character escape

The path you are using is badly formatted for python. You need to escape the \ character itself, otherwise python thinks you are escaping the character that follows the \.
Proper string formatting:
NLTK_DADA = "E:\\NLtk\\nltk_data"

Another way is to tell python that the string is a raw string by prefixing it with r:
NLTK_DADA = r"E:\NLtk\nltk_data"

See string literals in python.


text:
Q: How to make a custom table widget in flutter? I'm making a custom widget for showing a weekly schedule. I want it to look somewhat like a normal table, with the days in the header and the time of day on the vertical axis. Then I want to add events in the calendar, but as an event can span several cells, I can not use the built in table (it has no col/row span).
So I started to make my own table using CustomPaint. It went OK until I came to the header part, which I am stuck on the layout with my idea. In the code I supplied you can see that the header will have the same width as the side bar (with time) and the WeekView (the CustomPaint table). This means I have no idea how to align the header (Monday, Tuesday etc..) with the grid in the WeekView as the space the side bar takes up is not known. And as I want the side bar to scroll with the table, it has to be inside the scrollview. Can I solve this any other way? Maybe with slivers (that I know very little of yet)?
@override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        WeekSelector(
          week: controller.week,
          onPrevPressed: onPrevPressed,
          onNextPressed: onNextPressed,
        ),
        WeekHeader(),
        Expanded(
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Container(
              child: Row(
                children: <Widget>[
                  Text("09:00"), // here will be a bar for the time
                  Expanded(
                    child: WeekView(
                      startHour: 9,
                      endHour: 18,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }


text:
Q: Remove proximity alerts when uninstalling app I have a problem with proximity alerts on Android.
Here's what I'm doing in my app

*

*Fetch list of locations from server.

*Add proximity alerts of these locations (now GPS icon shows in status bar).

*When user enters the area launch my app activity.

Problem is that, when I uninstall my app with proximity alerts added it still shows GPS icon in status bar. User can turn off all proximity alerts in app but it doesn't solve my problem. I also now that it's impossible to do anything during uninstall process. Any ideas?
//EDIT:
Only way to get rid of GPS icon after app uninstall is to restart the device.

A: Report bug to Android developers. LocationManager should handle such use case (this case is easy to forget and apparently Android developers forgot about that).
As a workaround you can try to create a service which will exist as long as you need proximity alert. I'm hoping that service is gracefully closed on removal and not just killed. In such case you will remove proximity alert. You have to try it to be sure that this is good solution.


text:
Q: How to show image of tif coordinates obtained from Tessnet (Tesseract) I'm running OCR on the tesseract engine with Tessnet as a C# wrapper. I have obtained image coordinates of the recognized words and I would like to use those coordinates to show only that part of the page. I don't care if this page portion is saved as a separate image or if it just highlights the section of the tif image somehow.
Here is my current code:
TextWriter tw = new StreamWriter(@"U:\user files\bwalker\ocrTesting.txt");
            Bitmap image = new Bitmap(@"u:\user files\bwalker\2849257.tif");
            tessnet2.Tesseract ocr = new tessnet2.Tesseract();
            ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // If digit only
            ocr.Init(@"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // To use correct tessdata
            List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
            string Results = "";
            foreach (tessnet2.Word word in result)
            {
                Results += word.Confidence + ", " + word.Text + ", " +word.Top+", "+word.Bottom+", "+word.Left+", "+word.Right+"\n";
            }
            using (StreamWriter writer = new StreamWriter(@"U:\user files\bwalker\ocrTesting2.txt", true))
            {
                writer.WriteLine(Results);
                writer.Close();
            }
            MessageBox.Show("Completed");

And here's a section of the resulting .txt file:
14, Due, 105, 136, 1886, 1962
89, Date, 105, 136, 1978, 2064
50, 06/16/2009, 105, 136, 2298, 2504

A: I have solved this. After getting the coordinates for the words, I am doing this to display the associated images:
System.Drawing.Rectangle dueDateRectangle = new System.Drawing.Rectangle(dueDateRect1, dueDateRect2, dueDateRect4 - dueDateRect1, dueDateRect3 - dueDateRect2);
System.Drawing.Imaging.PixelFormat format = image.PixelFormat;
Bitmap cloneBitmap = image.Clone(dueDateRectangle, format);
MemoryStream ms = new MemoryStream();
cloneBitmap.Save(ms, ImageFormat.Png);
ms.Position = 0;
BitmapImage dueDateImage = new BitmapImage();
dueDateImage.BeginInit();
dueDateImage.StreamSource = ms;
dueDateImage.EndInit();
dueDateImageBox.Source = dueDateImage;


text:
Q: Passing a Scalar reference into another Scalar In SQL Server, I have a stored procedure that accepts a date parameter.  That date paramater is then passed along to another stored procedure.  However, the 2nd stored procedure parameter  is named as the first parameter.   and then I need to I have 2 different scalar variables:
DECLARE @date date, @sql varchar(100);

SET @date = '2012-07-01';
SELECT @sql = ('EXEC pStoredprocedure @date = '''+@date+'''')

I need the @sql scalar to contain this text so the stored procedure can call the other stored procedure:
EXEC pStoredprocedure @date = '2012-07-01'
But, when I run my code above, I get this error:
Msg 402, Level 16, State 1, Line 4
The data types varchar and date are incompatible in the add operator.
It's almost like I need to escape the @date operator.  Can this be done?
Side note:  Yes, I'm trying to dynamically pass along some variables.  I understand the dangers of doing so, but doing it this way is much simpler...

A: The date variable is being used in string concatenation, so it should be treated as a string, either through its declaration, a convert function, or a cast.  I tried this:
 DECLARE @date varchar(20), @sql varchar(100);
SET @date = '2012-07-01';
SELECT @sql = ('EXEC pStoredprocedure @date = ''' + @date + '''')

 PRINT @sql

and got this:
 EXEC pStoredprocedure @date = '2012-07-01'

I am stuck on 2005, so I don't have the date datatype, but when I tried to use datetime, I got this error:

Msg 241, Level 16, State 1, Line 4 Conversion failed when converting
  datetime from character string.

You can also try
 DECLARE @date datetime, @sql varchar(100);
SET @date = '2012-07-01';
SELECT @sql = ('EXEC pStoredprocedure @date = ''' + CONVERT(varchar(20), @date, 102) + '''')
 PRINT @SQL;

and get
 EXEC pStoredprocedure @date = '2012.07.01'


text:
Q: HIVE query takes very long time to fetch 20 gb records Hi I have a hive table on HBASE that has 200gb of records .
I am running simple hive query to fetch 20 gb records .
But this takes around 4 hours of time .
I can not create partition on HIVE table cause it is integrated on HBASE.
Please suggest any idea to improve performance
This is my HIVE query
INSERT OVERWRITE LOCAL DIRECTORY '/hadoop/user/m6034690/FSDI/FundamentalAnalytic/FundamentalAnalytic_2014.txt'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
select * from hbase_table_FundamentalAnalytic  where FilePartition='ThirdPartyPrivate' and FilePartitionDate='2014';

A: If you can, then I think Apache Phoenix will speed things up.
https://phoenix.apache.org/faq.html
Very simple and intuitive to use and super fast.


text:
Q: Why do I need to dispose a postgresql sqlalchemy engine? >>> import subprocess, sqlalchemy
>>> engine = sqlalchemy.create_engine("postgresql+psycopg://myuser:secret@localhost/mydb")
>>> subprocess.Popen(['/usr/bin/dropdb', '-U', 'myuser', 'mydb'])
dropdb: database removal failed: ERROR:  database "openstack_citest" is being accessed by other users
DETAIL:  There are 1 other session(s) using the database.

I checked which user is using the database and it's the user that's trying to drop it.
I can solve this by issuing an engine.dispose() call, but I don't know why. There shouldn't be any open connections to the database in the first place.
Trying the same thing with mysql as the backend works without the dispose() call works just fine to drop the database.

A: That's by design:

DROP DATABASE drops a database. [...]. Also, it cannot be executed
  while you or anyone else are connected to the target database


text:
Q: Média e contagem para cada produto SQL Estou tentando fazer uma atualização de uma tabela no meu banco de dados em duas colunas novas, uma que trás a média das avaliações e outra que trás o número de avaliações.
Esses dados são obtidos através de duas tabelas, a relação entre elas é o id e o product_id.
Tentei o seguinte código:
UPDATE product
INNER JOIN
 product_review ON product.id = product_review.product_id
SET
 product.review_rating = (
  SELECT AVG(product_review.rating) WHERE state='approved'
 );

Mas ele retorna a média de todos os produtos e não de cada um em separado, alguma sugestão?

A: Tente fazer um teste fazendo um Join com uma tabela derivada onde é calculada a média. Ex:
UPDATE product
INNER JOIN
(
  SELECT product_id, AVG(product_review.rating) as review_rating
  FROM product_review
  WHERE state='approved'
  GROUP BY product_id
) rv
  on product.id = rv.product_id
SET product.review_rating = rv.review_rating

Nessa tabela derivada você também pode fazer a contagem de avaliações que você citou.


text:
Q: How to get the first row with value in range In a google script with spreadsheet, I need to get the first row with a non blank value in a range.
But I'm a little bit blocked, I don't find a way to get my first row with a value.
For example in my code, I'm trying to loop to find every 4 line, the first rows with value.
Any idea ?
Thank you !
function findStartDate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(roadmapSS);

  var sourceLength = ss.getSheetByName(trelloSortSS).getLastRow()-1;
  var lastColumn = sheet.getLastColumn();
  var column = sheet.getLastColumn();
  var lastRow = columnToLetter(column);

  for (var h = 11; h < (sourceLength*4)+11; h+=4) {
    var range = sheet.getRange(h, 11, sheet.getLastRow(), sheet.getLastColumn());
    // here I need to get my first row
  }
}

A: Here is a script that find the row number for the first row with nonempty column C. Modify as needed.
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
  if (data[i][2]) {   // index 2 = 3rd column = C
    break;
  }
}
Logger.log("First nonempty row is " + (i+1))  // i is 0-based but row numbers are 1-based

A: Based on useruser6655984's answer here

function getFirstColumn(){
  for (var m = 0; m < data.length; m++) {
    for (var j = 0; j < data[0].length; j++) {
      if (data[m][j]) {
        break;
      }
    }
  }
  return j+1
}

You can find first Row;
function getFirstRow(firstColumn){ // firstColumn will be the j+1 from getFirstColumn
  for (var m = 0; m < data.length; m++) {
    if(data[m][firstColumn]){
      break
    }
  }
  return m+1
}


text:
Q: how to write a crossover function for genetic algorithm def crossover(parents):
    result = copy.deepcopy(parents[0].brain)
    for param in result.parameters():
        print((param.shape[0] / 2))
        if len(param.shape) == 2:  # weights of linear layer
            for i0 in range(param.shape[0]):
                for i1 in range(param.shape[1]):
                    if i0 < (param.shape[0] / 2) and i1 < (param.shape[1]):
                        param[i0][i1] = [param[i0][i1] for param in parents[0].brain.parameters() if
                                         len(param.shape) == 2]
                        # print("x is", x)
                        # print(f"param{i0}{i1}", param[i0][i1])
                        # param[i0][i1] = 2
                    else:
                        param[i0][i1] = [param[i0][i1] for param in parents[1].brain.parameters() if
                                         len(param.shape) == 2]

I am using pytorch library and trying to write a crossover function for my project. initially for the crossover result i just copied the brain of the one of the parents for the ease. then I'm cutting it from the middle and the merging the brains of both of the parents in it. The problem is the output of this "param[i0][i1] for param in parents[1].brain.parameters()" comes out to be a list of 3 tensors which shouldn't.
output
x is [tensor(0.0775), tensor(0.0372), tensor(0.2628)]
param07 tensor(0.0775)

how do i fix this?

A: something is wrong with the list comprehension i tried to use there which i think i don't understand completely still. so i wrote a proper loop for it and it worked.
def crossover(parents):
    result = copy.deepcopy(parents[0].brain)
    for param in result.parameters():
        if len(param.shape) == 2:  # weights of linear layer
            for i0 in range(param.shape[0]):
                for i1 in range(param.shape[1]):
                    if i0 < (param.shape[0] / 2) and i1 < (param.shape[1]):
                        for p in parents[0].brain.parameters():
                            if len(p.shape) == 2 and param.shape == p.shape:
                                param[i0][i1] = p[i0][i1]
                    else:
                        for p in parents[1].brain.parameters():
                            if len(p.shape) == 2 and param.shape == p.shape:
                                param[i0][i1] = p[i0][i1]


text: Q: Infinite canvas It seems that all LaTeX formatting assumes we will ultimately print the document but if the goal is to publish online - under some circumstances, we might desire to have all the document in one "infinite" page so the reader can scroll it. That is the idea behind the infinite canvas. How should go about to try to implement this idea in a TikZ picture? How to avoid the picture being cropped by the page length set by document class?


text:
Q: Variable 'this.userInfo' is unbound and cannot be determined I am developing a maven JDO project, but I am getting this error when I am trying to make relation between two tables (user_login, user_role)
User_Login: user_id(primary key), user_name, user_password,user_role_id
User_Role: id(primary key), role
user_role_id is same as id of user_role table
User.java:
@PersistenceCapable(table = "user_login")
public class User {
@PrimaryKey
@Column(name="user_id")
private Integer userId=0;
@Column(name="user_profile_name")
private String userProfileName=null;
@Column(name="user_email")
private String userEmail=null;
@Column(name="user_contact")
private String userContact=null;
@Column(name="user_name")
private String userName=null;
@Column(name="user_password")
private String userPassword=null;
@ManyToOne
@Column(name="user_role_id")
private Integer userRoleId=0;

Role.java:
@PersistenceCapable(table = "user_role")
public class Role {
@PrimaryKey
@Column(name="id")
private Integer id=0;
@Column(name="role")
private String role=null;

@OneToMany
private User userInfo=null;

DAOImpol:
public List<Role> getUser(String username, String userpassword) {
    PersistenceManager pm = this.pmf.getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    JDOPersistenceManager jdopm = (JDOPersistenceManager)pm;
    try {
    // Start the transaction
    tx.begin();

    TypesafeQuery<User> tq = jdopm.newTypesafeQuery(User.class);
    //QUser user = QUser.candidate();
    QRole role = QRole.candidate();
    QUser userInfo=role.userInfo;
    List<Role> result = tq.filter(userInfo.userName.eq(username).and(userInfo.userPassword.eq(userpassword))).executeList();

    //result = tq.executeResultList(true, user.userId);

    if(result.size()>0){
        log.info(">>>>>00000000"+"    "+result.get(0).getUser().getUserEmail());
        log.info(">>>>>11111111"+"    "+result.get(0).getRoleId()+"    "+result.get(0).getRole());
    }else{
        log.info("<<<<<<<=====000000");
    }
    // Commit the transaction, flushing the object to the datastore
    tx.commit();
    return result;
    }
    finally {
        if (tx.isActive())
        {
            // Error occurred so rollback the transaction
            tx.rollback();
        }
        pm.close();
    }

I am getting this error:
javax.jdo.JDOUserException: Variable 'this.userInfo' is unbound and
cannot be determined (is it a misspelled field name? or is not intended
to be a variable?)
NestedThrowables:
org.datanucleus.exceptions.NucleusUserException: Variable
'this.userInfo' is unbound and cannot be determined (is it a
misspelled
field name? or is not intended to be a variable?)

A: I found that you'll get this error from JDO if you're using progaurd and progaurd renames your private fields.  Adding a -keep to the progaurd config to keep the package with your Persistence Capable classes will fix it.
For example, if you keep all of your Persistence Capable classes in com.example.server.orm package you'd add this to progaurd.conf
-keep class com.example.server.orm.** {*;}


text:
Q: Python 3 pip installation of pygraphviz fails, "Microsoft Visual C++ is required", Visual Studio 2017 is installed I tried to pip install pygraphviz, which failed with the error:
"Microsoft Visual C++ 14.0 is required. ..."
I have Visual Studio 2017 installed. Shouldn't that do the job? I think I checked every box related to C.
If I try to install vc_redist.x64.exe, it tells me another version is already installed.
(I think I have a similar/related problem with SciKit-learn and Scipy.)

A: From PyGraphviz documentation -

To use PyGraphviz you need Python version 2.6.x or 2.7.x. PyGraphviz
  does not work with Python 3.

link to more info.

A: Visual Studio 2017 comes with version 15 of the C++ compiler.  It's quite possible that pygraphviz truly wants version 14 (rather than 14-or-better).  Version 14 came with VS 2015.
Microsoft's C++ compiler routinely breaks the ABI of the standard library between major versions.  They may stop doing that in the future, but that doesn't help you with this problem.  You need to get your hands on VC++ 14 (or at least the redistributables that came with VC++14).


text:
Q: Where magento 2 send mail, when create customer from admin Anybody know where magento 2 in adminhtml customer creation, get email template, put it in transport builder, and send mail to customer with cunfirmation link.

A: Check the following class:

vendor/magento/module-customer/Model/AccountManagement.php

protected function sendEmailConfirmation(CustomerInterface $customer, $redirectUrl)
{
    try {
        $hash = $this->customerRegistry->retrieveSecureData($customer->getId())->getPasswordHash();
        $templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED;
        if ($this->isConfirmationRequired($customer) && $hash != '') {
            $templateType = self::NEW_ACCOUNT_EMAIL_CONFIRMATION;
        } elseif ($hash == '') {
            $templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD;
        }
        $this->getEmailNotification()->newAccount($customer, $templateType, $redirectUrl, $customer->getStoreId());
        $customer->setConfirmation(null);
    } catch (MailException $e) {
        // If we are not able to send a new account email, this should be ignored
        $this->logger->critical($e);
    } catch (\UnexpectedValueException $e) {
        $this->logger->error($e);
    }
}

The following line is sent email template for resetting the password:

$templateType = self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD;


text:
Q: docker: can not start xvfb-run with docker run, but can start with docker exec -it I'm trying to run a node app with xvfb-run, here is my Dockerfile
FROM node:lts-alpine

RUN apk --no-cache upgrade && apk add --no-cache chromium coreutils xvfb xvfb-run

ENV CHROME_BIN="/usr/bin/chromium-browser"\
  PUPPETEER_SKIP_CHROMIUM_DOWNLOAD="true" \
  UPLOAD_ENV="test"

WORKDIR /app

COPY  package.json .
COPY  .npmrc .

RUN npm install

COPY . .

# EXPOSE 9999

ENTRYPOINT xvfb-run -a npm run dev

I can successfully build the image, but when I run it with docker run, it gets stuck without any log

But when I open an interactive shell and run the ENTRYPOINT command, it works...

How do I fix it?

A: You should add --init to docker run, for example:
docker run --init --rm -it $IMAGE$ xvfb-run $COMMAND$


text:
Q: How to give Form-param, both values and files in a http request in python I wanna make a http request as shown in the below curl command:
curl -X PUT \
https://anypoint.mulesoft.com/cloudhub/api/v2/applications/highfiles \
-H 'authorization: Bearer XXX' \
-H 'cache-control: no-cache' \
-H 'content-length: 0' \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-H 'host: anypoint.mulesoft.com' \
-H 'postman-token: XXX' \
-H 'x-anypnt-env-id: XXX' \
-H 'x-anypnt-org-id: XXX' \
-F 'appInfoJson={
"muleVersion": {
    "version": "3.8.5"
},
"properties":{"env":"dev"}
}'

I have tried the below request but all vain
files = {'file': open('C:\Users\\highfiles.zip', 'rb')}
    appInfoJson1 = {
        "muleVersion": {
            "version": "3.8.5"
        },
        "properties": {"env":"dev1"}
    }
    print dict(appInfoJson=appInfoJson1)
    headers = {"X-ANYPNT-ORG-ID": "XXXX",
               "X-ANYPNT-ENV-ID": "XXXX",
               "Authorization": "Bearer " + access_token,
               }
    response = requests.put("https://anypoint.mulesoft.com/cloudhub/api/v2/applications/highfiles",
                            data=dict(appInfoJson=appInfoJson1) , files=files, headers = headers)

How do I give a form-Param values and file in a python http request.

A: I was doing it wrong.
The change was only w.r.t handling the dict values, shown below:
response = requests.put("https://anypoint.mulesoft.com/cloudhub/api/v2/applications/highfiles",
                            data=dict(appInfoJson=appInfoJson1.values()) , files=files, headers = headers)


text:
Q: starting service failed docker I follow this install guide run dcm4chee in docker container, when I start the service up by sudo docker-compose -p dcm4chee start it gives me error
Starting ldap ... done
Starting db   ... done
Starting arc  ... failed

this is my docker-compose.yml.
docker-compose.env:
STORAGE_DIR=/storage/fs1
POSTGRES_DB=pacsdb
POSTGRES_USER=pacs
POSTGRES_PASSWORD=pacs

Why ldap and db start fine but arc failed.
Edit:

*

*/var/local/dcm4chee-arc/wildfly:/opt/wildfly/standalone

*/var/local/dcm4chee-arc/storage:/storage

these files are in docker-compose.yml in volumes attribute, but I didn't find wildfly folder/file in system.

A: It worked, the problem is that for some reason this up command (docker-compose -p dcm4chee up -d) failed to create the wildfly and storage folders,
so when I then run start command, the docker failed to start the service as the required folders wasn't created, the solution was simply run up command again,
this time it creates the folders correctly.


text:
Q: Cell Referencing Formula Was using this formula SheetName!CellAddress
I need to import Data that is available on other 2 sheets namely (sheet2 and sheet3)  into sheet 1 in a way such that
the row values will be alternate i.e one value from sheet 2 and other value from sheet 3 respectively
Have tried like this
=Sheet2!C2
=Sheet3!D2
when i dragged for other values i was get only values in the even cell like(c4,d4,c6,d6)
If i change the for formula to
=Sheet2!C1
=Sheet3!D1
i was get only values in the even cell like(c3,d3,c5,d5)
But what i need is continous cells in row( c1,d1,c2,d2,c3,d3...)
So what formula i need to use for getting this result

A: I am still not 100% clear on what the question is asking, so let me know if the below answer doesn't work for you.
It sounds like what you're looking for can be accomplished with OFFSET and clever use of IF statement.
Suppose your formulas will be in column A, starting in A2.  Then enter the following formula into A2 (line split added for readability; remove it):
= IF(MOD(COUNTA(A$1:A1),2)=0, OFFSET(Sheet2!$C$1, COUNTA(A$1:A1) / 2, 0),
    OFFSET(Sheet3!$D$1, COUNTA(A$1:A1) / 2, 0))

Then drag the formula down.
What it does:

*

*MOD(COUNTA(A$1:A1),2)=0 - checks whether we're in odd row or even row.

*COUNTA(A$1:A1)/ 2 - takes half of the number of non-empty cells immediately above the current cell.

*OFFSET(Sheet2!$C$1, COUNTA(A$1:A1) / 2, 0) - takes the cell which is COUNTA(A$1:A1)/ 2 cells below Sheet2!$C$1.

A: Here's a fairly basic method:

*

*Enter the first two formulas as Text - you can either do this by formatting the cell number as text or preceding the formula by an apostrophe.

*Select cells and fill down to get:
=Sheet2!C2
=Sheet3!D2
=Sheet2!C3
=Sheet3!D3
=Sheet2!C4
=Sheet3!D4
...

*Select the column and choose Data|Text to Columns|Finish to change text to values.


text:
Q: Alter values in two differrent lines with awk I have a parameter card that's fixed. I need to change the value of lines 10 and 20, I am trying using awk but so far didn't get it. Those positions are fixed, so I will need to do this with a loop but it will be always the same 2 lines, lines 10 and 20. I tried this way but it changes the $1 of all lines from 10 to 20. Since I will be changing these values I cannot use sed to match a pattern because I won't have one, the values will be random each time, only the lines are fixed.
awk 'FNR==10,FNR==20{$1="new_value"}1' dummycard.txt > dummynew.txt

Thatś my file:
DATAFILE
p365.txt
TRAITS
2
FIELDS_PASSED TO OUTPUT

WEIGHT(S)

RESIDUAL_VARIANCE
300
EFFECT
3 cross numer
EFFECT
1 cross numer
RANDOM
animal
FILE
pednem.txt
(CO)VARIANCES
200
OPTION conv_crit 1d-12
Convergence criterion (default 1d-10).
OPTION maxrounds 10000
maximum rounds (default 5000).

A: You should give OR condition for FNR checking.
awk 'FNR==10 || FNR==20{$1="new_value"}1' Input_file

OR as per Ed sir's suggestion, you could try:
awk 'FNR ~ /^[12]0$/{$1="new_value"}1' Input_file

In case you want to have your new value in an awk variable then try following.
awk -v new_value="10" 'FNR==10 || FNR==20{$1=new_value}1' Input_file

For example I have set its value to 10 you could set it as per your need.
Why OP's code didn't work: Since OP is using , between line numbers so it is taken as a range thus all lines changed from line numbers 10 to 20.


text:
Q: Rails routes index for nested resource I'm searching a reason why rake routes doesn't match the index path of my nested resource.
Here is my code:
namespace :api do
  resources :photos do
    resource :comments
  end
end

Here is the result of the command: rake routes | grep comment
           batch_action_admin_user_comments POST       /admin/user_comments/batch_action(.:format)            admin/user_comments#batch_action
                        admin_user_comments GET        /admin/user_comments(.:format)                         admin/user_comments#index
                                            POST       /admin/user_comments(.:format)                         admin/user_comments#create
                     new_admin_user_comment GET        /admin/user_comments/new(.:format)                     admin/user_comments#new
                    edit_admin_user_comment GET        /admin/user_comments/:id/edit(.:format)                admin/user_comments#edit
                         admin_user_comment GET        /admin/user_comments/:id(.:format)                     admin/user_comments#show
                                            PATCH      /admin/user_comments/:id(.:format)                     admin/user_comments#update
                                            PUT        /admin/user_comments/:id(.:format)                     admin/user_comments#update
                                            DELETE     /admin/user_comments/:id(.:format)                     admin/user_comments#destroy
                             admin_comments GET        /admin/comments(.:format)                              admin/comments#index
                                            POST       /admin/comments(.:format)                              admin/comments#create
                              admin_comment GET        /admin/comments/:id(.:format)                          admin/comments#show
                         api_photo_comments POST       /api/photos/:photo_id/comments(.:format)               api/comments#create
                     new_api_photo_comments GET        /api/photos/:photo_id/comments/new(.:format)           api/comments#new
                    edit_api_photo_comments GET        /api/photos/:photo_id/comments/edit(.:format)          api/comments#edit
                                            GET        /api/photos/:photo_id/comments(.:format)               api/comments#show
                                            PATCH      /api/photos/:photo_id/comments(.:format)               api/comments#update
                                            PUT        /api/photos/:photo_id/comments(.:format)               api/comments#update
                                            DELETE     /api/photos/:photo_id/comments(.:format)               api/comments#destroy

I tried to add only: [:create, :index] to my comments resource but only the create route is visible.
According to the documentation about nested-resources I don't understand what's happening.
Thank you for your help.

A: It's because you are using a singular resource (resource :comments)
From the docs:

Sometimes, you have a resource that clients always look up without
  referencing an ID. For example, you would like /profile to always show
  the profile of the currently logged in user. In this case, you can use
  a singular resource to map /profile (rather than /profile/:id) to the
  show action

You'll need to use the standard resources method to get this working (resource omits the index action):
#config/routes.rb
namespace :api do
  resources :photos do
    resources :comments
  end
end

A: My mistake. A "S" was missing on my resource.
namespace :api do
  resources :photos do
    resources :comments
  end
end

Now it works.


text:
Q: Rails with paperclip Docx content_type is coming back as application/zip Has anyone else seen this?
I'm using rails 3 with paperclip, when I upload a .doc it works great application/msword but when I upload a .docx the content_type is being saved as application/zip.
thoughts?

A: Ironically IE can have difficulty recognising the new MS Office files while other browsers recognise them fine.
In order to get IE working with these files you need to add the mime types to the server config. In Rails this is done in config/initializers/mime_types.rb
Mime::Type.register "application/vnd.openxmlformats-officedocument.wordprocessingml.document", :docx
Mime::Type.register "application/vnd.openxmlformats-officedocument.presentationml.presentation", :pptx
Mime::Type.register "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", :xlsx

If your app is proxied through Apache and Apache serves your static assets you'll also have to configure apache with the new mime types (and restart) as per http://bignosebird.com/apache/a1.shtml
My mime types were located at /etc/mime.types but try locate mime.types if you're not sure.

A: I've seen this using IE with SSL. If that's the case for you, take a look at
http://www.kalzumeus.com/2010/10/25/how-to-use-ssl-to-secure-your-rails-app-against-firesheep-and-other-evils/
(The section called "Host downloadable files on SSL? You just broke IE.")
this may also help:
Rails PDF Generation with Prawn in IE7


text:
Q: npm install --save solc on Atom When I type npm install --save solc in the comment prompt on the mac, it's like
And after these a package is downloaded. I am a windows user and I tried to do this. I have an error like
C:\Users\senem\Desktop\inbox>npm install --save solc
npm ERR! code EJSONPARSE
npm ERR! file C:\Users\senem\Desktop\inbox\package.json
npm ERR! JSON.parse Failed to parse json
npm ERR! JSON.parse Unexpected end of JSON input while parsing near ''
npm ERR! JSON.parse Failed to parse package.json data.
npm ERR! JSON.parse package.json must be actual JSON, not just JavaScript.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\senem\AppData\Roaming\npm-cache_logs\2021-03-04T23_05_05_768Z-debug.log

I can't download it because I don't know which package it is. Is there anyone who can help? How can I download this or how can I solve this error?


text:
Q: Как пронавигироваться назад используя navigation component? Есть home fragment на котором есть кнопка выход. При нажатии на кнопку нужно перейти на экран авторизации (логин). Если создать action на это действие, то навигация выполняется, но появляется возможность вернуться назад на home при нажатии кнопки назад. Как выполнить навигацию на login, убрав из стека все экраны которые лежат под login?

A: В action в Вашем случае нужно указать, что фрагмент назначения становится самым верхним в истории:
  <action android:id="@+id/action_name"
          app:destination="@id/destination"
          app:popUpTo="@id/destination"
          app:popUpToInclusive="true"
          app:launchSingleTop="true">


text:
Q: Images infinitely looping on scroll I am trying to achieve an effect where each image moves upwards on scroll, each image moves at different speeds and moves out of screen at the top and reappears from the bottom of the page in an infinite loop.
Diagram below
Any examples or suggestions would be much appreciated, thank you

EDIT: https://codepen.io/JTParrett/pen/BkDie
This is a perfect example however I want the scroll to be infinite and the objects to reappear from the bottom
$.fn.moveIt = function(){
var $window = $(window);
var instances = [];

$(this).each(function(){
instances.push(new moveItItem($(this)));
});

window.addEventListener('scroll', function(){
var scrollTop = $window.scrollTop();
instances.forEach(function(inst){
  inst.update(scrollTop);
});
}, {passive: true});
}

var moveItItem = function(el){
this.el = $(el);
this.speed = parseInt(this.el.attr('data-scroll-speed'));
};

moveItItem.prototype.update = function(scrollTop){
this.el.css('transform', 'translateY(' + -(scrollTop / this.speed) +
'px)');
};

// Initialization
$(function(){
$('[data-scroll-speed]').moveIt();
});

A: You could use a pure CSS solution to make the desired effect, which can be created using CSS animations. In the example below all elements are in a grid and every item has a different execution time for the same animation gotop.

div {
  position: fixed;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  grid-column-gap: 5%;
  grid-template-columns: auto auto auto auto;
  overflow: hidden;
}

div.inner-container::-webkit-scrollbar {
  display: none;
}

.A {
  height: auto;
  animation-name: gotop;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.B {
  height: auto;
  animation-name: gotop;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.C {
  height: auto;
  animation-name: gotop;
  animation-duration: 6s;
  animation-iteration-count: infinite;
}

.D {
  height: auto;
  animation-name: gotop;
  animation-duration: 9s;
  animation-iteration-count: infinite;
}

@keyframes gotop {
  from {
    margin-top: 120%;
  }
  to {
    margin-top: -20%;
  }
}

    textA

    textB

    textC

    textD

A: For starters, you should have absolute positioning in your images.

.
.
.
.

This way you can adjust the starting position of each image. The scrollamount would also be different for each image.
Then you add an event listener for the window scroll event, . Here is some code:
window.addEventListener("scroll", function(){
    images.each(function(){
        this.style.top += this.dataset.scrollamount
    }
}


text:
Q: Iterate through list of dictionary and identify similar values in dictionary in Python Suppose I have a list of dictionary as below
[{'name': 'User_ORDERS1234', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_2']}, {'name': 'User_ORDERS1235', 'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}], 'users': ['User_1']}, {'name': 'User_ORDERS1236', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_3']}]

On iterate of this list I want to check if the expressions(key) a sub list values are same as some other set of dictionary key expression values.In the above case users key with value-User_2 has same expression values as User_3 .In this case I want to delete the entire dictionary of User_3 and add append the value User_3 to User_2 list(as 'Users':['User_2','User_3'])
exprected output:
[{'name': 'User_ORDERS1234', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_2','User_3']}, {'name': 'User_ORDERS1235', 'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}], 'users': ['User_1']}]

A: You can use enumerate to get the index and value of each order in the list of orders. scanned_exp is a dictionary with the unique expression as the key and the value is the index in the list of orders in which the first occurrence of the unique expression was found. When iterating, we check if the current expression has already been scanned, i.e., in scanned_exp. If it has been found already, we extend the list of users at the index position of the first occurrence of that expression with the list of users from the current expression. We then delete the current order from the list using remove.
scanned_exp = {}
for idx, order in enumerate(d):
    exp = order["expressions"][0]["exp"]
    if exp in scanned_exp:
        d[scanned_exp[exp]]["users"].extend(order["users"])
        d.remove(order)
    else:
        scanned_exp[exp] = idx

Your output then becomes:
[
    {
        'name': 'User_ORDERS1234',
        'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}],
        'users': ['User_2', 'User_3']
    },
    {
        'name': 'User_ORDERS1235',
        'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}],
        'users': ['User_1']
    }
]

Edit
Okay, let's make this dynamic. Firstly, the keys of a dictionary cannot be lists (unhashable type), so this breaks our original implementation. above. A collection that is able to be used as a key is tuple (unless the tuple contains unhashable types, i.e., list, dict). What we can do is make a tuple that contains all of the string values that appear as a value in the exp key.
So, you can replace this:
exp = order["expressions"][0]["exp"]

with this:
exp = tuple(e["exp"] for e in order["expressions"])

A: orders = [{
    'name': 'User_ORDERS1234',
    'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}],
    'users': ['User_2']
},{
    'name': 'User_ORDERS1235',
    'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}],
    'users': ['User_1']
},{
    'name': 'User_ORDERS1236',
    'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}],
    'users': ['User_3']
}]

for i, order in enumerate(orders):                # loop trough orders:
    exp1 = order['expressions']                   # 'exp' value of the order

    for next_order in orders[i+1:]:               # loop through the next orders:
        exp2 = next_order['expressions']          # 'exp' value of a next order

        if exp1 == exp2:                          # if the 'exp' values are the same:
            order['users'] += next_order['users'] # add the 'users' to the order 'users'
            next_order['users'] = []              # remove users from the next order

orders = [o for o in orders if o['users']]        # leave only the orders that have 'users'

print(orders)

Output
[{
    'name': 'User_ORDERS1234',
    'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}],
    'users': ['User_2', 'User_3']
},{
    'name': 'User_ORDERS1235',
    'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}],
    'users': ['User_1']
}]

A: dictt = [{'name': 'User_ORDERS1234', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_2']}, {'name': 'User_ORDERS1235', 'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}], 'users': ['User_1']}, {'name': 'User_ORDERS1236', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_3']}]

def sorting_it(d):
    for n,c in enumerate([x['expressions'] for x in dictt]):
        if c == d['expressions'] and dictt[n] != d and d['users']:
            d['users'] = d['users'] + dictt[n]['users']
            del dictt[n]
f = list(map(sorting_it,dictt))

print(dictt)

>>> [{'name': 'User_ORDERS1234', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_2', 'User_3']}, {'name': 'User_ORDERS1235', 'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}], 'users': ['User_1']}]

Explanation:
f = list(map(sorting_it,dictt))

using the map function, every dictionary in dictt is passed through function sorting_it one at a time as the variable d, so first is:
{'name': 'User_ORDERS1234', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_2']}

Now I'm looping through the the values of key 'expressions', [x['expressions'] for x in dictt] is the list for this
If the value of key 'expressions' in dictt d is equal to the value of key 'expressions' in [x['expressions'] for x in dictt] then I get the index n, use this to find the corresponding dictionary in dictt and add all the values for key 'expressions' together.
I then do del dictt[n] since the user for that dictionary has already been added to another dictionary, so in this case dictionary for 'user_3' is deleted since they were added to dictionary for 'user_2'.
Also dictt[n] != d and d['users'] makes sure I'm not comparing the same dictionary.

A: def function_1(values):
  for j in range(len(values)):
    for k in range(j + 1, len(values)):
      if values[j]['expressions'] == values[k]['expressions']:
        values[j]['users'] = values[j]['users'] + values[k]['users']
  return values

#In the performance
list_values = [{'name': 'User_ORDERS1234', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_2']}, {'name': 'User_ORDERS1235', 'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}], 'users': ['User_1']}, {'name': 'User_ORDERS1236', 'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}], 'users': ['User_3']}]

#call the function
function_1(list_values)

[{'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}],
  'name': 'User_ORDERS1234',
  'users': ['User_2', 'User_3']},
 {'expressions': [{'exp': '"table"."ORDERS"."STATUS"  = \'Shipped\''}],
  'name': 'User_ORDERS1235',
  'users': ['User_1']},
 {'expressions': [{'exp': '"table"."ORDERS"."STATUS" IN (\'Canceled\',\'Pending\')'}],
  'name': 'User_ORDERS1236',
  'users': ['User_3']}]
[ ]


text:
Q: Cannot modify header information - headers already sent when i have get mac Is there any other way to get a computer mac address and able to redirect page
i notice that if i remove the code for getting the mac address the redirect / header works
    <?php
    session_start();
    include('dbConnect.php');

    ob_start(); // Turn on output buffering
    system('ipconfig /all'); //Execute external program to display output
    $mycom=ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    $pmac = strpos($mycom, $findme); // Find the position of Physical text
    $mac=substr($mycom,($pmac+36),17); // Get Physical Address

    $qry=("SELECT * FROM table_comp_list WHERE comp_mac = '$mac'");
    $result=mysql_query($qry);

    if($result)
        {
        if(mysql_num_rows($result) != 1)
            {
                header("Location: add.php");
                die();
            }
        else
            {
                header("Location: edit.php");
                die();
            }
        }?>

A: Try this at start of your code. Add @ before session_start();
      <?php
@session_start();
// your code goes here -

?>


text:
Q: Transform a list of objects into a Map> I have a List of Containers, and each Container can have a single parent Container or no parent Container at all. I want to convert this list into a Map, where the key is the oldest ancestor / parent, and the value is a list of all descendants of that ancestor.
I have tried the following code, which almost works as expected, but it also collects children as parent keys if those children are also parents of other children:
public static void main(String[] args) {
    Container c1 = new Container("c1");
    Container c11 = new Container("c1_1");
    Container c111 = new Container("c1_1_1");
    Container c12 = new Container("c1_2");
    c11.setParent(c1);
    c111.setParent(c11);
    c12.setParent(c1);

    Container c2 = new Container("c2");
    Container c21 = new Container("c2_1");
    Container c22 = new Container("c2_2");
    c21.setParent(c2);
    c22.setParent(c2);

    List<Container> containers = Lists.newArrayList(c1, c11, c111, c12, c2, c21, c22);

    System.out.println("All containers: " + containers);

    Map<Container, List<Container>> parentsAndChildren = containers.stream()
            .collect(Collectors.groupingBy(container -> container.getParent() == null ? container : container.getParent(), Collectors.mapping(container -> container, Collectors.toList())));

    System.out.println("Ancestor / Descendants: " + parentsAndChildren);
}

@Data
@RequiredArgsConstructor
private static final class Container {
    private final String key;
    private Container parent;

    public String toString() {
        return key;
    }
}

This results in the following output:
All containers: [c1, c1_1, c1_1_1, c1_2, c2, c2_1, c2_2]
Ancestor / Descendants: {c1_1=[c1_1_1], c2=[c2, c2_1, c2_2], c1=[c1, c1_1, c1_2]}

While the expected output is:
All containers: [c1, c1_1, c1_1_1, c1_2, c2, c2_1, c2_2]
Ancestor / Descendants: {c2=[c2_1, c2_2], c1=[c1_1, c1_1_1, c1_2]}

Note that c1_1_1 is a direct descendant of the oldest ancestor c1. Is there a way I can do this easily using Java 8 Stream?


text:
Q: How can I make a jQuery UI Menu Button or find an already existing extension? I've just started working with jQuery UI, and while at first it looked like a wonderful tool, I've found that it lacks exactly what I need: a menu button widget.
What I want is the functionality of the jQuery UI Menu Widget, but with some additional bits, primarily a button/clickable area that will show/hide the menu. This alone is simple enough, but what is driving me mad is adding the expected keyboard functionality to this. When a button expands a menu, one expects that clicking outside that menu or pressing ESCAPE will close that menu, and while this works for the widget's submenus, it isn't built into the main widget.
I've been reading about the Widget Factory and extending/modifying widgets, but I'm completely lost as to how to accomplish this specific problem, and I can't seem to find any answers to this that aren't many years old. I've even tried overriding the "collapse" function in the menu instance, but the problem is that I don't quite understand the flow of the code. I basically added an 'else' statement that calls the 'click' event on the button when the conditions for closing a submenu aren't met. This just creates all sorts of weird bugs and I know I don't really have any idea what I'm doing.
A code example of how this is done would be greatly appreciated, but this is a common enough website behavior that I imagine someone has already put this together. I'm just not finding anything up to date.
Thank you in advance!

A: If you do not find a Widget that is needed, you can combine various elements and use them together.

$(function() {
  $(".widget button").button();
  $(".widget button").click(function(event) {
    event.preventDefault();
    if ($("#menu").is(":visible")) {
      $("#menu").hide();
    } else {
      $("#menu").show().menu("focus", null, $("#menu .ui-menu-item:first"));
    }
  });
  $("#menu").menu({
    select: function(e, ui) {
      console.log(ui.item.text().trim());
    }
  }).hide();
});
.ui-menu {
  width: 150px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Widget Buttons

  <button>A button element</button>

Toys (n/a)

Books

Clothing

Electronics

Home Entertainment

Car Hifi

Utilities

Movies

Music

Rock

Alternative

Classic

Jazz

Freejazz

Big Band

Modern

Pop

Specials (n/a)

Base Examples:

*

*https://jqueryui.com/menu/

*https://jqueryui.com/button/
You can also make use of the Widget Factory to create your own.


text:
Q: redirect without "?fbclid=" with webconfig or htaccess I know when we share a link inside facebook we got something like this:
http://flic.saolourenco.sc.gov.br/noticia/12/?fbclid=IwAR097TcuNFjCL09z2uoucc27xirEX7XYDAjTyt21ErOvPZ4K-31YmWF1s9A

and i'm trying to remove this kind of queryString from the URL and then REDIRECT to same domain and page, my case:
http://flic.saolourenco.sc.gov.br/noticia/12/

My website is running on Windows Server 2008 R2, IIS 7.5, with PHP 5.2.17 and CodeIgniter 1.7.2. Just for u kwowledge. I know this website it's too old and we can't do no one upgrade right now.
I've been trying to REDIRECT creating rules on web.config, here is the code.
<rule name="FBCLID"stopProcessing="true">
    <match url="(.*)"/>
    <conditions>
        <add input="{HTTP_HOST}" pattern="(\/\?|\?fbclid=)+(\w.+)"/>
    </conditions>
    <action type="Redirect" url="{R:1}" appendQueryString="true" redirectType="Permanent"/>
    </rule>

I tested many codes that i found on the internet but without success.
If you have any ideas how to do this, please tell me.

https://i.stack.imgur.com/061xa.jpg
https://i.stack.imgur.com/iN4IO.jpg
https://i.stack.imgur.com/9cnb6.jpg


text:
Q: Cordova: Invalid data, chunk must be a string or buffer, not object I updated to Ionic 3.5, and after that I get this error, when i try to do cordova build ios:
Invalid data, chunk must be a string or buffer, not object

There is no explanation of why this error is happening. I tried this both with Cordova 7.0.1 and 6.5.0. Interestingly, it works on Windows machine, but not on Mac. I only get the error on Mac. I appreciate any insights or helps.
 ionic info

global packages:
@ionic/cli-utils : 1.5.0
Cordova CLI      : 7.0.1
Ionic CLI        : 3.5.0

local packages:
@ionic/app-scripts              : 1.3.7
@ionic/cli-plugin-cordova       : 1.4.1
@ionic/cli-plugin-ionic-angular : 1.3.2
Cordova Platforms               : android 6.2.3
Ionic Framework                 : ionic-angular 3.5.3

System:
Node       : v7.10.0
OS         : Windows 10
Xcode      : not installed
ios-deploy : not installed
ios-sim    : not installed
npm        : 4.6.1

A: I got the fix from one of the github issue. It just needed correct path for strings.xml.
There is no need to downgrade cordova or cordova-android
The fix is to replace the code in
/cordova-plugin-fcm/scripts/fcm_config_files_process.js as below:
#!/usr/bin/env node
'use strict';

var fs = require('fs');
var path = require('path');

fs.ensureDirSync = function (dir) {
    if (!fs.existsSync(dir)) {
        dir.split(path.sep).reduce(function (currentPath, folder) {
            currentPath += folder + path.sep;
            if (!fs.existsSync(currentPath)) {
                fs.mkdirSync(currentPath);
            }
            return currentPath;
        }, '');
    }
};

var config = fs.readFileSync('config.xml').toString();
var name = getValue(config, 'name');

var IOS_DIR = 'platforms/ios';
var ANDROID_DIR = 'platforms/android';

var PLATFORM = {
    IOS: {
        dest: [
            IOS_DIR + '/' + name + '/Resources/GoogleService-Info.plist',
            IOS_DIR + '/' + name + '/Resources/Resources/GoogleService-Info.plist'
        ],
        src: [
            'GoogleService-Info.plist',
            IOS_DIR + '/www/GoogleService-Info.plist',
            'www/GoogleService-Info.plist'
        ]
    },
    ANDROID: {
        dest: [
            ANDROID_DIR + '/google-services.json',
            ANDROID_DIR + '/app/google-services.json',
        ],
        src: [
            'google-services.json',
            ANDROID_DIR + '/assets/www/google-services.json',
            'www/google-services.json'
        ],
        stringsXml: ANDROID_DIR + '/app/src/main/res/values/strings.xml'
    }
};

// Copy key files to their platform specific folders
if (directoryExists(IOS_DIR)) {
    copyKey(PLATFORM.IOS);
}
if (directoryExists(ANDROID_DIR)) {
    copyKey(PLATFORM.ANDROID, updateStringsXml)
}

function updateStringsXml(contents) {
    var json = JSON.parse(contents);
    var strings = fs.readFileSync(PLATFORM.ANDROID.stringsXml).toString();

    // strip non-default value
    strings = strings.replace(new RegExp('<string name="google_app_id">([^\@<]+?)</string>', 'i'), '');

    // strip non-default value
    strings = strings.replace(new RegExp('<string name="google_api_key">([^\@<]+?)</string>', 'i'), '');

    // strip empty lines
    strings = strings.replace(new RegExp('(\r\n|\n|\r)[ \t]*(\r\n|\n|\r)', 'gm'), '$1');

    // replace the default value
    strings = strings.replace(new RegExp('<string name="google_app_id">([^<]+?)</string>', 'i'), '<string name="google_app_id">' + json.client[0].client_info.mobilesdk_app_id + '</string>');

    // replace the default value
    strings = strings.replace(new RegExp('<string name="google_api_key">([^<]+?)</string>', 'i'), '<string name="google_api_key">' + json.client[0].api_key[0].current_key + '</string>');

    fs.writeFileSync(PLATFORM.ANDROID.stringsXml, strings);
}

function copyKey(platform, callback) {
    for (var i = 0; i < platform.src.length; i++) {
        var file = platform.src[i];
        if (fileExists(file)) {
            try {
                var contents = fs.readFileSync(file).toString();

                try {
                    platform.dest.forEach(function (destinationPath) {
                        var folder = destinationPath.substring(0, destinationPath.lastIndexOf('/'));
                        fs.ensureDirSync(folder);
                        fs.writeFileSync(destinationPath, contents);
                    });
                } catch (e) {
                    // skip
                }

                callback && callback(contents);
            } catch (err) {
                console.log(err)
            }

            break;
        }
    }
}

function getValue(config, name) {
    var value = config.match(new RegExp('<' + name + '>(.*?)</' + name + '>', 'i'));
    if (value && value[1]) {
        return value[1]
    } else {
        return null
    }
}

function fileExists(path) {
    try {
        return fs.statSync(path).isFile();
    } catch (e) {
        return false;
    }
}

function directoryExists(path) {
    try {
        return fs.statSync(path).isDirectory();
    } catch (e) {
        return false;
    }
}

For fixing the issue:
Make sure you have copied the above file in "plugins" folder as cordova copies all the cordova-plugins from node_modules directory to plugins directory,
if you have already added the platforms before modifying the file
plugins/cordova-plugin-fcm/scripts/fcm_config_files_process.js, you need to remove the platforms and add again.

A: @Ari In case you are still having this issue, this is what I did to solve this issue.
I had to edit file "fcm_config_files_process.js" located in folder "plugins/cordova-plugin-fcm/scripts/":
// fs.writeFileSync("platforms/ios/" + name + "/Resources/GoogleService-Info.plist", contents)

For some unknown reason while building the project this line (42) was throwing the error "Invalid data, chunk must be a string or buffer, not object" so what I did was to comment that line and then manually copy the file "GoogleService-Info.plist" to "platforms/ios/" + name + "/Resources/"
Hope this help.

A: We had this error because our Development Push Certificate from apple was outdated. We have renewed it – and it worked.

A: Remove default added ios platform when creating Ionic 2 app then add again.
And also remove and add "cordova-fcm-plugin".
ionic platform rm ios
ionic platform add ios


text:
Q: flex children exceeding the size of the parent container I am trying to make the hotel search results feed be a fixed height, but also be able to scroll if the results exceed the size of the feed container.
It should look like this: mockup
But currently it looks like this: current
As you can see, the scroll bar appears on the entire page, instead of in the feed container.
I have the entire page wrapped in a flexbox parent container, and then the two immediate children are the searchBar and page content. page content is also a flex container currently, which contains the hotel search results and hotel suggestions components as flex children. I am currently writing the code in React with Styled Components, but this is essentially a css problem. Any ideas on how to structure my css to make it look the way I want?
App.js:

//entire screen
const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
`;

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchResults: [],
    };

    this.displaySearchFeed = this.displaySearchFeed.bind(this);
  }

  displaySearchFeed(data) {
    console.log("state set");
    this.setState({
      searchResults: data,
    });
  }

  render() {
    return (
      <Wrapper>
        <SearchBar displaySearchFeed={this.displaySearchFeed} />
        <HotelPageContent searchResults={this.state.searchResults} />
      </Wrapper>
    );
  }
}

HotelPageContent.js

const ResultsContainer = styled.div`
  display: flex;
`;

export default function HotelPageContent(props) {
  console.log("rendered");
  console.log(props.searchResults);
  return (
    <ResultsContainer>
      <HotelSearchResults searchResults={props.searchResults} />
      <HotelSuggestions />
    </ResultsContainer>
  );
}

HotelSearchResultsFeed.js

const Container = styled.div`
  height: 100%;
  flex: 3;
  border-color: red;
  border-width: 3px;
  border-style: solid;
  overflow-y: scroll;
`;
// display: grid;

// position: fixed;

export default function SearchResults(props) {
  return (
    <Container>

Hotel Search Results

      {props.searchResults.length > 0
        ? props.searchResults.map((data, index) => {
            return <HotelCard key={index} HotelData={data} />;
          })
        : null}
    </Container>
  );
}

HotelSuggestions.js

const Container = styled.div`
  height: 100%;
  display: grid;
  flex: 1;
  border-color: red;
  border-width: 1px;
  border-style: solid;
`;

export default function HotelSuggestions(props) {
  return (
    <Container>

Hotel Suggestions

    </Container>
  );
}

HotelCard.js

const Container = styled.div`
  height: 10em;
  display: flex;
  flex-direction: row;
  border-color: black;
  border-width: 1px;
  border-style: solid;
`;

const CenterSection = styled.div`
  background-color: #80cbc4;
  border: 1px solid #fff;
  text-align: center;
  flex: 2;
`;

const HotelImageWrapper = styled.div`
  flex: 1;
`;

const HotelImage = styled.img`
  height: 100%;
  width: 100%;
  object-fit: contain;
  border-color: black;
  border-width: 1px;
  border-style: solid;
`;

export default function HotelCard({ HotelData }) {
  return (
    <Container>
      {/* <HotelImage src={imgSrc} /> */}
      <CenterSection>{HotelData["name"]}</CenterSection>

{HotelData["rating"]}

    </Container>
  );
}

A: I would recommend to use CSS-Grid over flexbox for such design. CSS-Gris has the advantage to control height and width at the same time. In the sample below, the body is declared to 100vh and 100vw to fill out the exact screen size. The cals is needed to counter the paddings. The search result and hotel suggestion has an overflow rule added so that those cards will get a scrollbar instead of the body.
Test the snippet best in full screen. Of course you can change it as you want, the snippet just shows an example how to accomplish it with the sue of a CSS-Grid

body {
  height: calc(100vh - 40px);
  width: calc(100vw - 40px);
  display: grid;
  grid-template-columns: auto min-content;
  grid-template-rows: min-content auto;
  grid-gap: 20px;
  padding: 20px;
  margin: 0px;
}

p {
  margin: 0;
}

#search-bar,
#search-result,
#hotel-suggestion {
  border: 1px solid black;
  padding: 20px;
}

#search-result,
#hotel-suggestion {
  overflow-y: auto;
}

#search-bar {
  grid-column: span 2;
}

#hotel-suggestion {
  width: 25vw;
}

#search-result div,
#hotel-suggestion div {
  border: 1px solid black;
  padding: 10px;
  margin-top: 5px;
}

#search-result div:last-child,
#hotel-suggestion div:last-child {
  margin-bottom: 10px;
}

  Insert searchbar here

hotel search results

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

dummy result

hotel suggestion

dummy suggestion

dummy suggestion

dummy suggestion

A: check this.(SCSS)
main { //ResultContainer
    display: flex;
    width: 100%;
    height: calc(100vh - 80px);
    .list { //SearchResultFeed
        flex-grow: 1;
        padding: 0 10px 10px 10px;
        background-color: #82e9de;
        overflow-y: auto;
    }
    .curation { //Suggestions
        flex-basis: 150px;
        background-color: #4db6ac;
    }
}

https://codepen.io/chamuchamu/pen/dypMLze


text:
Q: SceneBuilder looks different to JavaFX program? When I edit on SceneBuilder, the program looks like this
When I run the program, it looks like this:

This is my first time trying to use FXML and I have no idea what is going wrong. I tried to follow this question but don't see a solution..
Here is my FXML code:
<?xml version="1.0" encoding="UTF-8"?>

<GridPane alignment="center" hgap="10" prefHeight="633.0" prefWidth="869.0" stylesheets="/sample/sample.css" vgap="10" xmlns="http://javafx.com/javafx/8.0.76-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <columnConstraints>
      <ColumnConstraints />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints />
   </rowConstraints>
   <children>
      <BorderPane prefHeight="662.0" prefWidth="869.0" stylesheets="@sample.css">
         <top>
            <ImageView fitHeight="173.0" fitWidth="409.0" pickOnBounds="true" preserveRatio="true" BorderPane.alignment="CENTER">
               <image>
                  <Image url="@../../../../../Pictures/title.png" />
               </image>
            </ImageView>
         </top>
         <right>
            <VBox prefHeight="305.0" prefWidth="105.0" BorderPane.alignment="CENTER">
               <children>
                  <Button mnemonicParsing="false" text="Make a Graph" />
                  <Button mnemonicParsing="false" text="Save" />
                  <Button mnemonicParsing="false" text="Delete" />
               </children></VBox>
         </right>

            <VBox prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
               <children>
                  <Pane prefHeight="41.0" prefWidth="764.0">
                     <children>
                        <BorderPane prefHeight="0.0" prefWidth="764.0">
                           <left>
                              <ComboBox prefWidth="150.0" promptText="Sort or Filter" BorderPane.alignment="CENTER" />
                           </left>
                           <right>
                              <TextField text="Search" BorderPane.alignment="CENTER" />
                           </right>

                              <StackPane prefHeight="150.0" prefWidth="200.0" BorderPane.alignment="CENTER">
                                 <children>
                                    <HBox disable="true" prefHeight="100.0" prefWidth="200.0">
                                       <children>
                                          <ComboBox prefWidth="150.0" />
                                          <CheckBox mnemonicParsing="false" prefHeight="33.0" prefWidth="120.0" text="Favourties" />
                                       </children>
                                    </HBox>
                                 </children>
                              </StackPane>

                        </BorderPane>
                     </children></Pane>
                  <ScrollPane prefHeight="507.0" prefWidth="764.0">
                     <content>
                        <GridPane prefHeight="90.0" prefWidth="762.0">
                          <columnConstraints>
                            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                              <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                              <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                          </columnConstraints>
                          <rowConstraints>
                            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                          </rowConstraints>
                           <children>

                           </children>
                        </GridPane>
                     </content>
                  </ScrollPane>
               </children>
            </VBox>
         </BorderPane>
   </children>
</GridPane>

Here is my Java code:
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Sorry for the huge chunks of code. Just not sure where the problem is coming from.

A: You just seem to throw together some layouts that make the UI look the right way in SceneBuilder.
This approach is bad. This way you can be almost sure the layout will be messed up when it's resized. If a Stage is resized this forces the content of the Scene to a appropriate size depending on the Stage size.
You can observe the behaviour in SceneBuilder too, if you wrap the root node in a AnchorPane, set all anchors for the original root to 0 and resize the AnchorPane.
You should learn, what the layouts do and then design the UI in SceneBuilder. In general it's best to keep the scene simple instead of nesting more layouts than necessary.
In your case 3 Panes seem to suffice:

*

*A GridPane as root

*A VBox containing the Buttons

*The GridPane inside the ScrollPane
By using the GridPane's layout parameters you can design a UI that has a much nicer resizing behavior:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.image.*?>

<GridPane alignment="center" hgap="10" prefHeight="633.0" prefWidth="869.0" stylesheets="/sample/sample.css" vgap="10" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <children>
        <ImageView fitHeight="173.0" fitWidth="409.0" pickOnBounds="true" preserveRatio="true" GridPane.halignment="CENTER" GridPane.columnSpan="5" >
            <image>
                <Image url="@../../../../../Pictures/title.png" />
            </image>
        </ImageView>
        <VBox prefWidth="105.0" GridPane.columnIndex="4" GridPane.rowIndex="1" GridPane.rowSpan="2" >
            <children>
                <Button mnemonicParsing="false" text="Make a Graph" />
                <Button mnemonicParsing="false" text="Save" />
                <Button mnemonicParsing="false" text="Delete" />
            </children>
        </VBox>
        <ComboBox prefWidth="150.0" promptText="Sort or Filter" GridPane.rowIndex="1" />
        <ComboBox prefWidth="150.0" GridPane.rowIndex="1" GridPane.columnIndex="1" disable="true"/>
        <CheckBox mnemonicParsing="false" prefHeight="33.0" prefWidth="120.0" text="Favourties" GridPane.rowIndex="1" GridPane.columnIndex="2" disable="true"/>
        <TextField text="Search" GridPane.rowIndex="1" GridPane.columnIndex="3"/>
        <ScrollPane prefHeight="507.0" prefWidth="764.0" GridPane.rowIndex="2" GridPane.columnSpan="4">
            <content>
                <GridPane prefHeight="90.0" prefWidth="762.0">
                    <columnConstraints>
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                        <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                    <children>

                    </children>
                </GridPane>
            </content>
        </ScrollPane>
    </children>
</GridPane>

A: In your case, Size of Scene is less than size of GridPane
 primaryStage.setScene(new Scene(root, 600, 400));

and in grid pane size is
 <GridPane alignment="center" hgap="10" prefHeight="633.0" prefWidth="869.0"

because of this there is difference in layout :)


text:
Q: Change Orientation forcefully In my app, While playing video user can play in  full screen in both orientation landscape and portrait. But while move back to original position from full screen, i want to change my controller's orientation to portrait if its running in landscape.
Its working fine if i push that controller, but i have to present it. So its not working with presented controller.
I m using code as below to make it portrait.
  [appdel.navigationController.presentedViewController.view removeFromSuperview];

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
[[UIApplication sharedApplication].self.delegate.window addSubview:[appdel.navigationController.presentedViewController.view];
self.navigationController.navigationBar.hidden=NO;

Thanks for any help

A: see in case of presenting the controller when u come in previous controller the
viewWillApear: of previous method will call so change your orientation in viewWillApear: mthod


text:
Q: Cakephp Get key & value from database I just Created Web-installer in Cakephp and now i stated working on writing and reading configuration on database table .. but dont know how to start. do i have to create a model.. seems thats not the right way could some one show me the way.
UPDATE: just need to know reading config based from database table
Web Insaller

A: Checkout how the popular CakePHP CMS Croogo does it.


text:
Q: Two sites with two different log files - SSL Apache2 Ubuntu I have two websites in the same web server (Ubuntu 16.04.2 LTS - Apache/2.4.18). Everything works well when I try to access to both websites using HTTP (port 80). This is the vhosts.conf file content:
<VirtualHost *:80>
    ServerName site1
    DocumentRoot /var/www/html/site1
    ErrorLog ${APACHE_LOG_DIR}/site1_error.log
    CustomLog ${APACHE_LOG_DIR}/site1_access.log combined
</VirtualHost>
<VirtualHost *:80>
    ServerName site2
    DocumentRoot /var/www/html/site2
    ErrorLog ${APACHE_LOG_DIR}/site2_error.log
    CustomLog ${APACHE_LOG_DIR}/site2_access.log combined
</VirtualHost>

So, both sites are accessible through "mydomain.com/site1" and "mydomain.com/site2". I have installed a Let's Encrypt certificate and, to make it works, I have configured a virtual host like this:
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName mydomain.com
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/site_error.log
    CustomLog ${APACHE_LOG_DIR}/site_access.log combined
    SSLCertificateFile /etc/letsencrypt/live/mydomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

I can access both site using SSL (port 443) successfully but I can't use different log files for different sites. I have tried something like this:
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName mydomain.com/site1
    DocumentRoot /var/www/html/site1
    ErrorLog ${APACHE_LOG_DIR}/site1_error.log
    CustomLog ${APACHE_LOG_DIR}/site1_access.log combined
    Alias /site1 /var/www/html/site1
    SSLCertificateFile /etc/letsencrypt/live/mydomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
<VirtualHost *:443>
    ServerName mydomain.com/site2
    DocumentRoot /var/www/html/site2
    ErrorLog ${APACHE_LOG_DIR}/site2_error.log
    CustomLog ${APACHE_LOG_DIR}/site2_access.log combined
    Alias /site2 /var/www/html/site2
    SSLCertificateFile /etc/letsencrypt/live/mydomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

But it doesn't work. How can I distinguish between two sites in order to have two different log files?

A: Following the link proposed by CBroe, I have found the solution by using the SetEnvIf directive. The final working virtual host configuration looks like this:
<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName mydomain.com
    DocumentRoot /var/www/html
    SetEnvIf Request_URI ^/site1(/|$) site1
    SetEnvIf Request_URI ^/site2(/|$) site2
    CustomLog ${APACHE_LOG_DIR}/site1_access.log combined env=site1
    CustomLog ${APACHE_LOG_DIR}/site2_access.log combined env=site2
    ErrorLog ${APACHE_LOG_DIR}/site_error.log
    SSLCertificateFile /etc/letsencrypt/live/mydomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>


text:
Q: How can I specify multiple address_space structs for an inode? Say that two different processes each open two different files. Normally, they would each have their own inode and each inode would have their own struct address_space (this is the guy who remembers where the page cache pages are in memory).
But, let's say I knew that these files were initially identical. I want to come up with a way to smart share caching to the extent possible.
I was considering these strategies:

*

*Add a new field to the struct address_space struct: a pointer to a "parent". Then, whenever I look for an existing page, I'll also look in the parent (if it exists). Whenever I write to a page, I will therefore need to fault and C-O-W the page into the main address_space. Both files will share the common parent.

*Group each related set of struct address_space in a linked list. Whenever I look for an existing page, search the entire linked list. In this scenario, though, it would be disallowed to "find" a dirty page on a friend's address_space. In other words, if a page gets dirty it can't be used as a backup anymore. In this scenario, if anyone ever wrote data to the file, I would need to disassociate the address_spaces. I would also need some sort of C-O-W behavior to sustain this as well.
Can anyone tell me:

*

*Is either or both of these ideas are sound?

*What things in particular should I watch out for?

As a point of reference, I am doing a custom kernel hack to save memory because on my system there are multiple identical files being opened (but not the same inode = not sharing pagecache).
EDIT: 3rd idea:

*

*Keep a linked list of the "related" pagecache address_space and then every time we read from disk, update every address_space struct that's open. Opening a new related file would have to cause a big page table copying thing to happen, except skip any dirty pages.


text:
Q: Changing width of GridLayout I use the GridLayout for my JPanel and was wondering, if it's possible to change the width of the columns:
GridLayout grid = new GridLayout(5,2);
panel.setLayout(grid);

Is there a simple way?

A: Check the GridLayout api to see that the grid is made so all cells are the same size. If you want a component to be shown at it's preferred size, like (15,15), add it to a JPanel and add the JPanel to the GridLayout. The JPanel will expand to fill the gird cell and allow the component to be shown at it's preferred size.
For a row of different size you'll have to try something else. Nested layouts would be a good starting place...
You could always use the dreaded GridBagLayout.

A: You can use separate grid layout for each column.
GridLayout grid = new GridLayout(1,2);
    GridLayout grid1 = new GridLayout(5,1);
        GridLayout grid2 = new GridLayout(5,1);

        grid.add(grid1);
        grid.add(grid2);

You can now set widths of grid1 one  and grid2.


text:
Q: Save Using Ajax And Include Notice - Rails I've added :remote => true to the _form.html.erb and wondered now how I can get it so when the user saves what's on the page, it saves and then comes up with a notice.
In my documents_controller.rb, I have;
def create
  @document = current_user.documents.build(params[:document])

  if @document.save
    redirect_to @document.edit, notice: 'Saved'
  else
    render action: "new"
  end
end

def update
  @document = current_user.documents.find_by_url_id(params[:id])

  if @document.update_attributes(params[:document])
    redirect_to @document, notice: 'Saved'
  else
    render action: "edit"
  end
end

A: You'll need to write the appropriate JavaScript to make use of the following jQuery events:
ajax:beforeSend
ajax:complete
ajax:success
ajax:error

E.g.
$(document).ready(
    $(".ajax_rails_link").bind("ajax:success", function(evt, data, status, xhr){
        console.log(data);

        // Display your notice logic goes here
    })
});

More information can be found here: http://guides.rubyonrails.org/ajax_on_rails.html


text:
Q: NumPy: is there a better way to construct a specific matrix with specific value? I've managed to construct a matrix with this piece of code
c_bed = np.append(np.array([1, 2, 3]), np.nan).reshape(4, 1)
c_bath = np.array([1, 1, 2, 2], dtype=np.float).reshape(4, 1)
ds = np.append(c_bed, c_bath, axis=1)

which gives
array([[ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  2.],
       [nan,  2.]])

the output is exactly what i want though, I am wondering is there a better way to construct this matrix?

A: How about using zip_longest
from itertools import zip_longest
np.array(list(zip_longest([1,2,3],[1,1,2,2],fillvalue=np.nan)))
Out[228]:
array([[ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  2.],
       [nan,  2.]])

A: Is there any reason not to use this matrix = numpy.array([[1, 1], [2, 1], [3, 2], [numpy.nan, 2]])?

A: If you have
beds = [1, 2, 3]
baths = [1, 1, 2, 2]
data = (beds, baths)

You can do as follows:
ds = np.full((max(map(len, data)), 2), np.nan)
ds[:len(beds), 0] = beds
ds[:len(baths), 1] = baths

A: Disclaimer: the following may well be the shortest method, but it is most certainly not the healthiest. I wouldn't use it in production code.
np.c_[[2,4,6,np.nan],2:6]//2
# array([[ 1.,  1.],
#        [ 2.,  1.],
#        [ 3.,  2.],
#        [nan,  2.]])


text:
Q: DIV of Social Icons Not Appearing On Wordpress Mobile I have a set of social media icons in the footer of my website.
The icons are inserted there via a Text widget; the code for the icons is as follows -

[social-media items_align="center"]

For some reason, the icons won't appear on a mobile device. How do I rectify this?

A: I've checked you website and the .site-footer-first-widget-area is hidden on mobile phones. The code for this is present in the main.css file.
If you want it to be always visible you can make the following changes to your main.css
/*=========================================================================
   3. Footer styles
 ======================================================*/

.site-footer-first-widget-area
{
    display: block;
    margin-bottom: 10px;
}

PS: your inline css in the opening post has a small flaw. There is no such thing as float: center;
Hope this answer helps!