text:
Q: В качестве параметров два массива целых чисел. Найти произведение каждого массива, после найти разность двух массивов. Как записать в одну строку? //решил без записи в одну строчку
function example(a, b) {
    let multiplayA = 1;
    for (let item of a) {
        multiplayA *= item;
    };

    let multiplayB = 1;
    for (let item of b) {
        multiplayB *= item;
    };

    let result = multiplayA - multiplayB;

    return result;
};

A: Не знаю зачем, но можно так:

const productAndSub = (arr1, arr2) =>
  arr1.reduce((a, b) => {return a * b}, 1) -
  arr2.reduce((a, b) => {return a * b}, 1);

console.log(productAndSub([1, 2, 3], [-1, -2, -3]));

UPD: Исключительно для Алексея Шиманского :) реально в одну строку:
const productAndSub = (arr1, arr2) => arr1.reduce((a, b) => {return a * b}, 1) - arr2.reduce((a, b) => {return a * b}, 1);

UPD 2: Исключительно для Алексея Шиманского :) minify + uglify (воспользовался этим сервисом):
const productAndSub=(c,d)=>c.reduce((c,d)=>c*d,1)-d.reduce((c,d)=>c*d,1);


text:
Q: C++ calling function with unknown type of arguments? I am trying to achieve the same as RapidCheck: call any Callable no matter its arguments.
Here is an example from RapidCheck:
#include <rapidcheck.h>

int main() {
  rc::check("Addition is commutative.",
            [](int a, int b) {
              RC_ASSERT(a + b == b + a);
            });

  return 0;
}

*

*Unlike RapidCheck, which uses random data to call the Callable, I
would like to use a source of data. In particular, I am casting a uint8_t array to whatever type I need. (See the example below.)

*I am okay with using C++17 but would prefer C++11. I currently only have a C++17 example.

*My example below works for an arbitrary number of arguments to a Callable but not for arbitrary types of argument. And certainly not for mixed types of arguments.

*I am doing this, so that I can use the awesome API of RapidCheck with libFuzzer from LLVM. Similar to my previous approach here (Example).

What I have so far with some comments (online):
// Compiles with Clang(trunk)/GCC(7.2) using -std=c++17!

#include <cassert>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <type_traits>

/** Provides access to a uint8_t array as specific types.
*
* Fulfills thus the LLVMFuzzerTestOneInput-interface, which uses
* (uint8_t *Data, size_t Size) as input.
*/
class RawQueue {
public:
  RawQueue(uint8_t *Data, size_t Size)
      : data_(Data), size_(Size / sizeof(uint8_t)), index_(0){};

  /** Takes one element of type T from queue.
  *
  * Throws if empty.
  *
  * NOTE: Little endianess means that uint8_t {1, 0, 0, 0} == int {1}.
  */
  template <typename T> T pop() {
    assert(data_);
    std::scoped_lock<std::mutex> lock(data_mutex_);

    const size_t new_index = index_ + sizeof(T) / sizeof(uint8_t);
    if (new_index > size_) {
      std::runtime_error(
          "Queue depleted!"); // TODO: Thou shall not use plain runtime_error!
    }

    const T val = *reinterpret_cast<const T *>(&(data_[index_]));
    index_ = new_index;

    return val;
  }

private:
  const uint8_t *data_; ///< Warning: Ownership resides outside of RawQueue.
  std::mutex data_mutex_;
  const size_t size_;
  size_t index_;
};

template <> std::string RawQueue::pop<std::string>() {
  return std::string("Left-out for brevity.");
};

template <typename T, typename F, typename... Args>
decltype(auto) call(RawQueue *Data, F &&f, Args &&... args) {
  if constexpr (std::is_invocable<F, Args...>::value) {
    return std::invoke(f, args...);
  } else {
    assert(Data);
    // Is there a way to deduce T automatically and for each argument
    // independently?
    auto val = Data->pop<T>();
    return call<T>(Data, f, val, args...);
  }
}

int adder(int a, int b, int c) { return a + b + c; }
std::string greeter(const std::string &name) { return "Hello, " + name + "!"; }

int mixed_arguments(int i, float f, const std::string &s) { return 42; }

int main() {
  constexpr size_t Size = 16;
  uint8_t Data[Size] = {1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0};
  RawQueue data(Data, Size);

  auto res_int = call<int>(&data, adder);
  std::cout << "Integer result: " << res_int << std::endl;

  auto res = call<std::string>(&data, greeter);
  std::cout << "String result: " << res << std::endl;

  // Impossible with current approach:
  // std::cout << "Mixed-types: " << call(&data, mixed_arguments) << std::endl;

  return 0;
}

A: You could use variadic templates.
If you want to call, at runtime, an arbitrary function of arbitrary signature with arbitrary arguments, you should consider using libffi (a foreign function interface library which knows your ABI and calling conventions).

A: I found a solution using callable.hpp. Answers which do not rely on an external library are still welcome!
The relevant new addition is this:
constexpr size_t pos = sizeof...(args);
typedef typename callable_traits<F>::template argument_type<pos> T;
auto val = Data->pop<T>();

Complete Example:
#include <cassert>
#include <functional>
#include <iostream>
#include <mutex>
#include <string>
#include <type_traits>

#include "external/callable/callable.hpp"

class RawQueue {
public:
  RawQueue(uint8_t *Data, size_t Size)
      : data_(Data), size_(Size / sizeof(uint8_t)), index_(0){};

  /** Takes one element of type T from queue.
  *
  * Throws if empty.
  *
  * NOTE: Little endianess means that uint8_t {1, 0, 0, 0} == int {1}.
  */
  template <typename T> T pop() {
    assert(data_);
    std::scoped_lock<std::mutex> lock(data_mutex_);

    const size_t new_index = index_ + sizeof(T) / sizeof(uint8_t);
    if (new_index > size_) {
      // TODO: Thou shall not use plain runtime_error!
      std::runtime_error("Queue depleted!");
    }

    const T val = *reinterpret_cast<const T *>(&(data_[index_]));
    index_ = new_index;

    return val;
  }

private:
  const uint8_t *data_; ///< Warning: Ownership resides outside of RawQueue.
  std::mutex data_mutex_;
  const size_t size_;
  size_t index_;
};

template <> std::string RawQueue::pop<std::string>() {
  std::scoped_lock<std::mutex> lock(data_mutex_);
  assert(data_);
  assert(index_ < size_);
  size_t string_length = data_[index_]; // Up-to 255 ought to be enough.
  const size_t new_index =
      index_ + string_length + 1; // +1 b/c first value is length of string.

  if (new_index > size_) {
    // TODO: Thou shall not use plain runtime_error!
    std::runtime_error("Queue depleted!");
  }

  const std::string val(reinterpret_cast<const char *>(&(data_[index_ + 1])),
                        string_length);
  index_ = new_index;
  return val;
};

template <typename F, typename... Args>
decltype(auto) call(RawQueue *Data, F &&f, Args &&... args) {
  if constexpr (std::is_invocable<F, Args...>::value) {
    return std::invoke(f, args...);
  } else {
    assert(Data);
    constexpr size_t n_already = sizeof...(args);
    constexpr size_t n_needed = callable_traits<F>::argc;
    static_assert(n_needed >= n_already, "Too many arguments!");
    constexpr size_t pos = n_already;
    typedef typename callable_traits<F>::template argument_type<pos> T;
    auto val = Data->pop<T>();
    return call(Data, f, args..., val);
  }
}

int adder(int a, int b, int c) { return a + b + c; }

std::string greeter(std::string a) { return "hello " + a; };

void mixed(int i, float f, std::string s) {
  std::cout << "Mixed: " << i << ", " << f << ", " << s << std::endl;
}

int main() {
  constexpr size_t Size = 28;
  // clang-format off
  uint8_t Data[Size] = {
      3, 'A', 'd', 'a',
      1, 0, 0, 0,
      2, 0, 0, 0,
      4, 0, 0, 0,
      42, 0, 0, 0,
      0xDA, 0x0F, 0x49, 0x40, // 3.141...
      3, 'P', 'i', '!'};
  // clang-format on
  RawQueue data(Data, Size);

  std::cout << "String: " << call(&data, greeter) << std::endl;
  std::cout << "Integers: " << call(&data, adder) << std::endl;
  call(&data, mixed);
  call(&data, []() { std::cout << "Nothing to do!" << std::endl; });

  return 0;
}

Prints:
String: hello Ada
Integers: 7
Mixed: 42, 3.14159, Pi!
Nothing to do!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does the ascending chain condition only apply to countable chains of ideals? In my algebra class we are discussing Noetherian rings, and the definition we were given is that a ring is Noetherian if every chain of ideals satisfies the ascending chain condition; that is, if $I_1\subseteq I_2\subseteq\cdots$, then there exists $n\in\mathbb{N}$ such that $I_n=I_{n+1}=\cdots$. But this to me seems to discount the possibility that we might have an uncountable chain of ideals.
Is it not possible to have an uncountable totally-ordered set $\mathscr{A}$ and an ascending chain of ideals $\{I_\alpha:\alpha\in\mathscr{A}\}$? If it is possible, is the ascending chain condition actually that for every ascending chain of ideals $\{I_\alpha:\alpha\in\mathscr{A}\}$, there is an $\alpha_0\in\mathscr{A}$ such that $I_{\alpha}=I_{\alpha_0}$ for all $\alpha\geq\alpha_0$? Or is an ascending chain of ideals of a ring $R$ necessarily countable?

A: I think the added generality you ask about gives you back the same notion, nothing new.
Let's temporarily call a ring "Noetherian" if every countable ascending chain of ideals stabilizes, and a ring "strongly Noetherian" if every ascending chain (of possible uncountable number of) of ideals stabilizes, where stabilizes means exactly what you suggest:
for an ascending chain of ideals $\{I_\alpha:\alpha\in\mathscr{A}\}$, there is an $\alpha_0\in\mathscr{A}$ such that $I_{\alpha}=I_{\alpha_0}$ for all $\alpha\geq\alpha_0$
I think noetherian and strongly noetherian are equivalent notions.
I think it's clear that every strongly noetherian ring is noetherian.
Now assume we have a noetherian ring and let's show it is strongly noetherian. Let $\{I_\alpha\}_{\alpha \in A}$ be a possibly uncountable ascending chain of ideals. Assume for contradiction that it did not stabilize, meaning, for every $\alpha \in A$, there is an $\beta \in A$ such that $I_{\alpha} \subsetneq I_{\beta}$. So pick some $\alpha_0 \in A$ (if $A$ is empty the chain stabilizes), then we get an $\alpha_1 \in A$, such that $I_{\alpha_0} \subsetneq I_{\alpha_1}$.  Apply this reasoning again now to $\alpha=\alpha_1$ so there is  $\alpha_2 \in A$ such that $I_{\alpha_1} \subsetneq I_{\alpha_2}$. And then by axiom of dependent choice we can continue and find a sequence $\alpha_3, \alpha_4, \ldots$
such that
$$I_{\alpha_0} \subsetneq I_{\alpha_1} \subsetneq I_{\alpha_3} \subsetneq I_{\alpha_4} \cdots$$
i.e. a countable ascending chain that does not stabilize, contradicting the hypothesis that our ring was noetherian.

