text:
Q: Calculating the mean of elements in a list in Scala I'm trying to write a method that calculates the mean of the elements in a given List in Scala. Here's my code:
def meanElements(list: List[Float]): Float = {
  list match {
    case x :: tail => (x + meanElements(tail))/(list.length)
    case Nil => 0
  }
}

When I call meanElements(List(10,12,14))), the result I get is different than 12. Can someone help?

A: You can simply do it using inbuilt functions:
scala> def mean(list:List[Int]):Int =
     | if(list.isEmpty) 0 else list.sum/list.size
mean: (list: List[Int])Int

scala> mean(List(10,12,14))
res1: Int = 12

scala>

A: The formula is not correct, it should be:
case x :: tail => (x + meanElements(tail) * tail.length) / list.length

But this implementation is performing a lot of divisions and multiplications.
It would be better to split the computation of the mean to two steps,
calculating the sum first,
and then dividing by list.length.
That is, something more like this:
def meanElements(list: List[Float]): Float = sum(list) / list.length

Where sum is a helper function you have to implement.
If you don't want to expose its implementation,
then you can define it in the body of meanElements.
(Or as @ph88 pointed out,
it could be as simple as list.reduce(_ + _).)


text:
Q: 'struct user_regs_struct' has no member named 'rsi' in sys/user.h I am installing a python software named 'lorun' on centos8.

uname -a : Linux ecs-kc1-large-2-linux-20200801141048 4.18.0-147.5.1.el8_1.aarch64 #1 SMP Tue Feb 4 23:44:08 UTC 2020 aarch64 aarch64 aarch64 GNU/Linux

When I'm compiling a .h file named 'access.h',some error has occurred:
In file included from lorun/cext/access.c:19:
lorun/cext/access.c: In function 'checkAccess':
lorun/cext/access.h:30:33: error: 'struct user_regs_struct' has no member named 'orig_rax'
     #define REG_SYS_CALL(x) ((x)->orig_rax)
                                 ^~
lorun/cext/access.c:46:27: note: in expansion of macro 'REG_SYS_CALL'
     if (!runobj->inttable[REG_SYS_CALL(regs)])
                           ^~~~~~~~~~~~
lorun/cext/access.h:30:33: error: 'struct user_regs_struct' has no member named 'orig_rax'
     #define REG_SYS_CALL(x) ((x)->orig_rax)
                                 ^~
