text:
Q: Desenhar apenas com o "pincel" e apenas "círculos" quando clicar nos determinados botões Estou construindo um programa simples para desenhar no canvas no qual você consegue desenhar um círculo e desenhar com o pincel clicando nos determinados botões Desenhar círculo (clicando no canvas é desenhado o círculo) e Pincel (movendo o mouse por cima do canvas é feito o desenho com o pincel):

let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY;

canvas.onmousemove = () => {
    mouseX = event.offsetX;
    mouseY = event.offsetY;
}

btnCircle.onclick = () => {
    canvas.onclick = () => {
        ctx.beginPath();
        ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
        ctx.stroke();
    };
}

btnBrush.onclick = () => {
    canvas.onmousemove = () => {
        mouseX = event.offsetX;
        mouseY = event.offsetY;

        ctx.fillStyle = 'red';
        ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
    };
}
canvas {
    display: block;
    margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>

Até ai parece que está funcionando bem, mas se, por exemplo, eu clicar no botão Desenhar círculo eu consigo desenhar de boa os círculos e se eu clicar no botão Pincel eu também consigo desenhar com o pincel, mas clicando nos dois botões acaba acontecendo um problema eu consigo desenhar ao mesmo tempo com o pincel e os círculos o que acaba gerando uma bagunça:

O que era para acontecer é quando eu clicar no botão Desenhar círculo eu desenho apenas círculos e quando eu clicar no botão Pincel eu desenho apenas com o pincel, mas não está acontecendo isso, porque isso está acontecendo? e como eu posso resolver esse problema?

A: Basta setar uma flag (booleana) ou remover o evento canvas.onclick = () => { quando for pincel e remover o evento canvas.onmousemove = () => { quando for circulo, em programação esse é o básico: o que não é usado deve ser desabilitado ou removido.
Exemplo removendo os eventos:

let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY;

function circulo()
{
    //Substitui o onmousemove para usar com o circulo
    canvas.onmousemove = () => {
        mouseX = event.offsetX;
        mouseY = event.offsetY;
    };

    //Aplica o click
    canvas.onclick = () => {
        ctx.beginPath();
        ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
        ctx.stroke();
    };
}

btnCircle.onclick = circulo;

btnBrush.onclick = () => {
    //Remove o click
    canvas.onclick = null;

    //Substitui o onmousemove para usar com o pincel
    canvas.onmousemove = () => {
        mouseX = event.offsetX;
        mouseY = event.offsetY;

        ctx.fillStyle = 'red';
        ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
    };
}
canvas {
    display: block;
    margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>

Ou com flags booleanas:

let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY, circulo = false, pincel = false;

canvas.onmousemove = () => {
    mouseX = event.offsetX;
    mouseY = event.offsetY;

    if (pincel) {
        ctx.fillStyle = 'red';
        ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
    }
}

canvas.onclick = () => {
    if (circulo) {
        ctx.beginPath();
        ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
        ctx.stroke();
    }
};

btnCircle.onclick = () => { circulo = true; pincel = false; }
btnBrush.onclick = () => {  circulo = false; pincel = true; }
canvas {
    display: block;
    margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>


text:
Q: Helper Devise: could not find the `Warden::Proxy` instance on request environment I try to use Devise for my Rails app. I can sign up and login but when I go to my other page "build" I get the following error:

Devise::MissingWarden in Home#show Devise could not find the
  Warden::Proxy instance on your request environment. Make sure that
  your application is loading Devise and Warden as expected and that the
  Warden::Manager middleware is present in your middleware stack. If
  you are seeing this on one of your tests, ensure that your tests are
  either executing the Rails middleware stack or that your tests are
  using the Devise::Test::ControllerHelpers module to inject the
  request.env['warden'] object for you.

Here is my controller:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  private
  # Overwriting the sign_out redirect path method
  def after_sign_out_path_for(resource_or_scope)
    build_path
  end
end

Here rea my two partial views:

<% if user_signed_in? %>

  <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>

<% else %>

  <%= link_to('Login', new_user_session_path)  %>

<% end %>

and

<% if user_signed_in? %>

  <%= link_to('Edit registration', edit_user_registration_path) %>

<% else %>

  <%= link_to('Register', new_user_registration_path)  %>

<% end %>

After debugging, I figured out that the problem is coming from this line in my "show" controller: template = HomeController.render('layouts/_template')
Thanks for your help.

A: I had a similar problem when testing views where 'current_user' was present in some conditional.
I solved it with this:
let(:user) { FactoryGirl.create :customer }

before(:each) do
  allow(view).to receive(:current_user).and_return(user)
  ...

A: Based on this SO answer you need to include the Devise::Test::ControllerHelpers module in your controller specs. Add the following to your rails_helper:
RSpec.configure do |config|
  config.include Devise::Test::ControllerHelpers, type: :controller
end

A: It can happen when you call Devise methods, like current_user, in code being managed by action cable. like a background job to render comment or something else.
You may resolve it by doing something like the following in your controller. It propagates warden to the the @env['warden'] variable so that Devise can use it:
def create
  @product = Product.find(comment_params[:product_id])
  @comment = @product.comments.build(comment_params)
  @comment.save!

  gon.comment_id = @comment.id
  gon.comment_user_id = @comment.user_id

  ActionCable.server.broadcast "chat", comment: render_comment

  render :create, layout: false
end

def render_comment
  CommentsController.renderer.instance_variable_set(
    :@env, {
      "HTTP_HOST"=>"localhost:3000",
      "HTTPS"=>"off",
      "REQUEST_METHOD"=>"GET",
      "SCRIPT_NAME"=>"",
      "warden" => warden
    }
  )

  CommentsController.render(
    partial: 'comments/comment_detail',
    locals: {
      product: @product,
      comment: @comment
    }
  )
end

This will help you resolve the warden issue, if you have used Devise's current_user in that partial, it will give you the commentor user (as it should since that user initiated the rendering of partial).
Now to solve this, if you have a front end framework you might need to fetch the current user from cookies in order to restrict some actions like edit/delete. but if you are working in pure rails the solution I came across is that you have to make a hidden field in the dom having current users id, and you will fetch that id for comparison in a script. you might need to access rails variables in javascript, for that you can use GON gem.
I know this answer might contain much more than asked but I've searched alot and no where I found a satisfactory solution to this problem, feel free to discuss.

A: Add
config.include Devise::Test::ControllerHelpers, type: :controller

in your rails_helper.rb file.

A: Well, i have faced the same issue "devise could not find the warden :: proxy in actioncable" It can be resolved by passing the current user_id to your perform method in your job as you might be accessing the current user in your view which you rendering through broadcast and due to this issue was caused

A: If you are having this problem outside of Rspec say you were trying to render a view within an ActionCable channel, a scalable/maintainable approach is to use a helper or a view library like ViewComponents/cells. This way, you can extract your existing view into a component and parameterize any devise/warden methods called in the view. The advantage of this approach is

*

*The view is easier to test

*You can call it from anywhere in your code

*There are no coupled dependencies

Example using view helpers
Say you have in app/views/messages/show.html.erb the following
<%= current_user.first_name %>
<%= @message %>

Calling MessagesController.render :show outside the controller will cause an error since access to the request object is not available. Using ViewComponents, we extract the view into its own component
in app/components/message_component.rb
class MessageComponent < ViewComponent::Base
  def initialize(user:, message:)
    @user = user
    @message = message
  end
end

in app/components/message_component.html.erb
<%= @user.first_name %>
<%= @message %>

Usage
In app/views/messages/show.html.erb just call
<%= render(MessageComponent.new(message: @message, user: current_user) %>

In ActionCable, call it like so
ApplicationController.render(MessageComponent.new(message: @message, user: current_user)

Since you have access to ActiveRecord models from anywhere in your code, you should be able to fetch @message

A: I have to use the current_user in the helper method, which was used in view of which I was writing specs.
let(:user) { create(:user) }
before do
 allow(helper).to receive(:current_user).and_return(user)
end

but if you are working on view specs then do this
let(:user) { create(:user) }
before do
 allow(view).to receive(:current_user).and_return(user)
end

A: I had this error and could not find answer anywhere else. It was after dropping and creating the db. But I didn't load the schema.
This fixed it:
rake db:drop db:create db:schema:load

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как получить список всех фотографий на своей странице ВК на Python? Как получить количество фотографий со страницы пользователя через токен, используя VK_Api, нужно именно количество, не нужны сами фотографии, просто их количество. Именно применять Python не Json, как это представлено на vk.com/dev.

A: Используй метод photos.getAll. Допустим ты присвоил JSON ответ в переменную photos. Их число получишь по photos.count
Ссылка на метод


text:
Q: How to know which process interacts with input events How to monitor which process interacts with /dev/input/eventX. In this case, keyboard input events. Is there a way to know which process entered a specific input and watch for that event? Is that even possible?
Context
Recently, my Ubuntu 20.04 installation started to exhibit weird behaviour. After using it for a time, a precise bug happens

*

*Windows get minimized and restored multiple times

*The Gnome shell is displayed and hidden many times

*The mouse is moved many times almost instantly

*The Gnome workspace (desktop) is also changed

*A right-click is issued

This is always the same behaviour.
While using logkeys utility in the keyboard input (/dev/input/event3), I recorded the following keys being pressed while the bug happens:
2022-09-24 20:23:20-0400 > <Enter><E-72><E-73><E-73><E-72><E-72><E-72><E-72><E-72><E-73><BckSp><BckSp>ȁ
2022-09-24 20:24:05-0400 > <Enter><LCtrl><LShft><PgDn><Esc><LAlt><Tab><LAlt><Tab><LCtrl><LAlt><Up>

This allows me to conclude that an unknown program (and therefore process) triggers these events directly in my keyboard device.


text:
Q: Why is char a = 65 less portable than char a = 'A' I've just asked this question What is the reason for the double negation -(-n)? where the answerer mentions in a comment that
char a = 'A';
is more portable than
char a = 65;
Why is this? Surely they are exactly the same?

A: A is represented by 65 in ASCII; but that doesn't mean that every character system will represent it by 65.
If you write
char a = 65;

then you're implicitly assuming that the system will be using ASCII. That's less portable than writing
char a = 'A';

which doesn't make that assumption.

A: 65 is ASCII code for A, which can work on many systems, but what if the system does not support ASCII or doesn't have 65 for A? If that happens, then it's less portable due to the dependence on the system.
char a = 'A';

is a char literal which will work on all systems, but:
char a = 65;

is ASCII and may not work on all systems. You basically depend on the fact that the user is using ASCII, and depending on the user is never dependable.

A: If the variable a should store the letter 'A', then it's better to write
char a = 'A';

because it is more portable, since there may be other character encodings than ASCII, but also because it is clearer to the reader that a stores the letter 'A'.
The opposite case is even more obvious: Nobody would ever write
int a = 'A';

when a should hold the value '65' for a calculation.


text:
Q: What exactly are cout/cin? I know Java and now want to learn C++. I can't understand what are cout (character output stream) and cin (character input). Are these global variables? Then why
"My message">>cout;

doesn't work? But
cout<<"My message";

works.

A: std::cout and std::cin are indeed global variables.  Your code doesn't compile because that's not the way the language works.  You have to put the stream on the left, and then the operator and then the variables you are streaming into/out of.  (For output, you can use literals and expressions as well as variables.)

A: cout is an instance of the class std::ostream, and yes, it's a global variable. But operator>>(char *, ostream& os); hasn't been declared by the relevant header, so "My message">>cout;  will give an error of something like "can't find an operator >> which takes arguments const char * and std::ostream" (and possibly a lot more errors because sometimes compilers get very confused by these sort of things).
cin is the same thing, except std::istream
If you really want to mess with peoples heads, you could do:
template<typename T>
std::ostream& operator>>(T x, std::ostream& os)
{
   os << x;
   return os;
}

Of course, it won't work for "My Message " >> "Some other string" >> cout;, which is probably one of the reasons it's not done that way.
Note that this is simply slight abuse of the operator overloading, where we have a custom type as the left-hand side, and standard or non-standard type on the right hand side. cout is no different from some other variable of a custom type.

A: consider the arrows as streams. << stands for output stream , while >> stands for input stream.
so cout << "hello"  means output to screen
when cin >> a  means asks from a user input for variable a
cout can also use "+" like for example you can add more strings to one stream like this
cout << "Hello" << "world" << "I am john";
cin in the same way can ask for input from multiple variables
cin >> a >> b ;  will ask from user to input two times one for each variable

A: iostream is a header file which contain classes handling input and output operations for a console. Its like you create a object when you say "cin" for the input class handling input operation for a console in the header file. Same can be said about "cout" where a object is being created from a class handling output operation to a console in the header file.
When you consider "cin", imagine creating a pipe connected to the console and your program and an object "cin" taking your inputs from the console which you provide through your keyboard and dumping them on to the program. That's the reason you can see having a ">>" operator for cin and you can find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cin".
Whereas for "cout", imagine creating a pipe connected to the console and your program and an object "cout" taking its input from the program and dumping them on to the console. That's the reason you can see having a "<<" operator for cout and you find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cout".
So basically you need to first specify what object you would be creating for your operations and then assigning an operator to accomplish your task. If you include the header file, then its like you could use those objects anywhere throughout your program.
So, "My message">>cout; doesn't function the way you expect it to be because there is no object and an operator to accomplish your task whereas cout<<"My message"; does.
The technical aspects have been described by Mats Petersson. This is just to give you a general picture of what's actually happening pictorially. Hope this helps you.


text:
Q: Use the Taylor series for $\sin(x)$ to find a Taylor series for $f(x) = p(\sin x) $ around point $x=0$, where $p(x) = 4x^3 - 3x$ A question asks:

Consider the polynomial $p(x) = 4x^3 - 3x.$ Use the Taylor series for $\sin(x)$ to find a Taylor series for $f(x) = p(\sin x) $ around point $x=0$.
Don't just calculate this by differentiating right away. Instead, start with the first few terms of the Taylor series for $\sin(x)$, and substitute those into the given polynomial to figure out the first few terms.

I am not sure what exactly they want me to do here. The first few terms of $\sin x$ are: $$ x - \frac{x^3}{6} + \frac{x^5}{120} -+\cdots.$$
Are they just looking for me to plug this expression into the original polynomial?
The answer that the site linked below shows is $$-3x + \frac{9}{2}x^3+ \frac{-81}{40}\,x^5 . . .$$
Were they actually cubing trinomials to find the answer, or am I missing an easier method?
https://ximera.osu.edu/course/kisonecat/multivariable-calculus/master/taylor-series/remainders

A: Hint:
First show that
$$4\sin^3(x)-3\sin(x)=-\sin(3x)$$
Then show that
$$f(x)=-\sin(3x)=\sum_{n=0}^\infty\frac{(-1)^{n+1}(3x)^{2n+1}}{(2n+1)!}$$

A: It is known that
$$
\sin x=\sum_{k=0}^\infty(-1)^k\frac{x^{2k+1}}{(2k+1)!}, \quad x\in\mathbb{R}.
$$
On page 43 in the handbook [1] below, there is the series expansion
$$
\sin^3x=\frac14\sum_{k=1}^\infty(-1)^{k+1}\bigl(3^{2k+1}-3\bigr)\frac{x^{2k+1}}{(2k+1)!}, \quad x\in\mathbb{R}.
$$
Consequently, we obtain
$$
p(\sin x)=4\sin^3x-3\sin x=\sum_{k=1}^\infty(-1)^{k+1}\frac{(3x)^{2k+1}}{(2k+1)!}, \quad x\in\mathbb{R}.
$$
Reference

*

*I. S. Gradshteyn and I. M. Ryzhik, Table of Integrals, Series, and Products, Translated from the Russian, Translation edited and with a preface by Daniel Zwillinger and Victor Moll, Eighth edition, Revised from the seventh edition, Elsevier/Academic Press, Amsterdam, 2015; available online at https://doi.org/10.1016/B978-0-12-384933-5.00013-8.

A: A general and alternative answer to this kind of questions is the following theorem obtained in Lemma 2 of the paper [1] below.

For $\ell\in\mathbb{N}$ and $x\in\mathbb{R}$, assume that the value of
the function $\bigl(\frac{\sin x}{x}\bigr)^{\ell}$ at the point $x=0$
is $1$. Then \begin{equation}\label{sine-power-ser-expan-eq}
 \biggl(\frac{\sin x}{x}\biggr)^{\ell}
 =\sum_{j=0}^{\infty} (-1)^{j}\frac{R\bigl(\ell+2j,\ell,-\frac{\ell}{2}\bigr)}{\binom{\ell+2j}{\ell}}
 \frac{(2x)^{2j}}{(2j)!}, \end{equation} where
$R\bigl(\ell+2j,\ell,-\frac{\ell}{2}\bigr)$ is given
by\begin{equation}\label{S(n,k,x)-satisfy-eq}
 R(n,k,r)=\frac1{k!}\sum_{j=0}^k(-1)^{k-j}\binom{k}{j}(r+j)^n
 \end{equation}
for $r\in\mathbb{R}$ and $n\ge k\ge0$.

The notation $R(n,k,r)$ stands for weighted Stirling numbers of the second kind, which was first introduced in [2] below.
References

*

*F. Qi, Series expansions for any real powers of (hyperbolic) sine functions in terms of weighted Stirling numbers of the second kind, arXiv (2022), available online at https://arxiv.org/abs/2204.05612 or https://doi.org/10.48550/arXiv.2204.05612.

*L. Carlitz, Weighted Stirling numbers of the first and second kind, I, Fibonacci Quart. 18 (1980), no. 2, 147--162.


text:
Q: Oracle SQL - Modify the Content Based on the Value From Another I keep getting the ORA-00905: missing keyword error here. Could you take a look please?
The task is to replace the content of the attribute with 'N/A' if another variable is equal to 'R', otherwise - keep the value as is.
Here is an extract of my code:
SELECT
CASE
   WHEN SCHEMA.TABLE.VAR1 = 'R' THEN SCHEMA.TABLE.VAR2 = 'N/A'
   ELSE SCHEMA.TABLE.VAR2
END AS NEW_NAME

A: You should be using an update here rather than a select, if you intend to change the data in your SQL table:
UPDATE yourTable
SET SCHEMA.TABLE.VAR2 = 'N/A'
WHERE SCHEMA.TABLE.VAR1 = 'R'

If you need to do a select here, then use the following:
SELECT
    CASE WHEN SCHEMA.TABLE.VAR1 = 'R' THEN 'N/A' ELSE SCHEMA.TABLE.VAR2 END AS NEW_NAME
FROM yourTable

A: If you want a select, the column alias goes after the select.  = is not allowed in the then clause:
SELECT (CASE WHEN SCHEMA.TABLE.VAR1 = 'R' THEN 'N/A'
             ELSE SCHEMA.TABLE.VAR2
        END) AS NEW_NAME

Note:  You should use table aliases, so the query is easier to write and to read:
SELECT (CASE WHEN t.VAR1 = 'R' THEN 'N/A'
             ELSE t.VAR2
        END) AS NEW_NAME,
       . . .
FROM SCHEMA.TABLE t . ..


text:
Q: Which class is positive recurrent? Here's my transition matrix with state $\{1,2,3,4\}$:
\begin{bmatrix}
1/3 & 1/3 & 0 &1/3\\
1/4 & 1/4 & 1/4 &1/4\\
0 & 0& 1/2 &1/2\\
0 &0 &1/2 &1/2
\end{bmatrix}
There will be two commutation class $\{1,2\}$ and $\{3,4\}$. Ther are all irreducible. Which one is null recurrent and which one is positive recurrent? Or all transit?

A: Some hints that apply for any finite-state Markov Chain:
(1) Due to the pigeonhole principle, it is not possible for all states to be transient. At least one state must be visited infinitely often with a positive probability, and that state is recurrent.
(2) Null recurrence is never possible. Let $x$ be a recurrent state, and for any state $y$ in the same commuting class, define $f(y) := \mathbb P_y(T_x < k)$ where $T_x$ is the hitting time of $x$ and $k$ is the number of states in the chain. By the pigeonhole principle, $f(y) > 0$. Moreover, let $S$ represent the set of states in the same communicating class as $x$; then $c := \min_{y \in S} f(y)$ and $c > 0$ because there are a finite number of states. This implies a geometric bound on the return times of a walk started at $x$; after a walk takes one step away from $x$, it has a probability of at most $1 - c$ of not returning within the next $k$ steps, and a probability of at most $(1 - c)^2$ of not returning within the next $2k$ steps, and so on. Since this probability tends to $0$, the excursions are dominated by a geometric random variable and they have finite expectation.
(And just to re-emphasize the point: these comments only apply for finite-state Markov chains. Infinite-state Markov chains are much more complicated / interesting.)


text:
Q: Вывод информации из базы данных MYSQL PHP Есть четыре таблицы "Тип работ", "Отдел", "Задачи", "Подзадачи". У каждого типа работ может быть несколько отделов, у каждого отдела может быть несколько задач, и у каждой задачи может быть несколько отделов. Надеюсь объяснил понятно. Все это надо вывести в виде списка.
С горем пополам получилось вывести "Тип работ" -> "Отдел"
    <?php
    include('config2.php');
    $sql_works = "SELECT * FROM otdel,works,exam WHERE works.id = otdel.id_type and exam.id_otd = otdel.id_type ";
    $result = mysql_query($sql_works);
    while ($row = mysql_fetch_array($result)) {
          $data[$row['name_work']][] = $row['name_otdel'];
          $data2[$row['name_otdel']][] = $row['name_exam'];
    }

        echo "
";
        foreach ($data as $name_work => $name_otdel) {
              echo "
" . $name_work . "
";
              echo "

" . implode('

',$name_otdel) . "

";

        }
         foreach ($data2 as $name_otdel => $name_exam) {
              echo "
" . $name_otdel . "
";
              echo "

" . implode('

',$name_exam) . "

";

    }
    echo "
";

?>

А вот как вывести "Тип работ" -> "Отдел" -> "Задачи" не знаю...
Сейчас это выглядит вот так:

A: Возможно ты хотел что то подобное?
<?php

include('config2.php');
$sql_works = "SELECT * FROM otdel,works,exam WHERE works.id = otdel.id_type and exam.id_otd = otdel.id_type ";
$result = mysql_query($sql_works);
while ($row = mysql_fetch_array($result)) {
    $data[$row['name_work']][$row['name_otdel']][] = $row['name_exam'];
}
echo "
";
foreach ($data as $name_work => $otdel_array) {
    echo "
" . $name_work . "
";
    echo "
";
    foreach ($otdel_array as $otdel_name => $exam_names) {
        echo "
" . $otdel_name . "
";
        echo "

" . implode('

', $exam_names) . "

";
    }
    echo "
";
}
echo "
";

A: Как вариант
$sql_works = "SELECT * FROM otdel,works WHERE works.id = otdel.id_type";
$result = mysql_query($sql_works);

$data = [];
while ($row = mysql_fetch_array($result)) {
      $data[$row['name_work']][] = $row['name_otdel'];
}
if($data) {
    echo "
";
    foreach ($data as $name_work => $name_otdel) {
          echo "
" . $name_work . "
");
          echo "

" . implode('

, '$name_otdel) . "

";
    }
    echo "
";
} else {
    // нет результатов
}

Можно и в один цикл, но код не очень красивый


text:
Q: Proof for the Mass gap of sine-Gordon action with $g \cos(\beta \Phi)$ This is the sine-Gordon action:
$$
\frac{1}{4\pi} \int_{ \mathcal{M}^2} dt \; dx \; k\, \partial_t \Phi \partial_x \Phi - v \,\partial_x \Phi  \partial_x \Phi
+   g \cos(\beta_{}^{} \cdot\Phi_{})
$$
Here $\mathcal{M}^2$ is a 1+1 dimensional spacetime manifold, where 1D space is a $S^1$ circle of length $L$.
At $g=0$ : it is a chiral boson theory with zero mass, gapless scalar boson $\Phi$.
At large $g$ :  It seems to be well-known that at large coupling $g$ of the sine-Gordon equation, the scalar boson $\Phi$ will have a mass gap.

Q1: What is the original Ref which states and proves this statement about the nonzero (or large) mass gap for large $g$?

-

Q2: What does the mass gap $m$ scale like in terms of other quantities (like $L$, $g$, etc)?

-
NOTE: I find S Coleman has discussion in
(1)"Aspects of Symmetry: Selected Erice Lectures" by Sidney Coleman
and this paper
(2)Quantum sine-Gordon equation as the massive Thirring model -
Phys. Rev. D 11, 2088 by Sidney Coleman
But I am not convinced that Coleman shows it explicitly. I read these, but could someone point out explicitly and explain it, how does he(or someone else) rigorously prove this mass gap?
Here Eq.(17) of this reference does a quadratic expansion to show the mass gap $m \simeq \sqrt{\Delta^2+\#(\frac{g}{L})^2}$ with $\Delta \simeq \sqrt{ \# g k^2 v}/(\# k)$, perhaps there are even more mathematical rigorous way to prove the mass gap with a full cosine term?


text:
Q: Do you think that we as developers are worried about languages/tools than problem at hand? I am a .NET developer now and have come from Foxpro/VB6/COM background.
Over the time, I think we have changed to worry too much about languages/tools to do the work. If you look at what a developer in the .NET space would use, the list is ever growing.
More so, the tools itself are so complex that - days are gone where you would find a solution by yourself.
All of us has our dear friend Google (put your favorite search engine here) to rescue.
How/When can we expect to raise the abstraction so that we don't have to worry too much about the complexity with the number of tools and instead focus on problem at hand?
(Look at the number of tools a .NET developer would use. Yes, there are questions on it on Stack Overflow).
How many of us can really fix some issue without looking it up?
I am not saying that looking up is bad. But it wasn't the case some time back.
Your thoughts are appreciated.
There is no right/wrong answer for this. I am encouraging views of smart people here.
If you think the question is flawed - please delete it :)

A: I think it's a good question, but possibly with a rose-tinted look at the past. There have always been issues with APIs not working the way they're expected to etc. The internet certainly makes it a lot easier to find other people who've had the same problem, but I don't think it's any harder to find the solution yourself than it was before.
I would agree that there's an ever-increasing number of technologies that you have to learn in order to keep up. Again, "it was ever thus" to some extent, but in the in the last few years it seems to me to have become a lot more serious an issue. For instance, I don't believe many people have the time to achieve a "reasonable to good" understanding of all of even the main .NET peripheral APIs (by which I mean the ones outside the core: ASP.NET, WinForms, WPF, WCF, WF, ASP.NET MVC, LINQ to SQL, Entity Framework etc). You either have to specialise, or learn in a "just-in-time" fashion, pretty much always working with unfamiliar APIs. Back in the days of .NET 1 and 2, there were few enough APIs to make it feasible to have a fairly good grasp of everything. (I didn't personally have that knowledge - my WinForms and ASP.NET knowledge is pretty minimal - but others seemed to.)
Having said all of that, I wouldn't really want to put the genie back in the bottle even if I could - things like LINQ and WPF are just too good to worry overly about how long they take to learn.

A: New Ideas -> New Tools -> New Ideas
Evolution of CS is as simple as that.

A: Projects need people to specialize in different fields in order to share knowledge burden. Like if you have an architect, he is more experienced and specialized in tools and frameworks than common developers. The architect can come up with the tools for a solution. Then you have programmers that create most of the application with the help of the architect.
If I am in a project as a lonely developer, I might not have that much help from an architect and I have to find out lots of things myself. But if I had the architect to help me out, I could concentrate in programming the actual application functionality.
If we call ourselves developers and try to learn everything maybe because we hope to get ahead in our lives, then we still have to understand, that not everyone should be the architect. We need lots of programmers too. Also analysts, designers, lead developers, and administrators are needed.

A: Sometimes I spend more time working around a problem in a framework that I could have been able to write my own class that does the exact same thing in less time than it took to solve the framework-problem.
But I still think that the frameworks are needed, there is no way you can learn and create all these technologies yourself. Compare it to renovating your kitchen, 200 years ago you would do it all by yourself, 100 years ago you would call a carpenter, today you call a carpenter, a plumber, a electritian and maybe even a designer. Nobody can know how to do all these things properly all by himself/herself.


text:
Q: asset_path returns wrong path for folder I have .swf files under vendor/assets/images/swf/. I need the asset path of that folder.
But this (.js.coffee.erb)
#= soundmanager2

$ ->
  soundManager.setup
    url: '<%= asset_path "swf/" %>'

is rendering this (.js):
(function() {
  var $ = jQuery;
  $(function() {
    return soundManager.setup({
      url: '/swf/'
    });
  });
}).call(this);

I am using rails 4.0.0.rc1. I am on development mode. The path /assets/swf/soundmanager2.swf returns 200, while /swf/soundmanager2.swf returns 404. The helper image_path returns /images/swf/, but /images/swf/soundmanager2.swf also returns 404.

A: It is not worth the trouble, because you would have to disable digest to get the name of the files right. So the solution is to fix the library. In the case of Sound Manager 2, I did this:
Some CoffeeScript that I require:
#= require soundmanager2

jQuery ->
  soundManager.swfNames =
    "/soundmanager2.swf":              "<%= asset_path('swf/soundmanager2.swf') %>"
    "/soundmanager2_debug.swf":        "<%= asset_path('swf/soundmanager2_debug.swf') %>"
    "/soundmanager2_flash9.swf":       "<%= asset_path('swf/soundmanager2_flash9.swf') %>"
    "/soundmanager2_flash9_debug.swf": "<%= asset_path('swf/soundmanager2_flash9_debug.swf') %>"

  soundManager.setup
    debugMode: <% if Rails.env.development? %>true<% else %>false<% end %>
    url: '/'

In my copy of soundmanager2.js (V2.97a.20130512), inside the definition of normalizeMovieURL:
url = ...                // After url is set

url = sm2.swfNames[url]; // Workaround

A: on rails 4 all the asset helpers (image_path, asset_path and the likes) appear to only return a config.assets.prefix-prefixed path if the asset you're accessing is actually resolvable by sprockets.
put simply: it must exist in you asset path on the disk after precompilation.
therefore, asset_path('swf/') will not work since it is a directory and not a file.
also, i experienced the following: rails < 4 (sprockets, rather) copied original images (and thus swf files) and created a digested version of that same file. because of this soundmanager was still able to find the non-digested swf files even though i have config.assets.digest = true.
with rails 4, these original images are not copied anymore because they changed some precompile internals which leads soundmanager to throw up if it wants to fallback to flash.
to properly fix this soundmanager needs to be patched, like michelpm proposes.
for soundmanager-rails i started working on a fix including a proper patch for soundmanager which you can find over on github.


text:
Q: Get all values from web service API without iterating through every item I've build a small C# application that has been able to get all values I wanted, specifically this is about products, from a webservice API. I have just switched to a larger database (via webservice API access) and now finding out that I get blocked while iterating through the requests, since I've gone from 25 products to 1000 products.
Well, honestly I'm guessing this is the case, but the database is the same built in both my trails, so what has changed is just the amount.
Might mention that I'm new to the whole conect of using webservices/API:s.
I have not tried anything specific yet. I guess one could use a timer between the requests, to have the server rest in between.
Currently I'm iterating through the list of all products, getting their URI, then each URI to get the specifics about each product.
In the best of worlds, I would like to either find a solution whichs allows me to make the numer of reqests lesser than what it is today, or to find a way to let the service rest from making requests. I.e. compare to SQL SELECT * FROM dbTable, make one request, use it
Anyone have any good suggestions. Thanks :)
Thanks to Jeremy, I understand that my backgroundinfo was incomplete. My programs purpose is to fetch all the data from a webshop (products) and distribute them to other systems. So this process of iterating through them will happen ever so often, to detect changes made to the products.


text:
Q: Strategies to map attributes from multiple dimension tables I'm trying to tackle a requirement in AAS (Azure Analysis Service) tabular model.
In the underlying data model (specific to a particular application), I've a Sales Fact table which joins with multiple dimension tables (lets call these application specific dimension tables) using usual PK-FK relationships.

*

*These application specific dimension are frozen for any changes in
DWH, at the end of reporting month-year and hence can be considered
to have snapshots for all reporting month-years.

*Each of these dimension tables has a corresponding "enterprise"
version which is a Type 2 dimension table. That is, for a dimension
such as Product, the enterprise version of the stores the history of
changes for dimension attributes with usual fields such as valid-from
date (start of the month-year), valid to-date (end of the month date)
and latest indicator ('Y' value for the latest version of a specific
reporting month-year) . An new attribute value means a new Product
FK.

Both versions of these dimension tables and the Sales fact would be part of the AAS tabular model.
Now, as part of the reporting requirement I need to build a report (over this tabular model) running for a particular reporting month-year and show Sales data along with specific dimension attribute for the month-year.
Additionally, the report needs to show the data of these dimension attributes from the "enterprise version" of the dimension tables as well, with the latest values (Latest indicator='Y').
For example
Considering just one set of dimension tables
Product-App (Product Name, Product Group, Product PK .... so on)
Product-Enterpise (Product Name, Product Group, Valid-From, Valid-To, Latest Indicator ... so on)
and the Sales Fact :-
**if the user is running the report for Nov-2021 and running this in Jan-2022, the report needs to show Nov Sales data with

*

*Product attributes from Product-App and

*Latest values of the Product attributes from Product-Enterprise
That is; for point 2 requirement, the tabular model needs to provide a way for the user to bring the latest values of the Product dimension attributes from Product-Enterprise.**

My understanding is: such capability would mean that to bring the latest values of specific dimension attribute in this scenario/data model, a calculated column or measure approach would need to be taken. Either a calculated column: to map and get the latest values of dim attributes in application-specific dimension or a measure. These calculated columns and measure would then can be consumed from the model for reporting.
I'm looking to any pointers if this is the best approach or are there any alternate approaches can be taken to best address such a requirement.
Thanks!


text:
Q: Chrome Driver Cannot Get Cookies? I'm using selenium with the chrome driver to attempt to get some cookies from google my code:
import json
from selenium import webdriver
import time

taskID = input("Choose task: ")

driver = webdriver.Chrome("chromedriver.exe")
driver.get("https://accounts.google.com/ServiceLogin?service=accountsettings&passive=1209600&osid=1&continue=https://myaccount.google.com/intro&followup=https://myaccount.google.com/intro")
while "sign" in driver.current_url:
    continue
driver.quit()
gcooks = driver.get_cookies()
with open('cookies'+str(taskID)+'.json', 'w') as outfile:
    json.dump(gcooks, outfile,indent=4)

However it returns this error:
Traceback (most recent call last):
  File "cookieinjector.py", line 12, in <module>
    gcooks = driver.get_cookies()
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 825, in get_cookies
    return self.execute(Command.GET_ALL_COOKIES)['value']
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 310, in execute
    response = self.command_executor.execute(driver_command, params)
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 466, in execute
    return self._request(command_info[0], url, body=data)
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 490, in _request
    resp = self._conn.getresponse()
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 1331, in getresponse
    response.begin()
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 297, in begin
    version, status, reason = self._read_status()
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 258, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "C:\Users\ninja_000\AppData\Local\Programs\Python\Python36\lib\socket.py", line 586, in readinto
    return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Help is really appreciated

A: Something to do with the chromedriver being broken on the version I'm using, Firefox works a lot better

A: some cookies can not retrieve Selenium. I assume that this is HTTPonly cookies. You can solve the problem by retrieving and decrypting the cookies from the "/Default/Cookies" file via sqlite3. So far I have only found a way to do this for Linux and Windows. It works with Google Chrome and Chromium.
import sqlite3
import sys
from os import getenv, path
import os
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
import keyring

def get_cookies(url, cookiesfile):

    def chrome_decrypt(encrypted_value, key=None):
        dec = AES.new(key, AES.MODE_CBC, IV=iv).decrypt(encrypted_value[3:])
        decrypted = dec[:-dec[-1]].decode('utf8')
        return decrypted

    cookies = []
    if sys.platform == 'win32':
        import win32crypt
        conn = sqlite3.connect(cookiesfile)
        cursor = conn.cursor()
        cursor.execute(
            'SELECT name, value, encrypted_value FROM cookies WHERE host_key == "' + url + '"')
        for name, value, encrypted_value in cursor.fetchall():
            if value or (encrypted_value[:3] == b'v10'):
                cookies.append((name, value))
            else:
                decrypted_value = win32crypt.CryptUnprotectData(
                    encrypted_value, None, None, None, 0)[1].decode('utf-8') or 'ERROR'
                cookies.append((name, decrypted_value))

    elif sys.platform == 'linux':
        my_pass = 'peanuts'.encode('utf8')
        iterations = 1
        key = PBKDF2(my_pass, salt, length, iterations)
        conn = sqlite3.connect(cookiesfile)
        cursor = conn.cursor()
        cursor.execute(
            'SELECT name, value, encrypted_value FROM cookies WHERE host_key == "' + url + '"')
        for name, value, encrypted_value in cursor.fetchall():
            decrypted_tuple = (name, chrome_decrypt(encrypted_value, key=key))
            cookies.append(decrypted_tuple)
    else:
        print('This tool is only supported by linux and Mac')

    conn.close()
    return cookies

if __name__ == '__main__':
    pass
else:
    salt = b'saltysalt'
    iv = b' ' * 16
    length = 16

#get_cookies('YOUR URL FROM THE COOKIES', 'YOUR PATH TO THE "/Default/Cookies" DATA')


text:
Q: Calculator for Addition 3 private double data members with three public properties Calculator Version 1
Create a Console project.
Rename "Program.cs" to "CalculatorRun.cs"
Add class "Calculator.cs"
- 3 private double data members with three public properties
- firstOperand, FirstOperand;
- secondOperand, SecondOperand;
- result, Result;

*

*1 public method Addition()

*do addition in this method, Result = FirstOperand + SecondOperand;

In "CalculatorRun.cs", have users to enter values for firstOperand and secondOperand,
show addtion result.
I have worked on this for hours and it makes no sense still. My code is useless. Does anyone have input?
This is what I have:
namespace CalculatorRun
{
    class Calculator
    {
        static void Main(string[] args)
        {
            decimal FirstOperand, SecondOperand, Result, result;
            Console.Write("Addition Calculation");
            Console.Write("      \n\n");
            Console.Write("   Enter first operand:       ");
            FirstOperand = Convert.ToDecimal(Console.ReadLine());
            Console.Write("   Enter second operand:      ");
            SecondOperand = Convert.ToDecimal(Console.ReadLine());
            Console.Write("-------------------------\n\n");
            Result = FirstOperand + SecondOperand;
            result = Convert.ToDecimal(Result);
            Console.WriteLine("Addition Result: {0}", string.Format("{0}", result));
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

But it needs to be more like this (of course using the directions at the top). But when I have tried it, I can't get it to work. :
    using System;
namespace Calculator
{
    class Program
    {
        public static void Main(string[] args)
        {

        }//<-----------

        public int number01;
        public int number02;
        public int Number03
        {
            get
            {
                return number02 / number01;
            }
        }//<----------

        class Program1 : Program
        {

            public void DivideFinal()//<---- void not int
            {
                Console.Write("Enter a number to be divided: ");
                Console.ReadKey();
                number01 = Convert.ToInt32(Console.ReadKey());
                Console.WriteLine("Enter another number to be divided");
                number02 = Convert.ToInt32(Console.ReadKey());
                Console.WriteLine("The result is: " + Number03);
                Console.ReadKey();
            }
        }

    }
}

A: This will do it for you. Explanation in comments:
using System;

namespace ConsoleApplication1 {
    class Program {

        static void Main( string[] args ) {
            Calculator calculator = new Calculator();

            Console.Write( "   Enter first operand:       " );

            calculator.FirstOperand = Convert.ToDouble( Console.ReadLine() ); //get the first

            Console.Write( "   Enter first operand:       " );

            calculator.SecondOperand = Convert.ToDouble( Console.ReadLine() ); //get the second

            calculator.Addition(); //Do addition

            Console.WriteLine( "Addition Result: {0}", calculator.Result ); //show result

            Console.WriteLine( "Press any key to continue....." );
            Console.ReadLine();
        }

    }

    class Calculator {
        private double firstOperand, secondOperand, result; //double data members

        //3 public properties
        public double FirstOperand {
            get { return firstOperand; }
            set { firstOperand = value; }
        }

        public double SecondOperand {
            get { return secondOperand; }
            set { secondOperand = value; }
        }

        public double Result {
            get { return result; }
            set { result = value; }
        }

        //1 public method Addition()
        public double Addition() {
            return result = firstOperand + secondOperand;
        }

    }

}


text:
Q: Vue: Bind Change event to dynamically inserted content I have a Vue app which get an html from API that contains some code like
 <input type="text" class="input-1"/>

Calling the API with axios via a promise, it is inserted into the dom something like:

How can I bind on change events to the children inputs with the .input-1 class?

A: You could query the container for those inputs, and add an event handler to each:

*

*Apply a template ref (named container) on the container div:

*Add a watcher on content that queries the container (via this.$refs.container.querySelectorAll()) for <input class="input-1">, and adds an event handler to each input. Note that the handler needs to wait until $nextTick(), after which the v-html directive would have had a chance to update.
export default {
  watch: {
    content: {
      async handler(content) {
        // wait til v-html directives takes effect
        await this.$nextTick()

        this.$refs.container
          .querySelectorAll('.input-1')
          .forEach((input) => input.addEventListener('change', this.onInputChange))
      },
      immediate: true,
    },
  },
  methods: {
    onInputChange(e) {
      console.log('input change')
    },
  },
}

demo

A: There are two approaches that rise to the top for me:

*

*From inside a vue app, use vanilla javascript to append those nodes to the DOM and then query for their inputs and add event handlers. Since you're inside the Vue app you can write the handlers to interact with Vue components. Or you could probably do something fancy with vuex getters returning those elements (if they're still attached to the document).

*Use Vue.compile to create render functions from the html or add an async omponent. However, this will only work if you have a robust way to add @change="doSomething" to the template. For this reason, I'd probably should go with option 1) unless you control the source of the templates.

Whichever you do, keep malicious injections in mind.

const someHtml = '
<input type="text" class="input-1"/>
'

var app = new Vue({
  el: '#app',
  mounted() {
    const dynamicContent = document.createElement('div');
    dynamicContent.innerHTML = someHtml;
    dynamicContent.querySelector('input').addEventListener('change',
      e => this.inputValue = e.target.value);
    this.$refs.container.appendChild(dynamicContent);
  },
  data() {
    return {
      name: 'Vue',
      inputValue: ''
    }
  }
})

type something below then click this text

The user entered: {{inputValue}}


text:
Q: How to convert multiple rows into a single stacked column in excel? I'm very new to using excel and have been browsing the answers for similar questions. I have only used the data.table package to convert it into a column as well as a complicated excel formula:
=INDEX( $RANGE$ ,INT((ROW()-ROW( $CELL$ ))/COLUMNS( $RANGE$ ))+1,MOD(ROW()-ROW( $CELL$ ),COLUMNS( $RANGE$ ))+1).
I was experiencing errors using this excel formula (it told me I needed an extra comma somewhere).
This is how my data looks now:

This is how I want it to look (so I can use it in R):

I have multiple rows of data that need to be converted into one stacked column. Is there a formula in excel or R that can do this?


text:
Q: How to update ngModel when updating ui-ace editor's value using setValue? I'm using ui-ace directive to implement ace editor in an angular application.
I have a button that I use to dynamically add data to an ace editor.
Now when a user clicks on the button, I use setValue method to update the value of ace editor but the value doesn't reflect in ngModel. What is the best way to do so?
Here's how I set the value...
$scope.addUserInput = function (input) {
    var currentValue = $scope.aceEditor.getValue();

    if(SqlTokenizer.isIdentifier(input.name)){
        $scope.aceEditor.setValue(currentValue + ":" + input.name, false);
    } else{
        $scope.aceEditor.setValue(currentValue + ':"'+ input.name +'"', false);
    }
};

I've created plunkr for the same here http://plnkr.co/edit/ez0cwr6PWhALpqu3wjZT?p=preview

A: updated plnkr : http://plnkr.co/edit/GCnDPQnC7xoC6xqdOeqd
The problem is ur adding/updating the text in your editor dont need to do that.
just need to update your scope variable it will reflect in all the bind places.
instead of this
//$scope.editor.setValue($scope.editor.getValue() + new Date().getTime());

Do this
$scope.text = $scope.text + new Date().getTime();


text:
Q: When were control flow features added to CoreImage? I remember in years prior (under the Unsupported Items header) that I could not use if for while when writing CoreImage kernels, but now I can (under the Control Flow header).
What version of macOS and iOS first allow this language style?
Note that I do see the different copyright years, but that's not definitive as to what version of the OS it correlates to.

A: I was watching the 2015 WWDC videos and found that it was noted as a new feature for that convention. Seeing as OS X 10.11 was released 30 September 2015, it would be logical that that would be the first OS release that supported this feature.


text:
Q: Null context in onResponse callback method retrofit android I have a DialogFragment. When i click the OK button, i execute a retrofit call to my api like this
 @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                int code = response.code();
                if (code == 200) {
                    LoginResponse lr = response.body();
                    if (lr.getError()) {
                        Utils.showToast(getActivity(), "Error! Los datos son incorrectos.");
                    } else {
                        startActivity(new Intent(getActivity(), ConfigGeneralActivity.class));
                    }
                } else {
                    Toast.makeText(getActivity(), "Error: " + String.valueOf(code), Toast.LENGTH_LONG).show();
                }

            }

at this part of the code, getActivity() is null.
Another option is to pass the context from the oncreatedialog to this callback, but when i do this, i got the error that says activity is not attached to fragment.
I know i can implement Otto but it's too complex for what i want to do. I just want to start a new activity from a retrofit callback inside a DialogFragment.
Any ideas? Thanks!

A: You need to runOnUiThread to get the Context inside OnResponse Callback
Like:
@Override
public void onResponse(Call call, Response response) throws IOException {
    if (response.isSuccessful()) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //your code
            }
        });
    }
}


text:
Q: Excel macro that suspends Application.Calculation breaks Save As menu I am experiencing baffling behavior with an Excel macro running in Office 365 that I have reduced to the following block.  The Excel process becomes corrupted if:

*

*Sheet1!A1:A1000 are filled with letters (just "A" is sufficient).  This is to create a sufficiently large computation load in the macro.  Too little load and it doesn't break things.

*A formula references something that will be altered by the macro.  E.g., set Sheet1!B1 formula to =ISNUMBER(E1).

*The TestMacro() below is invoked from within the VBA editor (using F5).

(Omit any of these test conditions and the behavior described below does not occur.  However with more complex sheets it occurs much more easily, including not requiring the macro be invoked from within the VBA editor.)
Sub TestMacro()

    On Error GoTo EH

    Dim row As Integer
    Dim col As Integer
    row = 1
    col = 5

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

    Do While Not IsEmpty(Cells(row, 1).Value)
        Cells(1, col).Value = Cells(row, 1).Value & " col"
        Cells(3, col).FormulaR1C1 = "test" & Cells(1, col).Value
        Range("E2:K2").Select
        Selection.Copy
        Cells(2, col).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False

        col = col + 8
        row = row + 1
    Loop

CleanUp:
    On Error Resume Next
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
Exit Sub

EH:
    ' Do error handling
    GoTo CleanUp
End Sub

The symptom I check to see whether the macro has messed up Excel is to go to File >> Save As and when things are not right I get a blank dialog screen like this:

Further testing shows that if I omit the two lines in TestMacro that suspend and then resume Application.Calculation then no problems arise.
I have tried putting a simple DoEvents call immediately before Exit Sub but that puts the Excel instance into a state in which the cursor perpetually flits rapidly between normal and Wait.
I suspect there is something structurally incorrect in this VBA subroutine structure, but it is tricky to reveal, and I can't begin to understand what is going wrong.


text:
Q: How to access WebElement from executeScript in RSelenium? I want to extract data from this website which has shadow-dom. I think I've managed to access the elements inside the shadow-dom using JavaScript, but I haven't figured out how to use the returned value from the JavaScript as WebElements so that I can process the data.
library(RSelenium)

rD <- rsDriver(browser="firefox", port=4547L, verbose=F)
remDr <- rD[["client"]]

remDr$navigate("https://www.transfermarkt.us")

## run script to enable dropdown list in the website. This creates a <ul> tag in the shadow-dom which lists all items in the dropdown list.
remDr$executeScript("return document.querySelector('tm-quick-select-bar').setAttribute('dropdown-visible', 'countries')")
Sys.sleep(5)

This is only the portion that contains the shadow-dom. I'm not sure if this is required, but this is where the dropdown lists is present
wrapper <- remDr$findElement(using="tag name", value="tm-quick-select-bar")

Below is the script to access the dropdown list
script <- 'return document.querySelector("#main > header > div.quick-select-wrapper > tm-quick-select-bar").shadowRoot.querySelector("div > tm-quick-select:nth-child(2) > div > div.selector-dropdown > ul");'

test <- remDr$executeScript('return document.querySelector("#main > header > div.quick-select-wrapper > tm-quick-select-bar").shadowRoot.querySelector("div > tm-quick-select:nth-child(2) > div > div.selector-dropdown > ul");', list(wrapper))

This returns the following list.
> test
$`element-6066-11e4-a52e-4f735466cecf`
[1] "4adac8f8-2c94-4e48-b7a3-521eb961ef8c"

I have no idea how to extract the items from this. It doesn't seem like it's a WebElement. What is this list and what information does it contain? How can I extract it?
I tried this
lapply(test, function(x){
    x$getElementText()
    x[[1]]$getElementText()
})

But, it returns the errors:
Error in x$getElementText : $ operator is invalid for atomic vectors

A: Not sure if selenium can deal with shadow DOM, there is a plugin here that supposedly solves that for java.
Nevertheless, you can extract innerHTML an manage it with rvest
library(RSelenium)

rD <- rsDriver(browser="chrome", port=4547L, verbose=F, chromever="106.0.5249.21")
remDr <- rD[["client"]]

remDr$navigate("https://www.transfermarkt.us")

## run script to enable dropdown list in the website. This creates a <ul> tag in the shadow-dom which lists all items in the dropdown list.
remDr$executeScript("return document.querySelector('tm-quick-select-bar').setAttribute('dropdown-visible', 'countries')")
Sys.sleep(5)

wrapper <- remDr$findElement(using="tag name", value="tm-quick-select-bar")

script <- paste0(
  'return document.querySelector("#main > header > div.quick-select-wrapper > tm-quick-select-bar")',
  '.shadowRoot.querySelector("div > tm-quick-select:nth-child(2) > div > div.selector-dropdown > ul")'
  '.innerHTML;')

test <- remDr$executeScript(script)

html <- rvest::read_html(test[[1]])

rvest::html_text(html)

# " Afghanistan Albania Algeria American Samoa American .....

A: I don't know R, but for example:
let shadowEls = [...document.querySelectorAll('*')].filter(el => el.shadowRoot)
return shadowEls[0].shadowRoot.innerHTML

That should be enough to figure this bit out.


text:
Q: Cómo guardar en un Array resultados de un consulta en MySQL? tengo el siguiente query en MySQL.
$select =" SELECT concat(colonia, ', ', calle, ' ', y_calle, ' ', no_exterior, ' ', no_interior) as direccion FROM scpd_incidencia WHERE colonia='EXTREMADURA INSURGENTES' ";

El cual arroja resultados:

Quiero saber si los resultados del concat direccion se pueden guardar en un array, he hecho lo siguiente:
$dir = array();
while ($row = @mysqli_fetch_array($result)) {
   $dir[] = $row['direccion'];
}
echo $dir[0];

pero eso solo me arroja un resultado, lo que me guataria es que se mostrara asi:
$dir=['direccion1','direccion2', 'direccion3', etc...]

Hay manera de lograrlo??

A: El problema con lo que estas haciendo es que estas guardando en la misma posición de tu arreglo, así deberia de funcionar:
$dir = array();
$cont = 0;
while ($row = @mysqli_fetch_array($result)) {
   $dir[$cont] = $row['direccion'];
   $cont++;
}

Ahora ya tienes todo en tu arreglo $dir y para acceder a cada elemento tienes que recorrer tu arreglo.
foreach ($dir as $valor) {
    echo $valor;
}

A: Una solución podría ser:
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row);

print_r($set);

mysqli-result


text:
Q: How to change the color of a line of text in quill.js? I have an editor like this
var container = document.getElementById('editor');
var quill = new Quill(container);
quill.setText('Hello\nWorld!\n');

Im trying to change the color of the first line to blue.
When I use the formatLine method like this
quill.formatLine(0, 1, {
    color: 'rgb(0, 255, 0)'
});

Nothing happens
When I change it to formatText I see a color change (only a single character though)
quill.formatText(0, 1, {
    color: 'rgb(0, 255, 0)'
});

Im guessing that color changes fall under inline formatting and are ignored
Formats all lines in given range, returning a Delta representing the change. See formats for a list of available formats. Has no effect when called with inline formats.

Does anyone know how I would change the color of a specific line? Is it possible to get the start and end character indices of a specific line?


text:
Q: bsDatepicker is not setting default time in angular I am using bsDatepicker library to get date and time, but if user clicks on date first instead of selecting time then the date picker picks the time automatically when the component was initialized. Is there any solution that I can set default time to it like 12:00 when user did not select time??
the HTML code is ====>>>
<input placeholder="Datepicker" name="endDate" required class="form-control" [bsConfig]="{withTimepicker: true, dateInputFormat: 'MMMM Do YYYY, H:mm:ss',   showWeekNumbers:false}" bsDatepicker ngModel>

A: Have you tried turning initCurrentTime false ?


text:
Q: Why won't PySys_SetPath() work? I'm using the Python C API, and numerous times now I've tried using PySys_SetPath() to redirect the interpreter to a path where I've stored all of my scripts. Yet, every time I try it, I get the following error:
Unhandled exception at 0x1e028482 in app.exe: 0xC0000005: Access violation reading location 0x00000004.
I use it in the following syntax: PySys_SetPath("/Python/"). Is that incorrect? Why does it keep crashing? Thanks in advance.

A: Unless your python directory is located in your systems root folder, the path is named wrong. It should be
PySys_SetPath("Python");

assuming that the python folder is located in the current working directory.

A: I had the same problem but when I fixed all the \ to / and added a . at the beginning of the path it worked  ie. the path should look sth like that PySys_SetPath("./Python/") or PySys_SetPath("C:/full/path/Python/")


text:
Q: Copy join-query from database to another datable Previously, I am using  dblink to achieve the mission but it involved copy one query only. What if I have doing the join query (4 tables) in one database, then i want to copy the data output into another database.Anyone know about it ?
select
    a.sysname, a.ip, b.host_id, b.resource_name, b.resource_id
    , c.metric_id, d.metric_name,  c.value, c.resource_id
    , to_timestamp(c.date_id)as datetime
from inv.el a
inner join inv.if b on a.host_id = b.host_id
inner join me.me_cr c on b.resource_id = c.resource_id
inner join inv.me d on c.metric_id = d.metric_id
where date_id = (
    select max(date_id) from me.me_cr
)

A: you can try using postgres_fdw on Release > 9.6 as it

... now supports remote joins...

https://www.postgresql.org/docs/9.6/static/release-9-6.html


text:
Q: Random number generator upto 2 decimal places using Python How do I generate random numbers upto 2 decimal places? I am using random.rand but it goes upto 8 decimal places.
import numpy as np
Pe = np.random.rand(5,5)

The current output is
array([[0.53084542, 0.39162757, 0.08501123, 0.00391447, 0.83859363],
       [0.16194795, 0.06216611, 0.96712453, 0.01319061, 0.19207092],
       [0.90371594, 0.80225188, 0.87797408, 0.71086006, 0.2258896 ],
       [0.33869247, 0.16054   , 0.85156147, 0.25426089, 0.87377881],
       [0.79342404, 0.08150748, 0.62888488, 0.43499343, 0.98077841]])

A: I see two options:
generate floats and round to the wanted decimal places:
D = 2
np.random.rand(5,5).round(D)

or use integers and divide:
D = 2
np.random.randint(10**D, size=(5,5))/10**D

example output:
array([[0.21, 0.6 , 0.75, 0.64, 0.6 ],
       [0.3 , 0.73, 0.95, 0.43, 0.78],
       [0.06, 0.84, 0.19, 0.4 , 0.3 ],
       [0.08, 0.9 , 0.37, 0.53, 0.49],
       [0.13, 0.21, 0.08, 0.51, 0.26]])


text:
Q: mapply doesn't read the list items individually I think I need the mapply rather than the lapply function in what I was trying to do.
This is the function that I have in mind - not working yet.
genctrlvars <- function(varorder, ...) {
for (j in 1:varorder)
    {
    #   print(nameofvar)
    #   print(varorder)
    # print(str(testdf))

        testdf[, (ncol(testdf) + 1)] <- -1
        testdf[, ncol(testdf)] <- testdf[, nameofvar]^j
        existingname <- names(testdf[ncol(testdf)])
        newname <- paste0(nameofvar, "_", j)
        names(testdf)[names(testdf) == existingname] <- newname
        # print(str(testdf))

    }
    return(testdf)
}

Its called like this:
mymapplytest <- mapply(genctrlvars, varorder, nameofvar, MoreArgs = list(testdf))

The idea being that the function is called for each of element of the 2 lists viz varorder and nameofvar - both of these lists have 2 elements. The data frame is the same for both of the lists.
So, why doesn't it run? What am I doing wrong?
The details of all of the parameters are shown below:
"varorder" is a list of 2 'varorder' values i.e. c(1, 1)
"nameofvar" is a list of the names of 2 the variables i.e. c("Trend", "Temp")
"testdf" is a data frame - structure is shown below :-

varorder <- list(1, 1)
nameofvar <- as.list(gsub("order", "", c("Trendorder", "Temporder")))
testdf <- list(controlvarsdfobjects[[1]])

str(testdf)
List of 1
 $ :'data.frame':   44640 obs. of  6 variables:
  ..$ Trend       : num [1:44640] 1 1 1 1 1 1 1 1 1 1 ...
  ..$ Temp        : num [1:44640] NA 22.8 23 22.8 22.7 22.4 21.3 20.7 20.4 20 ...
  ..$ Wind        : num [1:44640] NA 8 10 10 9 5 2 0 0 0 ...
  ..$ Humidity    : num [1:44640] NA 77 77 77 78 79 82 85 87 88 ...
  ..$ Sunhrs      : num [1:44640] NA 8.82 8.82 8.82 8.82 8.82 8.82 8.82 8.82 8.82 ...
  ..$ Temp_Recency: num [1:44640] NA NA NA NA NA NA NA NA NA NA ...

This is the error I get when run with print statements active:
    mymapplytest <- mapply(genctrlvars, varorder, nameofvar, MoreArgs = list(testdf))
    [[1]]
    [1] "Trend"

    [[2]]
    [1] "Temp"

    [1] 1
T    List of 1
     $ :'data.frame':   44640 obs. of  6 variables:
      ..$ Trend       : num [1:44640] 1 1 1 1 1 1 1 1 1 1 ...
      ..$ Temp        : num [1:44640] NA 22.8 23 22.8 22.7 22.4 21.3 20.7 20.4 20 ...
      ..$ Wind        : num [1:44640] NA 8 10 10 9 5 2 0 0 0 ...
      ..$ Humidity    : num [1:44640] NA 77 77 77 78 79 82 85 87 88 ...
      ..$ Sunhrs      : num [1:44640] NA 8.82 8.82 8.82 8.82 8.82 8.82 8.82 8.82 8.82 ...
      ..$ Temp_Recency: num [1:44640] NA NA NA NA NA NA NA NA NA NA ...
    NULL
    Error in testdf[, (ncol(testdf) + 1)] <- -1 :
      incorrect number of subscripts on matrix

The concern I have is that why does it print both the list item of Trend and Temp for the first element run - shouldn't it only be looking at the first element viz Trend?
Edit
I did it as a loop and it works but I would prefer to use the mapply function. This is the working code for looped version. If anyone can help me transform it in to the mapply form that would be highly appreciated.
orderlist <- list(trendorder, temporder, windorder, humidityorder, sunhrsorder, temp_recencyorder)  #pvorder not included yet
names(orderlist) <- list("Trendorder", "Temporder", "Windorder", "Humidityorder", "Sunhrsorder", "Temp_Recencyorder")   #"PVvorder" not included yet
orderlistnames <- as.list(names(orderlist))

for (j in 1:length(orderlist))
    {thisvarname <- gsub("order", "", orderlistnames[[j]])
    thisvarorder <- orderlist[[j]]
    if (j == 1)
        {thisvarorigdfobjects <- testdf
        }
    for (k in 0:thisvarorder)
        {if (k == 0)
            {if (thisvarorder == 0)
                {thisvarorigdfobjects[, (ncol(thisvarorigdfobjects) + 1)] <- NA
                existingname <- names(thisvarorigdfobjects[ncol(thisvarorigdfobjects)])
                newname <- paste0(thisvarname, "_", k)
                names(thisvarorigdfobjects)[names(thisvarorigdfobjects) == existingname] <- newname
                }
            else
                {k <- k + 1
                }
            }
        else
            {thisvarorigdfobjects[, (ncol(thisvarorigdfobjects) + 1)] <- -1
            thisvarorigdfobjects[, ncol(thisvarorigdfobjects)] <- thisvarorigdfobjects[, thisvarname]^k
            existingname <- names(thisvarorigdfobjects[ncol(thisvarorigdfobjects)])
            newname <- paste0(thisvarname, "_", k)
            names(thisvarorigdfobjects)[names(thisvarorigdfobjects) == existingname] <- newname
            }
        }
    }

This is how the final output from the looped version looks like:
head(thisvarorigdfobjects)
Trend_1 Temp_1 Temp_2 Wind_0 Humidity_0 Sunhrs_0 Temp_Recency_1
1       1     NA     NA     NA         NA       NA             NA
2       1   22.8 519.84     NA         NA       NA             NA
3       1   23.0 529.00     NA         NA       NA             NA
4       1   22.8 519.84     NA         NA       NA             NA
5       1   22.7 515.29     NA         NA       NA             NA
6       1   22.4 501.76     NA         NA       NA             NA


text:
Q: Call C++(C) from D language How to call C++ function from D program?
I still can't understand how to do it.
What commands do I need to execute?
I use dmd in Fedora.

A: Simplest example I can think of, if you're calling C functions:
$ cat a.c
int f(int a, int b){
    return a + b + 42;
}
$ cat a.di
extern (C):
int f(int, int);
$ cat b.d
import std.stdio;
import a;
void main(){
    writeln( f( 100, 1000) );
}
$ gcc -c a.c
$ dmd b.d a.o
$ ./b
1142
$

If you're using shared objects, you could so something like:
$ cat sdltest.di
module sdltest;

extern (C):

struct SDL_version{
    ubyte major;
    ubyte minor;
    ubyte patch;
}

SDL_version * SDL_Linked_Version();

$ cat a.d
import std.stdio;
import sdltest;

void main(){
    SDL_version *ver = SDL_Linked_Version();
    writefln("%d.%d.%d", ver.major, ver.minor, ver.patch);
}

$ dmd a.d -L-lSDL
$ ./a
1.2.14
$

In this example, I linked with an SDL function. The -L argument to dmd allows you to pass arguments to ld, in this case -lSDL to link with SDL.
D interface files (.di) are described here.
You should also take a look at htod.


text:
Q: Amazon EC2 permissions and a simple web server I just started experiment with EC2 tonight, and got a server running locally.  I know it works locally because when I curl http://localhost:8080/hello it outputs hello.
I want to access this from the outside world.  I modified my permissions in my security group to allow 8080 access, and then typed in "curl http://ec2-123-45-67-891.compute-1.amazonaws.com:8080/hello" into my local terminal.  I got the response "curl: (7) couldn't connect to host".
Do I need to do something differently?  (Obviously yes, but what?)

A: Have you bound your server only to localhost?  If so, you'll only be able to connect from localhost.
Check the netstat output for your process with something like:
sudo netstat -ltnp | grep your_server_process

Look for whether your server process is bound to 127.0.0.1:8080 or 0.0.0.0:8080.  If the former, then you're only bound to localhost and you need to reconfigure it.

A: I met the same issue. Try use 0.0.0.0 instead of 127.0.0.1.

A: You allowed access on 8080, but in your localhost example, it's running on port 80.


text:
Q: Primefaces taking random form ID What is the way to refresh page in primefaces?
I have tried

Add Legend

View Legend

The third one would generate error in page with datatable. The error I get:
Cannot find component with expression "pnlform" referenced from "j_idt22:legendviewdatatable:0:editLink". I would like to refresh the form when I hit edit and open editpanel. And I would like to refresh only datatable when I hit delete.
The full html:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Legend</title>
    </h:head>
    <h:body>
        <ui:composition template="/generalTemplate.xhtml">
            <ui:define name="title">Legend </ui:define>
            <ui:define name="content" >
                <f:view>
                    <h:form id="legendform" prependId="false" >

                            <f:facet name="header">

Add Legend

View Legend

                            </f:facet>

                                <h:panelGrid columns="2"  >
                                    <h:outputLabel value="Legend Name" for="legendname" />
                                    <h:inputText id="legendname" value="#{legendcontroller.legendType.legendname}" title="Legendname" required="true" requiredMessage="The Legendname field is required."/>
                                    <h:outputLabel value="Legend Description" for="legendDesc" />
                                    <h:inputText id="legendDesc" value="#{legendcontroller.legendType.legendDesc}" title="LegendDesc" />
                                    <h:outputLabel value="Legend For" for="legendfor" />
                                    <h:inputText id="legendfor" value="#{legendcontroller.legendType.legendfor}" title="Legendfor" required="true" requiredMessage="The Legendfor field is required."/>
                                </h:panelGrid>

                                        <f:facet name="header">
                                            <h:outputText value="Legend SN"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.legendSn}"/>

                                        <f:facet name="header">
                                            <h:outputText value="LegendDesc"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.legendDesc}"/>

                                        <f:facet name="header">
                                            <h:outputText value="Lower Range"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.lowerrange}"/>

                                        <f:facet name="header">
                                            <h:outputText value="Upper Range"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.upperrange}"/>

                                        <f:facet name="header">
                                            <h:outputText value="Color"/>
                                        </f:facet>

                                        <f:facet name="header">
                                            <h:outputText value="ADD/Delete"/>
                                        </f:facet>

                                        <h:outputText value=" / "/>

                                    <f:facet name="footer">

                                    </f:facet>

                                    <f:facet name="header">
                                        <h:outputText value="Legendname"/>
                                    </f:facet>
                                    <h:outputText value="#{legendtype.legendname}"/>

                                    <f:facet name="header">
                                        <h:outputText value="LegendDesc"/>
                                    </f:facet>
                                    <h:outputText value="#{legendtype.legendDesc}"/>

                                    <f:facet name="header">
                                        <h:outputText value="Legendfor"/>
                                    </f:facet>
                                    <h:outputText value="#{legendtype.legendfor}"/>

                                    <f:facet name="header">
                                        <h:outputText value="Edit/Delete"/>
                                    </f:facet>

                                    <h:outputText value=" / "/>

                    </h:form>
                </f:view>
            </ui:define>
        </ui:composition >
    </h:body>