A: I've been thinking about how to answer this for quite some time. Mulling over the original question and the existing answer has crystallized some things that I had previously not appreciated.
I'm sure every student of ring theory (including myself) has had that these questions at some point: "Why is this stated in terms of a sequence? Is it the same as if you had used arbitrary chains? Is it an oversight that it isn't defined for arbitrary chains?"
After discovering the same equivalence outlined in usr0192's solution (as a student, many years ago), I felt I had settled the second and third question, but I did not have a good answer for the first one.  In this solution I'm trying to address this topic to complement the existing solution.
This is what was going through my head when I read the comments and solution here:
The index set
Firstly, notice that the linear containment order of the ideals immediately gives you a linear order on your index set. Everyone here, I think, observed this that we may as well assume the index set is linearly ordered to reflect the order of the ideals. That is one step closer to $\mathbb N$.
One person commented "Any infinite totally ordered set  has an initial segment isomorphic to ℕ." and so aimed to suggest the same inductive argument given by usr0192's solution.  Unfortunately, this is not true: take the set $T=\{\frac1n\mid n\in\mathbb N^+\}\cup\{0\}$ with its usual order in the reals. It is linearly ordered, but quite clearly does not have an initial segment isomorphic to $\mathbb N$, nor does it even contain a copy as a subsequence.  This is not an improbable totally ordered set either: it is what the ideals of the ring of formal power series ring $F[[X]]$ look like, for a field $F$.
So an infinite total order is not quite the context to think about growing sequences.
The meaning of it all

What the Noetherian condition means is, if you have any totally ordered set  and any chain of ideals $\{_\}_{∈}$ where $_⊆_$ iff $≤$, then if you start at any fixed ideal $_$ in the chain and go upwards, then the set $\{|=_ \text{ for some } _⊇_\}$ is actually finite.

Here was another clue that tells us that "stepping up" is not indispensable.  The commenter opted to cast Noetherianness as a condition on arbitrarily totally ordered chains of ideals. Was anything lost?
Apply it to our total order $T$ above, indexing the ideals of $F[[x]]$ with $T$, and pick $0$ as the ideal you start at. We find that the set of ideals above $I_0=\{0\}$ is not finite at all.  But $F[[x]]$ is a Noetherian ring...
Part of the problem with this recasting is that "going up" does not make as much sense with $T$ as it does with a sequence indexed by $\mathbb N$.
I think what these two problems are trying to tell us is that it is important to 1) start somewhere and 2) be able to step-up to successors in a well-defined way.  It is not enough to only talk about "an infinite totally ordered chain," not even countable such chains.
What does the sequence definition get us
The halting-sequence definition provides us with these things:

*

*It gives you a place to start;

*It makes it clear where the steps are; and

*it says you arrive at a maximal element in the chain only finitely many steps from the bottom.

What usr0192's proof shows is that a chain of any cardinality with no maximal element necessarily contains a subchain order isomorphic to $\mathbb N$ (hence it is also well-ordered). This is what the claim in the "index set" paragraph should have said, rather than "initial segment."
Conclusion
The definition as it is so frequently stated is sufficient to preclude strictly increasing chains of any cardinality, and you only have to check a smaller subfamily of chains, not all of them.  That makes your life easier, right?  Furthermore, it guarantees a theoretical $n$ where it stops.  This is much more interesting than, say knowing a chain stabilizes at $\omega +5$.

A: Yes, general rings can have ascending chains of ideals of arbitrarily large cardinality.
But by definition, a Noetherian ring is one in which every ascending chain of ideals stabilizes after a finite number of steps.


text:
Q: (How many years) have you been married?/studying English? Grammar books set rules for ELL when they want to ask questions to use present perfect form for counting, and present perfect progressive for periods of time.
Now what if you want to ask about a period of time in years, i.e. the question is a counting and a period at the same time? Does the question below sound natural or awkward?
Present Perfect Progressive:
How long have you been married? (this is OK)

(How many years) have you been married for? (Is it OK?)

Present Perfect:

(How many years) have you studied English? (Is it OK?)

If none is OK, how would you ask otherwise if you want the answer in years?

A: I think your questions are both OK. Your only mistake is that you mention the Present Perfect Progressive (also called the Present Perfect Continuous) but you don't use it.
When inquiring about periods of time regarding activities that still occur/are still true (and are not completed), the right approach in English is always a Present Perfect tense. Whether that be Continuous (+ing) or Simple (+ past participle) (and if the action is completed, but we don't know when), depends on the verb. State verbs (like "be" in your first example) can only be employed using Present Perfect Simple, whilst action verbs (like "study" in your second example) can be employed in PPS/PPC. Using PPC gives your sentence/question that emphasis of "repeated/continuous" activity, but is not mandatory.
So:

How long/How many years have you studied English?

Is just as worthy as:

How long/How many years have you been studying English?

(The same applies to your first example too)
Which brings us to your question of how to phrase your query if you wish to receive an answer using a specific "time reference" (ie "years" in your example). Generally speaking, the native English speaker will likely not worry about the "time" part of the question too much, leaving the listener to respond in the most logical way. In your example, this would likely be in years, or possibly:

Since I was 5.

Of course, sometimes specificity is needed or desired as in your question. If you don't want "since I was 5" type answers, then you need to "lead" the listener, by encouraging them to respond according to the "time" part of the question you use.

How many years? = For x years
How many days? = For x days

Etc.
Consider this last example of a situation where a specific (maybe overly?) response is needed.
A manager has to enter a candidate's information into the following box on their computer during a job interview: Years of higher education studies completed: [ ]
The manager will obviously require a response in years, and so will need to ask his question accordingly:

How many years of higher education studies have you completed?

Note the use of PPS for the "finished action".
Or, if the candidate is still studying:

How many years have you been studying in higher education?

Naturally, my examples work just as well with a more general "time query" (ie "How long?") if the answer doesn't need to be specific.
I hope that answers your question fairly well. Maybe I went into too much detail on PPS/PPC and confused you (I hope not!). As a final observation, I think your first question reads more naturally without "for".

A: As already mentioned, sentence 1 is simple, not progressive and in the second question "for" in unnecessary.
About your question: a period of time can be either unspecified (for a long time, for ages, since I was a baby) or more specific (5 years, 10 days, 5 weeks). Even if a number is mentioned, we are still talking about a period of time and both the simple and progressive tenses can normally be used, with similar meaning:
How long have you worked here?
How long have you been working here?
If you use state verbs (like, agree, know), then the progressive cannot be used, as in any other case of progressive tenses:
How long have you known him?
How long have you been knowing him?


text:
Q: Upload file using Selenium opens windows file explorer Ive been struggling for a couple days with this issue,
Im trying to send a file path to a "Upload File" button (not field)

<button type="button" class="browser button button-hero" style="position: relative; z-index: 1;" aria-labelledby="__wp-uploader-id-1 post-upload-info" id="__wp-uploader-id-1">Select files</button>

Im using send keys in order to do so but it keeps opening the file explorer. tried everything.
Any ideas? :)

driver.find_element(By.XPATH, "//div[contains(@class, 'upload-ui')]//button[contains(@class, 'button-hero')]").send_keys('C:\\01.png')


text:
Q: Consuming json values from a kafka topic and writing them and formatting them in a csv file using JQ I am trying to write into a csv file keys and values that are in a kafka topic. I have been able to select the keys and values that I want, but I am not able to get them separated by rows (three values per row values in rows separated by commas).
This is an example of two json records that I consumed from my kafka topic without doing any filtering. The command that I used is:
./kafka-run-class.sh kafka.tools.ConsoleConsumer --bootstrap-server kafka1.example.net:9092 --topic prod.example.v1 --max-messages 2 | jq -r '. '
{
  "count": "0",
  "source": 3,
  "lastModified": "2018-03-09T21:03:54.039Z",
  "isBusiness": false,
  "countryCode": " MX",
  "phone": "52/4446789864"
}
{
  "count": "0",
  "source": 3,
  "lastModified": "2018-03-09T21:03:54.039Z",
  "isBusiness": false,
  "countryCode": " GB",
  "phone": "44/0187567846"
}
I tried using this command, but each value is being put into its own row:
./kafka-run-class.sh kafka.tools.ConsoleConsumer --bootstrap-server kafka1.example.net:9092 --topic prod.example.v1 --max-messages 3 | jq -r ' .isBusiness, .countryCode, .phone ' > file.csv
Ideal output would be:
false, MX, 52/4446789864
false, GB, 44/0187567846
true, BE, 32/8745687645

A: jq -r '[.isBusiness, .countryCode, .phone] | @csv'

produces CSV:
false," MX","52/4446789864"
false," GB","44/0187567846"

The filter:
"\(.isBusiness), \(.countryCode), \(.phone)"

produces
false,  MX, 52/4446789864
false,  GB, 44/0187567846

You might want to "trim" the string values, e.g. using:
def trim: sub("^ +";"") | sub(" +$";"");


text:
Q: Probleme with jQuery each() function and size image Here's my problem, I have a portfolio where images appear dynamically :
<?php echo'

' ?>

They must resize in rapport by the size of the image.
So, in jQuery, I assign a class in rapport by the size of the image :
$(".real img").each(function(){
  var widthImage = $(this).width();
  var heightImage = $(this).height();

  if(widthImage > heightImage ){
     $(".real img").addClass('realHeight');
  }else{
     $(".real img").addClass('realWidth');
  }
});

But it's not working :

2 class are applied, when I want it to be one or the other.
(CSS):
.realWidth{width: 100%;}

.realHeight{height: 100%;}

Can someone help me, please ?
(sorry for my bad english)

A: Your echo seems to be wrong:
<?php echo'

' ?>

which should be like this:
<?php echo'

' ?>

Ans as you are looping so you can use $(this)
if(widthImage > heightImage ){
   $(this).addClass('realHeight');
}else{
   $(this).addClass('realWidth');
}

A: Use $(this) in your loop to manipulate the right DOM Element (your image tag)
And use naturalWidth and naturalHeight to get the correct size of the image.
$(".real img").each(function(){
  var widthImage = $(this).naturalWidth;
  var heightImage = $(this).naturalHeight;

  if(widthImage > heightImage ){
     $(this).addClass('realHeight');
  }else{
     $(this).addClass('realWidth');
  }
});

A: Use this instead of applying the class selectors inside each
$(".real img").each(function(){
  var widthImage = $(this).width();
  var heightImage = $(this).height();

  if(widthImage > heightImage ){
     $(this).addClass('realHeight');
  }else{
     $(this).addClass('realWidth');
  }
});

$(".real img").addClass('realHeight');

This will apply realHeight class to all the images with class real. We dont want that


text:
Q: Launch multiple X displays on boot I'm running a machine with seven monitors on two GPUs.  Each monitor runs an independent full-screen application and there is no need for X-inputs (no mouse, no keyboards) or even a desktop environment.
How can I create a systemd service which:

*

*Creates an X display attached to a specific monitor

*Runs a fullscreen application on this X display

*Runs a VNC server on this X display (port specified)

I intend to create one of these services for each of the seven monitors.

Update:  I'm getting closer.  I can now run windows and VNC for each display.  I'm still having trouble getting it to run automatically, and also having troubles thinking about how I am going to split up one script into several services.
First I use nvidia-settings to generate an xorg.conf with each monitor on a seperate screen.  Then boot into a headless environment:
sudo mv xorg.conf /etc/X11/xorg.conf
sudo systemctl mask gdm
sudo reboot