lorun/cext/access.c:49:13: note: in expansion of macro 'REG_SYS_CALL'
     switch (REG_SYS_CALL(regs)) {
             ^~~~~~~~~~~~
lorun/cext/access.c:50:14: error: 'SYS_open' undeclared (first use in this function); did you mean 'SYS_openat'?
         case SYS_open: {
              ^~~~~~~~
              SYS_openat
lorun/cext/access.c:50:14: note: each undeclared identifier is reported only once for each function it appears in
In file included from lorun/cext/access.c:19:
lorun/cext/access.h:31:30: error: 'struct user_regs_struct' has no member named 'rdi'
     #define REG_ARG_1(x) ((x)->rdi)
                              ^~
lorun/cext/access.c:56:21: note: in expansion of macro 'REG_ARG_1'
                     REG_ARG_1(regs) + i * sizeof(long), NULL);
                     ^~~~~~~~~
lorun/cext/access.c:59:31: warning: comparison of integer expressions of different signedness: 'int' and 'long unsigned int' [-Wsign-compare]
                 for (j = 0; j < sizeof(long); j++) {
                               ^
In file included from lorun/cext/access.c:19:
lorun/cext/access.h:32:30: error: 'struct user_regs_struct' has no member named 'rsi'
     #define REG_ARG_2(x) ((x)->rsi)
                              ^~
lorun/cext/access.c:68:21: note: in expansion of macro 'REG_ARG_2'
                     REG_ARG_2(regs))) {
                     ^~~~~~~~~
error: command 'gcc' failed with exit status 1

It says that there is no fields named rdi in struct user_regs_struct. I went to watch the /usr/include/sys/user.h,and it dose not has that field.
[user.h of centos8][1]
but i went to watch the same file in centos 7 ,it has all the fields of the user.
[user.h of centos7][2]
now i want to use the fields in centos7 ,but using centos8 .what should i do ?
[1]: https://i.stack.imgur.com/GgYNn.png
[2]: https://i.stack.imgur.com/3on2Y.png

A: Your uname suggests that you're running on AArch64, i.e. 64-bit ARM. rdi, rsi, orig_rax and the like are registers on 64-bit Intel processors, indicating that the code you're working with has Intel-specific code that hasn't been ported to ARM.
Unfortunately, unless you know how to port that code, you probably will not be able to get this to work. I would suggest filing a bug report with the project and seeing if the maintainers or developers will be willing to make the appropriate changes.
EDIT: given that this appears to be an Amazon AWS box, you also have the option of just starting over with an Intel (x86_64) machine, assuming that your other dependencies will work there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install yum on Fedora Core 6 I have searched in google but have found no result and have been unable to install it yet.
I want to install yum on fedora core 6 on my server to install ffmpeg and ffmpeg-php.
How can i install it without error ?
I have ssh connection so i have to use the command prompt

A: You do not absoluetly need yum to get or install packages.
You might be able to find needed packages (even yum if you wish) from the archived mirror servers.  You can find these under http://fedoraproject.org.
Have you thought of installing the latest Fedora release?

A: You say "without errors" so i take it you have tried a few things already, what have you tried? and where did it go wrong?
Have you tried this guide ?
http://www.mjmwired.net/resources/mjm-fedora-fc6.html#yum
Seems to be what you're looking for, but it's quite old though (Published: 11 October 2006 (updated: 31 May 2007))


text:
Q: Play sounds with a batch file I want to play a sound or music file with Batch files, but I don't want that Windows show the window from the music player.
So I want to play a sound in the background...
I hope you can help me :D

A: Here are few scripts.
mediarunner.bat  - it uses windows media player active x objects so you cannot used if there's no installed Windows Media Player (though it usually comes packed with the Windows).Accepts only one argument - the path to the file you want to play.
spplayer.bat - uses SP Voice objects but can play only .wav files.Again it accepts as only argument the path to the file you want to play.
soundplayer.bat - uses Internet Explorer objects and specific bgsound tag that can be used only in internet explorer.Can play .mp3,wav,.. files. It can accepts two arguments. The file you want to play and the sound volume (a number between -10000 to 0) :
 call soundplayer.bat "C:\Windows\Media\Windows Navigation Start.wav" 0


text:
Q: Django: Replacing piece of url with integer variable I am trying to replace a url call with a variable as follows:
href="{% url 'educators:pay_patient' 9 %}".replace(/9/, x)

And the value x is just a primary key of a model, i.e. x=1,2,3, etc..
My issue is that it seems that the number of digits of x and the number it is replacing has to match. For example, x=1 works with 9 but not 90.
if x=1,
href="{% url 'educators:pay_patient' 90 %}".replace(/90/, x)

yields a 404 error with
Request URL:    http://127.0.0.1:8000/educators/study/pay/90/

How do I make this scheme generalizable for any number of digits of x?

edit: As requested, my url pattern matching this view is:
path('educators/', include(([
    path('study/pay/<int:pk>/', educators.PayPatientView.as_view(), name='pay_patient')

A: You can use callback function of replace to assign value according to length of match.

let href="{% url 'educators:pay_patient' 9010325%}"

let op = href.replace(/\d+/, function(match){
  return new Array(match.length).fill(0).map((e,i)=>i+1).join('')
})

console.log(op)

This is just an example added based on input you provide, you can replace regex as per you need. or you can specify more details about you url pattern.

A: from django-url official doc link we can assign variable as  url args and for your case  this can be
urlpatterns = [

    path('/educators/study/pay/<int:pk>/', your_view, name=your_view_name),
    ...
]

and in views.py you can have extra pk variable as an argument.


text:
Q: Check if value exists in php multi-dimensional array before adding I have a separate set of functions that grabs a "Date" and a "Time" from my application and puts the date into as a key, and the time as a multi-dimensional value.
For example purposes:
$alldatetimes = array(
    'date1' => array('13:00','14:30','14:30','14:30','15:00'),
    'date2' => array('09:00','10:00','10:30','10:30','12:00')
    );

foreach ($alldatetimes as $date => $times) {
echo '
This Exports:
';
echo '
'.$date.'

';
    foreach ($times as $time) {

        echo $time.'
';
    }
}

This exports:
date1
13:00
14:30
14:30
14:30
15:00

date2
09:00
10:00
10:30
10:30
12:00

I'm trying to control if the time is put into the array so only one value each is in the array (I don't want 3 instances of 14:30 for that date).
Based on other posts here I tried to build something like this to identify if the value was there, but I can't figure out how to tie it all together:
function searchForId($id, $array) {
    foreach ($array as $date => $times) {
        foreach ($times as $time) {
            if ($time === $id) {
                return $time;
            }
        }
    }
    return null;
}

Any ideas?
Update:  Here is how the array is initially being created - this probably can be more efficient:
while ($schedule_q -> have_posts() ) : $schedule_q->the_post();
    $alldatetimes [get_the_date()][] = get_the_time();
endwhile;

A: You can add a array_unique() call over each sub-array before you loop over your results to ensure it's all unique:
foreach ($alldatetimes as &$row) {
    $row = array_unique($row);
}

Output:

This Exports:

date1

13:00

14:30

15:00

This Exports:

date2

09:00

10:00

10:30

12:00

A: You can write a recursive function
function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

A: It is not shown in your question, but how about modifying your function that builds the date/time array to use the times as keys instead of values? Using something like
$alldatetimes[$date][$time]++

in that function would give you an array with one value for each time that would be the number of occurrences of that date/time combination, like this:
$alldatetimes = array(
    'date1' => array('13:00' => 1,'14:30' => 3,'15:00' => 1),
    'date2' => array('09:00' => 1,'10:00' => 1,'10:30' => 2,'12:00' => 1)
    );

Then you could change your code that prints them out to use the key.
foreach ($times as $time => $count) {
    echo $time.'
';
}


text:
Q: Appending to file, sed unterminated address regex I'm trying to append to the end of a file, using the style from this answer but I get the error:

sed: -e expression #1, char 16: unterminated address regex

the command (I've also tried without the -i and same error):
sed -i -e '\$ahaha_value=26' example.txt

where I'm expecting $ to get the end of the file and a to append.
I've looked at these questions here, here, and here. The issues there seem to be regex based and I don't see the issue with my regex.

A: With single quotes you don't need to escape $ sign since it's not going to be evaluated by shell.
Either
 sed -e '$a...'

or
sed -e "\$a..."

A: You can use this sed:
sed -i '' '$a\
haha_value=26
' example.txt


text:
Q: Past due approval tasks to show rejected (how to) Hope someone can help me on this.
I have created an approval workflow in Sharepoint Designer wherein the results could be approved or rejected. What i want to do is when a task/approval is past due the outcome defaults to rejected. Hoping to get some guidance on how i can make this happen.

A: I am assuming that you are building this in Power Automate, so I'll tell you what I would do there. I would start and approval but not use the start and wait for approval card, just the start approval card. Then I would put a separate wait for approval card into a do until control with the condition set to "utcNow() greater that TaskDueDate." I haven't tested this yet, but it should cause the flow to wait for the approval as long as the current date isn't beyond the due date of the task in planner. Then you can configure it to do whatever you want after that if the approval does come or doesn't. You can just play with the run after setting on the step after the do-until to get it to do whatever you want. Hope this helps!


text:
Q: Non browser JS library I'm using Appcelerator Titanium but I want a good JS library to help with object and array manipulation.
A cut down version of dojo or jQuery with out references to window, navigator or the DOM would be good.
Many thanks.
Can anyone suggest one?

A: underscore.js has a lot of useful features not strictly related to the DOM.

A: Try underscore


text:
Q: How to partition and then group by different properties through Linq Suppose a class like this below
public class Student
{
    public string Name {get;set;}
    public string Topic {get;set;}
    public string Age {get;set;}
}

and a list like this
var students = new List<Student>();

with data:
Name           Topic       Age
S1             alpha       15
S2             beta        15
S3             gamma       17
S4             theta       16
S5             alpha       15
S6             alpha       17
S7             gamma       17
S8             theta       18
S9             alpha       19

..

I need to create a dataset like below out of the students list
Topic  15    16    17   18   19
alpha  2      0    1    0     1
beta   1      0    0    0     0
gamma  0      0    2    0     0
theta  0      1    0    1     0

what is the best way to go about solving this without having to create a strongly typed dataset with properties 15,16..
Is there a way I can partition my collection using linq to generate an anonymous datastructure like just above?
Also, was not sure on how to word the question, hence if you think title of the question is totally misleading, please suggest how can I improve the title

A:     Dictionary<string,IGrouping<int,Student>> partition = students.GroupBy(s=> s.Topic).
     ToDictionary(grp=> grp.Key, grp=> grp.GroupBy(g=> g.Age));

This will give you a dictionary of all Topics to a grouping by age a simple count on the grouping will give you the amount. This is off the cuff without intellisense so you might need to fix a bad naming or 2


text:
Q: Последовательное изменение фона при наведении на ссылку или div Привет, ребята!
Мне надо сделать реализацию изменения фона при наведении на див. Навел див окрасился в красный убрал он так красным и остается, еще раз навел он стал синим убрал синим остается ну и так далее.
Немного изменила методы поиска и нашла практически то, что мне надо но только цвета меняются рандомно. Может кто помочь, я только учусь, идея есть на сайте хочу сделать)
Надо что бы можно было цвета задавать в ручную, а не что бы они рандомно менялись
Вот что получается сейчас [Пример например]http://jsfiddle.net/marusia/cL17z15p/1
A: Добавь еще одну переменную и проверяй ее значение при наведении. Если равна 1, то ставим зеленый и присваиваем переменной значение 2. Если равна 2, то ставим красный и присваиваем переменной значение 3. И так далее, хоть 64000. Можно просто inc() использовать, кстати, вместо присваивания конкретных чисел.
Обновление
Оформите код на jsfiddle, если будет время - напишу пример. Вообще, тут разговор простой: Хочешь учиться - все двери открыты и информации море, учись. Хочешь сразу получить результат - заплати тому, кто учился вместо тебя. А новичкам с 1 вопросом и совсем без ответов даже помогать не хочется, вы, вероятно, просто хотите халявы.


text:
Q: Recode variable referring to multiple vectors / columns This is a question about writing logical conditions efficiently.
Let's say I want to recode a variable if any column in a set equals a particular value.
test <- tibble(
 CompanyA = rep(c(0:1),5),
 CompanyB = rep(c(0),10),
 CompanyC = c(1,1,1,1,0,0,1,1,1,1)
)
test

A basic way would be:
test$newvar <- ifelse(test$CompanyA==1 | test$CompanyB == 1 | test$CompanyC == 1,-99,0)

table(test$newvar)

But what if I have several dozen columns? I don't want to write out CompanyA, CompanyB, etc. Is there a way of essentially using an %in type statement? Here's an obviously wrong method:
condition <- columns %in% c("CompanyA", "CompanyB", "CompanyC") . # obviously doesn't work

test$newvar[condition] <- 1

Or is that an even simpler way to do this - e.g., if CompanyA:CompanyC == 1, then do...?

A: Overview
By reshaping test from long to wide, I was able to create a column that tests if any of the values in your CompanyX columns contain a value of 1.
Code
# load necessary packages ----
library(tidyverse)

# load necessary data ----
test <-
  tibble(CompanyA = rep(c(0:1),5),
         CompanyB = rep(c(0),10),
         CompanyC = c(1,1,1,1,0,0,1,1,1,1)) %>%
  # create an 'id' column
  mutate(id = 1:n())

# calculations -----
new.var <-
  test  %>%
  # transfrom data from long to wide
  gather(key = "company", value = "value", -id) %>%
  # for each 'id' value
  # test if any 'value' is equal to 1
  # if so, return -99; else return 0
  group_by(id) %>%
  summarize(new_var = if_else(any(value == 1), -99, 0))

# left join new.var onto test ---
test <-
  test %>%
  left_join(new.var, by = "id")

# view results ---
test
# A tibble: 10 x 5
#    CompanyA CompanyB CompanyC    id new_var
#       <int>    <dbl>    <dbl> <int>   <dbl>
#  1        0        0        1     1     -99
#  2        1        0        1     2     -99
#  3        0        0        1     3     -99
#  4        1        0        1     4     -99
#  5        0        0        0     5       0
#  6        1        0        0     6     -99
#  7        0        0        1     7     -99
#  8        1        0        1     8     -99
#  9        0        0        1     9     -99
# 10        1        0        1    10     -99

# end of script #


text:
Q: A monomorphism in the category of compact Hausdorff spaces is regular Let $f \colon X \rightarrow Y$ be a monomorphism of compact Hausdorff spaces. This is just a continuous injection. I am trying to show that $f$ is regular, i.e. it is an equaliser.
My first thought was to consider the constant map $f(X) \rightarrow [0,1]$ which maps everything to $0$. By Urysohn's Lemma, there exists a morphism $g \colon Y \rightarrow [0,1]$ which extends the other map. $f$ would be the coequaliser of $g$ and the constant zero map if we could write
$$
f(X) = \{ y \in Y \mid g(y) = 0\}
$$
But unfortunately I don't think we can guarantee that $g(y) \not=0$ for $y$ outside of $f(X)$.

A: First note that a monomorphism $f:X\to Y$ must be injective: If $f(x)=f(y)$, then the compositions of $f$ with the maps $(*\to X)$ sending the single point to $x$ and $y$, respectively, are equal, thus these maps are equal, hence $x=y$.
So let $f:X\to Y$ be a monomorphism in $\mathbf{CHaus}$. Since a map from a compact space to a Hausdorff is perfect (meaning that it's closed and all fibers are compact), all maps in $\mathbf{CHaus}$ are perfect maps. Now consider the quotient map $q:Y\to Y/f(X)$, collapsing the image of $f$ to a single point. This space is clearly compact, but it's also Hausdorff, as is every quotient of a Hausdorff regular space by a closed subset (alternatively you could use that perfect surjective maps preserve the Hausdorff property). Now if $c:Y\to Y/f(X)$ is the constant map to $\{f(X)\}$, then $q$ and $c$ agree precisely on $f(X)$. If $g:Z\to Y$ is any map such that $qg=cg$, then its image $g(Z)$ must be a subset of $f(X)$. Since $f$ is injective, $g$ factors uniquely as set maps $fh:Z\to X\to Y$. Finally, $h$ is continuous since $f$ is a (closed) embedding.

A: Your idea to use Urysohn's Lemma can be made to work, in the following way.
First note that $f(X)$ being the continuous image of a compact space is compact  and thus closed (because $Y$ is Hausdorff).  In fact $f(C)$ is closed in $Y$ for every closed subset $C$ of $X$ for the same reason, a fact that will come in useful later on.
Now, since every compact Hausdorff space is normal, we can find, using Urysohn's Lemma, for every $y\in Y\backslash f(X)$ a continuous map $g_y\colon Y\to [0,1]$ with $g_y(y)=1$ and $g_y(f(x))=0$ for all $x\in X$.
We combine these $g_y$'s into one continuous map $g\colon Y\to [0,1]^{Y\backslash f(X)}$ by setting $g(z)(y)=g_y(z)$. Note that $[0,1]^{Y\backslash f(X)}$ is a compact by Tychonoff's theorem.
Let $\nu  \colon Y\to [0,1]^{Y/f(X)}$ be the continuous map given by $\nu (z)(y)=0$.
We claim that $f\colon X \to Y$ is the equalizer of $\nu,g \colon Y\to [0,1]^{Y\backslash f(X)}$.
To begin, we have $\nu\circ f = g\circ f$, because $\nu(f(x))(y)=0=g_y(f(x))$ for all $x\in X$ and $y\in Y\backslash f(X)$.
Let $Z$ be a compact Hausdorff space, and let $h\colon Z\to Y$ be a continuous map with $\nu \circ h = g\circ h$. We must show that there is a unique continuous map $h'\colon Z\to X$ with $h=f\circ h'$. Since $f$ is injective (by Stefan's argument) the "uniqueness" part is clear; the question is whether such a map $h'$ exists.
Let $z\in Z$. We have $h(z)\in f(X)$, because if this would not be the case, then $h(z)\in Y\backslash f(X)$, and so $(g\circ h)(z)(h(z))=g_{h(z)}(h(z))=1\neq 0=(\nu\circ h)(z)(h(z))$, which contradicts $\nu\circ h = g\circ h$.
Thus (since $f$ is injective) there is a unique $x\in X$ with $f(x)=h(z)$. Hence we may define a map $h'\colon Z \to X$ by $f(h'(z))=h(z)$ for all $z\in Z$.
It remains to be shown that $h'\colon Z \to X$ is continuous. Let $C\subseteq X$ be closed subset. It suffices to show that ${h'}^{-1}(C)$ is closed.  Since $f$ is injective, we have $f^{-1}(f(C))=C$. Since $h$ is continuous, and $f(C)$ is closed (as we saw in the second paragraph), we see that
$${h'}^{-1}(C) \ =\  {h'}^{-1}(f^{-1}(f(C)))
\ = \ (f\circ h')^{-1}(f(C))\ = \ h^{-1}(f(C))
$$
is closed. Thus $h'$ is continuous. Hence $f$ is an equalizer.


text:
Q: CakePHP: Friendly urls using inflector and no id I have built a simple portfolio using CakePHP and it has urls like: domain.com/portfolio/82/This_is_an_item
What I want to do is remove the ID from the url. How would I do this?
Here is my controller code for the view:
function view ( $id, $slug )
{
    $post = $this->Portfolio->read(null, $id));

    $this->set(compact('post'));
}

and here is the link generator:
<?php echo $this->Html->link($post['Portfolio']['title'],
        array('admin' => false, 'controller' => 'portfolio', 'action' => 'view', $post['Portfolio']['id'], Inflector::slug($post['Portfolio']['title'])),
        array('title' => $post['Portfolio']['title'])); ?>

I'm guessing I need to change the controller method to do some sort of find on the title?
Any help would be much appreciated. Thanks

A: I would save the slug in the database, along with the title. That way you only have to create it once. Also you may or may not be able to get a unique link from slug to title, so it's best not to try.
For easy processing you can use the Sluggable behaviour, see https://gist.github.com/338096 (or just Google).
Update
If you use the sluggable behaviour from https://gist.github.com/338096 (save as sluggable.php in app/model/behaviors), you would only need to do a few steps:
In your Profile model class add var $actsAs = array('Sluggable'); or
var $actsAs = array(
    'Sluggable' => array(
        'fields' => 'title',
        'scope' => false,
        'conditions' => false,
        'slugfield' => 'slug',
        'separator' => '-',
        'overwrite' => false,
        'length' => 256,
        'lower' => true
    )
);

if you want to override settings
In the database, add a column slug in the profiles table.
When you save a profile, it will automagically add fill in the slug field, you do not need to take any special actions.

A: You can eliminate the id completely, but you'll have to make sure the slugs are unique (specify inUnique validation rule is a option). When saving the post, use Inflector::slug() on the 'title' field (you might want to save it to a 'slug' field, if you want to keep the title intact:
$this->data['Portfolio']['slug'] = Inflector::slug($this->data['Portfolio']['title'])

function view ($slug ){
   $post = $this->Portfolio->find('first', array('conditions'=>array('Portfolio.slug'=>$slug))));
   $this->set(compact('post'));
}

and for the link:

<?php echo $this->Html->link($post['Portfolio']['title'],
    array('admin' => false, 'controller' => 'portfolio', 'action' => 'view', $post['Portfolio']['slug']),
    array('title' => $post['Portfolio']['title']));


text:
Q: Can I use silverlight application in wpf application? I got a silverlight sample from http://gallery.expression.microsoft.com/ like the analog clock and the progress bar. I am making a wpf desktop application using microsoft blend 4. My problem is how to put/run/embed the sample in my wpf application using the blend 4.
I choose wpf application because I can add windows/form and the codes are almost the same with the windows application form.
and if silverlight is not possible to run in wpf application, can you suggest how to do layered controls? My plan is to run first the loading bar. and then hide it to show the main menu and the analog clock.

A: Silverlight is very-very-very compact version of WPF functionality.
You can just rewrite sample to WPF and it will run more efficient.

A: Silverlight is just like adobe flex which helps in making(running) web browser apps..
If you use silverlight in your wpf application , then you have to use webbrowser control..
For knowledge:
When we want to try to bring wpf for webbrowser apps we use silverlight..
& doing vice versa(like you are doing), don't make much sense..


text:
Q: How can I run `powershell` command on mcr.microsoft.com/powershell container My docker image is from mcr.microsoft.com/powershell:latest which has powershell installed. Why do I get this error when build docker image: /bin/sh: 1: Install-Module: not found
Below is my dockerfile:
FROM mcr.microsoft.com/powershell:latest
RUN Install-Module dbatools -Force

I can run the command Install-Module dbatools -Force when I manually launch a container from mcr.microsoft.com/powershell:latest. Why can't I run it from building the image? Does it have a different context? If it uses my localhost context, does it mean I need to install powershell on my Mac OS?
If I want to run a powershell script as ENTRYPOINT, how can I specify it?

A: you can use SHELL directive in Dockerfile:
escape=`
SHELL ["powershell","-command"]
RUN New-Item -ItemType Directory C:\Example

see more here


text:
Q: Can I use lock to ensure instruction order? As stated in this link https://golang.org/ref/mem, the code below uses an incorrect synchronization:
var a, b int

func f() {
    a = 1
    b = 2
}

func g() {
    print(b)
    print(a)
}

func main() {
    go f()
    g()
}

Because it's possible that it prints a = 0 and b = 2.
However, I wonder if this result is possible in the code below where a and b are protected with Lock:
var a, b int
var mu sync.Mutex

func f() {
    mu.Lock()
    a = 1
    b = 2
    mu.Unlock()
}

func g() {
    mu.Lock()
    print(b)
    print(a)
    mu.Unlock()
}

func main() {
    go f()
    g()
}

Because the link says:
For any sync.Mutex or sync.RWMutex variable l and n < m, call n of l.Unlock() happens before call m of l.Lock() returns.
However, it is not clear about whether the assignment of a and b is guaranteed to be executed before the Unlock statement

A: The code is safe in regard that it has no data race.
The behavior is not defined though. There is no synchronization regarding goroutine scheduling, so it may be that g() locks the mutex first, and once it releases, main() ends and your app may end with it, and f() might not complete (might not even start). The app may print nothing, may print 2, or may print 21.
It may also be that f() locks first, carriers out the assignments, and then g() in main() will print the assigned new values: 21.
If you want f() to assign first, you may use a sync.WaitGroup, e.g.:
var a, b int
var wg sync.WaitGroup

func f() {
    defer wg.Done()
    a = 1
    b = 2
}

func g() {
    print(b)
    print(a)
}

func main() {
    wg.Add(1)
    go f()
    wg.Wait()
    g()
}

This will always print 21, try it on the Go Playground.
And a convoluted example to prove it can be solved with sync.Mutex too. This is not its designed use, but this also works:
Lock mu in the main(), before launching the goroutine. Have g() also lock, which will obviously block at first. f() can unlock it once its job is done, giving "green light" to g():
var a, b int
var mu sync.Mutex

func f() {
    a = 1
    b = 2
    mu.Unlock()
}

func g() {
    mu.Lock()
    print(b)
    print(a)
    mu.Unlock()
}

func main() {
    mu.Lock()
    go f()
    g()
}

Try this one on the Go Playground.

A: It is guaranteed that once f executes mu.Unlock(), all goroutines reading a and b will see the updated values of a and b provided those goroutines also access a and b using the same lock. If there are goroutines that read a and b without lock then there is a race.


text:
Q: Pyparsing: How to parse SQL Hints I am trying to parse the EBNF below (commentated in the code) and I'm struggling to resolve the STRING part of the optional comments.. (written as extra comment in my test string)
 from pyparsing import *

# SQL HINT EBNF
'''
{ /*+ hint [ string ]
      [ hint [ string ] ]... */
| --+ hint [ string ]
      [ hint [ string ]...
}
'''

test_string = "/*+ALL_ROWS extra comment FIRST_ROWS CACHE*/"

LCOMMENT = Literal("/*+")
RCOMMENT = Literal("*/")

grammar = Forward()

hint_all_rows = Literal("ALL_ROWS")
hint_first_rows = Literal("FIRST_ROWS")
hint_cache = Literal("CACHE")

comment_in_hint = Word(printables)

all_hints = (hint_all_rows | hint_first_rows | hint_cache)+ ZeroOrMore(comment_in_hint)

grammar <<  all_hints  + ZeroOrMore(grammar)

all_grammar = LCOMMENT + grammar + RCOMMENT

p = all_grammar.parseString(test_string)

print p

A: This is the code that now runs thanks to Paul McGuire's help in the comments on the OP.  I did get rid of the forward function when initially setting the answer here. But checking the code by attaching result names to the different elements, I noticed that my first answer here was classifying all but the first hint as comments. So therefore I kept the Forward but utilised some other suggestions of Pauls.
from pyparsing import *

# SQL HINT EBNF
'''
{ /*+ hint [ string ]
      [ hint [ string ] ]... */
| --+ hint [ string ]
      [ hint [ string ]...
}
'''

LCOMMENT = Literal("/*+")
RCOMMENT = Literal("*/")

grammar = Forward()

hint_all_rows = Keyword("ALL_ROWS")
hint_first_rows = Keyword("FIRST_ROWS")
hint_cache = Keyword("CACHE")

comment_in_hint = Word(printables, excludeChars='*')

grammar = Forward()

all_hints = (hint_all_rows | hint_first_rows | hint_cache).setResultsName("Hints", listAllMatches=True) + Optional(comment_in_hint)("Comments*")

grammar << all_hints + ZeroOrMore(grammar)

all_grammar = LCOMMENT + grammar + RCOMMENT

p = all_grammar.parseString("/*+ ALL_ROWS aaaaaaa FIRST_ROWS bbbbb */")

print p["Hints"]

print p["Comments"]


text:
Q: SQL SERVER 2016 OFFSET Deseo realizar dos consultas la primera me debe traer los primeros 18 datos con top 18 sale. Pero la segunda me debe traer los 18 posteriores pero sql server no tiene la funcion limit y dice que la reemplaza offset pero el sql no la toma me sale "incorrect syntax near "offset""
Lo que hice fue crear un tabla temporal realizar la consulta y sacarla luego los datos con un select row_number. Pero me parece excesivo para una consulta , ademas debo llevarla al jasper y entre mas sencilla mejor.
Agradezco cualquier dato sobre una función que me ayude a sacar los siguiente "n" registro de una consulta obviando los primeros "m" de la misma.

A: Hola amigo posiblemente sea una versión menor a 2012 en ese caso no existe el OFFSET en ese caso te puedes apoyar del ROW_NUMBER y de unas variables para seleccionar lo que deseas te muestro como y si gustas lo puedes volver un sp y así trabajarlo saludos.
--Creamos la tabla de prueba llamada Customers
DECLARE @Customers TABLE (
    FirstName VARCHAR(50),
    LastName  VARCHAR(50),
    PhoneNumber VARCHAR(10),
    EmailAddress VARCHAR(50),
    CreationDate DATETIME
)
--Llenamos MIL de datos
;WITH L0 AS (SELECT 1 c FROM(SELECT 1 UNION ALL SELECT 1)c(D)),
      L1 AS (SELECT 1 C FROM L0 CROSS JOIN L0 AS B),
      L2 AS (SELECT 1 C FROM L1 CROSS JOIN L1 AS B),
      L3 AS (SELECT 1 C FROM L2 CROSS JOIN L2 AS B),
      L4 AS (SELECT 1 C FROM L3 CROSS JOIN L3 AS B),
      L5 AS (SELECT 1 C FROM L4 CROSS JOIN L4 AS B),
      L6 AS (SELECT 1 C FROM L5 CROSS JOIN L5 AS B) --SUFICIENTE PARA UN MILLON

INSERT INTO @Customers (FirstName, LastName, PhoneNumber, EmailAddress, CreationDate)
SELECT TOP 1000 REPLACE(NEWID(),'-',''), REPLACE(NEWID(),'-',''),
    CAST( CAST(ROUND(RAND(CHECKSUM(NEWID()))*1000000000+4000000000,0) AS BIGINT) AS VARCHAR(10)),
    REPLACE(NEWID(),'-','') + '@gmail.com',
    DATEADD(HOUR,CAST(RAND(CHECKSUM(NEWID())) * 19999 as INT) + 1 ,'2006-01-01')
FROM L6

DECLARE
@InitialRow INT=0--Donde iniciara puede ser 10,20,30 etc
,@RowsRetrieve INT=10--cuantos quieres 10,20 30 es decir si mandamos

--@InitialRow=0 y @RowsRetrieve =10 nos devolvera del 1 al 10 si mandamos
--@InitialRow=10 y @RowsRetrieve =10 nos devolvera del 11 al 20 asi sucesivamente.

--Asigamos que sigue
DECLARE @lFirstRec INT,
@lLastRec INT,
@lTotalRows INT
SET @lFirstRec = ( @InitialRow)
SET @lLastRec = ( @InitialRow + @RowsRetrieve + 1 )
SET @lTotalRows = @lFirstRec - @lLastRec + 1

--prueba empezando del 1 al 10
;WITH CTE AS (
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ROWNUM,* FROM @Customers)
SELECT * FROM CTE
WHERE ROWNUM > @LFIRSTREC AND ROWNUM < @LLASTREC

Aqui un ejemplo aqui puedes jugar con los parametros para que veas como funciona.
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=8c11361399692901fe9678362bd00134


text:
Q: How to use external JS with parameters in component in Angular 2 Let's say you have an external js that has some parameters that you generate, like datetime/etc, and the result looks like this 'http://example.com/example.aspx?lang=en&displaylanguage=true&time=9:00 AM'
None working example
ngOnInit() {
  let s = document.createElement("script");
  s.id = "exampleScript";
  s.type = "text/javascript";
  s.src = "http://example.com/example.aspx?lang=en&displaylanguage=true&time=9:00 AM";
  document.getElementById("some-id").appendChild(s);
}

How do you use this on your component?


text:
Q: Closing questions on mobile theme also shows me flag counts When I'm using the Stack Exchange mobile view (specifically on my iPhone), after voting to close a question I am also shown the flag count. If I refresh the page afterwards, the flag count disappears and I don't think there is (or should be) any way that a non-moderator should see this.
Take for example this question. This is what I see before my close vote:

Additionally, the close vote dialog doesn't make it immediately obvious like the desktop version how the close votes are distributed, but this is a lesser issue:

After the close dialog is gone, I get the "x votes remaining" message, and I am also shown the flag count, which I don't think I should be able to see.

A: This was an error in shared JavaScript between main and mobile once the flag link was separate on mobile (it wasn't originally), it'll be fixed in the next build.

A: As slhck already said, that is not the number of flags: It's the number of closing votes that, instead of being reported to the right of "close" is shown to the right of "flag." This doesn't mean there is just a closing vote, and three flags for that question. Three is the number of closing votes for that question: the one that there was before you voted to close, yours, and the vote from another user who voted while you were voting. That is the reason the dialog box says, "This question still needs 2 vote(s) from other users to close."
If you refresh the page, the number of closing votes should be shown correctly.


text:
Q: Running C++ with VStudio Code using CodeRunner extension I am unable to run my .cpp files from VStudio Code using the Code Runner extension.
When I replace #include "test.h" with #include "test.cpp" in main it works fine but replacing it back gives me the following error;

[Running] cd "c:\Users\dree\Desktop\TestRun\" && g++ main.cpp -o main
  && "c:\Users\dres\Desktop\TestRun\"main
  c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe:
  C:\Users\dree\AppData\Local\Temp\ccm2RSvw.o:main.cpp:(.text+0x15):
  undefined reference to `MyClass::foo()' collect2.exe: error: ld
  returned 1 exit status
[Done] exited with code=1 in 1.1 seconds

Main.cpp
#include "test.h"
#include <iostream>

int main()
{
    MyClass a;
    a.foo();
    return 0;
}

test.cpp
#include "test.h"
#include <iostream>

void MyClass::foo()
{
    std::cout << "Hello World" << std:: endl;
}

test.h
class MyClass
{
public:
    void foo();
    int bar;
};

settings.json
{
    "workbench.colorTheme": "Visual Studio Dark",
    "workbench.iconTheme": "material-icon-theme",
    "python.linting.flake8Enabled": false,
    "terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\cmd.exe",
    "editor.minimap.enabled": false,
    "liveServer.settings.donotShowInfoMsg": true,
    "python.pythonPath": "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_86\\python.exe",
    "python.linting.pylintEnabled": true,
    "python.linting.enabled": true,
    "explorer.confirmDelete": false

}

Is there a way to change the Code Runner extension to call the g++ command with all of the .cpp files in the directory of the file being ran?
For example:
It is running the following command;
cd "c:\Users\drees\Desktop\TestRun\" && g++ main.cpp -o main && "c:\Users\drees\Desktop\TestRun\"main

Can I somehow change it to this?
cd "c:\Users\drees\Desktop\TestRun\" && g++ *.cpp -o main && "c:\Users\drees\Desktop\TestRun\"main

A: Solved by changing a setting for Code Runner extension;
Added this into my settings.json file;
"code-runner.executorMap": {
        "cpp": "cd $dir && g++ *.cpp -o $fileNameWithoutExt && $fileNameWithoutExt.exe"
    }

A: This is how I set my code-runner for C++
code-runner.executorMap": {
    "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && ./$fileNameWithoutExt && rm ./$fileNameWithoutExt",
}

This command tells code-runner to

*

*Change to directory where my present source code is

*Compile code

*Execute binary file

*Removed binary file

A: As pointed out by drescherjm, the problem is in the arguments passed to the compiler: the output shows that the command that was used is g++ main.cpp -o main. There's no reference to test.cpp!
You probably think that telling g++ to compile main.cpp is enough, because it includes test.h and obviously the definition of whatever is in test.h can be found in test.cpp. Unfortunately, it is obvious to you but not to the compiler. The fact that files with the same name but different extension (like test.cpp and test.h) are related is very convenient for us programmers, but the compiler doesn't know it. All it knows is that test.h declares a class called MyClass, but it has no clue that its definition is inside test.cpp. To solve it, you must call g++ like this:
g++ main.cpp test.cpp -o main

That is, you must explicitly list all the source files that must be used to build main.
That's why replacing #include "test.h" with #include "test.cpp" works: because this way you are telling the compiler to take the content of test.cpp and paste it at the top of main.cpp, so that the definition of MyClass is available. But this is a code smell: if you are including a .cpp file, you can be pretty sure you are doing something wrong. The compiler doesn't care about the extension, .h or .cpp is the same to it, that's why it works. But you should avoid it.

A: Just wanted to post the thing that helped me. I tried dree's answer, but kept getting errors
Edit the code-runner executor map settings, but use this:
"cpp": "cd $dir && g++ -o $fileNameWithoutExt *.cpp && $dir$fileNameWithoutExt",


text:
Q: Year Quarter PHP / Javascript pattern I need pattern for a quarter of a year, for example 1/2015 -> first quarter of the 2015. 4/2015 -> fourth quarter of the year. I need to validate given value for being a quarter. How I can achieve that in javascript or php ? I guess that in PHP preg_match function is good way to go but I have difficulties with creating correct pattern...

A: It depends on the range of years that you'd like to support.
Assuming anything between quarter 1/1000 and 4/2999 should be accepted then the regular expression you want to use is
/^[1234]\/[12]\d{3}$/

For example this JavaScript function will test for valid quarters
function is_quarter(text) {
  return text.match(/^[1234]\/[12]\d{3}$/) != null;
}

A: Mm. Not 100% sure I understand, but how about this?
function is_quarter($string) {
    $parts = explode('/', $string);

    if(count($parts) == 2) {
        $quarter = (int) $parts[0];

        return $quarter >= 1 && $quarter <= 4;
    }

    return false;
}

function isQuarter(string) {
    var parts = string.split('/');

    if(parts.length == 2) {
        var quarter = parseInt(parts[0]);

        return quarter >= 1 && quarter <= 4;
    }

    return false;
}

A: Try this:

function Check(){
  var v = document.getElementById("Quarter").value;
  alert(/^[1-4]\/\d{4}$/.test(v));
}
<input type="text" id="Quarter" />
<input type="button" value="Check" onclick="Check();" />


text:
Q: Error reading time stamp in a timer task I am reading time stamp data from a file, and these time stamps I woule like to use them later in a Timer scheduler to fire some events based on the time stamps. the time stamp format is some thing like this 0.012999999999 and they are of type string and i used Long.parseLong to convert it to long. I tried the below code but at run time i receive the below errors, it seems to me it is about the formating of the time stamp but i do not know how to handle it.
code:
    static TimerTask timedTask = new TimerTask() {

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
};

Timer timer = new Timer();
    timer.schedule(timedTask, Long.parseLong(logfile.getFileHash().get(1).getTimeStamp()));

errors:
Exception in thread "file processing" java.lang.NumberFormatException: For input string:
"0.012999999999"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.example.File_IO_00.File_IO.processFile(File_IO.java:77)
at com.example.File_IO_00.File_IO.access$1(File_IO.java:69)
at com.example.File_IO_00.File_IO$1.run(File_IO.java:20)
at java.lang.Thread.run(Unknown Source)

A: Long is an integer type, i.e. 0.012999999999 is not a valid value. you should use Float.parseFloat() or Double.parseDouble() instead.


text:
Q: How to pass domain as a context in odoo I have a domain like this ["&",["customer","=",True],["type","=","contact"]] and
have context also like this {"lang":"en_US","tz":"Europe/Brussels","uid":2,"allowed_company_ids":[1],"params":{"action":157,"cids":1,"menu_id":112,"model":"crm.lead","view_type":"kanban"},"default_type":"opportunity","search_default_assigned_to_me":1}
Now, What I want to do is when I edit the domain and if it contains '&' then our context will be the previous one with the new domain(means that context will look like {"lang":"en_US","tz":"Europe/Brussels","uid":2,"allowed_company_ids":[1],"params":{"action":157,"cids":1,"menu_id":112,"model":"crm.lead","view_type":"kanban"},"default_type":"opportunity","search_default_assigned_to_me":1}, "default_customer": True, "default_type":"contact") but if it contains '|' then our context will be previous one (means that now the context will look like {"lang":"en_US","tz":"Europe/Brussels","uid":2,"allowed_company_ids":[1],"params":{"action":157,"cids":1,"menu_id":112,"model":"crm.lead","view_type":"kanban"},"default_type":"opportunity","search_default_assigned_to_me":1}).
Can anyone suggest how to do this...


text:
Q: pigeonhole principle For 1-1 and onto function $|A|=|B|=n\in N$
Prove/Disprove that if $f:A \rightarrow B$ is 1-1 then $f:A \rightarrow B$ is onto.
The answer I saw used the Pigeonhole Principle, I am trying to prove it without the principle.
But I do not manage to prove that if cardinality is a finite number then all 1-1 functions must be onto too.
I mean that in the infinite case when two sets are equinumerous a bijection is exist, but in the finite case all 1-1 functions are bijection

A: Suppose $\exists$ an element $b \in B$ which is not mapped to an element in $A$. We know that $f$ is one-to-one. That is $f$ maps $n$ elements in $A$ to $n$ elements in $B$. Including $b$ the cardinality of $B$ is $(n + 1)$ leading to a contradiction.
And one more thing. Had to add this. If two sets have the same cardinality a bijection between them exists - by definition regardless of whether the range/domain is finite or not. But you've been given the function and are asked to prove that it is a bijection. You cannot use that fact in this particular question.

A: We have to prove that an injective $f: \>[n]\to[n]$ is automatically bijective.
This is obviously true for $n=1$. Therefore assume that it is true as stated for some $n\geq1$ and consider an injective $g:\>[n+1]\to[n+1]$.
(a) When $g(n+1)=n+1$ then the restriction $f:=g\restriction[n]$ is an injective map from $[n]$ to $[n]$, and so is bijective in virtue of the induction hypothesis. It follows that $g$ is bijective.
(b) When $g(n+1)=a\leq n$ denote by $T:\>[n+1]\to[n+1]$  the transposition $a\leftrightarrow n+1$. Then $h:=T\circ g:\>[n+1]\to[n+1]$ is an injective map with $h(n+1)=n+1$ and so is bijective according to (a). As $T$ is clearly bijective it follows that $g=T\circ h$ is bijective.


text:
Q: Passing a function argument with dots I'm trying to write a function to compute sample sizes in R.
The function uses a couple of smaller functions.  I'd like to pass arguments into the smaller functions using the dots.  Here is my function so far:
log_reg_var<-function(p){
  if(p<=0|p>=1) stop('p must be between 0 and 1')
  var<-1/(p*(1-p))
  return(var)
}

samplesize<-function(method_name, beta, sigma_x, mult_cor, power= 0.8,fpr = 0.05,...){

  if(method_name=='linear regression'){
    var_func <- lin_reg_var
  }
  else if(method_name=='logistic regression'){
    var_func <- log_reg_var
  }
  else if(method_name=='cox regression'){
    var_func <- cox_reg_var
  }
  else if(method_name=='poisson regression'){
    var_func <- pois_reg_var
  }
  else{
    stop('method_name not recognized. method_name accepts one of: "linear regression",
         "logistic regression","cox regression", or "poisson regression"')
  }

  top = (qnorm(1-fpr/2) + qnorm(power))^2
  bottom = (beta*sigma_x)^2*(1-mult_cor)

  n = (top/bottom)*var_func(...)

  return(ceiling(n))

}

I should be able to do
samplesize(method_name = 'logreg',1,1,0,p=0.5)
>>>32

But instead I am thrown the following error:
Error in var_func(...) : argument "p" is missing, with no default

Clearly there is something wrong with me passing p through the dots, but I'm not sure what is wrong.
What is my problem here?

A: You need to add the additional parameter p as an argument and you need to pass it into your log_reg_var() function. You also have to be careful with some other syntax:
log_reg_var<-function(p){
  if(p<=0|p>=1) stop('p must be between 0 and 1')
  var<-1/(p*(1-p))
  return(var)
}

# specify that you pass a parameter `p`
samplesize<-function(method_name, beta, sigma_x, mult_cor, power= 0.8,fpr = 0.05, p, ...){

# Initialize `var_func` to a NULL value
var_func = NULL

  if(method_name=='linear regression'){
    var_func <- lin_reg_var(p)
  }
  else if(method_name=='logistic regression'){
    # pass parameter `p` into log_reg_var since there is no default
    var_func <- log_reg_var(p)
  }
  else if(method_name=='cox regression'){
    var_func <- cox_reg_var(p)
  }
  else if(method_name=='poisson regression'){
    var_func <- pois_reg_var(p)
  }
  else{
    stop('method_name not recognized. method_name accepts one of: "linear regression",
     "logistic regression","cox regression", or "poisson regression"')
  }

  top = (qnorm(1-fpr/2) + qnorm(power))^2
  bottom = (beta*sigma_x)^2*(1-mult_cor)

  n = (top/bottom)*var_func

  return(ceiling(n))

}

> samplesize(method_name ='logistic regression', 1, 1, 0, p=0.5)
[1] 32


text:
Q: stop jquery onChange recursive iteration I have jstree plugin I simply fill this plugin by selected node and post data with ajax in node-select method. Althouh I make a control with "letChangeTrig"
it call himself onChamge method recursively due to I refrest tree.. but I want to call this when user select only..
$('#tree_2').jstree({
}).on('changed.jstree', function (e, datap) {
    debugger
    if(!letChangeTrig)
    {
        letChangeTrig = true;
        return;
    }

    $.ajax({
        url: "../../Controller/ActiveDirectoryController.php5",
        type: "POST",
        dataType: "json",
        data: params,
        success: function (result) {
            treeData_ = prepareObjectsforTree(result.Objects);
            resfreshJSTree(treeData_);
        },
        error: function (a, b, c) {

        }
    });
});

refresh:
function resfreshJSTree(treeDataa) {
    letChangeTrig = false;
    $('#tree_2').jstree(true).settings.core.data = treeDataa;
    $('#tree_2').jstree(true).refresh();

}

and this is my jstree refresh function which trigg the onChange method.. and post data.. after response back to success I call this again to rebuil tree with changed data but in this way it begins to call himself without users select evet and it fall into loop.. I need to stop it by logical control

A: Have you tried jQuery event.stopPropagation() method?
It stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.


text:
Q: Making a table with smaller tables from other sheets [I'm using Excel Pro 2013]
I have a sheet called '11', where I have a table in cells P41:S43
1     2      3     4
5     6      7     8
9     10     11    12
13    14     15    16

From sheet '12' I want to reproduce the same table (as in if I modify the table in '11', it gets updated in '12'). One way of doing this is manually, by using a formulas such as:
='11'!P41   ='11'!Q41   ='11'!R41
='11'!P42   ='11'!Q42   ='11'!R42
='11'!P43   ='11'!Q43   ='11'!R43

There are many other sheets (from 1:11) with each having a different table in the same cells (P41:S41). I want to have a sheet called 'All tables' where I have a big table with all individual tables put together. For tables 1:4 in 'All tables' sheet would look like this
1   ='1'!P41    ='1'!Q41    ='1'!R41    ='1'!S41
1   ='1'!P42    ='1'!Q42    ='1'!R42    ='1'!S42
1   ='1'!P43    ='1'!Q43    ='1'!R43    ='1'!S43
1   ='1'!P44    ='1'!Q44    ='1'!R44    ='1'!S44
2   ='2'!R38    ='2'!S38    ='2'!T38    ='2'!U38
2   ='2'!R39    ='2'!S39    ='2'!T39    ='2'!U39
2   ='2'!R40    ='2'!S40    ='2'!T40    ='2'!U40
2   ='2'!R41    ='2'!S41    ='2'!T41    ='2'!U41
3   ='3'!Q40    ='3'!R40    ='3'!S40    ='3'!T40
3   ='3'!Q41    ='3'!R41    ='3'!S41    ='3'!T41
3   ='3'!Q42    ='3'!R42    ='3'!S42    ='3'!T42
3   ='3'!Q43    ='3'!R43    ='3'!S43    ='3'!T43
4   ='4'!P38    ='4'!Q38    ='4'!R38    ='4'!S38
4   ='4'!P39    ='4'!Q39    ='4'!R39    ='4'!S39
4   ='4'!P40    ='4'!Q40    ='4'!R40    ='4'!S40
4   ='4'!P41    ='4'!Q41    ='4'!R41    ='4'!S41

Which in practice I achieved by writing always the first line of each group and then dragging the formulas down three rows e.g.,
    ='1'!P41    ='1'!Q41    ='1'!R41    ='1'!S41

When I would done with the 4 first rows, I would have to change the first row from referencing sheet '1' to sheet '2' and then dragging down three rows (for achieving rows 5-8).
Is there any way where I can achieve the same result (all tables from sheets in one super table) without so much manual work? My idea would be something like this:
=INDIRECT(CONCATENATE("'";A2;"'!P41"))
              =INDIRECT(CONCATENATE("'";A2;"'!Q41"))
                                =INDIRECT(CONCATENATE("'";A2;"'!R41")
                                                     =INDIRECT(CONCATENATE("'";A2;"'!S41")

(imagine those formulas in the same row)
with A2=1 (as you drag down the formula its value will be 1, 2, 3 or 4 depending on the table position. It represents the sheet name taken from the first row)
Problem is that when using this formula, dragging down won't change the reference from P41:S41 cells. Is there any way I can have a formula were dragging down the a row gets me P42:S42 from P41:S41 and so on?
Ignore the INDIRECT + CONCATENATE suggestion if there's an easier way to go about doing this.

A: If you have identical tables in different worksheets with same Data Range, the below written Formula can help to Merge Tables.
=IFERROR(INDEX(Comb1,ROWS(A$2:A2),COLUMN(A2)), IFERROR(INDEX(Comb2,ROWS(A$2:A2)-ROWS(Comb1),COLUMN(A2)), "-"))
Before use the Formula in New Sheet, copy the Header Row then place Cell Pointer in A2 Cell, write Formula & execute it then drag it right then down till it's needed.
NB: Comb1 & Comb2 are two Tables.
Hope this help you. I've posted the solution after been tested by me.


text:
Q: How to create array of ng- models I am developing website using angularJs. In app i need to create dynamic select boxes having same model name. code is given below
HTML Code

    {{results.domain}}
    {{results.status}}

        <select ng-model="price[$index]" class="form-control" name="price" ng-options="price.dp_id as price.title for price in results.price"> </select>

AngularJs Code
app.controller("Site", function($scope,$http) {
    $scope.selectedPerson = 0;
    $scope.urlName = "alankar12";
    $scope.domainExt = "";
    $scope.showresult=false;
    $scope.result = {};
    $scope.price=[];

    $scope.checkDomain = function() {
        $http({
            method: 'POST',
            url: 'http://localhost/domain/index.php?r=site/checkdomain',
            data:{urlName:$scope.urlName,domainExt:$scope.domainExt},
        }).success(function(data, status, headers, config) {
            $scope.domainExt=data;
            $scope.result=data.records;
            $scope.showresult=true;
            //$scope.price=data.price;
            console.log(data.price);
        }).error(function(data, status, headers, config) {

        });

    }; //end checkdomain Function

    $scope.addDomain = function() {

        console.log($scope.price);
    }
});

json response
{
    "response": "successful",
    "status": "200",
    "records": [{
        "domain": ".com",
        "status": "available",
        "price": [{
            "title": "1 year@600",
            "price": "600.00"
        }, {
            "title": "2 year @1150",
            "price": "1150.00"
        }]
    }, {
        "domain": ".co.in",
        "status": "available",
        "price": [{
            "title": "1 year@700",
            "price": "700.00"
        }, {
            "title": "2 year @1350",
            "price": "1350.00"
        }]
    }, {
        "domain": ".in",
        "status": "available",
        "price": [{
            "title": "1 year@660",
            "price": "660.00"
        }, {
            "title": "2 year @1350",
            "price": "1350.00"
        }]
    }, {
        "domain": ".org",
        "status": "available",
        "price": [{
            "title": "1 year@500",
            "price": "500.00"
        }]
    }, {
        "domain": ".au.in",
        "status": "available",
        "price": [{
            "title": "1 year 600",
            "price": "600.00"
        }]
    }, {
        "domain": ".au",
        "status": "available",
        "price": [{
            "title": "1 year@500",
            "price": "500.00"
        }]
    }]
}

Here every domain name has multiple prices, issue that i am facing , i am unable to get the value of price in model.
Please anyone help me to resolve issue

A: Problem is that you need to iterate over the records, not the prices.
Something like this might work:
<select ng-model="myPrice" class="form-control" name="price" ng-options="record.price.dp_id as record.price.title for record in results">
  <option value="">-- choose price --</option>
</select>

EDIT: on a closer look, I think you will need to do pre-processing on the results list before using it, so the above may not work.  Something like this would be better:
var allPrices = [];
results.each(function(result) {
  result.price.each(function(price) {
    // gather all prices here
  }
}
$scope.prices = allPrices;


text:
Q: Why is target event referring to parent element when the child element is the element that is being hovered Upon hovering of a child div, I am attempting to prevent event propagation such that the parent propagation will not be triggered however I am experiencing several issues where the parent onMouseEnter event is being triggered BEFORE the child despite the fact that the element being hovered is the child element.
The event target as identified by (($this)) is also printing the details of the outer
 instead of

Result

Code
$(document).ready(function() {
    $(function () {
        var outerElement = document.createElement("div");
        outerElement.id = "kingOuter";
        outerElement.textContent = "King Outer";
        var middleElement = document.createElement("div");
        middleElement.id = "kingMiddle";
        middleElement.textContent = "King Middle";
        outerElement.onmouseenter = function(e){
            console.log($(this));
            console.log("King outer mouse enter");
        }
        middleElement.onmouseenter = function(e){
            console.log("King middle mouse enter");
        }
        let ppp = document.getElementById('tttest');
        outerElement.appendChild(middleElement);
        ppp.appendChild(outerElement);
    });
})


text:
Q: Acumatica:Tabular Report generates unexpected lines when calling as sub report Using Acumatica report designer, I've designed a tabular report to fetch one field from SOShiplinesplit.The report's main parameters are RefNbr and ShipLineNbr. If run the tabular report individually, for 1 doc's 1 shipline,its result looks like below:
Tabular Report results when running individually
However, if I add this tabular as a subreport like below,
Add Tabular report as a subreport at ShiplineNbr group level
I met with confusing results if I run the master report to call tabular report
Run within master report
Could anyone give me a hand to get out of this trouble?


text:
Q: Returning an object in another class file Try this
Date.h
#ifndef DATE_H
#define DATE_H

#include<string>
using namespace std;

class Date{

  public:
    Date(int month, int day, int year);

    int getMonth() const;
    int getDay() const;
    int getYear() const;

  private:
    int month;
    int day;
    int year;
};

#endif

Date.cpp
#include "Date.h"
#include<string>
using namespace std;

Date::Date(int month, int day, int year) {
    this->month = month;
    this->day = day;
    this->year = year;
}

int Date::getMonth() const{
  return month;
}

int Date::getDay() const{
  return day;
}

int Date::getYear() const{
  return year;
}

Appointment.cpp
#include "Appointment.h"
#include "Date.h"
#include<sstream>
#include<string>
using namespace std;

Appointnment::Appointment(String description, int month, int day, int yr, int hr, int min)
{
    this->description = description;
    this->month = month;
    this->day = day;
    this->yr = yr;
    this->hr = hr;
    this->min = min;
}

void Appointinment::getDate()
{
    //cannot change calling object nor its date object member, just return it
}

}
I'm trying to implement the getDate() function, but I'm having trouble understanding how to return a Date given that this class is specified as an appointment. Are there any resources I can look at to tackle this specific problem?

A: You code looks good. But when return soemthing, you need either a pointer to Data, or a refernce to Date, or straight object.
Either of following will work:
Date Appointinment::getDate() const

const Date& Appointinment::getDate() const

const Date* Appointinment::getDate() const

Judge from context, maybe first one is what you want.

A: const Date& Appointinment::getDate()
{
     return Date(this->month, this->day, this->yr);
}

this is the most common way.


text:
Q: Why do inactive SSH sessions terminate with "Write Failed: Broken pipe"? I know that this is a common problem with a known solution. A quick web search turns up many results that point you toward the ServerAliveInterval (or less commonly the server-side ClientAliveInterval) configuration options. Setting one of these to some arbitrary value such as 15, 60, or 120 will solve the broken pipe issue.
My question is why? Why does this happen in the first place? Who is closing the socket?
I have my doubts about the OS killing the connection due to inactivity, given the fact that the TCPKeepAlive option is enabled by default, which causes TCP keepalive messages to be sent in order to detect clients dropping offline. So the OS won't see the connection as inactive anyway.
In that case, is it the sshd itself that is timing them out? And if so, why isn't that timeout documented or configurable? And if application-level keepalives are needed to keep SSH connections open, then why are they not enabled by default?
These questions are invariably overlooked whenever this issue pops up on discussion forums. Can anyone shed some light on this?

A: SSH itself is quite an old protocol, and wasn't originally designed for the mobile oriented world we live in today. If there's an interruption in the connection between server and client it doesn't recover very well, so if you're on an iffy connection, it wouldn't be too much of a surprise if there was a broken pipe. This is also partially due to the fact that SSH is completely reliant on TCP, which has a number of limitations in this area.
Either way, if you need something that is more robust for such connections, I recommend mosh. It's super easy to configure, and you shouldn't have any issue with disconnecting. In fact, you could even switch IP addresses and it will pick right back up where you were without so much as a hiccup. Mosh uses UDP, which is what allows for such behavior.
As for how it works, it uses SSH to establish a connection to the server, where it runs mosh-server. The program then listens on a UDP port (around 60000 by default), for the client to connect with mosh-client. This means that the only configuration you have to do is a simple port forward.
I hope this helps.

A:
Who is closing the socket?

Nobody is closing the "socket", i.e. neither client nor server. The connection problem is usually caused by a stateful packet filteri in between the communication parties. Such packet filters are used in firewalls and also in the simple SoHo routers where they are needed to handle the states for NAT which is the typical way to provide internet access to multiple internal systems behind the same external IP address.
Such stateful packet filters create a state for each new connection and tears it down on connection close. This means SYN/FIN packets with TCP connections like ssh. These states takes up memory so a packet filter can only support a limited number of states at the same time. Therefore it will remove these states after some time of inactivity (i.e. no packets for this connection).
If there is no activity within a TCP connection no packets will be send. This is true for SSH too. After some time of inactivity the state in the packet filter will be removed. If any party of the connection then will send more packets after the inactivity there will be no state in the packet filter and a RST packet will be issued. This results in the "Broken Pipe".
The TCPKeepAlive option in SSH enables the TCP keepalive option which causes the TCP layer to regularly send empty packets (i.e. TCP packet with no data payload) in times of inactivity. This way the packet filter keeps the state open.


text:
Q: Notice: Trying to get property 'num_rows' of non-object in <?php

$queryuser  = "SELECT id, email, firstname, lastname, address, city, country  FROM users WHERE role = 'client'";
$resultuser = $connection->query($queryuser);
if ($resultuser->num_rows > 0)
{
  // output data of each row
  while ($rowuser = $resultuser->fetch_assoc())
  {
    $id_user   = $rowuser['id'];
    $firstname = $rowuser['firstname'];
    $lasttname = $rowuser['lastname'];
    $email     = $rowuser['email'];
    $phone     = $rowuser['phone'];
    $city      = $rowuser['city'];
    $state     = $rowuser['state'];
    $address   = $rowuser['address'];
?>

A: Perhaps you've copied code from this page https://www.w3schools.com/php/php_mysql_select.asp

*

*Please understand code line by line first. You have not define $connection variable in your code (may be it is a intentional approach for security).

*Your notice saying that you are trying to get num_rows property from the object $resultuser but in this query $resultuser is not a object due to any error/faults of your query because query() returns FALSE on failure and object on success.

*To confirm, you can check your result set by using var_dump();

*Please replace this line if $resultuser->num_rows > 0 with  (!empty($resultuser->num_rows) && ($resultuser->num_rows > 0)))


text:
Q: Private GitHub Packages authentication from Kubernetes deployment.yml I'm trying to pull a docker image from a private GitHub Packages registry from within a K8s deployment.yml.
As I'm trying to avoid using personal access tokens (PAT), I'm currently trying to use something like this script to get an app access token.
It works and I can successfully "docker login" with it, but I get a "denied" when trying to pull an image.
My Argo CD installation gives me a 401 - Unauthorized.
I double checked the permissions of the GitHub App to include packages:read and to be installed on the repo, but it just doesn't work.
Is this currently not possible or am I missing something?


text:
Q: how to combine echo, redirection, comand output, and quotation in a shell script I want to include svn version number into my C/C++ code. I found a way to do it in linux, but I also compile the code under Windows, where I don't use svn.
One way to do it would be to create a file svn.h, which is then included into the code. The file should contain the following line:

#define SVNVERSION "12345M"

Here 12345M is the output of the command svnversion. How to create such a file using bash script (or how to include the command into the Makefile)?

A: echo '#define SVNVERSION "'$(svnversion .)'"' > svn.h

You may have to adjust svnversion . so it matches exactly what you write to get 12345M

A: AFAIR, SVN does keyword expansion, so you can get version numbers pasted in automatically on checkout.


text:
Q: Load Content in Application using inbuilt chrome web browser than Default System Webview I am currently implementing certain features in my application as it turned out that the default web view doesn't support such features.
SO, is there any possibility that i can render my application content in inbuilt chrome web view inside my application rather than android default web view or redirecting it open chrome browser.
I am currently on marshmallow. i came to know about this feature implemented in the NOUGAT version. However, i need it on API<23.
Below is my code:
webView = (WebView) findViewById(R.id.fullscreen_content);
           // webView.setWebViewClient();

            //you can also link to a website. Example:
            //webView.loadUrl("www.google.com");
            //I have included web permissions in the AndroidManifest.xml
            //
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);

            //loads the WebView completely zoomed out
            webView.getSettings().setLoadWithOverviewMode(true);

            //true makes the Webview have a normal viewport such as a normal desktop browser
            //when false the webview will have a viewport constrained to it's own dimensions
            webView.getSettings().setUseWideViewPort(true);

            //override the web client to open all links in the same webview
            webView.setWebViewClient(new MyWebViewClient());
            webView.setWebChromeClient(new MyWebChromeClient());

            webView.loadUrl(URL);

A: Try this sample code I derived from Building Web Apps in WebView but using WebChromeClient:
public class MainActivity extends AppCompatActivity {

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView=(WebView)findViewById(R.id.webview);
        webView.setWebChromeClient(new WebChromeClient());

        String urlString="https://www.youtube.com/watch?v=miomuSGoPzIe";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));

        intent.setPackage("com.android.chrome");

        try {
            startActivity(intent);
        } catch (ActivityNotFoundException ex) {

            Log.v("MainActivity", "NO CHROME APP INSTALLED");
            intent.setPackage(null);
            startActivity(intent);
        }
    }
}

Here's the WebView in activity_main.xml
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

I have Firefox and Chrome in the Nexus phone and it opened the WebView in Chrome so I think it works.


text:
Q: Easiest solution to sync an offline (local desktop application) database with a central server and multiple pc's? I have a desktop application which uses a local database. (This can be SQLite, SqlCe, PostgreSQL or any other database I will be able to install locally, I haven't decided which one to use yet.)
The plan is to achieve the following:
A user can subscribe to some kind of cloud service. If he does his local database should be synced with the online database (one for all users, or one per user, whatever the easiest solution is) so he will be able to sync his local database data between multiple PC's, can access his data online. (Much like dropbox does for files.)
What is the best, easiest (and preferably cheapest) solution to achieve this? I am looking into DataObjects.net but I can't find much documentation about their Sync feature. Or, are there other alternatives? For example, I start with some kind of cloud service which allows local caching and use the local caching for users who do not subscribe to the service.
Any pointers, tips or experiences are welcome.

A: OData can be used for sync data:
http://nicksnettravels.builttoroam.com/post/2010/08/03/OData-Synchronization-with-WCF-Data-Services.aspx
This example is not specific to your requirement, but can be used as a starting point.

A: Maybe you get as near as possible to an out of the box solution by taking a look into the Microsoft Sync Framework. Till now i didn't try the framework on myself, but it looks promising and hopefully it will worked as described.


text:
Q: rmi class can not found exception I wrote an simple project using java rmi and exported to an executable jar file. When I tries to run it, sometimes i got exceptions and sometimes it works. When I specify -Djava.rmi.server.codebase=file:serverClasses/, it seems it didn't create the jar file correctly.
Here is the stacktrace:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: com.ServerBootstrap.IServer
    at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:413)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
    at sun.rmi.transport.Transport$1.run(Transport.java:177)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:636)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:273)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:251)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:377)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Naming.java:177)
    at com.v3q6.eece411.A2.ServerBootstrap.ChatRoomServer.main(ChatRoomServer.java:37)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: com.ServerBootstrap.IServer
    at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
    at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:403)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:267)
    at sun.rmi.transport.Transport$1.run(Transport.java:177)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:553)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:808)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:667)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:636)