Finally I found that primefaces is not taking the id gave but is using random id:
<form id="j_idt12" name="j_idt12" method="post" action="/Configuration/LegendManager/LegendType.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt12" value="j_idt12">

<button id="j_idt12:j_idt15" name="j_idt12:j_idt15" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" title="Welcome" type="submit" role="button" aria-disabled="false">Home</button><button id="j_idt12:j_idt16" name="j_idt12:j_idt16" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" title="Configuration" type="submit" role="button" aria-disabled="false">Configuration</button>

<button id="j_idt12:j_idt18_button" name="j_idt12:j_idt18_button" type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" role="button" aria-disabled="false">sugandha</button>

<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="2044288989474132123:952602282947229034" autocomplete="off">
</form>

A: Since you used prependId="false", you should use update="pnlform" only, or remove prependId="false" so you will be able to keep update="yourformname:yourid" or update=":yourid".
More info :

*

*h:form

A: change your code as follow: <h:form id="legendform" prependId="true" > or without prependId attribute then reference to nested component inside this form with update=":legendform:pnlform" attribute from every where else.
in your case if you want to set prependId=false and then reference from nested components inside <datatable> in same form you should update withupdate=":pnlform".
this is because <datatable> has own NamingContainer


text:
Q: Matching one of several possible characters in a string In a bash (version 3.2.48) script I get a string that can be something like:

'XY'
  ' Y'
  'YY'
  etc

So, I have either an alphabetic character OR a space (first slot), then the relevant character (second slot). I tried some variation (without grep, sed, ...) like:

if [[ $string =~ ([[:space]]{1}|[[:alpha:]]{1})M ]]; then

and

if [[ $string =~ (\s{1}|.{1})M ]]; then

but my solutions did not always work correctly (matching correctly every combination).

A: This should work for you:
if [[ $string =~ [[:space:][:alpha:]]M ]]; then

A: if [[ ${string:1:1} == "M" ]]; then
    echo Heureka
fi

or (if you want to do it with patterns)
if [[ $string =~ ([[:space:]]|[[:alpha:]])M ]]; then
    echo Heureka
fi

or (even simpler)
if [[ $string == ?M ]]; then
    echo Heureka
fi

A: Without using regular expressions, simply pattern matching is sufficient:
if [[ $string == [[::upper:]\ ]M ]]; then
  echo match
fi

Given your example, you want [[:upper:]] rather than merely [[:alpha:]]


text:
Q: Merge multiple arrays together if not null I am building a React App and am using Async Actions to make request to outside API's and bring in data into my app. I have 4 arrays that I need to merge together. Since I am using Async Actions the default values if theres no data is null. I want to check to see if the array is not null and if it has a value then merge it with the others into a single array. Once I have all the data into a single array I am going to use the includes method to see if any of the values are present in the array. Using the spread operator I don't think is going to work here as it will fail as null is not an iterable. Is there a way to do this with reduce to check through each of the 4 separate arrays make sure the value is not null and then combine them together into one array.

