text:
Q: Can't access Go libraries I had a working go project and I added some libraries to it.
All was working fine till this step. Then I pushed my code to server. Again I tried to take fresh clone the repository and I am getting following error.
go file not find error
When I try to do go get - (repo again) I get
go get -u github.com/jinzhu/gorm
package github.com/jinzhu/gorm: directory "/testapp/src/github.com/jinzhu/gorm" is not using a known version control system

What is wrong in this approach??
And When I am checking repository I can see git library repository point to some other repository commit.

A: I ran into the same issue just today and I fixed it by initializing a .git repo inside the local dependency. So inside github.com/jinzhu/gorm run:
git init

git add .
git commit -m "first commit"

A: I tried this approach and it worked as this was the only work around i was left with:
Fresh clone the project and navigate inside it;
Created install.sh which would set GOPATH, remove libraries and then re download it.
#!/bin/sh

#GET current working directory
CURRENT_DIR=`pwd`
echo "GOPATH is pointing to ${CURRENT_DIR}"
#Export GOPATH for current working directory
export GOPATH=${CURRENT_DIR}

#Change Directory permission to executable
chmod +x ${GOPATH}

#Delete github dependency so that they can be reinstalled
#Github Issue: https://github.com/golang/go/issues/18591

#Modify this script if you are adding any other packages
rm -rf ${GOPATH}/src/github.com

#dependencies.txt contain list of go get -u (repo path)
#dependencies in new line add any new dependency and execute install.sh again
sh dependencies.txt

File dependencies.txt
go get -u -v github.com/gorilla/mux
go get -u -v github.com/gorilla/handlers
go get -u -v github.com/dgrijalva/jwt-go

Then finally run script which would boot my application
run.sh
#!/bin/sh

#GET current working directory
CURRENT_DIR=`pwd`
echo "GOPATH is pointing to ${CURRENT_DIR}"

#Export GOPATH for current working directory
export GOPATH=${CURRENT_DIR}

echo "Starting server at http://localhost:9096"
#Run server instance
go run ${GOPATH}/path/to/main/file/Main.go

All this hold true with following directory structure:
Project Root
-----bin
-----pkg
-----src
-----src/github.com/
-----src/github.com/gorilla/mux
-----src/github.com/gorilla/handlers
-----src/yours/project/code

A: There are couple things you can do.

*

*Check your version of your GO if not the latest version then update your GO to version  1.7

*Delete the repo and clone again after updating GO.

*You could try to create new export for Golang directory with the following step :

export GOPATH=/home/golang/    => try to modify your golang dir here
~$ mkdir -p $GOPATH
~$ go get github.com/jinzhu/gorm

this kind of problem mention in these link :

*

*https://github.com/golang/go/issues/6175

*https://go-review.googlesource.com/#/c/21342/
I think the latest version has fix this issue. Hope it


text:
Q: How to add a line break in C# .NET documentation This should be waaaay easier...
I want to add a "coded" line break to the XML documentation in my code
///
/// Get a human-readable variant of the SQL WHERE statement of the search element. <br/>
/// Rather than return SQL, this method returns a string with icon-tokens, which
/// could be used to represent the search in a condensed pictogram format.
///

As you can see, I found some answers that demonstrated adding < and > brackets.
Interestingly, the good 'ol
 line break does not create a line break in the Intellisense popup.
I find this annoying...
Any suggestions?

A: This is my usage, like
 , it's working :)
///
/// Value: 0/1/2
/// <para/>0 foo,
/// <para/>1 bar,
/// <para/>2 other
///

A:

 and
 do not seem to work, and sometimes it isn't really about making the <para> sentences separate as much as the desire to have a blank line for concern separation. I am mentioning this here because this question seems to be to parent to many closed questions of this nature.
The only thing I found to work was
<para> </para>

For example
///
///     <para>
///         "This sentence shows up when the type is hovered"
///     </para>
///     <para> </para>
///     <para>int PrimaryKey</para>
///     <para> </para>
///     <para>virtual Relation Relation</para>
///

Results in
"This sentence shows up when the type is hovered"

int PrimaryKey

virtual Relation Relation

A: You can use a <para /> tag to produce a paragraph break or you can wrap text in <para></para> tags as a way to group the text and add the blank line after it, but there is no equivalent to
 or anything like that. (Which according to this old MS forum post is by design.)  You can get the list of available tags in this documentation article from MS. Documenting your code
Example (based on original OP sample):
///
/// <para>Get a human-readable variant of the SQL WHERE statement of the search element.</para>
/// Rather than return SQL, this method returns a string with icon-tokens, which
/// could be used to represent the search in a condensed pictogram format.
///

A: Add a <para> tag with a special char in it, the 255 char, or invisible char.
///
/// Some text
/// <para>   </para>
/// More text
///
/// <param name="str">Some string</param>
public void SomeMethod(string str) { }

It will work like this:

A: As of Visual Studio 2019, use
 for newlines in comments.
Example:
///
/// This is a comment.

/// This is another comment

/// This is a long comment so i want it to continue
 on another line.
///

Notice that there is no extra line added when we use
 instead of <para>.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Есть ли лишнее копирование в std::optional? C++ Открыл для себя такую полезную штуку, как std::optional и std::expected. При прочтении документации по методу or_else() заметил, что он возвращает optional по значению. Значит ли это, что при каждом вызове or_else(), если optional содержит значение, то все его содержимое копируется/перемещается в новый экземпляр при возврате из функции? Например такой код:
// Методы хотят добавить в С++23, но, предположим, есть свой optional с такими методами
// Пусть foo() возвращает валидный std::optional
auto opt = foo().or_else([]{std::cout << "Invalid\n";})
                .or_else([]{std::cout << "Invalid 2\n";});
// Перемещение содержимого optional при возврате значения из or_else()
// При условии, что optional содержит значение

И если из-за ref-квалификаторов с перемещаемыми объектами все нормально, то что делать с объектами, которые хранят большое количество данных на стеке в полях класса? Их ведь не переместить, они будут копироваться в новый optional

A: Лишнее копирование/перемещение не запрещено, а даже требуется, и может быть исключено разве что через "as-if" правило.
Лишнее копирование/перемещение запрещено для случая optional не содержащего значение, если там внутри return неименованной переменной.
В общем случае оптимизация вряд ли возможна для с lvalue optional, т.к. после or_else можно получить независимые копии объекта, каждая со своим состоянием.
Для rvalue (т.е. для ...::or_else(...) &&) принципиально можно сделать оптимизацию в общем случае, трансформировав в:
void or_else(F f) {
 if (!*this)
 {
    *this = f();
 }
} // далее используем старый объект как якобы новый

И, возможно, какой-то будущий стандарт будет разрешать/требовать такую оптимизацию, как C++17 требует RVO, а предыдущие разрешают.


text:
Q: String Replace - address abbreviations Essentionally I have a column for street address (e.g. 321 North Laredo Road).  This column has 10,000+ records.  Some Records are completely unabbreviated some are partially and some are completely.  Point being no consistency (it was like this before I had access).  I need to make all addresses's Directionals (N,S,E,W) and street names (road, blvd, ave, etc) into the abbreviated forms and add to a second column.  any suggestions with methodology or possibly an already written solution.  getting mixed results with following test code. . .
/* First find/update directionals */
UPDATE hospital
set tiger_address = replace(street, 'North', 'N')
where street LIKE "%North%"
;
UPDATE hospital
set tiger_address = replace(street, 'South', 'S')
where street LIKE "%South%"
;
UPDATE hospital
set tiger_address = replace(street, 'East', 'E')
where street LIKE "%East%"
;
UPDATE hospital
set tiger_address = replace(street, 'West', 'W')
where street LIKE "%West%"
;
/* Second look for streets to abbreviate */
UPDATE hospital
set tiger_address = replace(tiger_address, 'Alley', 'Aly')
where tiger_address LIKE "%Alley%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Anex', 'Anx')
where tiger_address LIKE "%Anex%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Arcade', 'Arc')
where tiger_address LIKE "%Arcade%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Avenue', 'Ave')
where tiger_address LIKE "%Avenue%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Bayou', 'Byu')
where tiger_address LIKE "%Bayou%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Beach', 'Bch')
where tiger_address LIKE "%Beach%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Bend', 'Bnd')
where tiger_address LIKE "%Bend%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Bluff', 'Blf')
where tiger_address LIKE "%Bluff%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Bluff', 'Blfs')
where tiger_address LIKE "%Bluffs%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Street', 'St')
where tiger_address LIKE "%street%"
;

UPDATE hospital
set tiger_address = replace(street, 'Road', 'Rd')
where tiger_address LIKE "%road%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Drive', 'Dr')
where tiger_address LIKE "drive%"
;
UPDATE hospital
set tiger_address = replace(tiger_address, 'Boulevard', 'Blvd')
where tiger_address LIKE "boulevard%"
;

The age old there has to be a better way.
Thank You

A: Deleting one chunk out of a word can be accomplished using MariaDB's regexp_replace and positive look-ahead and look-behind assertions. For Bayou and Boulevard I use replace.
select replace(replace(
  regexp_replace(
    'North East South West Alley Anex Arcade Avenue '
    'Bayou Beach Bend Bluff Bluffs Street Road Drive Boulevard',

    '(?<=N)orth|(?<=S)outh|(?<=E)ast|(?<=W)est|(?<=Al)le(?=y)|'
    '(?<=An)e(?=x)|(?<=Arc)ade|(?<=Ave)nue|(?<=B)ea(?=ch)|(?<=B)e(?=nd)|'
    '(?<=Bl)uf(?=f)|(?<=St)reet|(?<=R)oa(?=d)|(?<=Dr)ive',

    ''),
  'Bayou', 'Byu'),
  'Boulevard', 'Blvd')


text:
Q: "The reason why X is because" or "The reason why X is that" So, there's a group called One sentence startup pitches in Facebook and I posted the following sentence there.

A startup/university/research institution that would prove that the reason why no one has traveled from future to the present is because climate change destroyed the planet before anyone could invent the time machine.

A native speaker corrected me and told me that it should be:

A startup/university/research institution that would prove that the reason why no one has traveled from future to the present is that climate change destroyed the planet before anyone could invent the time machine.

I am sort of naturally skeptical. So I thought I should post here to confirm.

A: The correction is appropriate.
However, you could also keep because if you remove the reason why and is:

A startup/university/research institution that would prove that no one has traveled from future to the present because climate change destroyed the planet before anyone could invent the time machine.


text:
Q: Which state in gstreamer indicates that the pipeline is working correctly? Concerning Gstream state changes, we should send a event when the pipeline is working correctly (Stream OK) and when there is an error we should send another event (Stream Error).
Catching errors over the message callback works, but we don't know which state indicate that the full pipeline is working correctly (from src to sync).

A: There is no specific error state in GStreamer (GStreamer states are: NULL, READY, PAUSED, PLAYING (*)). Thus, you need to watch and check if any error occurs. You should check, at least:

*

*the return value of the function for changing the state (gst_element_set_state)

*if any error message is sent to the bus:

Errors can be received by listening to the GstBus of the
  element/pipeline for GstMessage objects with the type
  GST_MESSAGE_ERROR or GST_MESSAGE_WARNING. The thrown errors should be
  inspected, and filtered if appropriate.

(*) Note: actually, the complete list of states in the API includes also a pending state that may be relevant in some cases (see e.g. How to resume playing after paused using gstreamer?)


text:
Q: Send email to IDN email ID How do I send email to non-Ascii email ID, for example I have adad@ÄÖß.com as emailID and when I try to send email to this emailID using
sendTo="adad@ÄÖß.com";
MailMessage msg = new MailMessage();
msg.To.Add(sendTo);

msg.To.Add(sendTo) throws an error saying "The specified string is not in the form required for an e-mail address.".
Did you guys face this ever?
Is this possible? if yes,
Any idea of how I can get this working?

A: Have a look at this its Jon Skeet doing the job once again.

A: System.Uri has a config parameter for IDN support. I'm not sure if this affects MailMessage, too, or if there is an additional parameter for it.
http://msdn.microsoft.com/en-us/library/system.uri.aspx
<configuration>
  <uri>
    <idn enabled="All" />
    <iriParsing enabled="true" />
  </uri>
</configuration>

A: I just found this, it might help you:
Convert non-ascii domain to SMTP compatible