Caused by: java.lang.ClassNotFoundException: com.ServerBootstrap.IServer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:336)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at sun.rmi.server.LoaderHandler.loadProxyInterfaces(LoaderHandler.java:728)
    at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:672)
    at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:609)
    at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:646)
    at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:311)
    at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:255)
    at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1548)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1510)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1749)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368)
    ... 12 more

It seems the program doesn't recognize the codebase. In my case, all the files are local. Does anyone know what is the problem? thanks

A: Try explicitly specifying the name of the JAR file containing the com.ServerBootstrap.IServer class in your codebase, e.g.
-Djava.rmi.server.codebase=file:serverClasses/myjarfile.jar

The "Dynamic code downloading using JavaTM RMI (Using the java.rmi.server.codebase Property)" doc provides more information on the use of codebase and the options for its specification.

A: That's not a complete stacktrace, and I think you may have left out the part that shows the root cause of your problem.
If I recall correctly, ClassNotFoundException can sometimes be due to an exception thrown during static initialization of the class that is being loaded, or some class that it depends on.  If this occurs, it will show up as a nested exception in the first stacktrace for the problem, at the next level of nesting.  I recall (maybe incorrectly) that if your application repeats the attempted class load, the initialization exception is not in the resulting stacktrace.
EDIT: The complete stacktrace says that my theory is not correct.