A: Here is a one line solution (ES6).
At the first part, we merge all arrays, and then filter array elements - we include only "not null" values and exclude duplicates:

const arr1 = [1, null, 6, 'q'],
      arr2 = null,
      arr3 = [1, 1, null, 1],
      arr4 = ['e', 'q', 6, 1, null];

const final = []
  .concat(arr1, arr2, arr3, arr4)
  .filter((item, i, arr) => item && arr.indexOf(item) === i);

console.log(final); // Expected output: [1, 6, "q", "e"]

A: Your question leads you to the answer. :)
Essentially you are asking how to filter all non-array inputs and then combine (or concatenate) them together into a new array.
A couple of notes on the following approach:

*

*For better stability in filtering, rather than using a blacklist (not null), use a whitelist (Array.isArray) to ensure only arrays are combined.

*The spread operator can be used to then create an arguments list for a new array's concat method.

const arr1 = [1,2];
const arr2 = null;
const arr3 = [3,4];
const arr4 = [5];

const concat = (...arrays) => [].concat(...arrays.filter(Array.isArray));

console.log(concat(arr1, arr2, arr3, arr4));

For a bit of fun, if the combined array needs to be unique values (assuming simple types for values) then including a quick cast to a Set and back to an Array can make that happen:

const arr1 = [1,2];
const arr2 = null;
const arr3 = [3,4];
const arr4 = [4,5];