text:
Q: How to keep previous filter values with custom filtering in Kendo Grid? I have created custom filtering, because there is a column in which (1) a certain property of an array of objects is displayed and (2) either one of two types of objects can be displayed in each row of the column: declarants or declarantMeetings.
The following code works for filtering. The problem is that if the user has filtered the grid by some other column, then this filter is not added to the previous filters - all the previous filters are deleted. So it becomes impossible to filter by multiple columns.
How can I keep the old filters?
var getGridOptions = function (dataSource) {
    return {
        dataSource: dataSource,
        //...
        filter: function (e) {
            var field = e.filter.filters[0].field;

            //if the user is filtering the column with multiple possible object arrays
            if (field == "declarants") {
                e.preventDefault();

                var filters = [];
                var filterValue = e.filter.filters[0].value.toLowerCase();

                var _personFilter = {
                    operator: function (item, filterValue) {
                        var properties = ["firstName", "lastName", "otherNames", "position", "email", "fullNameAndDivision"];
                        if (typeof item !== "undefined") {
                            for (var k = 0; k < item.length; k++) {
                                for (var i = 0; i < properties.length; i++) {
                                    if (typeof item[k][properties[i]] !== "undefined") {
                                        var value = item[k][properties[i]].toLowerCase();
                                        if (value.indexOf(filterValue) !== -1) {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    },
                    value: filterValue,
                    field: field
                };

                var subfilters = [];
                subfilters.push({
                    operator: function (item, filterValue) {
                        if (typeof item !== "undefined") {
                            for (var k = 0; k < item.length; k++) {
                                if (typeof item[k]["meetingType"]["name"] !== "undefined") {
                                    var value = item[k]["meetingType"]["name"].toLowerCase();
                                    if (value.indexOf(filterValue) !== -1) {
                                        return true;
                                    }
                                }
                            }
                        }
                    },
                    value: filterValue,
                    field: "declarantMeetings"
                });
                subfilters.push(_personFilter);
                filters.push({logic: "or", filters:subfilters})

                e.sender.dataSource.filter({
                    logic: "and",
                    filters: filters
                });
            }
        }
    }
}

A: You can get all existing filters using the dataSource.filter method. Thus, you could extend the existing filter query with your custom filters as follows:
function removeFiltersForField(expression, field) {
    if (expression.filters) {
        expression.filters = $.grep(expression.filters, function(filter) {
            removeFiltersForField(filter, field);
            if (filter.filters) {
                return filter.filters.length;
            } else {
                return filter.field != field;
            }
        });
    }
}

var getGridOptions = function (dataSource) {
    return {
        dataSource: dataSource,
        //...
        filter: function (e) {
            var field = e.filter.filters[0].field;

            //if the user is filtering the column with multiple possible object arrays
            if (field == "declarants") {
                e.preventDefault();

                var filters = e.sender.dataSource.filter() || { filters:[], logic: "and" };
                var filterValue = e.filter.filters[0].value.toLowerCase();

                removeFiltersForField(field, filters);

                var _personFilter = {
                    operator: function (item, filterValue) {
                        var properties = ["firstName", "lastName", "otherNames", "position", "email", "fullNameAndDivision"];
                        if (typeof item !== "undefined") {
                            for (var k = 0; k < item.length; k++) {
                                for (var i = 0; i < properties.length; i++) {
                                    if (typeof item[k][properties[i]] !== "undefined") {
                                        var value = item[k][properties[i]].toLowerCase();
                                        if (value.indexOf(filterValue) !== -1) {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    },
                    value: filterValue,
                    field: field
                };

                var subfilters = [];
                subfilters.push({
                    operator: function (item, filterValue) {
                        if (typeof item !== "undefined") {
                            for (var k = 0; k < item.length; k++) {
                                if (typeof item[k]["meetingType"]["name"] !== "undefined") {
                                    var value = item[k]["meetingType"]["name"].toLowerCase();
                                    if (value.indexOf(filterValue) !== -1) {
                                        return true;
                                    }
                                }
                            }
                        }
                    },
                    value: filterValue,
                    field: "declarantMeetings"
                });
                subfilters.push(_personFilter);
                filters.filters.push({logic: "or", filters:subfilters});

                e.sender.dataSource.filter(filters);
            }
        }
    }
}


text:
Q: Summary table with multiple factors in Rmarkdown for publication This is my second post about this question. The first one has been closed without resolving my table formatting issue.
I am new on Stack Overflow and fairly new to Rmarkdown. I am trying to write a publication using Rmarkdown (output = book down::pdf_book) and I have issues with table formatting. I want to built a flat table in a r chunk to obtain this kind of table but with mean value instead of count :
Goud format but with count:
                     F2       N0    N1    N2
                     F1       I II  I II  I II
Variable F3
V1     T                      3  3  3  3  3  3
         V                      3  3  3  3  3  3
V2      T                      3  3  3  3  3  3
         V                      3  3  3  3  3  3
V3    T                      3  3  3  3  3  3
         V                      3  3  3  3  3  3
V4      T                      3  3  3  3  3  3
         V                      3  3  3  3  3  3
V5      T                      3  3  3  3  3  3
         V                      3  3  3  3  3  3

Suppose I have a data frame which looks like this:
F1  F2  F3  V1  V2  V3  V4  V5
I   N0  T   1.977546019 137.5   0.83    8.114217417 1.032679447
I   N0  T   2.342365156 139.4   0.85    10.3602728  0.871637237
I   N0  T   2.170706854 141.2   0.82    11.59271819 1.258035755
I   N0  V   1.559072025 114.9   0.87    11.57618562 1.661523112
I   N0  V   1.984240008 118.6   0.88    11.9835584  1.60688624
I   N0  V   1.68756027  116.3   0.88    11.79686026 1.78102523
I   N1  T   2.19858517  139.7   0.85    33.1128997  4.312955185
I   N1  T   3.249054469 136.4   0.86    29.69128121 3.047780521
I   N1  T   2.223041022 142.1   0.85    20.65967924 2.332772924
I   N1  V   1.595849998 118.2   0.89    19.84579734 2.191828463
I   N1  V   1.72860847  114.8   0.86    20.16367213 5.017873836
I   N1  V   2.133891213 115.7   0.84    23.07712358 3.930948522
I   N2  T   3.152019262 131.3   0.89    35.5848969  5.589698563
I   N2  T   3.367223676 138.7   0.87    34.05297654 2.730557232
I   N2  T   3.059409463 137.4   0.83    35.37992694 3.548049932
I   N2  V   1.71633507  112.3   0.93    34.09476427 5.25868398
I   N2  V   2.284833663 116.9   0.84    22.19728478 3.518505779
I   N2  V   1.866355607 113.6   0.86    29.02993798 5.014262016
II  N0  T   1.768065012 127.8   0.83    7.6010075   9.42999993
II  N0  T   3.250876694 129.4   0.83    29.23677503 27.91017246
II  N0  T   2.815832568 133.6   0.83    4.051675097 10.12918774
II  N0  V   3.891509434 109.1   0.88    5.469474969 9.770670085
II  N0  V   2.882145915 111.2   0.87    17.00061485 21.40077399
II  N0  V   4.128069071 113.7   0.88    12.9571096  37.50296115
II  N1  T   3.003514751 126 0.84    39.39306152 7.043527056
II  N1  T   3.134655188 129.2   0.85    11.4866755  21.51749579
II  N1  T   2.785986782 131.5   0.83    19.78519656 2.176659469
II  N1  V   3.089649674 107.5   0.88    17.32529262 12.99396947
II  N1  V   4.466019417 112.6   0.89    12.03083642 20.22446923
II  N1  V   3.1820755   116.1   0.84    12.63619614 12.65798269
II  N2  T   3.428280773 134.2   0.87    16.67590015 14.49664664
II  N2  T   4.430091185 139.8   0.85    36.47033184 12.18635248
II  N2  T   3.362380446 132.4   0.86    67.7182946  11.7089442
II  N2  V   3.672823219 111.6   0.9 24.5684152  13.5849653
II  N2  V   3.031651201 110.1   0.88    19.7549665  15.6015459
II  N2  V   3.198950088 108.7   0.88    20.86135738 14.60295017

Where F columns are factors and V columns are variables
Lets named this data frame "df".
I have tried two ways to realize the flat table:
First
I put the variable names as column using the function pivot_longer from tidy verse package:
df %>% pivot_longer(
-c(F1,F2,F3),
names_to = "Variable",
values_to = "Value") -> df2

and used this code to built the flat table:
ftable(df2, row.vars = c("Variable", "F3"), col.vars = c("F2", "F1"))

Here I obtain the target table formatting but the values are counts, not means (see "GoodTable"").
Second
I compute means (and standard error) using '''dplyr''' package
df2_summary <- dplyr::summarise(df2_grouped,
                                     count = dplyr::n(),
                                     mean = round(mean(Value), 2),
                                     SE = round(sd(Value)/sqrt(count),2))

but I don't know how to transform df2_summary into a table that looks like the one above
I know I can use latex language to format and complete the table but it is time consuming and can also generate typing error.
Does someone know how to do it ?
Thanks !

A: Does this look close to what you want?  Please use 'dput' to send a dataframe
instead of text output that had extra spaces that had to be removed.
library(tidyverse)

df <- read_delim(file = "
F1 F2 F3 V1 V2 V3 V4 V5
I N0 T 1.977546019 137.5 0.83 8.114217417 1.032679447
I N0 T 2.342365156 139.4 0.85 10.3602728 0.871637237
I N0 T 2.170706854 141.2 0.82 11.59271819 1.258035755
I N0 V 1.559072025 114.9 0.87 11.57618562 1.661523112
I N0 V 1.984240008 118.6 0.88 11.9835584 1.60688624
I N0 V 1.68756027 116.3 0.88 11.79686026 1.78102523
I N1 T 2.19858517 139.7 0.85 33.1128997 4.312955185
I N1 T 3.249054469 136.4 0.86 29.69128121 3.047780521
I N1 T 2.223041022 142.1 0.85 20.65967924 2.332772924
I N1 V 1.595849998 118.2 0.89 19.84579734 2.191828463
I N1 V 1.72860847 114.8 0.86 20.16367213 5.017873836
I N1 V 2.133891213 115.7 0.84 23.07712358 3.930948522
I N2 T 3.152019262 131.3 0.89 35.5848969 5.589698563
I N2 T 3.367223676 138.7 0.87 34.05297654 2.730557232
I N2 T 3.059409463 137.4 0.83 35.37992694 3.548049932
I N2 V 1.71633507 112.3 0.93 34.09476427 5.25868398
I N2 V 2.284833663 116.9 0.84 22.19728478 3.518505779
I N2 V 1.866355607 113.6 0.86 29.02993798 5.014262016
II N0 T 1.768065012 127.8 0.83 7.6010075 9.42999993
II N0 T 3.250876694 129.4 0.83 29.23677503 27.91017246
II N0 T 2.815832568 133.6 0.83 4.051675097 10.12918774
II N0 V 3.891509434 109.1 0.88 5.469474969 9.770670085
II N0 V 2.882145915 111.2 0.87 17.00061485 21.40077399
II N0 V 4.128069071 113.7 0.88 12.9571096 37.50296115
II N1 T 3.003514751 126 0.84 39.39306152 7.043527056
II N1 T 3.134655188 129.2 0.85 11.4866755 21.51749579
II N1 T 2.785986782 131.5 0.83 19.78519656 2.176659469
II N1 V 3.089649674 107.5 0.88 17.32529262 12.99396947
II N1 V 4.466019417 112.6 0.89 12.03083642 20.22446923
II N1 V 3.1820755 116.1 0.84 12.63619614 12.65798269
II N2 T 3.428280773 134.2 0.87 16.67590015 14.49664664
II N2 T 4.430091185 139.8 0.85 36.47033184 12.18635248
II N2 T 3.362380446 132.4 0.86 67.7182946 11.7089442
II N2 V 3.672823219 111.6 0.9 24.5684152 13.5849653
II N2 V 3.031651201 110.1 0.88 19.7549665 15.6015459
II N2 V 3.198950088 108.7 0.88 20.86135738 14.60295017",
         delim = ' ') %>%
  mutate(across(starts_with("V"), as.numeric))

df2 <- df %>%
  pivot_longer(cols = starts_with("V"),
           names_to = "Variable",
           values_to = 'Value') %>%
  group_by(Variable, F3, F1, F2) %>%
  summarise(avg = mean(Value),
        count = n()) %>%
  ungroup() %>%
  pivot_wider(id_cols = c(Variable, F3),
          names_from = c(F1, F2),
          names_glue = "{F1}_{F2}",
          values_from = avg)

print(df2)

# A tibble: 10 x 8
   Variable F3       I_N0    I_N1    I_N2   II_N0  II_N1   II_N2
   <chr>    <chr>   <dbl>   <dbl>   <dbl>   <dbl>  <dbl>   <dbl>
 1 V1       T       2.16    2.56    3.19    2.61    2.97   3.74
 2 V1       V       1.74    1.82    1.96    3.63    3.58   3.30
 3 V2       T     139.    139.    136.    130.    129.   135.
 4 V2       V     117.    116.    114.    111.    112.   110.
 5 V3       T       0.833   0.853   0.863   0.83    0.84   0.86
 6 V3       V       0.877   0.863   0.877   0.877   0.87   0.887
 7 V4       T      10.0    27.8    35.0    13.6    23.6   40.3
 8 V4       V      11.8    21.0    28.4    11.8    14.0   21.7
 9 V5       T       1.05    3.23    3.96   15.8    10.2   12.8
10 V5       V       1.68    3.71    4.60   22.9    15.3   14.6

A: I have worked on this issue.
Here is a code giving not exact but similar table format as the one I wanted :
I used the function "collapse_rows" so I had to transpose the table as compared to the one I wanted. I am not aware of such a function for column.
df2 <- df %>%
  group_by(Month, Enrichment, Vegetation) %>%
  summarise(
    across(
      .cols =  starts_with(c("V")),
      .fns  = list(mean, sd),
      .names = "{col}_{fn}"
    )
  )

here is an ugly code to compute standard error instead of standard deviation:
df2[,c(5,7,9,11,13,15,17)] <- df2[,c(5,7,9,11,13,15,17)]/sqrt(3)

Then change the name of the column but keep in mind the order (you can look at the function "start_with" if you have forgotten). The two first column are factors I removed them since they are often long word and I need to reduced the size of the table. This is probably not the most efficient way to do it but at least it works
colnames(df2)[2:17] <- c("", "", "Mean", "SE","Mean", "SE","Mean", "SE","Mean", "SE","Mean", "SE")

I used kableExtra package for the following
library(kableExtra)
kable(df2, "latex", digits = 1,
      booktabs = TRUE, align = "c",
      caption = '(ref:df)',
      linesep = "") %>%
add_header_above(c(" " = 3, "V1" = 2, "V2" = 2, "V3" = 2, "V4" = 2, "V5" = 2),
                   bold = T) %>%
  collapse_rows(1:2,
                row_group_label_position = 'stack',
                latex_hline = "none")%>%
 landscape()

Just in case, their are very nice vignettes for kableExtra package


text:
Q: Получить экземпляр Fragment в activity.onСreate()? Есть такая проблема, подключаю ViewPager.
Работает все нормально, но мне надо что бы в Activity.onCreate() я получил экземпляр первого активити и присвоил значение TextView в фрагменте.
Вот что я делаю:
Фрагмент:
public class Frag1 extends Fragment {
    TextView textView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.artist_fragment,null);
        textView = (TextView) v.findViewById(R.id.textView);
        return v;
    }

    public void setTextTextView(String text){
        textView.setText(text);
    }
}

MainActivity:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewpager);
        Frag1 frag1 = new Frag1();
        frag1.setTextTextView("Текст");
}

После отладки я вижу что frag1 и все его элементы null. Он получает ссылку на frag1, но все параметры по null.

A: Компонент ViewPager работает немного по другому, присваивать данные в самом вызывающем акивити не стоит, их нужно передавать в адаптере, а потом присваивать методом viewPager.setAdapter(pagerAdapter); Хороший пример тут, разберись, все методы присваивания инкапсулированы в классе PagerAdapter

A: Как я вижу фрагмент просто не отображен нужно добавить
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewpager);
    Frag1 frag1 = new Frag1();

    getSupportFragmentManager().beginTransaction().add(R.id.frame_layout, frag).commit();
    frag1.setTextTextView("Текст");
}


text:
Q: Show a link with div php mysql jQuery I have a link that says remove I have hidden the like by
< div id="remove_$id"  style="display:none">< /div>
and then i want to be able to roll over a < tr id="$id" > and then remove comes up only for that id and when you roll off it the remove will be hidden I cant get the jquery code right for it to work
Can some one help me please

A: First off, give the div a class:
<div id="remove_$id" class="mydiv">
  ...
</div>

with:
div.mydiv { display: none; }

and
$(function() {
  var id = this.id;
  $("tr").hover(function() {
    $("#remove_" + id).show();
  }, function() {
    $("#remove_" + id).hide();
  });
});


text:
Q: Android passar Token de autenticação no header usando Volley Estou tendo dificuldades para enviar token de autenticação no header utilizando volley
Este é o meu código
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Log.i("onActivityCreated: ", "token: ====> " + deliverymanEntitie.getTokenEntitie().getToken());

    RequestQueue queue = Volley.newRequestQueue(getContext());
    String url = RunfoxService.URL_GET_ALL_ORDERS_TO(deliverymanEntitie.getId());
    StringRequest stringRequest = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.i("onResponse: ", response);
        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            try {
                String json = new String(error.networkResponse.data, "UTF-8");
                Log.e("onErrorResponse: ", json);
                Log.e("onErrorResponse: ", error.networkResponse.headers.toString());

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-type", "application/application/json; charset=UTF-8");
            headers.put("Accept", "application/json; charset=UTF-8");
            headers.put("api_token", deliverymanEntitie.getTokenEntitie().getToken());

            Log.i("getHeaders: ", headers.toString());

            return headers;
        }
    };

    queue.add(stringRequest);

}

No código acima temos toda a requisição realizada, aqui estão meus logs
log de erro da minha api
E/onErrorResponse:: {"message":"Token de acesso n\u00e3o informado"}

Testando com o Postman a mesma requisição e infirmando também no header o token eu consigo ter o resultado do json corretamente.
Aparentemente não estou conseguindo informar o token no headers, alguém sabe me dizer onde estou errando?

A: Resolvi meu problema simplementes removendo o "_" do api_token ficando assim:
headers.put("apitoken", deliverymanEntitie.getTokenEntitie().getToken());

dessa forma consegui passar e receber na minha API, não sei afundo sobre o motivo mas funcionou pra mim.


text:
Q: Get Facebook API Profile Picture ios Swift I am using interested in obtaining the following info from a user's fb profile :

*

*email

*name

*profile picture link

*age

To do so I use the following code:
let accessToken = FBSDKAccessToken.currentAccessToken()
    let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"picture.redirect(false),email,name,gender,age_range,birthday"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
    req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
        if(error == nil)
        {
            print("result \(result)")
        }
        else
        {
            print("error \(error)")
        }
    })    }