A: With a relative path specified for java.rmi.server.codebase, make sure that you are in the correct directory (the parent directory of "serverClasses") when starting the client. If that's hard to ensure, an absolute path for the codebase might be more reliable.
Also, remember that when running with the -jar option, the -classpath option is completely ignored. I don't think that's a problem here; the RMIClassLoader should still be able to work using the server's codebase setting. But if you are relying on the client having access to additional classes specified on the classpath, that won't work. You'll need to use the Class-path attribute in the main JAR file's manifest.


text:
Q: OpenCV duplicate locations of detected items Hello :) i have a problem with OpenCV detection items on screen, I wanted to make a memory game bot, It works, but there are duplicate card positions
        # load the image to find
        image = r'C:\\Users\\Komputer\\Desktop\\screen\\' + str(x) + '.png'
        templateim = pyscreeze._load_cv2(image, grayscale=False)
        (w, h, _) = templateim.shape

        # get screenshot
        screenim_color = img
        screenim_color = cv2.cvtColor(np.array(screenim_color), cv2.COLOR_RGB2BGR)

        Nsearch = 2  # number of times to search
        center_locations = []  # list to store locations
        for k in range(Nsearch):
            result = cv2.matchTemplate(screenim_color, templateim, cv2.TM_CCOEFF_NORMED)  # template matching
            (_, _, _, maxLoc) = cv2.minMaxLoc(
                result)  # get the location  where the correlation coefficient is maximum (This is the top-left tip of the box surrounding the template)

            cv2.rectangle(screenim_color, maxLoc, (maxLoc[0] + h, maxLoc[1] + w), (0, 0, 255),
                        -10)  # mask the detected region by drawing a solid rectangle over it

            center_loc = (int(maxLoc[0] + h / 2)+165), int((maxLoc[1] + w / 2) + 212)  # get the center location
            center_locations.append(center_loc)  # append to list
            print(center_locations)
        for x in range(2):
            pyautogui.click(center_locations[x])
            time.sleep(1.05)
    time.sleep(10)