const concat = (...arrays) =>[].concat(...arrays.filter(Array.isArray));

const unique = (array) => [...new Set(array)];

const concated = concat(arr1, arr2, arr3, arr4);
const uniqued = unique(concated);

console.log({concated, uniqued});

A: If you assign your arrays to properties of an object  obj, you can simply iterate over the object :

const a = ["a", "1"], b = null, c = ["c", 78], d = []

const obj = { a, b, c, d }

let res = []

for(let key in obj) {
 res = res.concat(Array.isArray(obj[key]) ? obj[key] : []);
}

console.log(res)

A: var a = [1, 2, 3]
var b = null

var c = [...a||[], ...b||[]]

console.log(c)


text:
Q: как настроить php mail Cоздал на apache сервере файл mail.php
var_dump( mail("myemail@gmail.com" ,"Test","Test") );

на страницу вывелось bool(false)
и письмо не пришло как это можно исправить ?
и как понять где проблемам в настройках apache или в php
чего то не установлено из модулей ?

A: Поставьте себе sendmail а так же скачайте библиотеку для работы с почтой PHPMailer.
Потом в скрипте подключаете библиотеку и вот пример кода.
$mail = new PHPMailer;
$mail->setFrom('mailFROM@info.ru', 'Name Name'); //от кого придет письмо
$mail->addAddress('mailTO@info.ru', 'Name2 Name2');//кому оно уйдет
$mail->addAttachment('/some/files/file.jpg');  //добавить вложение, если требуется
$mail->Subject = 'TableTask'; //тема письма
$mail->msgHTML("Some text here"); //текст письма
$r = $mail->send();