This returns:
result {
"age_range" =     {
    min = 21;
};
email = "dedewdd@gmail.com";
gender = male;
id = xxxxxxxxxxxx;
name = "John Smith";
picture =     {
    data =         {
        "is_silhouette" = 0;
        url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/dwqdwddqwdwqdw";
    };
};
}

The problem with this is that this image is 50X50 pixels, I would like to obtain a link to a larger image.

A: So I use Kingfisher to download the image but essentially the NSURL is the key to getting a larger image. IF this doesnt work, then try changing the "50x50" in the url to "250x250" and see if that works
if FBSDKAccessToken.currentAccessToken() != nil {

let userID = FBSDKAccessToken.currentAccessToken().userID

if(userID != nil) //should be != nil
{
print(userID)
}

let URL = NSURL(string: "http://graph.facebook.com/\(userID)/picture?type=large")!

profileImage.kf_setImageWithURL(URL)

}else{

}
}

A: Try this:
@IBAction func FacebookLogin(sender: AnyObject) {

    var message = String()
    if Reachability.isConnectedToNetwork() == true {

        let loginView : FBSDKLoginManager = FBSDKLoginManager()
        loginView.loginBehavior = FBSDKLoginBehavior.Web

        if (FBSDKAccessToken .currentAccessToken() != nil) {
            loginView.logOut()
        }else{

            loginView.logInWithReadPermissions(["email","public_profile"], fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) in

                if (error != nil){
                    print("Login Process Eroor!"+error.localizedDescription)
                }else if result.isCancelled{
                    print("User cancled Login")
                }else{
                    print("Login Success")
                    if result.grantedPermissions .contains("email"){
                        self.fetchUserInfo()
                    }else{
                         message = message.stringByAppendingString("Facebook email permission error")
                        WebService.ShowToastMessage(message, viewcontroller: self)
                    }
                }
            })
        }

    } else {
        message = message.stringByAppendingString("Make sure your device is connected to the internet.")
        WebService.ShowToastMessage(message, viewcontroller: self)
    }
}
func fetchUserInfo() -> Void {

    if (FBSDKAccessToken .currentAccessToken() != nil) {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,gender,birthday,email,name,picture.width(480).height(480)"])
        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

            if ((error) != nil)
            {
                print("Error: \(error.localizedDescription)")
            }
            else
            {
                print("fetched user: \(result)")
                let id : NSString = result.valueForKey("id") as! String
                let name:NSString = result.valueForKey("name") as! String
                let gender:NSString = result.valueForKey("gender") as! String
                let email:NSString = result.valueForKey("email") as! String
                print("User ID is: \(id)")
                print("User email is:\(email)")
                print("User name is :\(name)")
                print("User gender is :\(gender)")

            }
        })
    }
}

A: According to the facebook docs
https://developers.facebook.com/docs/graph-api/reference/user/picture/
You can pass width and height of image,following are the list of params..
So you can try something like ..
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{ @"fields" : @"id,name,picture.width(100).height(100)"}]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

}]

A: Use this code for getting user id, name and profilepicture with one request : https://stackoverflow.com/a/45462114/1168602
Tested on xcode 8.3.3


text:
Q: Is "Were you in time?" the right question? For example,

Hey, you went a few minutes ago, but haven't given me a call yet. Were you in time for your job?

Is this the right question to ask?

A: Was that the right question to ask? It depends.

Were you in time for work?

Might imply: Did you get to work before your boss saw you were missing? Or whether you got to your work place sufficiently in time to do your tasks.

Were you on time for work?

To be "on time" means not to arrive late. If my job starts at 8.30 a.m. and I get to my office desk at 8.29 a.m. I am on time.
If I arrive at my desk precisely at 8.30 a.m. then I would say

I arrived on the dot

A: 'Were you in time'?, or 'Were you on time'? are both normal familiar idioms. There is a tiny difference in the circumstances in which they are used, but they are virtually interchangeable.
In the example you need to say 'on time for work'. We tend to speak of 'work, rather than one's 'job', when it come to being 'on time' or 'late'.
'Being 'in time', is more appropriately used where the thing for which one is speaking could happen loosely at roughly a particular time. For example, 'Where you in time to see John before he left?'
Trains and buses arrive 'on time' or 'late'. You need to be 'on time' to catch one, but if you are unaware of the time it leaves, provided you arrive 'in time' you will be alright.
You will always be understood if you use the wrong one, but it is the sort of misuse that merely highlights when a person is not a native speaker.
Americans may have different thoughts to me on this matter.

A: I think you mean to say "were you on time?". I don't know of anyone to phrase it "were you in time".


text:
Q: How to create optional parameters using object array I am creating a method which MUST be use with or without parameters.
I am using object array so that I can hold string, integer, binary types, etc at the same time.
Method:
SQLDB_UsingReader(string strSQL_WithParam, params object[,] obj)
Error:
The array must be a single dimensional array.
P.S
This method SQLDB_UsingReader(string strSQL_WithParam, object[,] obj) is working, but when I add "params" as the solution I searched when creating optional parameter, the error occurs.
CODE
public void SQLDB_UsingReader(string strSQL_WithParam, params object[,] obj)
    {
        try
        {
            using (SqlCommand mCmd = new SqlCommand(strSQL_WithParam, mConn))
            {
                for (int i = 0; i < obj.Length / 2; i++)
                {
                    if (obj[i, 1] == null || obj[i, 1].ToString() == "" || obj[i, 1].ToString().Length == 0)
                    { mCmd.Parameters.Add(new SqlParameter(obj[i, 0].ToString(), DBNull.Value)); }
                    else
                    { mCmd.Parameters.Add(new SqlParameter(obj[i, 0].ToString(), obj[i, 1])); }
                }
                mConn.Open();
                mDataReader = mCmd.ExecuteReader();
                mConn.Close();
            }
        }
        catch (Exception ex) { ex.ToString(); }
    }