I create a script:
#!/bin/bash
DISPLAY=0.0 cvlc video1.mp4 &
DISPLAY=0.1 cvlc video2.mp4 &

x11vnc -display :0.0 &
x11vnc -display :0.1

From tty2, I run:
$ xinit /path/to/script

This will play video1 on monitor 1, and video2 on monitor2.  Then I can VNC to the two monitors using ports 5900 and 5901.
If I try to run this as a service:
[Service]
ExecStart=xinit /path/to/script

The service fails with:
/usr/lib/xorg/Xorg.wrap: Only console users are allowed to run the X server`
xinit: giving up
xinit: unable to connect to X server: Connection refused
xinit: server error

And /var/log/Xorg.0.log contains:
(WW) NVIDIA(GO): Unable to get display device for DPI computation.
(WW) NVIDIA(GO): Option "metamodes" is not used
(WW) NVIDIA(GO): Failed to set the display configuration
(WW) NVIDIA(GO):  - Setting a mode on head 0 failed: Insufficient permissions
(WW) NVIDIA(GO):  - Setting a mode on head 1 failed: Insufficient permissions
(WW) NVIDIA(GO):  - Setting a mode on head 2 failed: Insufficient permissions
(WW) NVIDIA(GO):  - Setting a mode on head 3 failed: Insufficient permissions

Update2: Getting even closer.
From TTY2, I run xinit
From TTY3, I run systemctl --user start disp@{0,1,2,3,4,5,6} vnc@{0,1,2,3,4,5,6}.
Where ~/.config/systemd/user/disp@.service is:
[Service]
Environment=DISPLAY:0.%i
ExecStart=cvlc /path/to/file%i.mp4

And where ~/.config/systemd/user/vnc@.service` is:
[Service]
Environment=DISPLAY:0.%i
ExecStart=x11vnc -display :0.%i

Now I just need to figure out how to get that user to login on startup and then run xinit.


text:
Q: How to sort numpy array by row sum and extract top N rows For example, given matrix
array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [ 0,  1,  2,  3,  4,  5],
       [24, 25, 26, 27, 28, 29]])

and top_n=3, it should return
array([[24, 25, 26, 27, 28, 29],
       [18, 19, 20, 21, 22, 23],
       [12, 13, 14, 15, 16, 17]])

This function should return a np.ndarray of shape (top_n, arr.shape[-1]), given the input 2D matrix arr.
Here's what I tried:
def select_rows(arr, top_n):
    """
    This function selects the top_n rows that have the largest sum of entries
    """
    sel_rows = np.argsort(-arr,axis=1)[:top_n]

    return sel_rows

I also tried:
sel_rows = (-arr).argsort(axis=-1)[:, :top_n]

to no avail.

A: You can use this simple 1-liner a[np.argsort(a.sum(axis=1))[:-top_n-1:-1]]
a.sum(axis=1) sums along axis 1
np.argsort(..., axis=0) argsorts along axis 0 (axis=0 is default option anyway so could be omitted)
...[:-top_n-1:-1] picks the last top_n indices in reverse order
a[...] then grabs the rows
%%timeit comparison
# data sample
a = np.random.randint(0, 101, (100000, 1000))

%%timeit
a[np.argsort(a.sum(axis=1))[:-3-1:-1]]
[out]:
9.73 ms ± 122 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
a[np.argsort(-a.sum(axis=1))[:3]]
[out]:
9.9 ms ± 303 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
sorted(a, key=lambda x: sum(x))[:-3-1:-1]
[out]:
1.04 s ± 36.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: Your code almost works, but you need to compute the sum of each row before sorting. You can try this:
import numpy as np

top_n = 3
arr = np.array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [ 0,  1,  2,  3,  4,  5],
       [24, 25, 26, 27, 28, 29]])

arr[np.argsort(-arr.sum(axis=1))[:top_n]]

It gives:
array([[24, 25, 26, 27, 28, 29],
       [18, 19, 20, 21, 22, 23],
       [12, 13, 14, 15, 16, 17]])

A: Without numpy, you can use the built-in function sorted combined with argument key:
sorted(A, key=lambda x: sum(x))[:-top_n-1:-1]


text:
Q: Adding removing leading and trailing spaces in this JavaScript RegEx How do I add code to remove leading and trailing spaces to this regular expression?
I tried putting the \s in several places, but end up with odd results.
The myString is just the way it is, and is sent from a PHP script with trailing spaces.
Original Code
var myString = "::This is string 1 ::This is string 2! ";