The output of console, seems like :
[(354, 471), (489, 471)]
[(353, 472), (488, 472)]
[(623, 297), (488, 648)]
[(355, 822), (220, 296)]
[(353, 296), (219, 296)]
[(353, 295), (624, 295)]
[(354, 295), (219, 295)]
[(488, 821), (220, 821)]

it looks like it detects the same item multiple times next to each other, is there an option to fix this?


text:
Q: If a Pokémon is shiny for someone, is it shiny for everyone in the same location? Let's take the case where two players would face the same Pokémon on the map. The first player would launch the battle, and find out that the opposite Pokémon is shiny.
If the second player launch the encounter with the same Pokémon, will the Pokémon also be shiny for him?

A: Bad luck, it seems that the second player won't get a shiny Pokémon, except if he is really lucky too.
Silph Road's Reddit users which were playing together confirmed that, while launching the encounter against the same Magikarp, only one of the two players faced a shiny Magikarp.
Another user confirmed it in the comments too:

I have a shiny magikarp, my girlfriend and I are both level 24. The magikarp she caught was not shiny.


text:
Q: Same instances between tests I wrote two test(I mean different classes) that is configured with this annotations:
@RunWith(SpringRunner.class)
@SpringBootTest
When I run them solitary - everything is Ok
Magic happens when I run them simultaneously using 'test' task from gradle. One test creates an instance and then, somehow, transfer it to another class.
Has anyone ever met smth like this?