A: Use Dictionary<string, object>. You have two values: a string and an object per parameter you wish to set. Either create a class that has one of each and use params for an array of that class or simply use the built in type for a collection of named values.
public void SQLDB_UsingReader(string strSQL_WithParam, IDictionary<string, object> obj)
{
    try
    {
        string where = obj.Any() ? ("where " + string.Join("AND", obj
                                   .Select(x => x.Key +"==@" + x.Key)) : "";
        using (SqlCommand mCmd = new SqlCommand(strSQL_WithParam + where, mConn))
        {
            foreach pair in obj
            {
                ... (use pair.Value and pair.Key)
            }
            ...
        }
    }
    ...
}


text:
Q: Редактирование выборки Возможно ли редактирование данных выборки, полученных в DBGrid в результате SQL-запроса?
Если да, то какими средствами это можно организовать?
Запрос выполняю через IBQuery.
То есть, я выполняю запрос на вывод данных по какому-либо условию. Затем, результат запроса возвращает данные в связанную с IBQuery таблицу DBGrid. Но при этом я понимаю, что это всего лишь результат запроса, который нельзя редактировать. А мне бы хотелось добавить такой функционал, как редактирование выбранных по какому-либо условию данных.
A: DBGrid не получает никаких данных, и в нем вы ничего не отредактируете. DBGrid только отображает выборку. Все редактирование происходит только запросами.
A: Редактировать результат запроса можно в некоторых случаях. Какие запросы редактируются а какие нет, не уточняется, но всегда есть возможность использования TIBUpdateSQL.
Т.е. создаем TIBUpdateSQL, для TIBQuery указываем его в свойстве UpdateObject.
У IBUpdateSQL есть четыре свойства:

*

*
DeleteSQL. Запрос будет вида
 delete from MyTable
 where
   id = :OLD_id

:OLD_id - спец параметр, который будет автоматом передаваться при редактировании текущей записи. Т.е. заполнять его не нужно, ключевым является префикс OLD_.

*
InsertSQL. Запрос будет вида:
 insert into MyTable
 (field1, field2, field3)
 values (:field1, :field2, :field3)

:field1, :field2, :field3 - параметры, содержащие значения соответствующих полей. Также значения подставятся автоматом для полей с соответствующими именами.

*
ModifySQL. Запрос вида:
 update MyTable
 set field1 = :field1
 where id = :OLD_id

*
RefreshSQL. Тот же запрос, который используется в TIBQuery.
Заполнять или нет соответствующие запросы - зависит от логики программы. Если какой-то из запросов будет не заполнен, соответственно и добавление/удаление/редактирование будет не доступно.


text:
Q: office 365 chat service in Ubuntu In my organization, people use Microsoft Office 365 for mail service.
In Windows system they can setup a chat client with Office 365 and use the instant message service. I'm using Ubuntu and when I searched around the web could not find the option to use Office 365 chat in my machine.  How can I do that?
Error message:
No setup available for this computer
Read: Set up your Mac for Office 365
Return to Home


text:
Q: How to show nested child data in recyclerview I want to show the items node details in recyclerview, but i getting some error. I have tried many method, but i didn't get the uid of items in items node in databasereference. I am trying to get items uid in firebase database reference, but unable to do it.how to get items uid database reference object
mainactivity code

class MainActivity : AppCompatActivity() {

lateinit var recyclerView: RecyclerView

lateinit var layoutManager: RecyclerView.LayoutManager

lateinit var RecyclerAdapter: RecyclerAdapter
lateinit var databaseReference: DatabaseReference
var database: FirebaseDatabase? = null

lateinit var auth:FirebaseAuth

    var personlist = arrayListOf<Persons>()

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    recyclerView = findViewById(R.id.recyclerpersonview)

    database = FirebaseDatabase.getInstance()
    auth = FirebaseAuth.getInstance()

 databaseReference=database?.reference!!.child("Users")
.child(auth.currentUser!!.uid).child("items")

    databaseReference.addValueEventListener(object
:ValueEventListener{

        override fun onDataChange(snapshot: DataSnapshot) {
            try {

                for (items in snapshot.children) {
                    val item1 = items.getValue(Persons::class.java)
                    personlist.add(item1!!)
                }

            }catch (e:Exception){

Toast.makeText(this@MainActivity,e.message,Toast.LENGTH_SHORT).show()
            }

        }
        override fun onCancelled(error: DatabaseError) {
            Toast.makeText(this@MainActivity,"unable to load
    data",Toast.LENGTH_SHORT).show()
        }

    })

    layoutManager = LinearLayoutManager(this)

    RecyclerAdapter = RecyclerAdapter(this, personlist)

    RecyclerAdapter.notifyDataSetChanged()

    recyclerView.adapter = RecyclerAdapter

    recyclerView.layoutManager = layoutManager

   }

  recycleradapter code

 class RecyclerAdapter(var context: MainActivity, var personlist:
  ArrayList<Persons>) :
 RecyclerView.Adapter<RecyclerAdapter.Personviewholder>() {
 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
 Personviewholder {
    val view =
 LayoutInflater.from(parent.context).inflate(R.layout.singlerow,
parent,
  false)

    return Personviewholder(view)
}

override fun getItemCount(): Int {
    return personlist.size
}

override fun onBindViewHolder(holder: Personviewholder, position:
Int) {
    val view = personlist[position]
    holder.personname.text = view.personname
    holder.persondesc.text = view.persondesc

Picasso.with(context).load(view.personimage).into(holder.personimg)

    holder.layoutlist.setOnClickListener {
        val intent = Intent(context, Additem::class.java)
        context.startActivity(intent)

    }

}

inner class Personviewholder(view: View) :
RecyclerView.ViewHolder(view)
 {
    var personname: TextView = view.findViewById(R.id.tvname)
    var persondesc: TextView = view.findViewById(R.id.tvpersondesc)
    var personimg: ImageView = view.findViewById(R.id.imgperson)
    var layoutlist: LinearLayout =
 view.findViewById(R.id.linearlayoutlist)
 }
 }

data class
data class Persons( var personname:String,
                var persondesc:String,
                var personimage:String)

debug information
06/21 22:05:29: Launching 'app' on Pixel 3 API 30.
$ adb shell am start -n
"com.a.recyclerview/com.a.recyclerview.LoginActivity" -a
android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.a.recyclerview |
com.a.recyclerview.test
Waiting for application to come online: com.a.recyclerview |
com.a.recyclerview.test
Connecting to com.a.recyclerview
Capturing and displaying logcat messages from application. This
behavior can be disabled in the "Logcat output" section of the
"Debugger" settings page.
I/System.out: Debugger has connected
waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8602', transport:
'socket'
I/chatty: uid=10155(com.a.recyclerview) identical 6 lines
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1337)
D/NetworkSecurityConfig: No Network Security Config specified, using
 platform default
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default

I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app
[DEFAULT]
I/FirebaseAuth: [FirebaseAuth:] Preparing to create service
connection to fallback implementation
D/FirebaseAuth: Notifying id token listeners about user (
rwy6MpJLxYWyIAQbj2xFR0sRaRw2 ).
I/FirebaseInitProvider: FirebaseApp initialization successful
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
I/DynamiteModule: Considering local module
com.google.android.gms.measurement.dynamite:51 and remote module
com.google.android.gms.measurement.dynamite:51
Selected remote version of
com.google.android.gms.measurement.dynamite, version >= 51
V/DynamiteModule: Dynamite loader version >= 2, using
loadModule2NoCrashUtils
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/.a.recyclervie: Accessing hidden method Landroid/view/View;-
>
computeFitSystemWindows(Landroid/graphics/Rt;Landroid/graphics
/Rect;)Z
(greylist, reflection, allowed)
Accessing hidden method Landroid/view/ViewGroup;-

makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
V/FA: onActivityCreated
W/.a.recyclervie: Verification of android.content.pm.ApplicationInfo
cn.a(java.lang.String, int) took 170.667ms (64.45 bytecodes/s) (984B
approximate peak alloc)
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id:
com.a.recyclerview, 1:14819963865:android:0fbd8c80422b89f216dfc8
I/FA: App measurement initialized, version: 42020
To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.a.recyclerview
D/FA: Debug-level message logging enabled
V/FA: onActivityCreated
V/FA: Connecting to remote service
D/HostConnection: HostConnection::get() New Host Connection
established 0xf580da60, tid 7482
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1
ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3
ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1
ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1
ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan
ANDROID_EMU_deferred_vulkan_commands
ANDROID_EMU_vulkan_null_optional_strings
ANDROID_EMU_vulkan_create_resources_with_requirements
ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer
ANDROID_EMU_vulkan_ignored_handles
ANDROID_EMU_vulkan_free_memory_sync
ANDROID_EMU_vulkan_shader_float16_int8
ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data
GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object
GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing
ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0
W/OpenGLRenderer: Failed to choose config with
EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf580cb80: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xf580cb80: ver 3 0 (tinfo
0xc53c7b90) (first time)
V/FA: Connection attempt already in progress
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection
established 0xf580dc20, tid 7482
D/goldfish-address-space: allocate: Ask for block of size 0x100
allocate: ioctl allocate returned offset 0x3fbc4d000 size 0x2000
V/FA: Connection attempt already in progress
V/FA: Activity resumed, time: 3149571
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1
ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3
ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem
ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2
ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands
ANDROID_EMU_vulkan_null_optional_strings
ANDROID_EMU_vulkan_create_resources_with_requirements
ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer
ANDROID_EMU_vulkan_ignored_handles
ANDROID_EMU_vulkan_free_memory_sync
ANDROID_EMU_vulkan_shader_float16_int8
ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data
GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object
GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing
ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0
I/FA: Tag Manager is not found and thus will not be used
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
I/OpenGLRenderer: Davey! duration=757ms; Flags=1,
IntendedVsync=3149655912401, Vsync=3149722579065,
OldestInputEvent=9223372036854775807, NewestInputEvent=0,
HandleInputStart=3149736734700, AnimationStart=3149737212900,
PerformTraversalsStart=3149737532500, DrawStart=3150142325100,
SyncQueued=3150160621300, SyncStart=3150229754900,
IssueDrawCommandsStart=3150230091100, SwapBuffers=3150464728600,
FrameCompleted=3150482529700, DequeueBufferDuration=422700,
QueueBufferDuration=1357200, GpuCompleted=72904454231491230,
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 5
I/.a.recyclervie: WaitForGcToComplete blocked RunEmptyCheckpoint on
ProfileSaver for 5.416ms
D/CompatibilityChangeReporter: Compat change id reported: 147798919;
UID
10155; state: ENABLED
V/FA: Inactivity, disconnecting from the service

![](https://i.stack.imgur.com/WR6Pd.png)

A: You're getting child("items") twice, so end up trying to read /Users/$uid/items/items, where no data exists.
To fix this, only specify child("items") once:
databaseReference =
database?.reference!!.child("Users").child(auth.currentUser!!.uid).child("items")

databaseReference.addValueEventListener(object :ValueEventListener{
  ...


text:
Q: MSI: installer for installers I need to create installer using MSI whose aim would be to invoke correct installer based on region (read from env. variables) of the user. That is, this installer is supposed to have 3 files(which are installers itself) one for US, one for Europe and one for Asia.
Now the point is that this Main installer never gets installed, but what it does is that it invokes the correct installer (Asia, Europe or US), so its installer that eventually gets installed.
Is it possible to do this. Any work arounds would be more than welcome.

A: It's called a custom EXE bootstrapper. It's a simple EXE application which determines the machine environment and launches the appropriate installer. Optionally you can pack all your installers into it and extract them at runtime.
You can write the EXE yourself or try to find an existing solution.


text:
Q: How to use Case Condition in Sequelize? how to convert case statement SQL query to Sequelize. I tried but it's not working for me
Imported my models here
const Proj = require('/models/Project');

Proj.findOne({
  attributes:[
    'Proj',
    [Sequelize.literal(`CASE Type WHEN 'Project_Name' THEN Project_Name : ${req.body.Project_Name}`),
    'Project'
  ],
  ...
]);

Now error:

    "error ReferenceError: models is not defined"

A: Import model as follows:
const Proj = sequelize.import(__dirname + '/models/Project');

Hope this help.


text:
Q: How does GRUB 2 work under multiple Linux partitions with UEFI When we install a new Linux, the installer will install a bootloader (efi file) at EFI partition and update the menu entry at NVRAM, and most likely set the newly added bootloader as default. The bootloader will read the /boot/grub/grub.cfg to load the kernel and initrd.
My question is, when there are multiple bootloaders (.efi) reside in ESP, are they identical? Since they are all GRUB2. Can each of them discover all the kernels in the system?
Since each OS's partition has /boot/grub/grub.cfg file, which one is being read by the default bootloader?

A:
My question is, when there are multiple bootloaders (.efi) reside in ESP, are they identical? since they are all grub2. Can all of them discover all the kernel in the system?

If there are multiple UEFI Linux installations on a disk, they normally use the same EFI System Partition (ESP), but their respective EFI executables live in different subdirectories of the ESP, of the form EFI/bootloader-id. The EFI executables have the same name; for 64 bit installations it is grubx64.efi. So the EFI variables would be located at EFI/bootloader-id/grubx64.efi
These executables are installed by grub-install running on their respective systems, though you might have to point grub-install to that partition using --efi-directory. And you may also have to choose the
value of bootloader-id with --bootloader-id. Different Linux distributions have different defaults for bootloader-id. For example, Debian defaults to debian. For more information about grub-install options, see man grub-install.
grub-install hard-wires the name of the boot/root devices into those executables using UUIDs.
These EFI executables are executed by the EFI firmware on the motherboard. Since the EFI executable knows the boot/root devices for its Linux installation, and since, by definition, grub.cfg has a fixed location relative to the  boot/root devices, the EFI executable can execute the /boot/grub/grub.cfg corresponding to that installation.  And grub.cfg of course has all the information needed to do a boot, including the names of the kernels installed on the system.
The Arch Wiki GRUB page has good coverage of these matters.
See also the Debian Wiki UEFI page.


text:
Q: Hollow cylinder with ball inside rolls down frictionless inclined plane I have an question about rotational motion of the following system
There is a hollow symmetric cylinder on a friction-less inclined plane (mass M, moment of inertia I, radius R, incline angle a). We place a small metallic sphere (mass m) inside the cylinder in an equilibrium state, but it can move inside without friction.

The cylinder is kept in place by external force and the small sphere is in equilibrium and not moving. The external force is removed at t=0.
Will the cylinder rotate while going down the plane?
It so, how to calculate the rotational acceleration?
(I assume that a symmetric cylinder without a sphere inside will not rotate)

A: In order to have a rotation, you have to have some force on it that doesn't act through the center of mass.
Gravity is considered to act entirely on the center of mass and never creates a torque.
The ramp can only supply a normal force at the point of contact (since it is frictionless).  This force must act through the center of mass and can impart no rotation.
Likewise the sphere inside can only supply a normal force at the point of contact, and this too must act on a line through the center of mass.  So there are no forces that can apply a rotation.

A: The normal force from the plane acting on the cylinder is thorough its center of mass, therefore not contributing to rotation. Same can be said for the metallic sphere. So nothing will rotate.


text:
Q: Capture YUV frames from OpenCV capture device I need to extract YUV frames directly from a web camera using OpenCV from C++ on the Windows platform. In other words: a setup in OpenCV that makes the capture device's read() method return a YUV Mat. I'm looking for a working example or documentation on how to do this.
The specific YUV subformat isn't that important for starters. The camera can produce YUV output. I cannot simply convert a BGR Mat to YUV - I need to capture it from the device without any conversions.
So far I've tried and combined

*

*connecting using several specific APIs (CV_CAP_DSHOW, CV_CAP_FFMPEG, CV_CAP_GSTREAMER, etc.)

*changing between different FOURCCs (MJPG, UYVY, etc.)

*toggling the CAP_PROP_CONVERT_RGB setting

*to find out what CAP_PROP_MODE might do

All to no avail as I'm still just getting output in BGR. So, any hints, links, three-liners?
(I'm using OpenCV 4.5.2)

A: You suppose to use the CAP_PROP_CONVERT_RGB.
From the docs:

Boolean flags indicating whether images should be converted to RGB.
GStreamer note: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output.

There a lot of issues with this flag. In this post the author added a fix for FFMPEG:
void cv_VideoCapture_setConvertToRGB(
        cv::VideoCapture& cap,
        const bool convertFormat)
{
    cap.set(cv::CAP_PROP_CONVERT_RGB, convertFormat);
#if CV_VERSION_MAJOR >= 4
    const cv::VideoCaptureAPIs backend =
            static_cast<cv::VideoCaptureAPIs>(qRound(cap.get(cv::CAP_PROP_BACKEND)));
    switch (backend) {
    case cv::CAP_MSMF:
        // Note in case something needs to change here:
        // MSMF backend uses fourcc codes for format and uses
        //  CAP_PROP_FORMAT and CAP_PROP_FOURCC interchangeably
        break;
    case cv::CAP_FFMPEG:
        // See cap_ffmpeg_impl.hpp
        cap.set(cv::CAP_PROP_FORMAT, convertFormat ? 0 : -1);
        break;
    default:
        break;
    }
#endif // CV_VERSION_MAJOR >= 4
}

A: Seems that OpenCV under windows is made with Direct Show which cannot grab YUV variants directly. So the solution is not to use OpenCV but Windows Media Foundation. OpenCV under other OS'es may be able to grab YUV.


text:
Q: "After {I have learned/learning} English for three months..." - which is the better choice?
*

*After I have learned English for three months, I met an American on a street.

*After learning English for three months, I met an American on a street.
Which one is right in grammar, or more accurate?

A: I'm not sure, but it might be worth pointing out, that in English, we don't typically use "learned" as a synonym for "studied." So even after correcting your grammar, your meaning might be getting lost.
Anyway, I think what you might be trying to say is this: "After I'd been studying English for three months, I met an American on the street."
When we use the verb "learn" in the past tense, we usually mean something we have mostly mastered. It is usually only while we are still in the process of learning that we use it as a synonym for studying.

A: In your sentence you would have to use "after learning", because you use the past tense for "met".

"After" + present perfect indicates a verb that will happen in the future:

After I have learned English, I will visit the UK.
After this pot of spaghetti has boiled for seven minutes, it must be drained.

"After" + gerund can go with any logical time. It doesn't insist on when the thing happened, happens, or will happen; all we know is that the next verb takes place after that.

Past
 After learning English, I met an American on the street.
Present
 After eating breakfast, I usually go for a run.
Future
 After buying a plot of land, I will build a cottage.

In fact, it works like a noun phrase ("after my English course", "after breakfast", "after the purchase").
This also works with a present progressive perfect:

After having learned English, I met an American on the street.

For your sentence, you could also use "After" + simple past, or "After" + past perfect. This indicates a verb that happened in the past.

Simple past
After I learned English, I met an American on the street.
Past perfect
After I had learned English, I met an American on the street.

There are other threads dealing with the differences between these two tenses, but for now I'll just say that I find the second one a little more natural for this context.


text:
Q: Wordpress get_pages meta_key don't show page I'm using get_pages in a Wordpress theme to create the nav.
I have some pages I don't want to show in the nav.
On all pages I have a 'dont_show_in_nav' true/false custom field.
I can use meta_key to add pages that have 'dont_show_in_nav' selected
but I'd like to not show the pages that have 'dont_show_in_nav' selected.
I could create a 'show_in_nav' custom field and select all the pages to show but I have to many pages to do that.
I've tried 'meta_value' => false
    $pages_args = array(
      'sort_column' => 'menu_order',
      'parent' => 0,
      'post_type' => 'page',
      'post_status' => 'publish',
      'meta_key'  => 'dont_show_in_nav',
      'meta_value' => true
    );

A: I'm guessing that the issue is that meta_value has to be a string since WordPress only supports strings for post meta.  When you create your field, what are you actually saving?  Is it the word "true", is it a '0', a '1' etc?
Regardless, a much better method for generating nav menus in wordpress is to take advantage of the nav menu functions.  Take a look at wp_nav_menu(), that should work much more reliably than a meta key.

A: As of now Wordpress documentation for get_pages() says the function doesn't support querying with a meta_key:

NOTE: This function will currently not retrieve pages using the 'meta_key' and 'meta_value' parameters in the $args array as described below. Until this is fixed in the WordPress codebase, you may want to use get_posts() instead.

So your code should call get_posts() instead:
$pages_args = array(
  'orderby' => 'menu_order',
  'parent' => 0,
  'post_type' => 'page',
  'post_status' => 'publish',
  'meta_key'  => 'dont_show_in_nav',
  'meta_value' => 'true'
);
$pages = get_posts($pages_args);

Note that I quoted 'true', since to Wordpress it's just a text field. Also, some arguments for get_posts are slightly different than for get_pages.


text:
Q: d.py number of bans in a guild So I tried using embed.add_field(name="Ban Count", value=f"{len(await ctx.guild.bans())} Bans",inline=False)
but I get this error object async_generator can't be used in 'await' expression   How do I display the amount of bans?

A: You must first convert the bans into a list, then get the length of the list:
bans_list = [entry async for entry in ctx.guild.bans()]
number_of_bans = len(bans_list)

# output number of bans, etc...


text:
Q: How do I fix this error log I get when launching eclipse? A few days ago I set up my Eclipse to use JavaFX for the first time. Eclipse has been set up on my computer for several months and worked on my computer with no issues. Today I tried to launch Eclipse and was unable to. The first exception in the log file is below. Full log file at: https://pastebin.com/NKLgdfhG
Any ideas?
!ENTRY org.eclipse.jdt.ui 4 0 2018-09-11 19:48:16.228
!MESSAGE Error retrieving proposal text.
Display string:
No Proposals
Pattern:
out.println("
!STACK 0
java.lang.StringIndexOutOfBoundsException: String index out of range: 13
    at java.lang.String.substring(Unknown Source)
    at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.getPatternMatchRule(AbstractJavaCompletionProposal.java:919)
    at org.eclipse.jdt.internal.ui.text.java.AbstractJavaCompletionProposal.getStyledDisplayString(AbstractJavaCompletionProposal.java:1256)
    at org.eclipse.jface.text.contentassist.CompletionProposalPopup.handleSetData(CompletionProposalPopup.java:861)
    at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$8(CompletionProposalPopup.java:844)
    at org.eclipse.jface.text.contentassist.CompletionProposalPopup$3.handleEvent(CompletionProposalPopup.java:597)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4428)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1103)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1088)
    at org.eclipse.swt.widgets.Table.checkData(Table.java:1189)
    at org.eclipse.swt.widgets.Table.wmNotifyChild(Table.java:6981)
    at org.eclipse.swt.widgets.Control.wmNotify(Control.java:5869)
    at org.eclipse.swt.widgets.Composite.wmNotify(Composite.java:2025)
    at org.eclipse.swt.widgets.Control.WM_NOTIFY(Control.java:5423)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4899)
    at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:359)
    at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1657)
    at org.eclipse.swt.widgets.Shell.windowProc(Shell.java:2199)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:5191)
    at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method)
    at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java:2454)
    at org.eclipse.swt.widgets.Table.callWindowProc(Table.java:587)
    at org.eclipse.swt.widgets.Table.callWindowProc(Table.java:453)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4941)
    at org.eclipse.swt.widgets.Table.windowProc(Table.java:6118)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:5191)
    at org.eclipse.swt.internal.win32.OS.SendMessageW(Native Method)
    at org.eclipse.swt.internal.win32.OS.SendMessage(OS.java:3333)
    at org.eclipse.swt.widgets.Table.select(Table.java:3519)
    at org.eclipse.swt.widgets.Table.setSelection(Table.java:5256)
    at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposal(CompletionProposalPopup.java:1407)
    at org.eclipse.jface.text.contentassist.CompletionProposalPopup.setProposals(CompletionProposalPopup.java:1179)
    at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:366)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:37)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4213)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3820)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1150)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1039)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:153)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:680)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:594)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:151)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:653)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:590)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1499)