A: вам нужно поставить почтовый сервер, например postfix, sendmail


text:
Q: Variable passed by 'docker run' to CMD of Dockerfile is not resolved Can anyone explain why is the environment variable passed by
docker run --rm -it -e APP_PORT=80 -p 8080:80 my_container <image-id>

to CMD in Dockerfile is not resolved in following cases:
...
ARG APP_PORT
ENV APP_PORT=${APP_PORT}
...
CMD ['gunicorn', "-b", "0.0.0.0:${APP_PORT}", "main:app"]  # DOES NOT WORK!
CMD ['gunicorn', "-b", "0.0.0.0:$APP_PORT", "main:app"]    # DOES NOT WORK!

CMD ["sh", "-c", "echo 0.0.0.0:$APP_PORT"]                 # WORKS!

CMD gunicorn -b 0.0.0.0:$APP_PORT main:app                 # WORKS!

DOES NOT WORK! means I get the error: Container log - Error: '$APP_PORT' is not a valid port number.

A: There are 2 forms of the CMD statement, like you show.
One is the exec form, which is the one that doesn't work. It's usually preferred because it doesn't start a shell first to run the command, so it uses a little less resources.
The other is the shell form, which is the one that works. The reason that it works is that you need a shell to replace environment variables in a command. The shell form starts up a shell, that then executes your command.
As you've seen in your echo example, you can also make the exec form work by running the shell manually.
You can read more about the 2 forms here: https://docs.docker.com/engine/reference/builder/#cmd
In short, the examples that don't work, don't work because there's no shell to insert the value of the environment variable in the command.