myString = myString.replace(/\::(.+?)(?![^::])/g,'
$1
');

alert(myString);

Tried
var myString = "::This is string 1 ::This is string 2! ";

myString = myString.replace(/\::(.+?)(?![^::\s])/g,'
$1
');

alert(myString);

The end result I'm trying to achieve is

This is string 1
 // No trailing spaces before or after the `This` and `1`

This is String 2

Fiddle

A: The point is that you match spaces with .+?, and (?![^::\s]) only tells the regex engine to not match a character if it is followed by a whitespace or :.
Since you already are using lazy matching, you just need to use a greedy \s* subpattern to match whitespaces after the .+?.
Use
::(.+?)\s*(?=::|$)

See demo
Explanation:

*

*:: - match 2 :s

*(.+?) - match and capture into Group 1 one or more characters other than a newline

*\s* - greedily match zero or more whitespaces

*(?=::|$) - only if followed by :: or end of string.

And here is my attempt at unrolling the regex (looks a bit more efficient than the above):
::(\S*(?:(?=(\s+))\2(?!:|$)\S*)*)

See another demo

A: Try this:
var myString = "::This is string 1 ::This is string 2! ";

myString = myString.replace(/\s*\::\s*(.*?)\s*(?=(::|$))/g,'
$1
');

JSFiddle


text:
Q: Reading a list inside a tuple in Django My problem is that I want to read a list (with a for loop) which is inside a tuple like this:
items = {a, b, [1, 2, 3]}

'a' and 'b' are other data I need.
Now for reading a list I do this, which doesn't work:
{% for item in items.3 %}
  {{item}}
{% endfor %}

So my question is how can I read, with a for loop, a list which is inside a tuple?
Thanks for the help.

A: Python indexes in lists/tuples are started from zero.  So you should use the index 2:
{% for item in items.2 %}
  {{ item }}
{% endfor %}

BTW, tuples are defined with round brackets, not the curly:
items = (a, b, [1, 2, 3])

A: I just deleted the part of code and started over.
An extra tip: If the list in the tuple is a list of tuples and you want to read a part of the tuple. You have to use a new for loop to read it.
For example, I have this:
items = {a, b, [{1, 2, 3}, {4, 5, 6}]}

Now for getting a list out of a tuple:
{% for item in items.3 %}
    {{item}}
{% endfor %}

Now for getting something out of the tuple from the list
I try to do this but it doesn't work, if there are people who know how to fix this, please add a comment:
{% for item in items %}
    {{item.1}}
{% endfor %}

This is my trick to get it done:
{% for item in items %}
    {% for i in item %}
        {{i}}
    {% endfor %}
{% endfor %}

To get the counter of the outer most loop check this post:
how-to-access-outermost-forloop-counter-with-nested-for-loops-in-django-template
Thanks


text:
Q: No error highlighting with Kotlin in Android Studio 3.3 [Android Studio Issue] I have no error highlighting in code (see screenshot below) Android Studio 3.3 (Ubuntu), but I have a notification about the error on scrollbar, in the project tree and on mouse hover over the bad code.

Additional info
My studio64.vmoptions:
-Xms256m
-Xmx2048m
-XX:ReservedCodeCacheSize=240m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-Djna.nosys=true
-Djna.boot.library.path=

-XX:MaxJavaStackTraceDepth=-1
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-ea
-Dawt.useSystemAAFontSettings=lcd
-Dsun.java2d.renderer=sun.java2d.marlin.MarlinRenderingEngine

Suggested solutions, which is not working:

*

*Invalidate cache and restart

*Mark directory with the code as sources

*Clean & Rebuild

*Set light theme in Android Studio

*Increase memory size using -Xmx


text:
Q: Cast between function pointers I am currently implementing a timer/callback system using Don Clugston's fastdelegates. (see http://www.codeproject.com/KB/cpp/FastDelegate.aspx)
Here is the starting code:
struct TimerContext
{
};

void free_func( TimerContext* )
{
}

struct Foo
{
    void member_func( TimerContext* )
    {
    }
};

Foo f;
MulticastDelegate< void (TimerContext*) > delegate;

delegate += free_func;
delegate += bind( &Foo::member_func, &f );

Okay, but now, i wish the user to be able to subclass TimerContext to store and send his own structures to the callbacks.
The purpose here is to prevent the user from having to downcast the TimerContext himself
struct TimerContext
{
};

struct MyTimerContext : TimerContext
{
    int user_value;
};

void free_func( TimerContext* )
{
}

void free_func2( MyTimerContext* )
{
}

struct Foo
{
    void member_func( TimerContext* )
    {
    }

    void member_func2( MyTimerContext* )
    {
    }
};

Foo f;
MulticastDelegate< void (TimerContext*) > delegate;

delegate += free_func;
delegate += free_func2;
delegate += bind( &Foo::member_func,  &f );
delegate += bind( &Foo::member_func2, &f );

As you guessed, GCC won't let me do that :)
error: invalid conversion from `void (*)(MyTimerContext*)' to `void (*)(TimerContext*)'
error:   initializing argument 1 of `delegate::Delegate<R ()(Param1)>::Delegate(R (*)(Param1)) [with R = void, Param1 = TimerContext*]'

So now my question is:
If I force the cast using reinterpret_cast, it'll work, but will it be safe ?
PS: These are time-critical callbacks, heavy virtual-oriented solutions are considered impracticable :/

A: C++ Standard says in 13.4/7 that:

there are no standard conversions (clause 4) of one pointer-to-function type into another. In particular, even if B is a public base of D, we have
D* f();
B* (*p1)() = &f;  // error
void g(D*);
void (*p2)(B*) = &g;  // error

Still you may be could use function adapter for storing pointers to function with one argument, something like boost::function, but I'm not sure right now whether it will solve your problem.

A: Of course, casting function pointers is generally a bad idea.
Casting a function pointer from void(*)(Derived*) to void(*)(Base*) might work or it might not. It certainly won't work in case the internal representation of Derived* and Base* pointers needs to be adjusted upon conversion. However, in case of your single inheritance relationship, this is not likely. Still, class layout and pointer adjustments are implementation-defined and you should not rely on this. If you want to take the risk: Go ahread.
Assuming pointers don't need to be adjusted, a conversion from void(*)(Derived1*) to void(*)(Base*) would still not be a good idea (not type-safe) because it allows a function that expects Derived1* to be called with a Derived2* where Derived1 and Derived2 are siblings in the inheritance hierachy.

A: reinterpret_cast is only as safe if the 'sender' and 'receiver' of the object correspond.  So if sender and receiver are implemented by the same piece of code, it might be quite safe, for some time.
If you want to add callbacks to a delegate, and you want them to have a different type, as you do, you have two scenario's:

*

*you know all the delegates upfront, at compile time => you can wrap them in a typelist.

*delegates can be made up at run time => you need to use runtime binding, i.e. virtual functions ( an exec method or the like ).


text:
Q: Resume Tilemill MBTiles export after crash Is there a way to resume a Tilemill export (MBTiles) after it has crashed?
Today I just got the following crash:
 FATAL ERROR: Evacuation Allocation failed - process out of memory

This was just a little sample export, but I will need to make a pretty huge export (size of Europe with Zoom Level from 0 - 18) and if that would happen inbetween this export I'd like to know that I don't loose everything, but just a little part and that Tilemill will continue afterwards...
Is there a button for resuming that I am missing?
Or what would be the most reliable solution for this process?
Thanks

A: Long Story Short:
You are screwed with the out of memory issue.  A memory failure is really hard for an application to safely recover from.

Edit --job=[file]   Store state in this file. If it exists, that job will be resumed. (Default: false) TileMill Command Line options may provide what you are looking for.  I provided this link in your other question on failed tiles.

Long Story Long:

*

*Try looking at your project's Export -> View Exports page.  That is the only place to try and resume your export that I can think of.

*You could look at your tilemill.log for any more clues as to why your process failed other than the memory issue failure.

*Bad spatial data could cause the render process to fail.

*Make sure that you have your data properly indexed.

*You will want to try the render with TileMill as the only process running on the computer.

*Wrench/configure your project settings.  Try just 1 zoom level.  Also look at the MetaTile setting and try more or less.

*Add more memory or install TileMill and all your project and work files on a solid state drive.


text:
Q: java confusion about Thread.interrupted() I was going through oracle java tutorial about threads and I saw this example
src: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:
for (int i = 0; i < inputs.length; i++) {
      heavyCrunch(inputs[i]);
      if (Thread.interrupted()) {
           // We've been interrupted: no more crunching.
      return;
}

The tutorial adds :
The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.
By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
now I'm confused. When does it happen? if there is an interrupt, shouldn't the thread receive an InterruptedException?
When someone might use these method of checking in their code?
The Thread.interrupt (the flag) is static, so with the above check, we actually check if any of the treads has been interrupted? even if that is the case, according to the tutorial, When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared.  or any method that exits by throwing an InterruptedException clears interrupt status when it does so
So, Am I missing something? or this is only useful, if some thread has received an interrupt, but doesn't check it, or does not throw it?

A: This is Thread.interrupted implementation
public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

private native boolean isInterrupted(boolean ClearInterrupted);

as you can see it can check / reset only current thread's interrupted status. If it were not static you could call it on other threads and reset their status which is not allowed by API.

A: Not all methods, in Thread, throws InterrupedExceptions. It is mostly common at sleeps and waits, or any time consuming methods. This is the way Java implemented it. (sleep(...) is native code, so I cant show you the source.)
For example:
try {
    Thread.sleep(1000); // one sec
} catch(InterruptedException e){
}

But you can't force to include a simple for loop, in a try..catch clause.
If you subclass Thread, you should follow the conventions, posted.

For your second question, about the static method, here's the internal code:
public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

So you can see, it just sets, an instance in the current thread.

A: Many times a Thread is doing a lot of waiting or blocking. In almost all of these cases the method that is doing the blocking supports InterruptedException. Some examples:

*

*Thread.sleep(millis);

*obj = arrayBlockingQueue.take();

*obj.wait();

What the referenced article is pointing out is that if your thread is not blocking, meaning there is no method that supports InterruptedException, then it is your responsibility to check if your thread has been interrupted. This is accomplished by testing Thread.interrupted().
The method Thread.interrupt() is in fact not static and is called from another Thread to interrupt that thread. See the following:
Thread.interrupt()
Does that make sense?


text:
Q: Lollipop set remote description error : rtcp-mux must be enabled when BUNDLE is enabled I tried to make Android WebRTC app
I tested on Android Oreo and Pie, the app works well.
But on Android Lollipop and Marshmallow, throw a error when I call setRemoteDescription function.
(org.webrtc.SdpObserver::onSetFailure(String))
Failed to set remote answer sdp: rtcp-mux must be enabled when BUNDLE is enabled.
//setRemoteDescription code
String channelId = json.getString("channel_id");
int index = getPeerConnectionIndex(channelId);
JSONObject sdp = json.getJSONObject("sdp");
SessionDescription sdpOffer = new SessionDescription(SessionDescription.Type.fromCanonicalForm(sdp.getString("type")), sdp.getString("sdp"));
Log.d(TAG, sdpOffer.description);
mSDPObserver[index] = new SDPObserverWithId(index);
mSDPObserver[index].setChannelId(channelId);
mPeerConnection[index].setRemoteDescription(mSDPObserver[index], sdpOffer);

local Sdp:
    v=0
    o=- 3986057299756726360 2 IN IP4 127.0.0.1
    s=-
    t=0 0
    a=group:BUNDLE audio video
    a=msid-semantic: WMS ARDAMS
    m=audio 9 UDP/TLS/RTP/SAVPF 111 103 9 102 0 8 105 13 110 113 126
    c=IN IP4 0.0.0.0
    a=rtcp:9 IN IP4 0.0.0.0
    a=ice-ufrag:vAIE
    a=ice-pwd:bVq8d3C2jNJ6+Q1Db90xCJxk
    a=ice-options:trickle renomination
    a=fingerprint:sha-256 B3:31:21:AA:DB:07:DC:F9:CF:BC:4F:86:01:46:C8:AF:BB:B3:65:F0:EC:B2:5A:1A:97:A8:52:CD:6C:4A:58:3F
    a=setup:actpass
    a=mid:audio
    a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
    a=extmap:2 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
    a=sendrecv
    a=rtcp-mux
    a=rtpmap:111 opus/48000/2
    a=rtcp-fb:111 transport-cc
    a=fmtp:111 minptime=10;useinbandfec=1
    a=rtpmap:103 ISAC/16000
    a=rtpmap:9 G722/8000
    a=rtpmap:102 ILBC/8000
    a=rtpmap:0 PCMU/8000
    a=rtpmap:8 PCMA/8000
    a=rtpmap:105 CN/16000
    a=rtpmap:13 CN/8000
    a=rtpmap:110 telephone-event/48000
    a=rtpmap:113 telephone-event/16000
    a=rtpmap:126 telephone-event/8000
    a=ssrc:3060595593 cname:tW/usjdUwhcVD9Gk
    a=ssrc:3060595593 msid:ARDAMS ARDAMSa0
    a=ssrc:3060595593 mslabel:ARDAMS
    a=ssrc:3060595593 label:ARDAMSa0
    m=video 9 UDP/TLS/RTP/SAVPF 96 97 98 99 100 101 127
    c=IN IP4 0.0.0.0
    a=rtcp:9 IN IP4 0.0.0.0
    a=ice-ufrag:vAIE
    a=ice-pwd:bVq8d3C2jNJ6+Q1Db90xCJxk
    a=ice-options:trickle renomination
    a=fingerprint:sha-256 B3:31:21:AA:DB:07:DC:F9:CF:BC:4F:86:01:46:C8:AF:BB:B3:65:F0:EC:B2:5A:1A:97:A8:52:CD:6C:4A:58:3F
    a=setup:actpass
    a=mid:video
    a=extmap:14 urn:ietf:params:rtp-hdrext:toffset
    a=extmap:13 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
    a=extmap:3 urn:3gpp:video-orientation
    a=extmap:2 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
    a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
    a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type
    a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing
    a=extmap:8 http://tools.ietf.org/html/draft-ietf-avtext-framemarking-07
    a=extmap:9 http://www.webrtc.org/experiments/rtp-hdrext/color-space
    a=sendrecv
    a=rtcp-mux
    a=rtcp-rsize
    a=rtpmap:96 VP8/90000
    a=rtcp-fb:96 goog-remb
    a=rtcp-fb:96 transport-cc
    a=rtcp-fb:96 ccm fir
    a=rtcp-fb:96 nack
    a=rtcp-fb:96 nack pli
    a=rtpmap:97 rtx/90000
    a=fmtp:97 apt=96
    a=rtpmap:98 VP9/90000
    a=rtcp-fb:98 goog-remb
    a=rtcp-fb:98 transport-cc
    a=rtcp-fb:98 ccm fir
    a=rtcp-fb:98 nack
    a=rtcp-fb:98 nack pli
    a=rtpmap:99 rtx/90000
    a=fmtp:99 apt=98
    a=rtpmap:100 red/90000
    a=rtpmap:101 rtx/90000
    a=fmtp:101 apt=100
    a=rtpmap:127 ulpfec/90000
    a=ssrc-group:FID 1050899396 3284914966
    a=ssrc:1050899396 cname:tW/usjdUwhcVD9Gk
    a=ssrc:1050899396 msid:ARDAMS ARDAMSv0
    a=ssrc:1050899396 mslabel:ARDAMS
    a=ssrc:1050899396 label:ARDAMSv0
    a=ssrc:3284914966 cname:tW/usjdUwhcVD9Gk
    a=ssrc:3284914966 msid:ARDAMS ARDAMSv0
    a=ssrc:3284914966 mslabel:ARDAMS
    a=ssrc:3284914966 label:ARDAMSv0

remote Sdp to set:
    v=0
    o=- 1555912613504775309 2 IN IP4 127.0.0.1
    s=-
    t=0 0
    a=group:BUNDLE audio video
    a=msid-semantic: WMS 4qgVUFPGGjzM2ZXwOgYUE5BTL0
    m=audio 9 UDP/TLS/RTP/SAVPF 111
    c=IN IP4 0.0.0.0
    a=rtcp:9 IN IP4 0.0.0.0
    a=mid:audio
    a=setup:active
    a=recvonly
    a=rtcp-mux
    a=rtcp-rsize
    a=ice-ufrag:TFH9
    a=ice-pwd:Ez2jn6OX7xdufJ58Gd1mbb01
    a=ice-options:trickle
    a=fingerprint:sha-256 8C:CC:45:9F:17:75:B7:6C:0B:A3:7F:5C:C5:0A:47:D9:6F:88:41:B7:8E:2C:AA:48:01:7F:C2:6C:77:E9:7A:2B
    a=rtpmap:111 opus/48000/2
    a=fmtp:111 minptime=10;useinbandfec=1
    a=ssrc:1732894969 cname:ori8UQ7mdYvrS7eO
    a=ssrc:1732894969 msid:4qgVUFPGGjzM2ZXwOgYUE5BTL0 kny6pqktc2YPysWY5MLS8pZW7rPyaqmiDKeS
    a=ssrc:1732894969 mslabel:4qgVUFPGGjzM2ZXwOgYUE5BTL0
    a=ssrc:1732894969 label:kny6pqktc2YPysWY5MLS8pZW7rPyaqmiDKeS
    m=video 9 UDP/TLS/RTP/SAVPF 0
    a=ssrc:1542320079 cname:ori8UQ7mdYvrS7eO
    a=ssrc:1542320079 msid:4qgVUFPGGjzM2ZXwOgYUE5BTL0 p91hXGGeqs923R0gEMdVpzUGL29j5Q8kPZpB
    a=ssrc:1542320079 mslabel:4qgVUFPGGjzM2ZXwOgYUE5BTL0
    a=ssrc:1542320079 label:p91hXGGeqs923R0gEMdVpzUGL29j5Q8kPZpB

As result of error, Android 5.0~6.0 devices can't stream out video/audio and can't get streams.
I'm try to build native WebRTC library for debuging, It is very hard to me...

A: It was a silly question for me, self.
The problem was a server only use h264 and those Android device dosen't support h264 with WebRTC.
So, remote sdp is lack of video options and setRemoteDescription() throw the rtcp-mux must be enabled error.
(Android WebRTC needs rtcp-mux & bundle that need audio and video both)


text:
Q: Consistency vs Inconsistency in a set of sentences: which is more common I'm curious whether there is any research in the "probability" that a set of sentences in a first-order logic is consistent.  Obviously, there are an infinite number of inconsistent sets and an infinite number of consistent sets.
    In sentential logic, you can come up with a "probability" by taking n atoms and the conjunction of the sentences and, if we pretend that the truth table column for this conjunction is equally likely to be true or false, we have $2^n$ ways to fill the column, only one of which is inconsistent.
    Does anyone know of something like this for predicate logics?  Is there a way to fix my above argument so it doesn't pretend true and false are equally likely in the column of the conclusion?

A: It depends a bit how you count / distinguish  sets of sentences,
If you assume that sets are closed under deduction then there is only one inconsistent set (the set of all sentences) all other sentences are consistent so the chance that you have the inconsistent set is almost nil.
If you don't assume closure it is the opposite, every consistent set has many ways to make it inconsistent so the chance that you have an consistent set is (again) almost nil.


text:
Q: Is it okay to use constructors to initialize a 2D Vector as a one-liner in C++? Is it okay to initialize a 2D vector like this (here all values in a 5x4 2D vectro are initialized to 3)?
std::vector<std::vector<int> > foo(5, std::vector<int>(4, 3));

This seems to behave okay, but everywhere I look on the web people seem to recommend initializing such a vector with for loops and push_back(). I was initially afraid that all rows here would point to the same vector, but that doesn't seem to be the case. Am I missing something?

A: Well, the code is valid and it indeed does what you want it to do (assuming I understood your intent correctly).
However, doing it that way is generally inefficient (at least in the current version of the language/library). The above initialization creates a temporary vector and then initializes individual sub-vectors by copying the original. That can be rather inefficient. For this reason in many cases it is preferrable to construct the top-level vector by itself
std::vector<std::vector<int> > foo(5);

and then iterate over it and build its individual sub-vectors in-place by doing something like
foo[i].resize(4, 3);

A: This is perfectly valid - You'll get a 2D vector ([5, 4] elements) with every element initialized to 3.
For most other cases (where you e.g. want different values in different elements) you cannot use any one-liner - and therefore need loops.


text:
Q: how to navigate between webview pages described in different files Good day, I have such a problem. The application is made on the basis of webview, at the beta stage. And I faced such a problem that after the registration stage I need to launch a separate page in which the native elements and the webview are combined. Please give a tip on how to cope with this task
U.P.D The crux of the problem is this. I have a file that describes one webview page. I need to make sure that after the user is registered, he is thrown to another file, where the webview is also described, but in addition to the webview there are native menu elements for the user to navigate the application. If it's not clear, I can try to make a block diagram, maybe this will be clearer


text:
Q: Launch Silverlight Out of Browser App Programmatically I am trying to use SLLAUNCHER.EXE to launch an SL Out-of-Browser App that is installed. The MyApp startup icon on the desktop just disappears after I run the below. If I try it without the overwrite switch nothing happens.
I am using this article as a guide:
http://timheuer.com/blog/archive/2010/03/25/using-sllauncher-for-silent-install-silverlight-application.aspx
Any suggestions would be appreciated.
    static void Main(string[] args)
    {
        string sllauncherPath = string.Format("{0}\\Microsoft Silverlight\\sllauncher.exe",
       Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));

        string originUri = @"http://localhost:52878/ClientBin/MyApp.xap";
        string xap = "MyApp.xap";
        string arg = string.Format(@"/emulate:""{0}"" /origin:""{1}""  /overwrite", xap, originUri);

        var startInfo = new ProcessStartInfo
        {
            CreateNoWindow = false,
            UseShellExecute = false,
            RedirectStandardOutput = false,
            FileName = sllauncherPath,
            Arguments = arg
        };

       var process = Process.Start(startInfo))

    }

A: Are You using 64bit machine?
http://social.msdn.microsoft.com/Forums/en-US/silverlightcontrols/thread/abedb9dc-d471-4d82-8a20-45f98671cac9
Could allso help:
This is how I do restart from within my SL OOB apps after I detect update has completed:
''put this in your App.xaml.vb[.cs] and call DoRestart
Public Shared Sub DoRestart()
    StartAgain()
    Application.Current.MainWindow.Close()
End Sub
Public Shared Sub StartAgain()
    If Not [String].IsNullOrEmpty(GetSLLauncherCommand) Then
        Using shell = AutomationFactory.CreateObject("WScript.Shell")
            shell.Run(GetSLLauncherCommand)
        End Using
    End If
End Sub
Public Shared Function GetSLLauncherCommand() As String
    Dim desktopPath As String
    Dim SLLauncherCommand As String = ""
    Using wShell As Object = AutomationFactory.CreateObject("WScript.Shell")
        desktopPath = wShell.SpecialFolders("Desktop")
    End Using
    Using shell As Object = AutomationFactory.CreateObject("Shell.Application")
        Dim DesktopFolder As Object = shell.[NameSpace](desktopPath)
        Dim DesktopItems As Object = DesktopFolder.Items()
        For Each item In DesktopItems
            If item.IsLink Then 'this is a shurtcut
                Dim fileName As String = item.Name.ToLower()

                If fileName.Contains("!!!<PART OF YOUR SL APPS SHORCUT NAME>!!!!") Then
                    Dim link = item.GetLink()
                    SLLauncherCommand = """" & Convert.ToString(link.Path) & """ " & Convert.ToString(link.Arguments)
                End If
            End If
        Next
    End Using
    Return SLLauncherCommand
End Function

You could try adapt the code for Your non-SL app!
THT


text:
Q: Wrap identifiers automatically with brackets in SSMS text editor Working in SQL Server Management Studio, when using the text editor:
Is there any way to automatically wrap schema names, table names, column names and other identifiers with brackets so I don't have to put them manually, just in the same way it does it when it auto-generates queries? Is there (perhaps) any Intellisense feature I'm missing?
EDIT: see accepted answer

A: There is no native function for this yet in SSMS. You can view the IntelliSense properties document here.
APEX makes a free formatting tool and there is another tool called Poor Man's T-SQL. RedGate also makes a tool that is paid, all three work nicely. I am sure there are other tools out there too.

A: there is a built in option:
Tools/Options/SQL Object Explorer/Commands --> Drag/Drop
Set Surround object names with brackets when dragged to False.

A: From the options given by @Shaulinator in his answer, ApexSQL Refactor does the job very nicely, integrates with SSMS and is free.
This is the particular option that I needed:


text:
Q: Expectation value and the probability of finding a particle I'm trying to understand basic quantum physics, as I understand, the expectation value of some random distribution gives us the outcome that we might expect(highest probability) if the event is done once. So I presume that the expectation value of the probability density function

$|\Psi|^2$ would give us the region with highest chance where the particle might be found right?

But in this problem - part (c)

When I sketch the function, I get that at point

$x = a$, the particle has the maximum value of the probability density function, isn't $x = a$ where the particle is most likely to be found?

But the expectation value $\left\langle x \right\rangle$ is not equal to $a$ (the most likely value). Why are they not equal if the definition of the expectation value of a random distribution is the most likely value (when the experiment is performed once)?
Am I going wrong somewhere? Humbly requesting your help, thanks for taking the time to read through this, I sincerely appreciate your time.

A: This sentence "the expectation value of some random distribution gives us the outcome that we might expect(highest probability) if the event is done once." is false. The expectation value of some random distribution does not contain information (and it should always be one)
$$ \int dx |\psi(x)|^2 = 1$$
It is the expectation value of some operator applied to the have function that gives us the expectation value. In the case of $\left\langle x  \right\rangle$ is
$$ \int dx |\psi(x)|^2x$$
The maximum of a distribution does not need to coincide with the mean. The expectation value is the mean value (in this case the mean position) and not the most likely position. It is the same as the difference between the mean and the mode:https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/mean-median-basics/a/mean-median-and-mode-review.

A: Expectation value of a dynamical variable means we prepare a set of identical systems (ensemble) and do the measurement and find the results. Then we find out the average of those result. Here we prepare a set of identical system, do position measurement , we average it and find  the expectation value of x.
Now, the maximum value of probability density function says that the particle is most likely to be found there. And if the probability density function do not change with time the particle will always have a greater chance to stay there.
So, the cases are different.

A: As the other answers have explained, you are confusing a few definitions in statistics, so I'll try to help.
The reason why the "expectation value of x" (or mean value) isn't necessarily the maximum of the probability is better understood if you take a look at a couple of curves. For example, take these distributions:

You can see how each curve has a different maximum, but it is also "twisted" in a way so that it occupies mostly a certain area of the graph, making it so the values are not evenly distributed around that maximum. So, it would be fair to say that most people have incomes that are lower than $40k$, because that's where most of the values land.
So even though the maximum is still the most probable value (as in, if you take just one measurement, it's the value you expect to get), in multiple extractions, you expect the value to be in the region where the graph of the distribution function shows higher probabilities. Or, in other words, you need to take the mean to see where most of your values are. That's what defines the "place where the particle is most probable to be found" and it doesn't have to coincide with the maximum.
Now, you can get that information by using the definition of the mean value and the knowledge you already have of the distribution function:
$$\text{Discrete:} \langle x \rangle = \sum_n x_n p(x_n) $$
$$\text{Continuous:}  \langle x \rangle = \int_{x_0}^{x_f} dx \cdot x  \cdot p(x)$$
Where $x$ represents all the possible values and $p(x)$ their probability.
In quantum mechanics, as you probably have found by now, the probability distribution is described as $p(x) = |\Psi (x)|^2$ (which is why $\int dx |\Psi (x)|^2 = 1 $), so you can either calculate the mean value with the expression above for the continuous distribution or, in the case where you have a function like:
$$\Psi (x,0) = c_1 \phi_1(x,0) + c_2 \phi_2(x,0)$$
where $\phi(x)$ represent normalized wave functions, you can just compare the coefficients, since the probability of $x$ being in a state $\phi$ is going to be $|c|^2$, and that will tell you in which state you're most likely to find the particle.
Bit of a long answer, but I hope it clears things up!


text:
Q: Multiple accounts in XMPPFramework I am new in XMPPFramework and I try to investigate it. So I have a question. Can XMPPFramework support multiple account login?

A: Yes, just use multiple instances of XMPPStream, one for each account.


text:
Q: openMP - parallelization with for loop and private I wrote a function to evaluate a given function at points in a set (set_). Code with no parallelization is like that:
void Method::evaluateSet(double* funcEvals_, double** set_)
{
    for(int j= 0;j<m_npts;j++)
    {
        if(!(isInsideConstraints(set_[j])) || qIsNaN(funcEvals_[j]) || !qIsFinite(funcEvals_[j]))
        {
            funcEvals_[j] = DBL_MAX;
        }
        else
        {
            solverInput input_(m_input);
            input_.setFunParameters(simplex_[j]);
            funcEvals_[j]=input_.apply(simplex_[j]);
        }
    }
}

and this is working properly.
I then parallelize using openMP, with a parallel construct, and a private copy of the variable set_ for each thread. Loop is
#pragma omp parallel for  private (set_)
for(int j= 0;j<m_npts;j++)
{
    if(!(isInsideConstraints(set_[j])) || qIsNaN(funcEvals_[j]) || !qIsFinite(funcEvals_[j]))
    {
        funcEvals_[j] = DBL_MAX;
    }
    else
    {
        solverInput input_(m_input);
        input_.setFunParameters(set_[j]);
        funcEvals_[j]=input_.apply(set_[j]);
    }
}
#pragma omp barrier

It crashes, and error occurs at if evaluation, with set_ is being used without been initialized. I don't understand. Since I set the set_ variable private, shouldn't there be a copy of original set_ in each thread?
What is wrong with the code and how to improve?
Thanks and regards.

A: When you use private for a variable a private copy starts with no value, I mean it is not initialized at that time. Therefore, the value passed by parameter do not set set_ variable. You need to use firstprivate instead, which first initializes the private copy with the current value.


text:
Q: Confirming password on registration with php In creating a registration page for a project I'm working on. It's very basic, just requires the user to enter a username and password but I want the user to confirm their password. I'm using:
$pattern = '/^[0-9]{6,}$/';

to ensure that only digits can be entered as a password and must be at least 6 digits long. Everything is working fine except for confirming password. I have attached my script below. Can anyone see what I'm doing wrong? When I enter two different values in the password boxes on my register.html page, it seems to just accept and enters the values to the database regardless.
    $username = $_POST['username']; //username
    $password = $_POST['password']; //password
    $confirmPass = $_POST['password2'];
    $error = array();
    $pattern = '/^[0-9]{6,}$/'; //pattern for password

if($_POST['register']){ //if register is clicked
    if(!preg_match($pattern, $password)){ //is password doesnt match...
        echo "Password must be at least 6 characters long and numerical characters only."; //error message
    }

$query = "SELECT * FROM users WHERE username = '$username'"; //calls exising profiles
$result = mysqli_query($conn, $query);
    if(mysqli_num_rows($result)>0){
        echo "You already have an account!"; //if username existsm error message displayed
    } else {

    }

if($password === $confirmPass){ //if two passwords do not match
    echo 'Passwords do not match!';
} else {
       if(preg_match($pattern, $password)){ //if passwords match
    $password = md5($confirmPass); //md5 encryption
    $query = "INSERT INTO users (username, password) VALUES ('$username', '$password')"; //inserts into the database
        echo'You are now a registered user!';
    if($conn->query($query) === TRUE){
    } else {
        echo"Error: " . $query / "<br>" . $conn->error;
    }
}
}

}

A: if($password === $confirmPass){ //if two passwords do not match
    echo 'Passwords do not match!';
} else {

This is incorrect. You're actually checking if they do match.
if($password != $confirmPass){ //if two passwords do not match
    echo 'Passwords do not match!';
} else {

This should fix the problem.


text:
Q: O que há de novo no R 3.3.3? O R-core team lançou em 06/03/2017 a versão 3.3.3 do R. Desde então, alguns pacotes estão lançando mensagens como esta:

package �nome_do_pacote� was built under R version 3.3.3

*

*O que há de novo no R 3.3.3?

*Vale a pena instalar o nova versão?

*Terei de reinstalar todos pacotes que uso?

A: *

*Aqui tem a lista do que há de novo no R 3.3.3. Como são 3.137 caracteres de informação, acho contraproducente copiar e colar tudo por aqui. Dê uma olhada no link para ver o que mudou.

*Defina "vale a pena". Dependendo do teu uso do programa, até mesmo uma versão 1.x pode ser útil. Particularmente, eu gosto de manter atualizados todos os programas do meu computador. Isto inclui o R e seus pacotes. O mensagem package "nome_do_pacote" was built under R version 3.3.3 só está te avisando que "nome_do_pacote" foi feito e testado com a versão 3.3.3 do R. Pode ser que haja algum problema se "nome_do_pacote" for utilizado numa versão anterior do programa. Mas pode ser que não haja problema algum. É só um aviso mesmo.

*Veja a resposta 2. Não é preciso reinstalar todos os pacotes, mas é sugerido que se faça. Pacotes atualizados podem ter bugs corrigidos, por exemplo.


text:
Q: Is there any config in laravel to disable function parameters logging during stack trace? Below is the log getting printed when an exception occurs in application:
"message"   => "Unhandled critical exception occured",
            "context"   => [
                "class"   => "Flight\\Exception\\FlightBookingErrorException",
                "code"    => "GATEWAY_ERROR_UNKNOWN_ERROR",
                "message" => "Booking processing failed due to error at bank or wallet gateway\nGateway Error Code=> \nGateway Error Desc: ",
                "data"    => [],
                "stack"   => [
                    "#0 /app/app/Http/Controllers/PaymentController.php(25): Flight\\Models\\Booking\\Service" .
                    "->generateTicket(**'Amul Baby', '99999999999', 9846372618163345, AmericanExpressB**)",
                    "#1 [internal function]: Flight\\Http\\Controllers\\PaymentController->processTicket()",
                    "#2 /app/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)",
                ]
            ]strong text

In the above code, generateTicket method has four arguments and all the sensitive data is logged. Is there a way to stop logging of function arguments as part of stack trace?


text:
Q: OpenOffice Calc: Fill Dropdown from Database? Is it possible to fill a dropdown list for a cell in OpenOffice Calc with entries from a database using a query?
I've found how to create the dropdown list using Data -> Validity and I created an .odb file to connect to by postgresql database using File -> New -> Database, but I can't find any input on what to do from that point on.
What I want is for example that when the Calc file is opened, the dropdown for the cell is populated by executing a select query against the database I created the .odb file for.


text:
Q: Spring Boot doesn't create tables in Postgres I am trying to generate schema tables based on entities. But tables are not created. What's wrong?
Entity example:
@Entity
@NoArgsConstructor
@Getter @Setter
public class User {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    public Long id;

    public String username;
    public String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User(String username) {
        this(username, username + "pass");
    }
}

application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/dbtest
spring.datasource.username=vssekorin
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update

Dependencies:
compile('org.springframework.boot:spring-boot-starter-data-jpa')
runtime('com.h2database:h2')
compile('org.telegram:telegrambots:3.6.1')
runtime('org.postgresql:postgresql')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')

Warning: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement

A: just change spring.jpa.hibernate.ddl-auto from update to create.

A: It should be:
spring.jpa.generate-ddl = true

in your application.properties.
Or you can change this line:
spring.jpa.hibernate.ddl-auto=update

in
spring.jpa.hibernate.ddl-auto=create

More details: Spring Database initialization

A: Try adding this property
spring.datasource.driverClassName=org.postgresql.Driver
and change spring.jpa.hibernate.ddl-auto from update to create

A: Entity(name="Users")
postgresql can't create a table named user
and
spring.jpa.hibernate.ddl-auto=create


text:
Q: How to test functions that use sink(type = "message") with testthat Within an R package I wrote a function that redirects all output from a sourced script to a log file using
sink(file = "some.log", type = "output")
sink(file = "some.log", type = "message")
source("script.R")

within the function. Now I want to test if this function works as expected which means that I need to test if certain output (including messages) was written to the specified log file.
This works fine when I run the test script in the console. But when I use devtools::test() or R CMD check, the messages are captured somewhere else and don't appear in the log file.
I understand that this behavior is somehow necessary for testthat to work, but how can I test if my function call produced all expected messages?

A: I think the best option is to leave it up to end-users to call sink() rather than include it as a function in your package. You can provide examples in a vignette to show users how you intend them to use sink() with their scripts.
Edit: you might find this vignette on test fixtures helpful, especially the case study on usethis: https://testthat.r-lib.org/articles/test-fixtures.html#case-study-usethis


text:
Q: Как фильтровать список на странице? Помогите пожалуйста исправить скрипт. jsfiddle
Я создал коллекцию из моделей, которые имеют только одно поле - 'title'. Потом я вывел их на страничку в виде списка и поместил рядом текстовое поле.
Я хотел бы чтобы пользователь вводил в поле для поиска буковки, а коллекция фильтровала модели. Соответственно на страничке список перестраивался бы. Но у меня скрипт не работает.
Делал по аналогии с этим рабочим примером
models and collection:
APP.NewsModel = Backbone.Model.extend({
  defaults:{
    "title": ""
  }
});

APP.NewsModelsCollection = Backbone.Collection.extend({
  model: APP.NewsModel,

  search : function(letters){ console.log(letters)
    if(letters == "") return this;

    var pattern = new RegExp(letters,"gi");
    return _(this.filter(function(data) {
        return pattern.test(data.get("title"));
    }));
  }
});

views:
APP.Filter = Backbone.View.extend({

  initialize: function() {
    var self = this;

    this.collection = new APP.NewsModelsCollection();

    var model1 = new APP.NewsModel({title: 'qwerty'}),
        model2 = new APP.NewsModel({title: 'qwddez'}),
        model3 = new APP.NewsModel({title: 'zxxc'});

    this.collection.add(model1);
    this.collection.add(model2);
    this.collection.add(model3);

    this.render();

    $('#filterTitleField').on('keyup', function() { self.search() });
  },

  render: function () {
    this._createNewsUnits();
    return this;
  },

  search: function(e){  console.log('search')
    var letters = $("#filterTitleField").val();
    this.collection.search(letters);
    console.log(this.collection.models)
    this._createNewsUnits();
  },

  _createNewsUnits: function () {
    $('#newsList').html('');

    this.collection.each(function (news) {
      var news = new APP.News({model: news});
      $('#newsList').append(news.render().el);
    }, this);
  }

});

APP.News = Backbone.View.extend({

  initialize: function(model) {
    this.model = model.model;
  },

  className: 'news',

  template: _.template($('#newsUnitTpl').html()),

  render: function () {
    this.$el.html(this.template({title: this.model.get('title')}));
    return this;
  }

});

A: Не думаю что это актуально, но раз я уж сюда заглянул:
Вероятно расставив консольлоги Вы убедились что если просто сделать так
this.collection.search(letters);

то это коллекцию не отфильтрует. В чем же дело?
Лезем в метод search и видим там такое:
return _(this.filter(function(data) {
        return pattern.test(data.get("title"));
    }));

Лезем в доки backbone и ищем там что же делает метод filter. Он в свою очередь валится в метод filter underscore. Ну да, так и есть, он просто возвращает вам отфильтрованную коллекцию.
Пункт 1. Метод filter возвращает Новую коллекцию, старую он не изменяет.
То есть для вашего списка это просто операция "сходи куда-то сделай что-то", данные с которыми этот список реально оперирует просто никто не меняет, вот он и не чешется перерисовываться.
То есть первую упомянутую строчку надо заменить на что-то вроде
this.collection = this.collection.search(letters);

Печатаем и получаем ошибку.  Что же такое? Ну наверное то, что
Пункт 2. Метод поиска должен возвращать коллекцию
а не массив, для верности зачем-то завернутый underscore враппером (ну ок, я понимаю, в примере так было, но пример немного другой, да и вообще не очень.)
То есть второй кусок кода можно переписать как-то так:
return new APP.NewsModelsCollection(this.filter(function(data) {
        return pattern.test(data.get("title"));
    }));

Наконец все фильтруется. Но возникает проблема в том, что фильтруется куда больше, чем мы хотим. Вводим "qw", хотим две записи, видим одну. И тут возникает
Пункт 3. Не доверяйте всякому левому коду из интернета.
На гитхаб может кто угодно выложить что угодно. Вы тоже можете. Я тоже могу, но мне влом. В частности в этом примере человек не учел, что регулярка с флагом g запоминает свою позицию, соответственно если эту регулярку вызывать в итераторе, то поведет она себя неинтуитивно. Можно впрочем каждый раз определять новую регулярку в теле цикла. Например так:
return new APP.NewsModelsCollection(this.filter(function(data) {
        var pattern = new RegExp(letters,"gi"); // вот здесь
        return pattern.test(data.get("title"));
    }));


text:
Q: Python Telegram Bot's webhook goes into infinite loop I built a simple telegram bot that runs on Google Cloud Functions. My webhook looks like this:
def webhook(request):
    bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"])
    if request.method == "POST":
        update = telegram.Update.de_json(request.get_json(force=True), bot)
        #my code calls functions in here
    return "ok"

The problem at this point is that my code takes too long to run, which causes either Telegram or Google Cloud (haven't quite figured that out yet) to resend the request, creating more instances, sending more requests …
My only idea at this point would be to send the "ok" answer before my code runs, which doesn't seem right to me (and I don't know how to do tbh). So please point me in the right direction on how to deal with these situations.


text:
Q: Getting videos from a playlist Is there a way to get a listing of videos from a specific playlist? I tried the following call, but it doesn't seem to be giving me a list of videos in that playlist
feed://gdata.youtube.com/feeds/users/USERNAME/playlists/PLAYLIST_ID

I want get all the playlists video url and name ...
Thanks in advance,

A: This is available in the JavaScript API:

player.getPlaylist():Array
This function returns an array of the video IDs in the playlist as
  they are currently ordered. By default, this function will return
  video IDs in the order designated by the playlist owner. However, if
  you have called the setShuffle function to shuffle the playlist order,
  then the getPlaylist() function's return value will reflect the
  shuffled order.

A: That's v2 of the API that was deprecated over a year ago. You need to use v3.
Start here: https://developers.google.com/youtube/v3/docs/playlistItems/list


text:
Q: Loading CSV file from Google Drive to BigQuery produces zero rows with no errors A vendor provided me with a set of CSV files over Google Drive. When I load it to a new table in BigQuery using the URL to its location in Google Drive it seems to work without any errors, but there are zero rows in the table. The schema loads correctly. When I download the file to my hard drive and upload the same file it works fine - all of the data is there.
Any thoughts on what the problem might be or how to diagnose it?

A: "Loading data into BigQuery from Google Drive is not currently supported, but you can query data in Google Drive by using an external table."


text:
Q: Showing that $f(x) = 4x^2 - 3x^7$ is a pemutation in $\mathbb{Z}_{11}$ and factoring it as a product of disjoint cycles I need to show that $f:\mathbb{Z}_{11}\to \mathbb{Z}_{11}$ given by $f(x) = 4x^2 - 3x^7$, where the operations are the usual in $\mathbb{Z}_{11}$, is a permutation of the elements of $\mathbb{Z}_{11}$. I also need to write $f$ as a product of disjoint cycles.
Given that I need to write it as product of disjoint cycles, I thought show the bijection by calculating $f$ in every point, but the direct calculations are long so I'm trying to use some modular arithmetic: the Fermat primality test gives that $x^{10}\equiv_{11} 1$ so that every $x^5$ is it's own inverse $\mod{11}$. So, once $11$ is prime, $x^5\equiv_{11} 1$ or $x^5\equiv_{11} -1$. So either $-3x^7\equiv_{11} -3x^2$ or $-3x^7\equiv_{11} 3x^2$, then we can simplify $f$ by:
$$
f(x) =
\begin{cases}
x^2,  & \text{if $x^5\equiv_{11} 1$} \\
7x^2, & \text{if $x^5\equiv_{11} -1$}
\end{cases}
$$
But still there's too much calculations to be done, there is another way or further simplifying on this one to have less calculations in the end? Thanks in advance.

A: Let $R$ denote the set of nonzero quadratic residues modulo $11$, and $N$ the set of quadratic nonresidues.  Note that $2$ is a generator of the multiplicative group $(\mathbb{Z}/11\mathbb{Z})^\times$.  Since $f(x)=x^2$ if $x\in R$, we have $f|_R:R\to R$ and $f$ maps
$$2^2\mapsto 2^4\mapsto 2^8\mapsto 2^6\mapsto 2^2\;\;(4\mapsto 5\mapsto 3\mapsto 9\mapsto 4)$$
and
$$2^0\mapsto 2^0\;\;(1\mapsto 1)\,.$$
Since $$f(x)=7x^2=128x^2=2^7x^2=2^{-3}x^2$$ if $x\in N$, we conclude that $f|_N:N\to N$.  Note that $f$ maps
$$2^1\mapsto 2^9\mapsto 2^5\mapsto 2^7\mapsto 2^1\;\;(2\mapsto6\mapsto 10\mapsto 7\mapsto 2)\,,$$
and
$$2^3\mapsto 2^3 \;\;(8\mapsto 8)\,.$$
Along with $f(0)=0$, we conclude that $f$ is a permutation on $\mathbb{Z}/11\mathbb{Z}$ with the following cycle decomposition:
$$(0)\,(1)\,(8)\,(2\;\;6\;\;10\;\;7)\,(4\;\;5\;\;3\;\;9)\,.$$
I am quite curious how these polynomials are found (namely, polynomial functions that act like permutations on $\mathbb{Z}/m\mathbb{Z}$, where the positive integer $m$ tends to be prime).  Is there a construction, or are these polynomials results of brute-force searching?
At least, if $p$ is a prime natural number such that $p\equiv 3\pmod{4}$, $r\neq 0$ is a quadratic residue modulo $p$, and $n$ is a quadratic nonresidule modulo $p$, then we can take
$$f(x):=(r+n)\left(\frac{p+1}{2}\right)\,x^2+\Biggl(r\left(\frac{p+1}{2}\right)+n\left(\frac{p-1}{2}\right)\Biggr)\,x^{\frac{p+3}{2}}\,.$$
Then, $f$ is a permutation on $\mathbb{Z}/p\mathbb{Z}$.  The polynomial of this particular question comes from $p=11$, $r=1$, and $n=7$.

A: Let's proceed as in the comments of @hardmath and @AndreasBlass.
We'll just evaluate and see which (if any) permutation it is.
$f(0)=0, f(1)=1,f(2)=6,f(3)=9,f(4)=5,f(5)=3,f(-5)=10,f(-4)=2,f(-3)=8,f(-2)=4,f(-1)=7$.
Thus we have $(26\,10\,7)(4539)$.


text:
Q: Python Selenium Headless Threading I have this Python Selenium Threading script but how can I make it run headless ?

def checkout(browser, url):
  browser.get(url)

browserThread1 = threading.Thread(target = checkout, args = (webdriver.Chrome(), 'https://www.google.com'))
browserThread2 = threading.Thread(target = checkout, args = (webdriver.Chrome(), 'https://www.google.com'))
browserThread3 = threading.Thread(target = checkout, args = (webdriver.Chrome(), 'https://www.google.com'))
browserThread4 = threading.Thread(target = checkout, args = (webdriver.Chrome(), 'https://www.google.com'))
browserThread1.start()
browserThread2.start()
browserThread3.start()
browserThread4.start()

A: You can create Chrome options and add it to thread which you want to run on headless mode.
import threading
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def checkout(browser, url):
   browser.get(url)

options = Options()
options.headless = True

browserThread1 = threading.Thread(target = checkout, args = (webdriver.Chrome(options=options), 'https://www.google.com'))
browserThread2 = threading.Thread(target = checkout, args = (webdriver.Chrome(options=options), 'https://www.google.com'))
browserThread3 = threading.Thread(target = checkout, args = (webdriver.Chrome(options=options), 'https://www.google.com'))
browserThread4 = threading.Thread(target = checkout, args = (webdriver.Chrome(options=options), 'https://www.google.com'))
browserThread1.start()
browserThread2.start()
browserThread3.start()
browserThread4.start()


text:
Q: Jenkins build fails after running Cucumber tests on Java heap space exception I get following exception when building using Jenkins. This exception raises after running Cucumber tests.
Can anyone tell the exact spot that fails on the java heap space?
Do you have any idea what can be done in order to solve it?
Some background: I had a java heap space during the Cucumber tests, after I increased the memory, Cucumber tests pass, but I get this java heap space right after.
Thanks,
Lior
mojoSucceeded org.apache.maven.plugins:maven-surefire-plugin:2.9(default-test)
[JENKINS] Recording test results
mavenExecutionResult exceptions not empty
message : Java heap space
Stack trace :
java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3209)
    at java.lang.String.<init>(String.java:215)
    at com.sun.org.apache.xerces.internal.xni.XMLString.toString(XMLString.java:185)
    at com.sun.org.apache.xerces.internal.util.XMLAttributesImpl.getValue(XMLAttributesImpl.java:537)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$AttributesProxy.getValue(AbstractSAXParser.java:2319)
    at org.dom4j.tree.AbstractElement.setAttributes(AbstractElement.java:543)
    at org.dom4j.io.SAXContentHandler.addAttributes(SAXContentHandler.java:916)
    at org.dom4j.io.SAXContentHandler.startElement(SAXContentHandler.java:249)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:179)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:377)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2756)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:647)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.dom4j.io.SAXReader.read(SAXReader.java:264)
    at hudson.tasks.junit.SuiteResult.parse(SuiteResult.java:112)
    at hudson.tasks.junit.TestResult.parse(TestResult.java:227)
    at hudson.tasks.junit.TestResult.parse(TestResult.java:163)
    at hudson.maven.reporters.SurefireArchiver.postExecute(SurefireArchiver.java:141)
    at hudson.maven.Maven3Builder$MavenExecutionListener.recordMojoEnded(Maven3Builder.java:421)
    at hudson.maven.Maven3Builder$MavenExecutionListener.mojoSucceeded(Maven3Builder.java:403)
    at org.jfrog.build.extractor.maven.BuildInfoRecorder.mojoSucceeded(BuildInfoRecorder.java:241)
    at org.apache.maven.lifecycle.internal.DefaultExecutionEventCatapult.fire(DefaultExecutionEventCatapult.java:87)
    at org.apache.maven.lifecycle.internal.DefaultExecutionEventCatapult.fire(DefaultExecutionEventCatapult.java:42)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:228)
channel stopped

A: Go into the Jenkins settings and add the environment variable MAVEN_OPTS to -Xmx512m -XX:MaxPermSize=256m. It looks like after your tests are finished it's trying to parse the results but the XML file is too large.

A: I'm not sure what your CI environment is like, but if you're running Jenkins as a Windows Service, you could also try increasing the heap size that's available to it.
To do this, locate the file at ${JENKINS_HOME}\jenkins.xml and update the command line arguments appropriately. (ie, change "-Xmx256m" to a larger value such as "-Xmx512m").

A: I would first try to analyze the reason for the longer output from the cucumber.
In my case it was same stack trace which was reported by the cucumber for too many tests.


text:
Q: PySide/PyQt4 draw nodes and connections Trying to create nodes and connect them to each other. I'm stacked on setElementPositionAt. The error is:
AttributeError: 'PySide.QtGui.QPainterPath' object has no attribute 'updateElement'
I have found the working code here: How can I draw nodes and edges in PyQT? but can't adapt it to my widget.
What I'm doing wrong?
Here is the code:
from PySide.QtCore import *
from PySide.QtGui import *

rad = 5

class WindowClass(QMainWindow):
    def __init__(self):
        super(WindowClass, self).__init__()
        self.view = ViewClass()
        self.setCentralWidget(self.view)

class ViewClass(QGraphicsView):
    def __init__(self):
        super(ViewClass, self).__init__()

        self.setDragMode(QGraphicsView.RubberBandDrag)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.s = SceneClass()
        self.setScene(self.s)
        self.setRenderHint(QPainter.Antialiasing)

class SceneClass(QGraphicsScene):
    def __init__(self, id=None):
        super(SceneClass, self).__init__()
        self.setSceneRect(-1000, -1000, 2000, 2000)
        self.grid = 30

        self.p = QPainterPath()
        self.it = None
        self.node = None

    def drawBackground(self, painter, rect):
        if False:
            painter = QPainter()
            rect = QRect()

        painter.fillRect(rect, QColor(30, 30, 30))
        left = int(rect.left()) - int((rect.left()) % self.grid)
        top = int(rect.top()) - int((rect.top()) % self.grid)
        right = int(rect.right())
        bottom = int(rect.bottom())
        lines = []
        for x in range(left, right, self.grid):
            lines.append(QLine(x, top, x, bottom))
        for y in range(top, bottom, self.grid):
            lines.append(QLine(left, y, right, y))
        painter.setPen(QPen(QColor(50, 50, 50)))
        painter.drawLines(lines)

    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:
            self.p.moveTo(0, 0)
            self.p.lineTo(200, 100)
            self.it = Path(self.p,None)
            self.addItem(self.it)
            for i in xrange(2):
                self.node = Node(self, i, QPointF(self.p.elementAt(i)))
                self.node.setPos(QPointF(self.p.elementAt(i)))
                self.addItem(self.node)

        super(SceneClass, self).mousePressEvent(event)

class Path(QGraphicsPathItem):
    def __init__(self, path, scene):
        super(Path, self).__init__(path)
        self.pth = path

        self.scn = SceneClass(self.setPen(QPen(Qt.red, 1.75)))

    def updateElement(self, index, pos):
        print pos
        self.pth.setElementPositionAt(index, pos.x(), pos.y())
        self.pth.setPath(self)

class Node(QGraphicsEllipseItem):
    def __init__(self, path, index, pos):
        super(Node, self).__init__(-rad, -rad, 2*rad, 2*rad)

        self.pos = pos
        self.rad = rad
        self.path = QPainterPath()
        self.index = index
        self.setZValue(1)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges)
        self.setBrush(Qt.green)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemPositionChange:
            self.path.updateElement(self.index, value)
        return QGraphicsEllipseItem.itemChange(self, change, value)

if __name__ == '__main__':
    app = QApplication([])
    wd = WindowClass()
    wd.show()
    app.exec_()

A: You have made changes to the base classes that you have taken as reference so it is normal for you to have errors if you do not understand the code.
When you call the updateElement method you must do it from an instance of the Path class, not an instance of the class QPaintePath, I have placed the same code of the author that you took as a reference initially and I have added to your graphic part.
class WindowClass(QMainWindow):
    def __init__(self):
        super(WindowClass, self).__init__()
        self.view = ViewClass()
        self.setCentralWidget(self.view)

class ViewClass(QGraphicsView):
    def __init__(self):
        super(ViewClass, self).__init__()

        self.setDragMode(QGraphicsView.RubberBandDrag)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.s = SceneClass()
        self.setScene(self.s)
        self.setRenderHint(QPainter.Antialiasing)

class SceneClass(QGraphicsScene):
    def __init__(self, id=None):
        super(SceneClass, self).__init__()
        self.setSceneRect(-1000, -1000, 2000, 2000)
        self.grid = 30
        self.it = None
        self.node = None

    def drawBackground(self, painter, rect):
        if False:
            painter = QPainter()
            rect = QRect()

        painter.fillRect(rect, QColor(30, 30, 30))
        left = int(rect.left()) - int((rect.left()) % self.grid)
        top = int(rect.top()) - int((rect.top()) % self.grid)
        right = int(rect.right())
        bottom = int(rect.bottom())
        lines = []
        for x in range(left, right, self.grid):
            lines.append(QLine(x, top, x, bottom))
        for y in range(top, bottom, self.grid):
            lines.append(QLine(left, y, right, y))
        painter.setPen(QPen(QColor(50, 50, 50)))
        painter.drawLines(lines)

    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:
            path = QPainterPath()
            path.moveTo(0, 0)
            path.lineTo(200, 100)
            self.addItem(Path(path, self))
        super(SceneClass, self).mousePressEvent(event)

class Node(QGraphicsEllipseItem):
    def __init__(self, path, index):
        super(Node, self).__init__(-rad, -rad, 2*rad, 2*rad)

        self.rad = rad
        self.path = path
        self.index = index

        self.setZValue(1)
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges)
        self.setBrush(Qt.green)

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemPositionChange:
            self.path.updateElement(self.index, value)
        return QGraphicsEllipseItem.itemChange(self, change, value)

class Path(QGraphicsPathItem):
    def __init__(self, path, scene):
        super(Path, self).__init__(path)
        for i in range(path.elementCount()):
            node = Node(self, i)
            node.setPos(QPointF(path.elementAt(i)))
            scene.addItem(node)
        self.setPen(QPen(Qt.red, 1.75))

    def updateElement(self, index, pos):
        path = self.path()
        path.setElementPositionAt(index, pos.x(), pos.y())
        self.setPath(path)


text:
Q: Counting how many entries in a different model have a certain criteria This is a problem I have been working on for a very long time to no avail.
Basically I have two Models: Units and Trades, what i want is when I am on the View for Units, which returns a paged list of the units. What I want is an additional column to the table which returns a count of how many entries in Trades have Trade.Name = model.Name for each Unit.
The first problem I am having is accessing two models from one view. I have tried tons of things based on searching, but can't seem to be able to make anything work.
The second problem is how to actually do the count. Is it possible to use Linq directly from the View? It hasn't been working for me so far.
Thanks in advance or any help!
The important part of the Units view:
@model PagedList.IPagedList<FTv2.Models.Unit>

        Name
        Type
        Skill
        Rating

@foreach (var item in Model) {

            @{ ViewBag.ImgUrl = item.Name + ".png";}

            @Html.DisplayFor(modelItem => item.Name)

            @Html.DisplayFor(modelItem => item.Type)

            @Html.DisplayFor(modelItem => item.Skill)

            @Html.DisplayFor(modelItem => item.Rating)

}

Last issue, not showing any results in the View.
Here's the relevant parts of the controller:
    var units = db.Units;
    var students = db.Units.Select(u => new UnitViewModel()
    {
        Unit = u,
        TradeCount =
               db.Movies.Where(t => t.Name == u.Name).Count()
    });
    return View(students.ToPagedList(pageNumber, pageSize));

A: Get everything you need server side and pass it to the view. You can do the count in the controller GET action first, and pass it using ViewBag or add a property in your view model to hold the counts.
    [HttpGet]
    public ActionResult MyView()
    {
       var units = _context.Units.Where(//whatever);

       var viewModels = units.Select(u => new UnitViewModel()
                                           {
                                               Unit=u,
                                               TradeCount =
                                                      context.Trades.Where(t => t.name == u.name).Count()
                                             });
       return View(viewModels);

    }

EDIT:
I would write a view model class for your view. So instead of the view using a model of List<Unit>, now it uses List<UnitViewModel>.
public class UnitViewModel
{
   public Unit Unit {get;set;}
   public int TradeCount {get;set;}
}

EDIT VIEW:
 @model PagedList.IPagedList<FTv2.Models.UnitViewModel>

            Name
            Type
            Skill
            Rating

    @foreach (var item in Model) {

                @{ ViewBag.ImgUrl = item.Name + ".png";}

                @Html.DisplayFor(modelItem => item.Unit.Name)

                @Html.DisplayFor(modelItem => item.Unit.Type)

                @Html.DisplayFor(modelItem => item.Unit.Skill)

                @Html.DisplayFor(modelItem => item.Unit.Rating)

                  @Html.DisplayFor(modelItem => item.TradeCount)

    }


text:
Q: Unity referances not working Visual Studio 2022 As seen in the image bellow, references are not showing up in visual studio.
I was just using visual studio and i closed the project opened some other project and opened the unity project again in visual studio.
But then none of the references shows up and i cant really fix it.
Any ideas on how to fix this?

A: In Unity Editor try:
Edit -> Preferences... -> External Tools -> Regenerate project files

A: This problem happened to me, I couldn't solve it, I reinstalled visual again and downloaded c# plugins and module so it worked

A: The code pair may not be able to compile due to not referencing the relevant library files and namespaces


text:
Q: BindingSeq and Constants in Binding.scala?
*

*Binding is val of Var.

*BindingSeq should also be val of Vars.

But, to construct sequence of Binding, the BindingSeq can not be constructed from sequence.
Is there something wrong?
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.{BindingSeq, Var, Vars}

val x1: Var[Int] = Var{1}
val x2: Binding[Int] = Binding{1}
val x3: Vars[Int] = Vars{Seq(1,2,3): _*}
val x4: BindingSeq[Int] = BindingSeq{Seq(1,2,3): _*}
ScalaFiddle.scala:18: error: .this.com.thoughtworks.binding.Binding.BindingSeq.type does not take parameters
  val x4: BindingSeq[Int] = BindingSeq{Seq(1,2,3): _*}


text:
Q: C++ error: a storage class can only be specified for objects and functions struct I get the error message :
error: a storage class can only be specified for objects and functions struct
in my header file..
/*
 * stud.h
 *
 *  Created on: 12.11.2013
 *      Author:
 */

//stud.h: Definition der Datenstruktur Stud
#ifndef _STUD_H
#define _STUD_H

struct Stud{
        long matrnr;
        char vorname[30];
        char name[30];
        char datum[30];
        float note;
    };

extern Stud mystud[];

int einlesen (struct Stud[]);
void bubbleSort(struct Stud[] , int );
void ausgeben(struct Stud[], int);

#endif

where is the problem?

A: I would say that your problem is with the
extern Stud mystud[];

It probably should change to something more like
extern struct Stud* mystud;

and then in the implementation file for this header:
struct Stud stud_storage[SIZE];
struct Stud* mystud = stud_storage;

I think you could possibly get away with the extern struct Stud mystud[]; declaration with some compilers that will always convert that internally the corresponding pointer type, but not with all compilers (Need to double check my ANSI standard (C89) to be sure, but the conversion is only allowed by the standard in function declarations and definitions not in variable declarations.)


text:
Q: extracting the column using AWK I am trying to extract column using AWK.
Source file is a .CSV file and below is command I am using:
 awk -F ',' '{print $1}' abc.csv > test1

Data in file abc.csv is like below:
xyz@yahoo.com,160,1,2,3
abc@ymail.com,1,2,3,160

But data obtained in test1 is like :
abc@ymail.comxyz@ymail.com

when file is opened in notepad after downloading the file from server.

A: Notepad doesn't show newlines created on unix. If you want to add them, try
awk -F ',' '{print $1"\r"}' abc.csv > test1

A: Since you're using a Window tool to read the output you just need to tell awk to use Windows line-endings as the Output Record Separator:
awk -v ORS='\r\n' -F',' '{print $1}' file