A: The mentioned log entry happened in September 2018. The last entries are inserted at the end of the log, not at the beginning.
Probably the upgrade from Java 8 to 11, which was done between April 8 and 13, 2019 on your system, is causing the problem (Java 11 does not contain JavaFX anymore):
!SESSION 2019-04-08 20:31:32.915 -----------------------------------------------
eclipse.buildId=4.7.1.M20171009-0410
java.version=1.8.0_161

[...]
!SESSION 2019-04-13 00:34:34.112 -----------------------------------------------
eclipse.buildId=4.7.1.M20171009-0410
java.version=11.0.2

Running Eclipse with Java 8 should solve your issue. If you want to run Eclipse with Java 11, you have to upgrade Eclipse first (you are four releases behind).


text:
Q: ASP.NET MVC 3 Web API - Securing with token I'm trying to find the simplest way of implementing token based authentication for a number of ASP.NET MVC actions.
The Api controllers sit alongside a web app, so I need to be able to specify which actions/controllers are subject to Api authentication.
I already have a membership provider that is used for forms authentication so I'd like to reuse this to validate the user and build the returned token.
I've read several articles on implementing OAuth, but most seem really complex.  I've seen several examples of using an API key, but I want to request a token and then pass it back as a parameter not necessarily as a value in the HTTP header.
Essentially process needs to be:

*

*User requests token from auth action passing in username and
password.

*Service returns enc token

*User passes enc token to future calls as a parameter to auth

What's the typical way this is done, does the client (say ajax call) need to compute a hash of the user name/pass in 1)? or plain text ok over TLS/SSL?
Any advice appreciated.

A: What are you concerned about with what you described?
The process you described seems viable.  Typically systems will have an expiration on how long the token will be valid for, after which they need to get a new token.  There are many variations for expiration though (fixed time, sliding time, etc..).
To your question regarding the username / password, the client shouldn't hash them.  Just make sure they are transmitted via a secure method (SSL).


text:
Q: Migrate from Simple Fields to Advanced Custom Fields I'm trying to migrate my WordPress site from the Simple Fields plugin to the Advanced Custom Fields plugin.
I've created all the ACF components now I just need to populate them with the data from the SF database.
The table that stores the data is wp_postmeta and the columns are meta_id, post_id, meta_key, and meta_value.
meta_id is the unique ID for each row so this column doesn't really help me much, so post_id is the column that matters.
I need to move data from meta_value where meta_key equals _simple_fields_fieldGroupID_3_fieldID_7_numInSet_0to meta_value where meta_key equals hero_description, hero_description is empty, and the post_id is identical.
I'm going to have to repeat this process for all the SF meta_key that have a corresponding ACF meta_key.
I know very very little mySQL so I don't know where to start.
Could anyone help me with the logic?

A: A friend gave me this query that works like a charm. Here it is for anyone else he needs to migrate from Simple Fields to Advanced Custom Fields
SET @key_from = " _simple_fields_fieldGroupID_3_fieldID_0_numInSet_0";
SET @key_to = "hero_title";

UPDATE wp_postmeta a,
(
   SELECT
   meta_id,post_id,meta_key,meta_value
   FROM wp_postmeta
   WHERE meta_key = @key_from
   AND meta_value <> ''
)
b SET a.meta_value = b.meta_value
WHERE a.meta_key = @key_to
and a.meta_value = ''
and a.post_id = b.post_id

Basically all you have to do is find out what SF meta_key corresponds to what ACF meta_key and set @key_from and @key_to accordingly.


text:
Q: How to solve SIGSEGV error for very large array inputs? So, I was solving a problem in HackerEarth which tests your code to very large testcases.  Thus, when I tried to submit the code ,  it passed for first 6 testcases, for 5 others , it gave "Time Limit Exceeded" and for all others, SIGSEGV Signal .
Here's the code:
#include<bits/stdc++.h>
#include<cmath>
using namespace std;

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long unsigned int tc,b, a , d,c;
cin>>tc;
for(int i=0;i<tc;++i)
{
    cin>>a;
    cin>>d;
    cin>>c;
    cin>>b;
    long long unsigned int arr[b+1];
    arr[0]=a;
    arr[1]=d;
    arr[2]=c;

    if(b>=3){

        for(long long unsigned i=3;i<=b;++i)
        {
            // arr[i]%=1000000007;
            (arr[i])=(arr[i-1]+3*arr[i-3]+2*i)%1000000007;
            arr[i]%=1000000007;
        }
        printf("%llu \n",arr[b]%1000000007);

    }
    else{
        printf("%llu \n",arr[b]%1000000007);
    }
}
return 0;
}

Please help. Thank you.

A: You are trying to access memory that is not accessible to you. That's the reason for SIGSEGV. You need to declare the array size statically and not dynamically.
However, it is better to use vector, since you are using C++.


text:
Q: Godot export Android: Android resource linking failed, AAPT: error: unexpected element  found in  I'm trying to export Godot project to Android apk, but I face this error:
* What went wrong:
Execution failed for task ':processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\MyUsername\.gradle\caches\transforms-2\files-2.1\cc8b432f7a68a976550fb6c3054f84d5\play-services-ads-lite-20.5.0\AndroidManifest.xml:28:5-44:15: AAPT: error: unexpected element <queries> found in <manifest>.

I have tried to find it on internet but I found no solutions.
Does anyone have faced this issue before, pls help me out

A: I had the same issue and after some research and debugging I finally found the solution. I solved the issue by upgrading build.gradle version.
Previous setting in build.gradle file of project was:
classpath 'com.android.tools.build:gradle:3.5.1'

Current setting:
classpath 'com.android.tools.build:gradle:4.1.0'

A: Try and clean the project and clear the cache, then lastly invalidate the cache