A: You could use @DirtiesContext to tell that a test class will be modifying the ApplicationContext. Therefore any other subsequent test class will not pick up that modification
@DirtiesContext
@RunWith(SpringRunner.class)
@SpringBootTest


text:
Q: syntax error at or near "RETURNING" PSQL Select with returning statement I have the following query:
WITH data AS (
    SELECT
        profileid as id_user,
        terms_accepted as terms_accepted_passport,
        lastname as last_name_user,
        firstname as first_name_user,
        picture_serving_url as picture_user,
        is_active as status_user,
        is_passport_active as status_passport,
        language as language_id_user,
        created as created_user,
        modified as modified_user,
        passport_completion_level as completion_level_passport,
        email as email_user,
        about_me as description_user,
        uni_code as institution_id_user,
        metadata as metadata_misc
    FROM import_temp_table
    RETURNING
        id_user
)
select * FROM data

The output is:
ERROR:  syntax error at or near "RETURNING"
LINE 19:     RETURNING

Am I doing something wrong?

A: this?..
WITH data AS (
    SELECT
        profileid as id_user,
        terms_accepted as terms_accepted_passport,
        lastname as last_name_user,
        firstname as first_name_user,
        picture_serving_url as picture_user,
        is_active as status_user,
        is_passport_active as status_passport,
        language as language_id_user,
        created as created_user,
        modified as modified_user,
        passport_completion_level as completion_level_passport,
        email as email_user,
        about_me as description_user,
        uni_code as institution_id_user,
        metadata as metadata_misc
    FROM import_temp_table
)
select id_user FROM data