text:
Q: Emacs ido: How to show particular file endings first? I use ido-mode under Emacs 24 with the following settings:
(ido-mode 1)
(setq ido-enable-flex-matching t)
(setq ido-everywhere t)
(setq ido-use-filename-at-point 'guess)
(setq ido-use-url-at-point t)
(setq ffap-require-prefix t)

Assume you have several files with the same name but different endings in the current directory. If you change buffers via C-x b, you receive several suggestions. Can the order of these suggestions be somehow influenced?
As an example, assume you have multiple Sweave (.Rnw) files in the current directory. They are always more important than the corresponding (.tex) files which are created from them. So in most of the cases, you want to change the buffer to the .Rnw file, not the .tex file. It would therefore be nice if the .Rnw files were suggested first (in all directories where both .Rnw and .tex files with the same base name exist).

A: "If you'd like to tweak the default file sorting, like making Sweave-files appear first, tell ido which files to give a higher sort priority:"
(setq ido-file-extensions-order '(".Rnw" ".tex"))

But it works only for ido-find-file not for ido-switch-buffer. Buffers are sorted by most recent property. I don't know about functionality, which adds another sorting property over most recent. Function ido-file-extension-lessp could be used for sorting list of buffers this way. But two kind of sorting may conflict with each other.


text:
Q: On Google analytics, page view stay to 1 for ads campaign, but work perfectly for natural search on a view.js SPA using tag manager We set a Google tag manager on our SPA website (with view.js and nuxe for server side rendering).
We add google analytics on tag manager which works perfectly for direct and natural traffic.
Enhance Ecommerce works well too.
We connected Google ads to Google analytics in order to see our ads campaigns.
Now we see our ads campaigns on Google analytics, but the bounce rate stay to 100% and the page view stay to 1 for around 95% of our campaigns.
Hotjar shows us many visits from ads campaigns with more than 1 page view, which let us think that there is a problem with ads campaign on Google analytics.
Using chrome extension "Google tag assistant" we saw google tagmanager duplication when we navigate on different page. But with F12 on Chrome I see only 1 tagmanager and it seems not be refresh when I navigate.
On tagmanager the analytics page view is triggered on "all page" for the page open and "history change" for the navigation.
The error appears when I click on a ads campaign on Google. But if I manually open the same page adding a gclid params it seems to work fine on Google analytics.
Errors appear on https://www.pandacola.com/
Can you help us, thank you


text:
Q: How to import all search result in to the lead list on LinkedIn sales navigator? Dear Stack Overflow community,
After I have done a search query on Linkedin, I have manually import 600 contacts into lead list (25 every time)
I know you can run the script in the google console.
The code should
click
Click Save to list
Select the first option from the list
Then we add for-in loop for the pages
7 .
Should I create a web clicker using python, or can I achieve this with a chrome console?


text:
Q: Lagrangian intuition I am new to lagrangian mechanics and it just baffles me the idea of subtracting potential energy from kinetic energy. Why don't we use kinetic energy alone and the least action path (between two points) would be the one with lowest kinetic energy integral (with respect to any possible variation)?
Note:

*

*what i understand is that potential energy is the work whcih "will" be done if the object observed is to finish its motion and kinetic energy is the work done already by the force. So subtracting them doesn't give me a good intuition about lagrangian.

*i know that there are other answers on stack, but they just derive the equations mathematically, i want a more intuitive approach (what the equation in itself means and how it differes from a path to another i,e if the path becomes longer ,greater in energy than least action, how would the value change?)


text:
Q: Obj-C: Why won't my image display in NSImageView? I have a document window with an empty NSImageView, and I have an outlet connect to this called *imageView. I also have the property: NSImage *image.
The NSImageView fills almost the entire window.
In windowControllerDidLoadNib: I call the following method:
-(void)addImageToImageView {
  imageView = [[NSImageView alloc] init];
  imageView.image = image;
}

There is definitely an image assigned to imageView.image but it does not display. I thought maybe it's because I'm adding the image to the view before the window is loaded but shouldn't all the code in windowControllerDidLoadNib run after the window has loaded?
Any help would be most welcome!

A: OK so:
Do NOT alloc init IBOutlets, these are references to objects that are instantiated by IB. Simply put what a .xib or .storyboard file is is information stored in XML format that is then unarchived automatically by your app (under the hood stuff). Therefore you should never alloc init an object that you've added in the interface builder.
What you've done above is change the variable *imageView from referencing whats in IB to a new imageView instance that isn't on screen.
You should check out some tutorials. There are some really good ones on youtube just search for them.


text:
Q: Часть фраз в WooCommerce не переводится через Loco Translate. Почему? Дано: WP + WooCommerce + Loco Translate. Переводим с английского на русский.
После ряда апргрейтов движка и плагинов "сломались" некоторые переводы. В частности, надпись на кнопке "Add to cart" в листинге товаров переводится, а в карточке товара - нет:

Я нашел файл-источник надписи. Если я в нем меняю надпись, изменения на сайте тотчас появляются.
Файл /plugins/woocommerce/includes/abstract/abstract-wc-product.php

Запись о нем присутствует в соответствующем .po файле
Файл \languages\loco\plugins\woocommerce-ru_RU.po

В самом Loco Translate, фраза переведена, других вхождений нет:

Других файлов перевода нет.
Итого - фраза включена в файл перевода, файл рабочий, перевод на сайте не появляется.
Почему фраза не переводится? Куда рыть, что проверить, может какие-то идеи?
Заранее спасибо!

A:
Почему фраза не переводится? Куда рыть, что проверить, может какие-то
идеи? Заранее спасибо!

Потому что это уже выводит тема или другой плагин.
Для перевода строк можно использовать Loco Translate или Say what?.
Я предпочитаю первый, тк обычно переводить приходится не мало.

A: Проблема была, как и подсказал @SeVlad, в другом плагине - Contact Form 7 Captcha, а возможно в плагине Contact Form 7. Возможно плагины как-то криво обновились или все-таки конфилктовали. Я по итогу еще раз обновил CF7, а CF7reCaptcha снес, так как функционал капчи есть в CF7. И тогда все переводы исправились.


text:
Q: Unique IDs for (Jquery) live content $("#addNewItem").on("click", function() {
    $.get('showItem.php',function(data) {
        // add new item
        $('#newItems').after(data);
    })
});

With that code I call the PHP-file as you can see. In the PHP file is a input-select that get data from a database. And there is an text-input field.
Every time the user click on the button #addNewItem the two inputs where created. Every click creates a new "item set". So far so good. But how can I handle it that the inputs gets unique IDs and names. So that I can give it later to a PHP form handler thats writes it to the database?
Code from the PHP-File:
<select class="form-control select2" style="width: 100%;" name="productitem" id="productitem">
    <option selected>Choose...</option>

    <?  //foreach($stmtPL as $rowPL) {
        while($rowPRL = $stmtPRL->fetch(PDO::FETCH_NUM)) {
            <option><? echo $rowPRL[1] . " / " . $rowPRL[2] . " / " . $rowPRL[4]; ?></option>
    <? } ?>

</select>

    Count:
    <input type="text" class="form-control" id="count" name="count" value="1" maxlength="5" required>

Update: the JS:
$("#addNewItem").on("click", function() {

var count = 0;
 count++;

 $.get('chunk.showBillItem.php?zahl=' + count ,function(data) {

        // Neue Items anfügen
        $('#newItems').after(data);

     })

});

The count is always 1 (?)


text:
Q: Change your home directory in vim I have changed the registry settings so that the user's folder is not saved in C: but in E:. Everything is working fine except for Vim (and Cygwin, but I don't want it now).
Whenever I launch Vim, it automatically creates a new folder C:\Users\Administrator and starts saving its files there.
That's because $HOME is C:\Users\Administrator. I want it to change so that it can point to my custom location.

A: I think Vim should set $HOME to ${HOMEDRIVE}${HOMEPATH} unless you already have %HOME% set to something else in the Windows environment.
If you start a Command Prompt, and run:
set | findstr /R "^HOME"

I think you should see
HOMEDRIVE=E:
HOMEPATH=\Users\Administrator

I suspect that either the HOMEDRIVE is still set to C: (your change of Users folder didn't take) or there's a setting there for HOME too.

A: You could set the environment variable VIMINIT to source E:/Users/Administrator/vimrc. Then in that vimrc file you'll need to set the 'runtimepath' option to an appropriate value to find all your plugins. See
:help VIMINIT
:help 'runtimepath'

A: If you do not want to change $HOME, try creating two new system environment variables:
$VIM: the directory you want to put vimrc and use as vimfiles
$VIMRUNTIME: the directory you install Vim (for example: E:\Program_Files\Vim\vim82)


text:
Q: Should I switch my main OS to something more suitable for coding? I want to take my python coding a lot further in the recent weeks and thought it would be a good idea to switch to something like Kali Linux or Ubuntu as they come built in with those things. I also want to be able to carry out my daily tasks like Youtube and gaming on Steam and such. Will switching to Linux hinder my choices of games I will be able to play and also would you recommend it and if so which OS?
Thank you :D

A: I suspect it will limit your choice of games, yes.  (Windows is probably still the most-supported OS for games.)
However, you should test the waters by installing Linux in a VM, e.g. using VirtualBox, and see if you find it more suitable as a programming environment.  If you really like it, you might prefer to use a dual-boot setup where you boot into Windows for games, and boot into Linux for your programming experiments.  Good luck!


text:
Q: select value= json_encode($array) is not returning entire array I tested the following:
<? echo json_encode($array) ?>    outputs: ["PG","Kevin Sad","8000","12"]

When I place it inside a form option value to be chosen by my script function:
<option value=<? echo json_encode($array) ?> > option1 </option>

When I click SUBMIT button and the following function fires from the script:
function submit_button(){
    var data=  player1.options[player1.selectedIndex].value;
    document.getElementById('print_result').innerHTML = data;
}

only the following is outputted inside the div id="print_result" :
["PG","Kevin

Something happens with the space character " " that I cannot figure out..
I expected whole array to show up specifically including missing portion:
 Sad","8000","12"]

A: Either you have to escape the double quotes and/or you use single quotes to contain the JSON.
See example and how it effects the outcome.

let options = document.querySelectorAll('option');
console.log(options[0].value, options[1].value);
document.getElementById('out').innerHTML = options[1].value;
<option value=["PG","Kevin Sad","8000","12"]> option1 </option>
<option value='["PG","Kevin Sad","8000","12"]'> option2 </option>