text:
Q: Can I use Google Places API without a personal Website? Ok, so, maybe I just do not understand the Google Places API, or maybe I have been failing miserably with following tutorials, but either way, I could definitely use some help.
I am making an android application where a screen zooms into where they are located and uses google places to search for a hard-coded String place.
(IE, you live in Los Angeles, California; the closest McDonald's to you is located here *). And then it would display the spot on the map.
When I follow every single tutorial I have found to get an API key for Google places, (IE: https://www.youtube.com/watch?v=8PVK1Ue5rvk) it says I need to enter a web address to obtain one (See pictures below)

-----(Gap inbetween photos)-------------------------------------------------

--
But I do not have a website or URL to put here as I am just writing this for my android device.
Do I need to get a website host URL in order to use this?
Is there a generalized URL we are supposed to use that I have not heard of?
Am I doing this entirely the wrong way?
I also copied and pasted code from here: http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
And I am able to run it, but the error I am receiving in the logcat is Places Status : REQUEST_DENIED
Which makes me think I need to change part of the code with a key of my own.
I do indeed already have a Google Maps API key which I am using here in the application.
Thanks in advance for your time and help all!
-Sil
EDIT: See additional picture:

A: See the [Android key] button next to the [Browser key] button you highlighted.
Click on that [Android key] button.
;)

A: Well, it turns out that my phrasing was just poorly worded :(
I rephrased what I was looking for here: How do I get a Google Places API key for my Android App
And the answer I received was:
Please Follow below steps
Visit the Google APIs Console at https://code.google.com/apis/console and log in with your Google account.
A default project called API Project is created for you when you first log in to the APIs Console. You can use the project, or create a new one by clicking the API Project button at the top of the window and selecting Create. Maps API for Business customers must use the API project created for them as part of their Places for Business purchase.
Click the Services link in the left-hand navigation panel.
Click the status switch (the on/off button) next to the Places API entry. The switch slides to ON.
Click API Access in the left-hand navigation panel.
Click Create new Server key. Enter one or more server IP addresses if you wish to restrict the servers that can send API requests.
Click Create. Your API key appears under the heading Key for server apps (with IP locking).

This solved the issue I was having entirely.
Thank you for taking the time to help Stephan, I appreciate it as you got me going in the right direction


text:
Q: Working with aws_lambda_permission and aws_apigatewayv2_api I'm trying to work with aws_apigatewayv2_api and aws_lambda_permission resources, but the examples I've found online show something like this (I omitted the resources which are not important for this specific issue):
resource "aws_apigatewayv2_api" "users_api" {
  name          = "API"
  description   = "Users API"
  protocol_type = "HTTP"
}

resource "aws_apigatewayv2_stage" "api_stage" {
  api_id      = aws_apigatewayv2_api.users_api.id
  name        = "$default"
  auto_deploy = true
}

resource "aws_apigatewayv2_integration" "get_user_integration" {
  api_id           = aws_apigatewayv2_api.users_api.id
  integration_type = "AWS_PROXY"

  connection_type    = "INTERNET"
  description        = "Get User"
  integration_method = "POST"
  integration_uri    = aws_lambda_function.get_user_lambda.invoke_arn

  payload_format_version = "2.0"
}

resource "aws_apigatewayv2_route" "get_user_route" {
  api_id    = aws_apigatewayv2_api.users_api.id
  route_key = "GET /users"
  target    = "integrations/${aws_apigatewayv2_integration.get_user_integration.id}"
}

resource "aws_lambda_permission" "api_permission" {
  statement_id  = "allow_apigw_invoke"
  function_name = aws_lambda_function.get_user_lambda.function_name
  action        = "lambda:InvokeFunction"
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_apigatewayv2_stage.api_stage.execution_arn}/${aws_apigatewayv2_route.api_route.route_key}"

The problem seems to come from source_arn, because after creating the resources, I'm getting the following error on the API Gateway trigger:
the API with ID *id* doesn't include a route with path /users.
I've managed to work around this by doing the following:
resource "aws_lambda_permission" "api_permission" {
  statement_id  = "allow_apigw_invoke"
  function_name = aws_lambda_function.get_user_lambda.function_name
  action        = "lambda:InvokeFunction"
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_apigatewayv2_api.users_api.execution_arn}/*/*/${split("/", aws_apigatewayv2_route.get_user_route.route_key)[1]}"
}

But this just seems a bit counterintuitive and...wrong?
Am I missing something, is there a more straightforward way to accomplish this?


text:
Q: Slide block element OUT when hovering I have a image with a info box layered over it, with the css posted below.
The normal thing would be to have this appear when hovering over the image, however, I want the opposite. I want the box to slide out/down about -50px when hovering the image. Anybody got a tip for this?
.imgTitleInfoTop {
    -moz-box-sizing: border-box;
    bottom: 0;
    font-size: 24px;
    font-weight: 500;
    height: 60px;
    line-height: 22px;
    width: 370px;
}

A: As I understood, you want the .imgTitleInfoTop element to hide when you hover an image, so the code should look like this then:
<script type="text/javascript">
 $('.yourImage').hover(function() {
  $(.imgTitleInfoTop).animate({
   height: 0
  }, 300);
 }, function() {
  $(.imgTitleInfoTop).animate({
   height: '60px'
  }, 300);
 });
</script>

(300 is the time in miliseconds, how much this action takes, so you can make it faster or slower)

A: Are you looking for something like this (using Jquery)?
<script type="text/javascript">
 $('.imgTitleInfoTop').hover(function() {
  $(this).animate({
   height: 0
  }, 300);
 }, function() {
  $(this).animate({
   height: '60px'
  }, 300);
 });
</script>


text:
Q: Accessing and modifying code in the APEX 19.1 buttons created through the wizard Beginner here.
How can I access and modify the code of the different buttons that are created when using APEX wizards (like the CREATE or SAVE button for instance.)
Can you help please with detailed instructions.

A: Have a look at button's properties. What it does, is described under "Behavior". For example, CREATE button will

*

*submit page

*perform SQL insert action

Furthermore, have a look at processes Apex created for you; you'll find Automatic Row Processing which is responsible for insert/update/delete.
If you want to create your own code that stands behind that button, create your own process. Its type might then be "PL/SQL Code" which calls a stored procedure, passes page items' values to it, whatever. Scroll down the process' properties to Server-side Condition which lets you specify button which should be pressed in order for that process to run - you'd choose the CREATE button here.
I guess that's it.


text:
Q: Python - How to construct for loop between multiple data frame? I have two df as shown below.
df1 = {'Aberdeen Tunnel':[22.2620666,114.1779123]
         , 'Lion Rock Tunnel':[22.35134,114.1753917]
         , 'Shing Mun Tunnels':[22.3773149,114.1513125]
         , 'Tseung Kwan O Tunnel':[22.3191321,114.2440963]
         , 'Tsing Sha Highway':[22.343242,114.141755]
         , 'Cross Harbour Tunnel':[22.2922422,114.1796539]
         , 'Eastern Harbour Crossing':[22.2951813,114.220724]
         , 'Western Harbour Crossing':[22.2973088,114.1508622]
            , 'Tate\'s Cairn Tunnel':[22.3588556,114.2079283]
            , 'Tai Lam Tunnel':[22.3917362,114.0598441]}
df1 = pd.DataFrame(data = df1, index = ['lat','lon'])
df1 = pd.DataFrame.transpose(df1)
print(df1)

df2 = {(22.250559,114.170959),(22.281769,114.180153),(22.336325,114.178978)}
df2 = pd.DataFrame(data = df2, index = ['lat','lon'])
df2 = pd.DataFrame.transpose(df2)
print(df2)

I want to construct a for loop so as to find out from df2, which "Tunnel" is the nearest to the respective coordinates.
I have tried the below to first calculate the respective distance, but it doesn't seem to produce the right output.
for i in df1:
  for j in df1:
    for h in df2:
      for k in df2:
        dist = math.hypot(i-h , j-k)
print (dist)

A: In case your two data frames are not tooo large, you can use a cross join:
DataFrame 1
dat1 = {'Aberdeen Tunnel':[22.2620666,114.1779123]
         , 'Lion Rock Tunnel':[22.35134,114.1753917]
         , 'Shing Mun Tunnels':[22.3773149,114.1513125]
         , 'Tseung Kwan O Tunnel':[22.3191321,114.2440963]
         , 'Tsing Sha Highway':[22.343242,114.141755]
         , 'Cross Harbour Tunnel':[22.2922422,114.1796539]
         , 'Eastern Harbour Crossing':[22.2951813,114.220724]
         , 'Western Harbour Crossing':[22.2973088,114.1508622]
            , 'Tate\'s Cairn Tunnel':[22.3588556,114.2079283]
            , 'Tai Lam Tunnel':[22.3917362,114.0598441]}

df1 = pd.DataFrame(data = dat1, index = ['lat','lon'])
df1 = pd.DataFrame.transpose(df1)
df1['coord'] = list(zip(df1.lat, df1.lon))
df1 = df1[["coord"]]
# use tunnel as a column
df1['tunnel'] = df1.index

DataFrame 2
df2 = pd.DataFrame(columns=["coord"], index=[])
dat2 = [(22.250559,114.170959),
        (22.281769,114.180153),
        (22.336325,114.178978)]
df2["coord"] = dat2
# there must be some sort of identification for each coordinate
df2["id"] = ["a", "b", "c"]
df2

Solution:
# Cross join between both data frames
df_merge = df1.merge(df2, how="cross")

# calculate the distance between each pair of coordinates
df_merge["distance"] = df_merge.apply(lambda row: distance.distance(row["coord_x"], row["coord_y"]), axis=1)

# find the minimum distance for each point
minimiums = df_merge.groupby("id").distance.transform("min")

# return the tunnel - id pair with the minimum distance for each id
df_merge.loc[minimiums == df_merge["distance"], ["id", "tunnel", "distance"]]
#       id  tunnel                  distance
# 0     a   Aberdeen Tunnel         1.4620087109472515 km
# 5     c   Lion Rock Tunnel        1.7032322759652727 km
# 16    b   Cross Harbour Tunnel    1.1608810339311775 km

Also found another solution using sort:
res = df_merge.sort_values(by="distance", ascending=True).groupby("id").first()
res.loc[:, ["tunnel", "distance"]]
#       tunnel                  distance
# id
# a     Aberdeen Tunnel         1.4620087109472515 km
# b     Cross Harbour Tunnel    1.1608810339311775 km
# c     Lion Rock Tunnel        1.7032322759652727 km


text:
Q: How to make NetBeans automatically move you inside curly braces? I downloaded NetBeans as a replacement for Eclipse, and I like it so far, but there's one thing I can't figure out.
In eclipse, when you are inside two curly braces and press enter, it will move you inside the body and add a tab. It doesn't do it in NetBeans, and I would like to know if there's a setting/plugin that does that. Example (The pipe symbol "|" is the location of the cursor, AKA the thing that shows you where you are typing):
Eclipse:
Before pressing enter:
public void example(){|}

After pressing enter:
public void example(){
    |
}

NetBeans:
Before pressing enter:
public void example(){|}

After pressing enter:
public void example(){
|}

A: try Editing Code Templates
1.Choose Tools > Options > Editor > Code Templates.
2.From the Language drop down list, select Java (or whichever language you want to create a code template for). The list of abbreviations and associated templates is displayed.
3.Use the New and Remove buttons to add or remove templates in the list. To edit an existing template, select the template and edit the code in the Expanded Text field below the list.
4.Choose the key which will be used to expand the templates. The default key is Tab.
To more about Code Assistance learn here:
https://netbeans.org/kb/73/java/editor-codereference.html


text:
Q: Do I need data separation in KNN? I am trying to use KNN with cancer data.
I have split my data into train and test sets.
Am I right or I should use LOOCV?

A: Using test set and a validation set are related to completely different tasks.
1. Testing your model
You should test your model to measure the performance of your model. For this task, you have to separate a set of data from the same data distribution and keep it separately. You cannot touch this dataset or do any parameter tuning with this dataset in the model training process.
2. Validating your model
This is a subtask of your training process. You can reduce overfitting problem or non-generalized problem of your model on the fly by validating it. Overfitting or High Variance is caused by a hypothesis function that fits the available data but does not generalize well to predict new dataHere you use a small fraction of data got from your training data set. Leave One Out Cross Validation is one method of doing that.
Final Note: Testing with test data set is done at the very end of the pipeline and validation is done during the training process. Never ever use test data for training purposes. Also, you have to use test data reserved from the same distribution you used for training purpose.
Training using LOOCV
You can divide your training dataset into K bins (simply K sets). Now leave the first set and use other K-1 sets to train your model. After training in that round use that first set to test your model. In the next iteration leave the second set and use other K-1 sets to train. Then validate your model with the second set. Repeat this method K times. As an example: divide your dataset into 10 bins. Inside a loop, in every iteration leave one bin and train on other bins, then validate with the left bin. Repeat this for 10 times.
Hope you get it


text:
Q: Rigorous way to find the limit of this difference? This is a question from an old released exam.

By the triangle inequality, $s-r<1$, so I eliminate answers D and E. Intuitively, since the lower angle between $1$ and $r$ is fixed at $110^\circ$, $s$ will always be a little longer than $r$, so I eliminate A and C to find B as the correct answer.
This is pretty informal, is there a more rigorous way one could prove the limit?

A: From the cosine law,
$$s^2=1+r^2-2r\cos\alpha,$$
where $\alpha=110^\circ$.
We can rewrite this as
$$s-r=\frac{1-2r \cos\alpha}{s+r}$$
and remember that $\cos\alpha \lt 0$.
As you say, $0 \lt s-r \lt 1$, so
$$\frac{1-2r \cos\alpha}{2r+1} \lt s-r \lt \frac{1-2r \cos\alpha}{2r}.$$
The left inequality is bounded away from $0$ and the right from $1$, so the answer is B.  In fact, we can say
$$\frac{1/r-2 \cos\alpha}{2+1/r} \lt s-r \lt \frac{1/r-2 \cos\alpha}{2}$$
so the limit is $-\cos\alpha=-\cos 110^\circ$.

A: A qualitative answer.
When $s$ and $r$ tend both to infinity, keeping the said elements fixed, the sides $s$ and $r$ tend to be parallel, so their difference is the projection of the third side on their common direction, given by
$$s-r\to|1\cdot\cos\alpha|$$

A: By the cosine law,
$c = \cos 110 = \frac{1+r^2-s^2}{2r}$,
or $2 r c = 1 + r^2 - s^2$.
Let $d = |c|$, so $d > 0$.
Since $s^2 = r^2 +2rd+1$,
$s = r\sqrt{1 + 2d/r + 1/r^2}
=r (1+d/r + O(1/r^2))
= r + d + O(1/r)$,
so $ s-r \to d = -\cos 110$.
A slightly modified look:
$s^2 = r^2+2rd+d^2 + 1-d^2
= (r+d)^2+1-d^2$,
so $s = \sqrt{(r+d)^2+1-d^2}
=(r+d)\sqrt{1 + (1-d^2)/(r+d)^2}
= (r+d)(1 + O(1/(r+d)^2))
= r+d + O(1/(r+d))
$.