and in case I guessed, this should do:
select profileid as id_user from import_temp_table

A: SELECT
        profileid as id_user
 FROM import_temp_table
    RETURNING id_user into id_user_


text:
Q: React-Native: Adding a Button on press of a Button A simple question I can't wrap my head around is this:
Let's say I have a button, if I press that button, I want another button to appear. Imagine that buttoncreation as something that loops, so I can't have a predefined list of buttons I just show or hide.
React can create with react.createElement(), but I don't seem to get the correct usage of createElement.
Can I steer around having to create Elements through react? (Kind of feels like against the nature of react to actually create new html into something)

Easier said: I'm currently developing an app that calculates a common route between multiple departures and destinations, I want to give the user the ability to enter as many departures and destinations as he'd like, since the backend algorithm can handle it.

A: You can try something like this:
state = {
  buttons: []
}

createButton() {
  let { buttons } = this.state

  const button = (
    <Button
      onPress={this.createButton.bind(this)}
    />
  )

  buttons.push(button)

  this.setState({
    buttons
  })
}

renderItem({ item }) {
  return (
    <View>
      {item}
    </View>
  )
}

render() {
  return() {
    <FlatList
      data={this.state.buttons}
      renderItem={(item) => this.renderItem()}
    />
  }
}


text:
Q: Routing Error No route matches [GET] "/documents/original/missing.png" I am using Paperclip to upload files (PDF and Word docs) to my Rails app. So far everything seems to work. Yet, when I click on the link for to view my pdf file (<%= link_to "My document", @pin.document.url, target: "_blank" %>) a new tap open and I get a Routing Error: No route matches [GET] "/documents/original/missing.png"
Should I include a new route in my route.rb file?
Rails.application.routes.draw do
  resources :pins

  devise_for :users
  root "pins#index"
  get 'about' => 'pages#about'

Pin model:
class Pin < ActiveRecord::Base

    has_attached_file :document
    validates_attachment :document, :content_type => { :content_type => %w(application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document) }

    end

A: I have the similar problem as yours, and got a tip from the below link:
http://archive.railsforum.com/viewtopic.php?id=20097
Simply: keep your PDF files under Public folder if possible.


text:
Q: Sort doesn't work if sheetname is included in formula (Excel) I have a problem with sorting in Excel and I cant find out why.
I have two tables which need sorting by a formula field (Field4 in the below image).
Basically, the formulas in two fields of these table are almost same. But for the first one, I use 'sheetname'!CellAddress ref and CellAddress ref only for the other.
I'd like to sort by Field4 (smallest to largest). Here is the result after sorting:

For the first case, it doesn't work and the formulas in Field4 are changed. For the second one, it's okay.
Could you please help me explain. Thanks


text:
Q: Errors appearing in code Help, I don't know what this error is
Console.WriteLine (num1 + " + " + num2 " = " answer);

This returns four errors (im using monodevelop)

*

*) expected

*; expected

*; expected (yes, it appear twice)

*Invalid expression term ')'
And three more similar lines got the same errors

Here is the whole code
using System;

namespace CMD_test
{
class MainClass
{
    public static void Main (string[] args)
    {
        Start:
        double num1;
        double num2;
        double answer;

        Console.WriteLine ("What operation shall we use? Type:");
        Console.WriteLine ("A - for addition");
        Console.WriteLine ("S - for subtraction");
        Console.WriteLine ("M - for multiplication");
        Console.WriteLine ("D - for division");

        KeyPress:
        string key = Console.Read ();

        if (key == "A") {
            Console.WriteLine ("You chose addition");
            Console.Write ("What is the first number? ");
            num1 = Convert.ToDouble (Console.ReadLine ());
            Console.Write ("What is the second number? ");
            num2 = Convert.ToDouble (Console.ReadLine ());
            answer = num1 + num2;
            Console.WriteLine (num1 + " + " + num2 " = " answer);
        }
        if (key == "S") {
            Console.WriteLine ("You chose subtraction");
            Console.Write ("What is the first number? ");
            num1 = Convert.ToDouble (Console.ReadLine ());
            Console.Write ("What is the second number? ");
            num2 = Convert.ToDouble (Console.ReadLine ());
            answer = num1 - num2;
            Console.WriteLine (num1 + " - " + num2 " = " answer);
        }
        if (key == "M") {
            Console.WriteLine ("You chose multiplication");
            Console.Write ("What is the first number? ");
            num1 = Convert.ToDouble (Console.ReadLine ());
            Console.Write ("What is the second number? ");
            num2 = Convert.ToDouble (Console.ReadLine ());
            answer = num1 * num2;
            Console.WriteLine (num1 + " * " + num2 " = " answer);
        } else if (key == "D") {
            Console.WriteLine ("You chose division");
            Console.Write ("What is the first number? ");
            num1 = Convert.ToDouble (Console.ReadLine ());
            Console.Write ("What is the second number? ");
            num2 = Convert.ToDouble (Console.ReadLine ());
            answer = num1 / num2;
            Console.WriteLine (num1 + " / " + num2 " = " answer);
        } else {
            Console.WriteLine ("You pressed a wrong button! Please retry.");
            goto KeyPress;
        }

        Console.Write ("Do you want to do another operation? Y/N: ");

        string restart = Console.ReadLine ();
        if (restart == "Y") {
            Console.Clear ();
            goto Start;
        } else if (restart == "N") {
            Console.WriteLine ("Press any key to exit");
            Console.ReadKey ();
        }
    }
}
}

and maybe some more other errors i dont know

A: Your expression
Console.WriteLine (num1 + " + " + num2 " = " answer);

isn't valid as you have missed a couple of +'s off your expression. Change it to:
Console.WriteLine (num1 + " + " + num2 + " = " + answer);

and it'll compile correctly. Better yet, do this and you'll avoid such typos:
Console.WriteLine ("{0} + {1} = {2}", num1, num2, answer);

Oh and as an aside, as and when you switch to C# 6, you'll be able to do this, which simplifies things even more:
Console.WriteLine ("{num1} + {num2} = {answer}");

A: Console.WriteLine (num1 + " + " + num2 " = " answer);

should actually be
Console.WriteLine (num1 + " + " + num2 + " = " + answer);

You missed two plus signs. That's why it is generating a error.
Your IDE has told you where the problem actually is.
Moreover, it is not a good practice to concatenate strings this way. Console.WriteLine lets you use string formatting:
Console.WriteLine ("{0} + {1} = {2}", num1, num2, answer);

Read about composite formatting here:
https://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx

A:
Here is an example of what you tried to do.


text:
Q: Using one string variable's value in another variable is converting all special characters in hex code My string variable is * string variable1 = '&config=1'.When i am using this variable into another variable then & and = is converted to hex code %26config%3D1

A: Sounds like you used these in the URL, of course then this will be URL-encoded and this is the correct behavior.
See link: https://www.w3schools.com/tags/ref_urlencode.asp
Also please use the param keyword for query-string parameters:
And param config = 1


text:
Q: iTextSharp sign verify fails even if acrobat verify that sign without error I'm using iTextSharp 5.4.2 and on a sign that Acrobat verify as a correct and not corrupted sign I get that the sign is not verified (here is a sample).
I debugged source code and I found that even if the RSAData in the sign was a SHA1 of the content (20 bytes) the messageDigest is created for a SHA256 and the verifyRSAdata = Arrays.AreEqual(msgDigestBytes, RSAdata) obiously fails.
In my opinion the "error" is in PdfPKCS7.cs at line 335
The sign was created with Filter /Adobe.PPKMS and SubFilter /adbe.pkcs7.sha1
What's wrong ?
Could someone take a look at code to fix it ?
Thank you
Domenico


text:
Q: Resque Scheduling using PHP I am using PHP to implement scheduler. My requirement is to run a queue between 9:00AM till 9:00PM. Added jobs in queue beside that time period should not process.
Below is my code:
<?php
include('autoload.php');
include('ResqueScheduler.php');
include('Resque.php');

Resque::setBackend('XXXXXXXXXXXXXXXXXXX');

$args = array('glid' => '1234');
$time = 10;

try{
  ResqueScheduler::enqueueAt($time, 'Test_Worker', $args);

}catch (Exception $e) {
  echo 'EXCEPTION';
  print_r($e);
}


text:
Q: vscode fails to start with Error: EMFILE: too many open files, watch '/snap/code' For a couple of days, my Visual Studio Code fails to start. Starting with code --verbose produces:
$ code --verbose
(process:9711): Gtk-WARNING **: 16:56:14.336: Locale not supported by C library.
        Using the fallback 'C' locale.
(code:9711): Gtk-WARNING **: 16:56:14.353: Theme parsing error: gtk.css:68:35: The style property GtkButton:child-displacement-x is deprecated and shouldn't be used anymore. It will be removed in a future version
(code:9711): Gtk-WARNING **: 16:56:14.353: Theme parsing error: gtk.css:69:35: The style property GtkButton:child-displacement-y is deprecated and shouldn't be used anymore. It will be removed in a future version

(code:9711): Gtk-WARNING **: 16:56:14.353: Theme parsing error: gtk.css:73:46: The style property GtkScrolledWindow:scrollbars-within-bevel is deprecated and shouldn't be used anymore. It will be removed in a future version
[9711:1016/165614.456088:ERROR:file_path_watcher_linux.cc(276)] inotify_init() failed: Too many open files (24)
Failed to watch /home/falko/.config/Code/User for changes using fs.watch() (Error: EMFILE: too many open files, watch '/home/falko/.config/Code/User')
[main 2019-10-16T14:56:14.582Z] Starting VS Code
[main 2019-10-16T14:56:14.582Z] from: /snap/code/18/usr/share/code/resources/app
[main 2019-10-16T14:56:14.582Z] args: { _: [], verbose: true, diff: undefined }
[main 2019-10-16T14:56:14.584Z] Resolving machine identifier...
[main 2019-10-16T14:56:14.584Z] Resolved machine identifier: aa83b26b19696e7dcb8a342740bd0a02c994ea16ca0bfc477cb434d622f2df6e (trueMachineId: undefined)
[main 2019-10-16T14:56:14.603Z] update#setState idle
[main 2019-10-16T14:56:14.604Z] telemetry/optInStatus { optIn: true }
[main 2019-10-16T14:56:14.604Z] telemetry/machineIdFallback { usingFallbackGuid: false }
[main 2019-10-16T14:56:14.605Z] Error: EMFILE: too many open files, watch '/snap/code'
    at FSWatcher.start (internal/fs/watchers.js:164:26)
    at Object.watch (original-fs.js:1232:11)
    at new g (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:391:55)
    at h._createInstance (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:252:51)
    at h._createServiceInstance (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:254:51)
    at h._createServiceInstanceWithOwner (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:253:661)
    at h._createAndCacheServiceInstance (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:253:336)
    at h._getOrCreateServiceInstance (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:252:559)
    at Object.get (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:251:129)
    at t.openFirstWindow (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:527:871)
    at c.invokeFunction.e (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:523:709)
    at h.invokeFunction (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:251:263)
    at t.startup (/snap/code/18/usr/share/code/resources/app/out/vs/code/electron-main/main.js:523:686)
[main 2019-10-16T14:56:14.605Z] Lifecycle#kill()

Currently, I'm on 1.39.2 installed via SNAP on Ubuntu 18.04.3 LTS.

A: You can run locate gtk.css and find where those files are:
Then you can comment out using command like:
sudo sed -i -E 's~^.*child-displacement-.*$~/* \0 */~g' /usr/share/themes/Breeze/gtk-3.20/gtk.css

For me, I also needed to run:
sudo sed -i -E 's~^.*-GtkScrolledWindow-scrollbars-within-bevel.*$~/* \0 */~g' /usr/share/themes/Breeze/gtk-3.20/gtk.css


text:
Q: using this percentage function in Flash AS3 Hi I have this function I found
function valueToPercent($value:Number, $min:Number, $max:Number):Number {
var myPercent:Number;
var difference:Number = $max - $min;
myPercent = (($value - $min) / difference);
return myPercent;
}

How would I define those variables and get a result? I need to output various percentages which will become variables, which will then power a pie chart...
This didn't work, but I've obviously done it wrong
function valueToPercent($value:Number, $min:Number, $max:Number):Number {
var myPercent:Number;
var difference:Number = $max - $min;
myPercent = (($value - $min) / difference);
return myPercent;
}

valueToPercent(45, 0, 345);

Trace(valueToPercent);

Thanks!

A: You're almost there. When a method returns a value, you can asign it to a variable of type that it returns
var percentage:Number = valueToPercent(45, 0, 345);
trace(percentage);

and/or
trace(valueToPercent(45, 0, 345));


text:
Q: How to find a sibling element for an element stored in an array using Appium for python? I declared an array of elements using this method:
checkboxes = self.driver.find_elements(AppiumBy.XPATH, '//XCUIElementTypeButton[@name="Square"]')
How do I find the sibling element to the first element in the array?
This
siblingElement = checkboxes[0].find_element(by=AppiumBy.XPATH, value='./following-sibling::XCUIElementTypeStaticText')
failed with the following error message:
NoSuchElementError: An element could not be located on the page using the given search parameters.
I tried using this documentation:
https://appium.io/docs/en/commands/element/find-elements/
https://appium.io/docs/en/commands/element/find-element/
Please note I'm using Python in my framework.
Domain of the UI:
<XCUIElementTypeButton type="XCUIElementTypeButton" name="Square" label="Square" enabled="true" visible="true" accessible="true" x="15" y="428" width="20" height="21" index="22"/>
<XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="checkbox 1 text" name="checkbox 1 text" label="checkbox 1 text" enabled="true" visible="true" accessible="true" x="43" y="428" width="308" height="18" index="23"/>
<XCUIElementTypeButton type="XCUIElementTypeButton" name="Square" label="Square" enabled="true" visible="true" accessible="true" x="15" y="478" width="20" height="21" index="24"/>
<XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="checkbox 2 text" name="checkbox 2 text" label="checkbox 2 text" enabled="true" visible="true" accessible="true" x="43" y="478" width="260" height="35" index="25"/>
<XCUIElementTypeButton type="XCUIElementTypeButton" name="Square" label="Square" enabled="true" visible="true" accessible="true" x="15" y="542" width="20" height="21" index="26"/>
<XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="checkbox 3 text" name="checkbox 3 text" label="checkbox 3 text" enabled="true" visible="true" accessible="true" x="43" y="542" width="333" height="86" index="27"/>
<XCUIElementTypeButton type="XCUIElementTypeButton" name="Square" label="Square" enabled="true" visible="true" accessible="true" x="15" y="657" width="20" height="21" index="28"/>
<XCUIElementTypeStaticText type="XCUIElementTypeStaticText" value="checkbox 4 text" name="checkbox 4 text" label="checkbox 4 text" enabled="true" visible="true" accessible="true" x="43" y="657" width="320" height="52" index="29"/>

A: First case
 def tap_by_index(self, locator_string, index):
        locator = self.get_locator(locator_string)
        if str(locator_string[0]).startswith("xpath"):
            self.driver.find_elements(AppiumBy.XPATH, str(locator))[index].click()

 def get_locator(locator):
     exploited_locator = locator[1]
     return exploited_locator

 Second case
  def tap_by_index(self, locator: Tuple[By, str], i: int):
        """i: element index"""
        self.wait(locator) # WAIT UNTIL VISIBLE
        elements = self.driver.find_elements(*locator)
        elements[i].click()