text:
Q: Change of basis of a linear map from $\mathbb{R}^2→\mathbb{R}^3$ I have the following question in my workbook:
The linear map      $f:\mathbb{R}^2→\mathbb{R}^3$ is given by
$f(x,y)=(−2x+y,−x−y,−x−3y)$
Consider the following new bases:

*

*in $\mathbb{R}^2: [1, 2], [1, 1]$

*in the image: $[0, −3, −7] , [3, 9, 19]$
Provide the matrix of $f$ with respect to these new bases.
This question is really throwing me off, any advice on how to approach this would be greatly appreciated.

A: So to find the matrix, we need to investigate how the linear map acts on the basis elements, and represent that in our new basis. In particular, we have the two bases $\mathcal{B}=\{(1,2),(1,1)\}$ and $\mathcal{B}'=\{(0,-3,-7),(3,9,19)\}$ (which we have ordered), and want to express $f(v)$ in $\mathcal{B}'$ for each $v\in\mathcal{B}$. Let's write
$$v_1=(1,2),\quad v_2=(1,1),$$
$$u_1=(0,-3,-7),\quad u_2=(3,9,19).$$
Now as
$$f(x,y)=(-2x+y,-x-y,-x-3y),$$
we get that
$$f(v_1)=u_1,\quad f(v_2)=-\frac{1}{3}u_1-\frac{1}{3}u_2$$
(I'll leave the details to you). We thus get the matrix of $f$ with respect to $\mathcal{B}$ and $\mathcal{B}'$ as
$$\begin{pmatrix}
1&-\frac{1}{3}\\
0&-\frac{1}{3}
\end{pmatrix}.$$
In particular, the columns are the coordinates of the images of the basis vectors of $\mathcal{B}$ with respect to $\mathcal{B}'$. The reason this is always the case is that the matrix is supposed to encompass how the linear map maps coordinates in the first basis to coordinates in the second basis, which is precisely what will occur if this is the case (I advise you play around with it a bit if it's not immediately clear why).


text:
Q: Apache NiFi with MongoDB over SSL I've faced the problem with SSL connection to MongoDB (SSLContextService processors).
all certificates I've generated (Root, Server and Client). Server and Client certificates I've signed with my root certificate. Since my MongoDB-Sever has more then one IP-Address, I've include all IP-Addresses in the server certificate.
MongoDB is also configured for ssl connections (tls), the old version of tls (1.1, 1.2) are not disabled in MongoDB.
SSL-Connection with mongo-shell works without problems. I've also checked everything with openssl s_client and connection was there and also worked properly.
For Apache NiFi I've created keystore (PKCS12)
openssl pkcs12 -export -name client -in client.crt -inkey client.key -certfile ca.crt -out client.p12

and also truststore with server certitiface
openssl pkcs12 -export -name server -in server.crt -inkey server.key -out server.p12

and I've also tried
openssl pkcs12 -export -name server -in server.crt -inkey server.key -certfile ca.crt -out server.p12

ca.crt is my root certificate. client.crt and server.crt were sigend with this ca.crt.
I've used both services in NiFi:
StandardSSLContextService and StandardRestrictedSSLContextService. In the parameter Keystore I've put client.p12 and in truststore parameter server.p12. Both types PKSC12. TLS protocoll just TLS.
But anyway I get an error "PKIX path building failed".
I'm not sure what I've missed, but may be someone had such problem already.
Thanks in advance.
P.S. forgotten:
If I set in MongoDBControllerService parameter "Client Auth" to "NONE" then it works.

A: PKIX path building errors mean that NiFi cannot construct the trusted "path" between the certificate that is presented by the other endpoint (in this case MongoDB) and any of the certificates which are loaded in the respective truststore to identify trusted certificates.
If I am watching my niece tells me she's allowed to have all the candy she wants, I am not likely to agree. However, if she has a signed note from her parent confirming that, she gets candy. If she has a note signed by herself in crayon, not so much.
The likely solution is to concatenate the root public certificate and the node certificate into a single file (literally just cat server.pem ca.pem > combined_server.pem; make sure the node cert is first). That command assumes the certificate files are in PEM-encoded ASCII format (i.e. starts with -----BEGIN CERTIFICATE-----) and I prefer using .pem for the extension here, though .crt files can also contain this data. You can then verify that the chain is correct with
openssl verify -verbose -purpose sslserver -CAfile ca.pem combined_server.pem

For consistency, I'd repeat the process with the client cert and CA as well (use -purpose sslclient in the verification command). Then regenerate the PKCS12 keystore & truststore and load them into NiFi.
I am slightly confused by the fact that you say disabling client authentication in NiFi allows this to work, as NiFi should be acting as the client, and clients don't get to determine the client authentication level (the setting is literally ignored when acting as a client). It should only matter if NiFi is somehow acting as the server and MongoDB is the client. What version of NiFi and MongoDB are you using?

A: NiFi uses its own truststore which is either jks or pfx (p12) format, not concatenated pem files and not system files under /etc/pki/ca-trust/. As far as I can tell, you are not allowed to pass the tlsCAFile url parameter from a nifi processor which is confusing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error: Cannot find module './quasar.server-manifest.json' I'am upload my existing quasar project to another server then i found this error when i start it. anyone know what im wrong?

*

*run npm -i

*install quasar-cli

*install quasar


text:
Q: Аналог zoom в css? Свойство transform: scale() как свойство zoom В css есть свойство zoom, оно делает то, что нужно, но нет поддержки в браузерах (в частности Firefox).
Так же есть свойство transform: scale(), но дело в том, что блок main_div становится видимым при использовании transform: scale(), чего нет при использовании свойства zoom. Мне нужно именно такое поведение
Может свойство transform: scale() можно применить таким образом, чтобы он работал как zoom?
Или какие аналоги есть у свойства zoom?
Как быть в этой ситуации?
Здесь мой код. Проверять нужно в Google Chrome, т.к. в Firefox свойство zoom не работает.
https://jsfiddle.net/tj2349f5/1/

let test_button = document.querySelector('input.test_button');
test_button.addEventListener('click', () => {
  //second_div.style.transform = 'scale(0.5)';
  second_div.style.zoom = 0.5;
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

div {
    display: flex;
}

div#main_div {
  display: block;
  margin: 10px auto;
    height: 80vh;
    width: 80vw;
    background: red;
    overflow: scroll;
}

div#second_div {
    height: 3000px;
    width: 3000px;
    background: green;
  transform-origin: 0% 0%;
}

Hello

<input class="test_button" type="button" name="button_name" value="test">

A: Я бы решил так

let test_button = document.querySelector('input.test_button');
test_button.addEventListener('click', () => {
  span.classList.add('active');
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

div {
  display: flex;
}

div#main_div {
  display: block;
  margin: 10px auto;
  height: 80vh;
  width: 80vw;
  background: red;
  overflow: scroll;
}

div#second_div {
  height: 3000px;
  width: 3000px;
  background: green;
}

span {
  transform-origin: 0% 0%;
}

.active {
  transform: scale(0.5);
}

Hello

<input class="test_button" type="button" name="button_name" value="test">

A: Вы можете попробовать повесить transform: scale(n) на body и затем принудительно установить ширину body так, чтобы он вписался в область видимости окна.
Например, можно отмасштабировать таким образом в 2 раза:
body {
  transform: scale(2);
  width: calc(100vw / 2);
}

Возможно, дополнительно потребуется добавить смещение:
transform: scale(2) translateX(50vw);


text:
Q: how to get color code from color tag in android Is there any way to get color code
For example
   <resources>
        <color name="colorPrimary">#ff000000</color>
        <color name="colorPrimaryDark">#ff000000</color>
        <color name="colorAccent">#ff008dcd</color>
        <color name="colorControlHighlight">#ff757575</color>
        <color name="colorControlNormal">#ff57beee</color>
        </resources>

So I want to get the color name and color code
Let's take the first code
So it's colorPrimary and code is #ff000000
Attention
This code is not a color.xml but it's a string and I want to take the name and color code from it

A: Without alpha you can do this:
int colorPrimary = getResources().getColor(R.color.colorPrimary);
String strColorPrimary = "#"+Integer.toHexString(colorPrimary);

A: Similar question answered here:
Android get list of string resources from special file
So you can try to enumerate color resources in your case to find name that matches specific value.


text:
Q: Retrieving an encrypted password in PHP The following code is what I've used to encrypt a password in PHP...
$password = sha1(sha1($_POST['password']).sha1("mySalt@$#(%"));

What code can I use so users can log in using what they typed?

A: sha1 is a hashing algorithm, not a 2-way encryption. You cannot retrieve the original password.

*

*Hash the submitted password using the same algorithm.

*Fetch, from your database, the password hash for the user in question.

*Compare the two hashes. If they match, the credentials are OK.

*

*Don't use sha1 for password hashing, it isn't safe enough

*Use a unique salt per credential, don't reuse the same one each time.

A: You should use crypt for password hashing, sha1/md5 are too weak.
All you need:
function check_password($password) {
    ...//get db password to compare
    if (crypt($post_password, $db_results[0]['password']) == $db_results[0]['password']) {
        return true;
    } else { return false; }
}


text:
Q: Undefined index when assigning value to array element In while loop I'm assigning value pulled from DB to the array like so:
$states[$row['state']]

PHP gives me the following notice:

Notice: Undefined index: ME in
  /var/www/vhosts/basementfinishing-md-de.com/httpdocs/inc/class.cityBlock.php
  on line 67

What I'm doing wrong here?

A: It means $row['state'] is 'ME' and this index is not defined for $states.

A: I don't have enough context to interpret the error message 100%, but I've been known to do something like this:
      $states = array();
      while ($row = mysql_fetch_assoc($result)) {
        array_push($states, $row['state']);
      }


text:
Q: How prove this inequality: $\sum_{i,j=1}^{n}|x_{i}+x_{j}|\ge n\sum_{i=1}^{n}|x_{i}|$? Let $x_{1},x_{2},\cdots,x_{n}$ be real numbers. Show that

$$\sum_{i,j=1}^{n}|x_{i}+x_{j}|\ge n\sum_{i=1}^{n}|x_{i}|.$$

I think this problem may be solved using nice methods, but I can't find them yet; I know this may be of use:
$$|a|+|b|\ge |a+b|.$$
But I can't make it work. Thank you everyone.

A: The following solution has been presented by one of the participants of Romanian team selection test. Essentially, the problem boils down to the following completing the square. Note that $|x_i|+|x_j|-|x_i+x_j|=0$ when $x_ix_j\ge 0$ and $=2\min{(|x_i|,|x_j|)}$ when $x_ix_j< 0.$
With this in hands, we can estimate
\begin{align}
&\phantom{=}\sum_{1\leq i,j\leq n}(|x_i|+|x_j|-|x_i+x_j|)
\le \sum_{x_ix_j< 0}2\min\{|x_i|,|x_j|\}\\
&=4\sum_{x_i>0>x_j}\min\{x_i,-x_j\}
\leq 4\sum_{x_i>0>x_j}\sqrt{-x_ix_j}\\
&\le 4\sum_{x_i>0}\sqrt{x_i}\sum_{0>x_j}\sqrt{-x_j}
\leq \left (\sum_{x_i>0}\sqrt{x_i}+\sum_{0>x_j}\sqrt{-x_j}\right )^2\\
&= \left (\sum_{1\leq k\leq n}\sqrt{|x_k|}\right )^2
\leq n\sum_{1\leq k\leq n}|x_k|.
\end{align}
And the result follows.

A: The inequality asked is a consequence of
$$ \sum_{i,j} |x_i + x_j| \geq \sum_{i,j} |x_i-x_j|, \quad(\star) $$
a proof of which can be found below, or there (in a more general case).
Indeed, because of the convexity of $|\cdot|$ we have
$$
\forall (i,j),\qquad |x_i| \leq \frac{|x_i+x_j|+|x_i-x_j|}{2},
$$
so that, when summing over $i,j$ the inequality $(\star)$ yields
$$
n\sum_{i} |x_i| \leq \frac{1}{2}\sum_{i,j} |x_i+x_j| + \frac{1}{2}\sum_{i,j} |x_i-x_j| \leq \sum_{i,j} |x_i+x_j|.
$$

For the sake of completness, I give a proof of $(\star)$ in this particular case.
Step 1. notice that $|x_i+x_j|-|x_i-x_j| = 2\min(|x_i|,|x_j|)\times \begin{cases}1 & \text{if } x_i x_j > 0\\ -1 & \text{if } x_i x_j < 0\end{cases}$.
Step 2. let $A_t = \{i : x_i > t\}$ and $B_t = \{i : x_i < -t\}$. Using step 1, we have
\begin{align}
\frac{1}{2} \sum_{i,j} (|x_i + x_j| -|x_i-x_j|) = \sum_{i,j \in A_0} \min(|x_i|,|x_j|) &+\sum_{i,j \in B_0} \min(|x_i|,|x_j|)\\ & -2 \sum_{i\in A_0,j\in B_0} \min(|x_i|,|x_j|)
\end{align}
Step 3. We use the trick $\min(|x_i|,|x_j|) = \int_0^\infty 1_{t < |x_i|}1_{t < |x_j|}dt$ and the fact that $\sum_{i} 1_{t < x_i} = \sum_{i \in A_t} 1 = |A_t|$.
\begin{gather}
\sum_{i,j \in A_0} \min(|x_i|,|x_j|) = \int_0^\infty |A_t|\cdot |A_t|\,dt\\
\sum_{i,j \in B_0} \min(|x_i|,|x_j|) = \int_0^\infty |B_t|\cdot |B_t|\,dt\\
\sum_{i\in A_0, j\in B_0} \min(|x_i|,|x_j|) = \int_0^\infty |A_t|\cdot |B_t|\,dt\\
\end{gather}
Step 4. Putting things together, we proved that
$$
\frac{1}{2} \sum_{i,j} (|x_i + x_j| -|x_i-x_j|) = \int_0^\infty (|A_t|-|B_t|)^2\,dt \geq 0.
$$

A: For real $x_i$, I just found that I had given this answer to a similar question. That answer shows that
$$
\sum_{i,j=1}^n|x_i|\le\sum_{i,j=1}^n|x_i+x_j|
$$
Which is the same as this question.


text:
Q: Shortest path from source to and from a negative cycle using Bellman Ford I would like to find the shortest path from a source node in the graph to a negative cycle without walking over any cycle twice. If there is a definitive answer to this, please answer. Otherwise, I would like to show how I have approached the problem in the hope that others may show me where I have erred.
Below is a simplified version of my code which implements the Bellman-Ford algorithm to detect negative cycles (using Networkx). This is a straightforward implementation of the algorithm. I discuss my alterations to it further along.
class NegativeWeightFinder:
  def __init__(self, graph: nx.Graph):
    self.graph = graph
    self.predecessor_to = {}
    self.distance_to = {}

  def initialize(self, source):
    for node in self.graph:
      # Initialize all distance_to values to infinity and all predecessor_to values to None
      self.distance_to[node] = float('Inf')
      self.predecessor_to[node] = None

    # The distance from any node to (itself) == 0
    self.distance_to[source] = 0

    def bellman_ford(self, source):

      self.initialize(source)
      for i in range(len(self.graph) - 1):
        for edge in self.graph.edges(data=True):
          self.relax(edge)

      for edge in self.graph.edges(data=True):
        if self.distance_to[edge[0]] + edge[2]['weight'] <
          self.distance_to[edge[1]]:
          yield self._retrace_negative_loop(edge[1])

I have also implemented a method to retrace negative loops:
def _retrace_negative_loop(self, start):
  loop = [start]
  while True:
    next_node = self.predecessor_to[next_node]
    # if negative cycle is complete
    if next_node in loop:
      loop = loop[:loop.index(next_node) + 1]
      loop.insert(0, next_node)
      return loop

I would like to find the least-weighted path from and to each negative cycle in the graph. I believe this could be accomplished by, after completing the negative cycle,

*

*iterating over the second-least-weighted path to source (as the first leads to a negative cycle).

*To go from the cycle to the source (instead of from source to cycle), I added a predecessor_from data structure, which tracked the shortest path from each node to source (whereas predecessor_to tracks the shortest path from source to node).
I created a hacky data structure to track the least-weighted paths from each node to and from source, which basically functions like a priority queue allowing only unique elements (the highest priority of two equal elements takes precedence over the other). The code for this "priority set" is below
class PrioritySet:
  def __init__(self):
    self.heap = []
    self.popped = {}

  def add(self, d, pri):
    heapq.heappush(self.heap, (pri, d))

    return True

  def pop(self):
    popped = heapq.heappop(self.heap)
    while popped[1] in self.popped.keys():
      # Raises IndexError if done popping
      try:
          popped = heapq.heappop(self.heap)
      # for debugging
      except Exception as e:
          raise e

    self.popped[popped[1]] = popped[0]
    return popped

  def peek(self):
    # self.heap[0][1] is the name of the element
    try:
      while self.heap[0][1] in self.popped.keys():
        # Raises IndexError if done popping
        heapq.heappop(self.heap)
    # for debugging
    except Exception as e:
      raise e

    return self.heap[0]

  def reset(self):
    for key, value in self.popped.items():
      heapq.heappush(self.heap, (value, key))
    self.popped = {}

  @property
  def empty(self):
    for elem in self.heap:
      if elem[1] not in self.popped.keys():
        return False

    return True

  def __str__(self):
    return str(list(self.heap))

  def __repr__(self):
    return str(self)

  def __len__(self):
    total = 0
    seen = set()
    for elem in self.heap:
      if elem not in self.popped and elem not in seen:
        total += 1
        seen.add(elem)

    return total

Here is my implementation of this algorithm:
class NegativeWeightFinder:

    def __init__(self, graph: nx.Graph):
        self.graph = graph
        self.predecessor_to = {}
        self.distance_to = {}
        self.predecessor_from = {}
        self.distance_from = {}

        self.seen_nodes = set()

    def initialize(self, source):
        for node in self.graph:
            # Initialize all distance_to values to infinity and all predecessor_to values to None
            self.distance_to[node] = float('Inf')
            self.predecessor_to[node] = PrioritySet()
            self.distance_from[node] = float('Inf')
            self.predecessor_from[node] = PrioritySet()

        # The distance from any node to (itself) == 0
        self.distance_to[source] = 0
        self.distance_from[source] = 0

    def bellman_ford(self, source):
        self.initialize(source)
        # After len(graph) - 1 passes, algorithm is complete.
        for i in range(len(self.graph) - 1):
            # for each node in the graph, test if the distance to each of its siblings is shorter by going from
            for edge in self.graph.edges(data=True):
                self.relax(edge)

        for edge in self.graph.edges(data=True):
            if self.distance_to[edge[0]] + edge[2]['weight'] < self.distance_to[edge[1]]:
                yield self._retrace_negative_loop(edge[1],
                                                  source=source)
    def relax(self, edge):
        if self.distance_to[edge[0]] + edge[2]['weight'] < self.distance_to[edge[1]]:
            self.distance_to[edge[1]] = self.distance_to[edge[0]] + edge[2]['weight']

        # no matter what, adds this edge to the PrioritySet in distance_to
        self.predecessor_to[edge[1]].add(edge[0], self.distance_to[edge[0]] + edge[2]['weight'])

        if self.distance_from[edge[1]] + edge[2]['weight'] < self.distance_from[edge[0]]:
            self.distance_from[edge[0]] = self.distance_from[edge[1]] + edge[2]['weight']

        self.predecessor_from[edge[0]].add(edge[1],
                                           self.distance_from[edge[1]] + edge[2]['weight'])

        return True

    def _retrace_negative_loop(self, start, source=''):
        arbitrage_loop = [start]
        if source not in self.graph:
            raise ValueError("source not in graph.")

        # todo: i do not remember to which edge case this refers, test to see which then specify in the comment.
        # adding the predecessor to start to arbitrage loop outside the while loop prevents an edge case.
        next_node = self.predecessor_to[arbitrage_loop[0]].peek()[1]
        if unique_paths and next_node in self.seen_nodes:
            raise SeenNodeError(next_node)

        arbitrage_loop.insert(0, next_node)

        # todo: refactor this so it is not while True, instead while not next_to_each_other
        while True:
            next_node = self.predecessor_to[arbitrage_loop[0]].peek()[1]

            # if this edge has been traversed over, negative cycle is complete.
            if next_to_each_other(arbitrage_loop, next_node, arbitrage_loop[0]):
                arbitrage_loop.insert(0, next_node)
                arbitrage_loop = arbitrage_loop[:last_index_in_list(arbitrage_loop, next_node) + 1]

                self.predecessor_to[arbitrage_loop[0]].pop()

                def _pop_arbitrage_loop(loop, predecessor):
                    while predecessor[loop[0]].empty:
                        loop.pop(0)

                # add the path from source -> min_distance_to_node to the beginning of arbitrage_loop
                while arbitrage_loop[0] != source:
                    _pop_arbitrage_loop(arbitrage_loop, self.predecessor_to)
                    next_node = self.predecessor_to[arbitrage_loop[0]].pop()[1]
                    # if this edge has already been traversed over/ added to arbitrage_loop, must exit the cycle.
                    if next_to_each_other(arbitrage_loop, next_node, arbitrage_loop[0]):
                            self.predecessor_to[arbitrage_loop[0]].pop()
                        # this prevents an error where every edge from a node has been traversed over.
                        _pop_arbitrage_loop(arbitrage_loop, self.predecessor_to)

                        next_node = self.predecessor_to[arbitrage_loop[0]].pop()[1]

                    arbitrage_loop.insert(0, next_node)

                # add the path from arbitrage_loop[-1] -> source to the end of arbitrage_loop
                while arbitrage_loop[-1] != source:
                    next_node = self.predecessor_from[arbitrage_loop[-1]].peek()[1]
                    if next_to_each_other(arbitrage_loop, arbitrage_loop[-1], next_node):
                            self.predecessor_from[arbitrage_loop[-1]].pop()

                        arbitrage_loop.append(next_node)

                    self.reset_predecessor_iteration()
                    return arbitrage_loop

                arbitrage_loop.insert(0, next_node)

    def reset_predecessor_iteration(self):
        for node in self.predecessor_to.keys():
            self.predecessor_to[node].reset()
            # predecessor_to and predecessor_to have the same keys
            self.predecessor_from[node].reset()

def next_to_each_other(li: list, *args):
    for i in range(len(li) - (len(args) - 1)):
        for j in range(len(args)):
            if li[i + j] != args[j]:
                break
            if j == len(args) - 1:
                return True
    return False

def last_index_in_list(li: list, element):
    return len(li) - next(i for i, v in enumerate(reversed(li), 1) if v == element)


text:
Q: Xamarin.Forms: Performance differences in using DynamicResource over StaticResource I've seen a few questions asked around the performance difference in using DynamicResource over StaticResource but it's mainly been around WPF and not Xamarin.Forms mobile apps.
The context of my question is around a specific use-case I've got:
I have an application that only uses StaticResources at the moment but need the ability to have a 'flavour' of the app  (determined by an internal build time flag) that is able to change the style/theme at runtime -- the variables to be controlled via an API upon app initialisation.
So I'm currently facing the situation where I would need to change all StaticResource references in the XAML layouts to use DynamicResource. What are the performance implications of this?
Alternatively, would it be possible to write my own markup extension to return if it should use DynamicResource or a StaticResource depending on the internal 'flavour' flag that is currently set? So that way I don't need to ship code that references dynamic resources if the flavour does not require it to do so.

A: According to offical document Dynamic Styles in Xamarin.Forms:

The DynamicResource markup extension is similar to the StaticResource
markup extension in that both use a dictionary key to fetch a value
from a ResourceDictionary. However, while the StaticResource performs
a single dictionary lookup, the DynamicResource maintains a link to
the dictionary key. Therefore, if the dictionary entry associated with
the key is replaced, the change is applied to the visual element. This
enables runtime style changes to be made in an application.

Edit:
The dynamicResources will override the staticresources if they both exist.
I did a test about change staticresources into dynamic.
Xmal:
 <ContentPage.Resources>
        <Style TargetType="Label">
            <Setter Property="FontAttributes"
                    Value="Bold"/>
            <Setter Property="TextColor"
                    Value="Red"/>
        </Style>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!" x:Name="MyLabel"/>
            <Button Clicked="OnButton_Clicked"/>
        </StackLayout>
    </ContentPage.Content>

codebehind:
public Page1(bool IsDynamic)
    {
        var dynamicstyle = new Style(typeof(Label)) {
            Setters = { new Setter { Property=Label.FontProperty,
            Value="Bold"},
            new Setter{
            Property=Label.TextColorProperty,
            Value="Blue"} }
        };
        InitializeComponent();
        if (IsDynamic)
        { MyLabel.Style = dynamicstyle; }
    }
    private void OnButton_Clicked(object sender,EventArgs e)
    {
        Navigation.PushAsync(new Page1(true));

    }


text:
Q: The folder containing your music library cannot be found. Appears even after finding my library When I attempt to open my Music app on my MacBook Pro (Early 2013), MacOS Catalina version 10.15.7, this message appears.
When selecting Choose library, it takes me to my Music Folder where my iTunes folder is stored. Clicking on this folder and then selecting on iTunes Library.itl file as per the screenshots below simply takes me back to the original message.

I would prefer not to have to Create a new library from scratch or to use an older iTunes version (next oldest version was 2018, and I have used Music multiple times since then). The last time I used Music was in late 2020 or early 2021.
How I can get around this message and use my current iTunes library?


text:
Q: How to get current year in dotCMS? How to get current year in dotCMS? I need to display it in footer copyright. I am try this $date.format('YYYY', $UtilMethods.getCurrentDate()) but not working.

A: $dateString = $date.format('yyyy',$UtilMethods.getCurrentDate())

Not sure entirely, looks right, maybe try lower case 'yyyy' is the only difference I found in research.

A: This will give the result 2012: $date.format('yyyy',$UtilMethods.getCurrentDate())
Here you can find alot more about dotCMS and Velocity http://dotcms.org/documentation/VelocityAndDotCMS


text:
Q: How to go move from one activity to a fragment in android? I have this code to move from a Fragment MyTask extends Fragment  to an Activity NewPage extends activity.
Intent i4=new Intent(getActivity(),NewPage.class);
startActivity(i4);

Now I want to go from NewPage.class back to my MyTask fragment.
How can  I do that?

A: Use the finish() method in the Activity to close it.

A: Its a as simple you have to just call
finish()

method in your NewPage.class file.

A: Add the below line in your MainActivity and add FrameLayout to your activity_main.xml give the id to that .
Look the below code
"getSupportFragmentManager().beginTransaction().replace(R.id.your xml_frmaelayout_id,new next_Fragment()).commit();"

A: startActivity(new Intent(MainActivity.this, getApplicationContext().getClass()));


text:
Q: Query to check whether the id exists in a table or not I'm working on SQL Server 2008.
Following is my query,
CREATE PROCEDURE Usp_Travelready_Admin_AddUser
  (
     @pLoggedUserId AS INT,
     @pMappedUser AS INT
   )
AS
BEGIN
   SET NOCOUNT ON

   IF EXISTS
   (
      INSERT INTO TESTUSER (Var_LoggedInUser, Var_MappedUSer)
      VALUES (@pLoggedUserId, @pMappedUser)
   )
   ELSE
   (
      UPDATE TESTUSER
      SET Var_MappedUSer = @pMappedUser
      WHERE Var_LoggedInUser = @pLoggedUserId
   )

   SET NOCOUNT OFF
END

where TestUser table contains 2 columns Var_MappedUSer and Var_LoggedInUser I want to write a stored procedure to update the Var_MappedUSer if Var_LoggedInUser already exists in the table and insert user if it is not available in the table
What mistake did I make in above stored procedure?

A: Exists check if query returned any result so do this:
IF EXISTS (select * from TESTUSER where Var_LoggedInUser = @pLoggedUserId)
begin
  INSERT INTO TESTUSER (Var_LoggedInUser, Var_MappedUSer)
  VALUES (@pLoggedUserId, @pMappedUser)
end
ELSE
begin
  UPDATE TESTUSER
  SET Var_MappedUSer = @pMappedUser
  WHERE Var_LoggedInUser = @pLoggedUserId
end

Also using parenthesis to group operations between if.. else is invalid, you have to use begin .. end syntax.


text:
Q: Classifying the twisted I-bundle over Klein bottle I wanted to know how can I prove there are only two twisted I bundle over the Klein bottle. As I looked some topology texts, I couldn't find any solid definition of twisted I-bundle (or general definition of twisted fiber bundle) except that it is not the trivial product bundle $K\times I$(K is the Klein bottle). I was looking to finding out
(1)How can I show that $K\tilde{\times}I$ is orientable?
(2)why there are only two $K\tilde{\times}I$?
I would appreciate any help anyone can give me. Also, any references to this subject might do the job.
Edith: I have denoted the twisted I bundle over the Klein bottle by $K\tilde{\times}I$


text:
Q: impresspages html widget not saving I have a problem with saving content in html widget. I am using impresspages 4.4.2 (although problem was present on 4.4.0 I just have upgraded from). CMS is installed on a shared hosting so I only have access to cPanel.
I found this question without an answer
Impress Pages - HTML widget not saving/publishing
The comment says that the problem was with theme, that was including jquery.
I use RevolvePro theme purchased on impresspages market place. Looking through the assets it seems like it does indeed include jquery. It didn't look too easy to remove it. So I tried to perform the same html widget editing action with the other themes (Private Free, Air and Quick Start supplied with the CMS) with the same result - nothing was saved. Neither of those themes have jquery included as far as I can see.
What I see in the browser console is the following error:
POST http://domain.com/403      (Forbidden)
k.cors.a.crossDomain.send       ipCore.min.js?3:124
n.extend.ajax                   ipCore.min.js?3:122
updateWidget                    management.min.js?3:10
processSaveQueue                management.min.js?3:67
n.isFunction.f                  ipCore.min.js?3:2
(anonymousfunction)             management.min.js?3:64
n.extend.each                   ipCore.min.js?3:2
n.fn.n.each                     ipCore.min.js?3:2
methods.save                    management.min.js?3:63
$.fn.ipWidget                   management.min.js?3:68
$this.save                      management.min.js?3:61
save                            management.min.js?3:115
n.isFunction.f                  ipCore.min.js?3:2
n.event.dispatch                ipCore.min.js?3:66
r.handle                        ipCore.min.js?3:65

or if I switch to debug mode:
POST http://domain.com/403      (Forbidden)
k.cors.a.crossDomain.send       jquery.js?4:1953
n.extend.ajax                   jquery.js?4:1843
updateWidget                    content.js?4:340
processSaveQueue                jquery.ip.widget.js?4:159
n.isFunction.f                  jquery.js?4:95
(anonymousfunction)             jquery.ip.widget.js?4:86
n.extend.each                   jquery.js?4:72
n.fn.n.each                     jquery.js?4:21
methods.save                    jquery.ip.widget.js?4:72
$.fn.ipWidget                   jquery.ip.widget.js?4:203
$this.save                      jquery.ip.widget.js?4:21
save                            Html.js?4:85
n.isFunction.f                  jquery.js?4:95
n.event.dispatch                jquery.js?4:1043
r.handle                        jquery.js?4:1010

jquery.js based on location is referenced from the CMS core code (Ip/Internal/Core/assets/ipCore/), rather than from the theme.
I tried manually editing widget table with phpMyAdmin and results work fine, so editing is the only issue. It also seems like the issue is hosting or host settings specific as on the other shared hosting I can edit html widget without any problems.

A: This is a problem on your host. Have a look at the Apache logs. You have some kind of a security module on Apache that prevents POST data with HTML input.


text:
Q: How to configure timeout when getting items from DynamoDB I want to put a timeout when getting an item from the DynamoDB in Go. I tried to provide the http.Client with 500ms timeout, but it did not work.
Here's how I configured the Timeout. But when I use GetItem and it was hanging there.
func LocalDynamo() *dynamodb.DynamoDB {
    creds := credentials.NewStaticCredentials("123", "123", "")
    awsConfig := &aws.Config{
        Credentials: creds,
        Region:      aws.String("us-east-1"),
        Endpoint:    aws.String("http://127.0.0.1:8001"),
        HTTPClient: &http.Client{
            Timeout: 500 * time.Millisecond,
        },
    }
    awsSession := session.Must(session.NewSession(awsConfig))
    return dynamodb.New(awsSession)
}

A: You can use Context with a Timeout.
ctx, cancel := context.WithTimeout(context.TODO(), 500*time.Millisecond)
defer cancel()

getOuput, err := c.GetItemWithContext(aws.Context(ctx), input)

See: https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.GetItemWithContext
Your requests shouldn't take 500ms though. Seems rather slow for DynamoDB.


text:
Q: Vertical center image in div differences in Safari and FireFox I currently am comparing this in Safari and Firefox.
A small image inside a div, which I need to center vertically.
Here is a simple test case that I have distilled down:
http://dl.getdropbox.com/u/340087/Drops/09.23.09/so-03f73322-164033.html
This one is probably even more simple:
http://dl.getdropbox.com/u/340087/drops/09.23.09/align-42fc19f2-154007.html
1) Why do I need a space after the image in order to get any align css to work?
2) What can I do to get Safari to perfectly center, it is 1-2px too low, essentially lining up the top of the image with the text.
Thanks

A: Images are considered inline elements, so they're basically treated as text.
If you want exact positioning across browsers, the safest way is to use the image for a background, rather than an inline img element.

A: Enclose the text in a span, and apply vertical-align to that as well.
HTML snippet:

    Chose a User Name

CSS addition:
span { vertical-align: middle; }

Tested in recent versions of FF, IE, Safari, Chrome and Opera (Windows).

A: Try the universal selector:
div * { vertical-align: middle }

or go old school (if you can) and use tables?
There's always a difference of few pixels in Safari (Mac) and browsers because of the way safari renders text. Read about it here.


text:
Q: What will happen if an ideal current source is connected to a isolated resistance? I know that ideal current source is a theoretical thing. But when it comes to solve problems we have to consider these scenarios. Now suppose an ideal current source is connected with an isolated resistance; now what should happen; should the current flow in the resistance?
I am asking as an isolated resistance has infinite potential now the ideal current source which is connected at its another end has also infinite resistance so what do I make out of it should the current flow or not?

A: In the "theoretically ideal" world,  an "ideal current source" has infinite voltage available, so it can assert its current flow through an infinite resistance- like the case where the other leg of the resistor is not connected to the return port of the current source.
In the real world: unless the current path is from the current source, through the resistor, and then back to the current source in a complete loop, no current will flow because no one has on their lab bench a current source that can push any amount of current through several million ohms of resistance in an open circuit.

A: There is a eminently practical answer.
You simply compute the capacitance of the open circuit (everything has one) and then treat it like any other RC circuit connected to a ideal DC power supply.
For practical circuits, however, even with a large resistance the time constant is shorter than your sampling oscilloscope can measure. So you aren't going to find it easy to observer the transient behavior.


text:
Q: Why ld.exe cannot find certain files? I recently installed network simulation tool omnet++. I am following the tictoc example given in the documentation. When i run the make command i am getting the following error. How can i correct this?

A: This is happens as window antivirus treat netool.exe file as a virus as well some others windows antivirus do the same.
disable the antivirus before build (make) the omnet++ will solve this problem.


text:
Q: Cropping Image to Center in Responsive Full Width Slider I will prefix this by saying I am new to coding. I am modifying a child theme in wordpress.
I am attempting to center images within a responsive full width slider to crop from both the top and bottom evenly at it's widest width. I've tried a couple of different options with no success.
Here is a link to the website: http://50.87.248.76/~topheran/. It is for the initial slideshow at the top of the page.
Thank you for any help.
EDIT with HTML/CSS:
Thanks Jon for clarifying the etiquette for posting questions. Please let me know if I can add any further information.
Thanks again for any help.
HTML

k

CSS
`.fullwidth_slider {
   max-height: 975px;
   max-width: 100%;
   overflow: hidden;
   position: relative;
   display: block;
   z-index: 0;
}
.fullwidth_slider .carousel-inner img{
   max-height: 100%;
}
.slider_overlay {
   background: none repeat scroll 0 0 rgba(40, 40, 40, 0.7);
   bottom: 0;
   height: 100%;
   left: 0;
   overflow: hidden;
   position: absolute;
   right: 0;
   top: 0;
   z-index: 1;
}
.fullwidth_slider .carousel-inner img {
   border-radius: 0;
   -moz-border-radius: 0;
   -webkit-border-radius: 0;
   left: 0;
   position: relative;
   width: 100%;
   min-width: 1400px;
   z-index: 0;
   max-height: 100%;
}

.fullwidth_slider .carousel{
   display: block;
   max-height: 1050px;
}
.fullwidth_slider .carousel-caption {
   background-color: rgba(0, 0, 0, 0);
   border-radius: 0;
   float: none;
   padding: 0;
   text-align: center;
   top: 30%;
}
.fullwidth_slider .carousel-control{
   cursor:pointer;
   z-index: 999;
}
.fullwidth_slider .carousel-indicators{
   bottom: 60px;
}
.fullwidth_slider .carousel-caption h1 {
   color: #FFFFFF;
   display: block;
   margin-top: 0;
   text-transform: uppercase;
}
.fullwidth_slider p.lead {
   color: #EBEDEF;
   font-size: 28px !important;
   line-height: 1.46429 !important;
   margin: 0 auto;
   max-width: 800px;
}
.fullwidth_slider .carousel-caption p {
   font-size: 18px;
   line-height: 1.72222;
   margin: 0 auto;
   max-width: 800px;
}
.fullwidth_slider .slider_overlay{
    z-index: 1;
}`

A: Since this is a WordPress tagged question, you can use the following code:
$image_width = 1280;
$image_height = 720;
add_image_size( 'Your_image_size_name', $image_width, $image_height, array( 'center', 'center' ) );

$image_width is currently set to 1280 and $image_height is set to 720. Both 1280 and 720 are number of pixels.
add_image_size() is the WordPress method for adding a new image size for each image you upload to your WordPress install. So each image you upload will have this size plus they will also be cropped from the center.
For more info about this go to
http://codex.wordpress.org/Function_Reference/add_image_size
and to
http://havecamerawilltravel.com/photographer/wordpress-thumbnail-crop
You can then use PHP's pathinfo() method like so and make your slideshow:
$IMG_parts = pathinfo( $img_url );
$html .= '';

Of Course, this will have to be inside a unordered list and each image will be inside a list item tag. Also don't forget your alt text for your images.


text:
Q: Let $ I $ be an ideal in $\mathbb Z [i]$. Show that $\mathbb Z[i] /I $ is finite.
Let $I$ be an ideal in $\mathbb Z[i]$. I want to show that $\mathbb Z[i]/I$ is finite.

I start with $Z[i]/I$ is isomorphic to $Z$.
$Z$ is ID then $I$ is prime .Here i get stuck.
Thanks for help.

A: Let $I \subseteq \mathbb{Z}[i]$ be a nonzero ideal. Since $\mathbb{Z}[i]$ is a principal ideal domain, it follows that $I = (\alpha)$ for some $\alpha \in \mathbb{Z}[i].$ Let $a + I$ be a coset of $I$ with $a = k \alpha + \beta$ and $\delta(\beta) < \delta(\alpha).$ In particular, every coset in $\mathbb{Z}[i]$ is represented by an element with norm less than $\delta(\alpha).$ Now let $z =  x+iy$ have norm $q.$ Then $x^2+y^2 = q$ with $|x|,|y| \leqslant q$ meaning that there are is a finite amount of possibilities for $z.$ Thus there are finitely many possible representatives of distinct cosets in $\mathbb{Z}[i].$ Therefore $\mathbb{Z}[i]/I$ is finite. $\hspace{1mm} \Box$

A: First of all you need $I \neq 0$ of course. Then you have some $0 \neq a+bi \in I$, in particular we have $\mathbb Z \ni D := a^2+b^2 = (a+bi)(a-bi) \in I$.
We obtain $(D) \subset I$, hence a surjection $\mathbb Z[i]/(D) \twoheadrightarrow \mathbb Z[i]/I$.
Thus it suffices to show that $\mathbb Z[i]/(D)$ is finite. $\mathbb Z[i]/(D)$ is an abelian group, generated by $1$ and $i$, which are both of finite order at most $D$.
But a finitely generated abelian group is finite if and only if all its generators have finite order.

A: Since I'm not sure what you wrote, I'll try to sketch the argument. Let $a+bi\in I$, with $a+bi\neq 0$. Then $b(a+bi)+ai(a+bi)\in I$, but this is equal to $(b^2+a^2)i\in I$. Thus also $b^2+a^2\in I$ by multiplication by $i^3$. Now we have that $\mathbb{Z}[i]/I$ contains less than $(b^2+a^2)^2$ elements (can you show how?). This gives the result.


text:
Q: UISearchDisplayController and related search result tableview I have 2 UITableView with UISearchDisplayController on a same UIView.
How to determine which one of the two UITableView relates to the UISearchDisplay Controller?
Welcome any comment

A: You can set tags both for the searchBars and tableViews, and check them appropriately in the callbacks of UISearchBarDisplayController and UITableView delegates.
For example:
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    if (controller.searchBar.tag == 1)
    {
        [self.tableView1 reloadData];
        return YES;
    }
    else if (controller.searchBar.tag == 2)
    {
        [self.tableView2 reloadData];
        return YES;
    }
    return NO;
}

You can always use tags on UIViews to check "who is who" in your code.
Hope this helps.


text:
Q: What should be REST response for GET call with identifiers as the query parameter if user does not have access to some of the requested resources? I am designing a REST API, where the user can place a GET call and fetch a list of items.
One of the query parameters that this API is allowing is also ids, a comma-separated list of identifiers that should be fetched.
This is an ability to filter items based on the known ids of resources.
GET /entities?ids=1,2,3
Now, there is also an authorization framework in this mix that provides an answer of what resources the user actually has access to.
So, say from the list of requested ids: 1,2,3 the user has access only to 1 and 3.
They are not allowed to access a resource with id 2.
What should be the REST response in this case?
Should I ignore the fact the user is asking for the forbidden resource and return 200 with the body containing items with ids 1 and 3?
Or, maybe, return 403 in this case... Opinions?

A: This request should fail
The client is explicitly requesting a specific resource that it doesn't have access to. That should not be part of the normal flow of your application, and I'd say it warrants an outright rejection.
The client may need to process the returned data, so a successful response that doesn't include the requested data should not be allowed to happen. If you do it, your client needs to write more code to account for this outcome, raising the likelihood of bugs and breaking trust with the client. Just return an error instead. Your client needs to handle these in any case.
My choice would be a 403 response with a message that informs the client why the request failed and includes steps to correct the issue.


text:
Q: LibGit2Sharp Cloning from a network file share I'm having issues cloning using the file transport when the remote is hosted on a network drive.
I downloaded the project and tried adding some test cases:
[Fact]
public void CanCloneALocalRepositoryFromANetworkDriveUri()
{
    var networkPath = @"file:///192.168.1.1/Share/TestRepo.git";
    var uri = new Uri(networkPath);
    AssertLocalClone(uri.AbsoluteUri, BareTestRepoPath);
}

That fails with:
LibGit2Sharp.LibGit2SharpException : failed to resolve path 'file://192.168.1.1/Share/TestRepo.git': The filename, directory name, or volume label syntax is incorrect.

I tried mapping a drive letter (Z:) to the share, and ran this:
[Fact]
public void CanCloneALocalRepositoryFromAMappedNetworkDrive()
{
    var networkPath = @"file:///Z:/TestRepo.git";
    var uri = new Uri(networkPath);
    AssertLocalClone(uri.AbsoluteUri, BareTestRepoPath);
}

That fails with:
LibGit2Sharp.LibGit2SharpException : failed to resolve path 'Z:/TestRepo.git': The system cannot find the path specified.

unless I set:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLinkedConnections
to a DWORD value of 1, as per this TechNet article - in which case the clone succeeds. However, this is not a viable solution in my situation, as it raises deployment issues in security-conscious environments.
It appears that LibGit2Sharp is not capable of cloning from a file UNC. Have I understood correctly, and if so is there any way to work around this?

A: The file:/// URL syntax is not appropriate for UNC paths.  Just use a UNC path, eg:
\\192.168.1.1\Share\TestRepo.git

This works in LibGit2Sharp and the git command-line client as well.


text:
Q: EventHandle.WaitOne + WebBrowser = Deadlock when waiting for DocumentComplete I've got a Problem with the automatisation of WebBrowsing in an C#-Program.
I've used the code before for a BHO and there it was working.
But within a pure c# Program there seems to be some kind of deadlock. I've instructed my program to click on a search button and then wait (via a manualresetevent) for documentcomplete to signal. But now it seems that the click on the search button isn't processed until the ManualResetEvent signals a timeout. Thereafter the click is made and also the DocumentComplete-Event is fired.
For the structure of that programm:
The WebBrowser-Control is part of a WindowsForm. The WebBrowser Control is passed to a Class which runs a Thread. This Class again passed the control to another class where the concrete behaviour according to the loaded webbrowser is programmed.
So in Code this lookes this way:

*

*Setup of the thread
_runner = new Thread(runner);
_runner.SetApartmentState(ApartmentState.STA);
_runner.IsBackground = true;
_runner.Start();

*Processing of withingthe Runner-Method
b.placeTipp(workStructure);

*The PlaceTipp-Method
public void placeTipp(ref OverallTippStructure tipp)
    {
        _expectedUrl = String.Empty;
        _betUrl = String.Empty;
        _status = BookieStatusType.CHECKLOGIN;

        while (true)
        {
            _mreWaitForAction.Reset();
            checkIETab();

            switch (_status)
            {
                case BookieStatusType.REQUESTWEBSITE:
                    ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Keine IE-Tab vorhanden. Fordere eine an", this.BookieName));
                    //if (RequestIETabEvent != null)
                    //    RequestIETabEvent(this, new EventArgs());
                    _status = BookieStatusType.NAVIGATETOWEBSITE;
                    _mreWaitForAction.Set();
                    break;
                case BookieStatusType.NAVIGATETOWEBSITE:
                    _webBrowser.Navigate(@"http://www.nordicbet.com");
                    break;
                case BookieStatusType.CHECKLOGIN:
                    checkLogin();
                    break;
                case BookieStatusType.LOGINNEEDED:
                    doLogin();
                    break;
                case BookieStatusType.LOGGEDIN:
                    _status = BookieStatusType.SEARCHTIPP;
                    _mreWaitForAction.Set();
                    break;
                case BookieStatusType.SEARCHTIPP:
                    searchTipp(tipp);
                    break;
                case BookieStatusType.NAVTOSB:
                    NavToSB();
                    break;
                case BookieStatusType.GETMARKET:
                    getMarket(tipp);
                    break;
                case BookieStatusType.PLACEBET:
                    placeBet(tipp);
                    break;
                case BookieStatusType.CONFIRMBET:
                    confirmBet();
                    break;
                case BookieStatusType.EXTRACTBETDATA:
                    extractBetId(ref tipp);
                    break;
                case BookieStatusType.FINISHED:
                    return;
            }

            if (!_mreWaitForAction.WaitOne(60000))
            {
                //Sonderüberpüfung be LoginNeeded
                if (_status == BookieStatusType.LOGINNEEDED)
                {
                    //checkLogin();
                    throw new BookieLoginFailedExcpetion();
                }
                //TIMEOUT!
                ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Timeout bei warten auf nächsten Schritt. Status war {1}", this.BookieName, this._status.ToString()));
                throw new BookieTimeoutExcpetion(String.Format("Bookie {0}: Timeout bei dem Warten auf Ereignis", this.BookieName));
            }
        }
    }

*The SearchTipp-Method where the Deadlock is happening:
private void searchTipp(OverallTippStructure tipp)
    {
        if (_webBrowser.InvokeRequired)
        {
            _webBrowser.Invoke(new delegatePlaceBet(searchTipp), new object[] { tipp });
        }
        else
        {
            ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Suche Tipp {1}", this.BookieName, tipp.BookieMatchName));
            _expectedUrl = String.Empty;
            if (!_webBrowser.Url.ToString().StartsWith("https://www.nordicbet.com/eng/sportsbook"))
            {
                ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Nicht auf Sportsbookseite. Navigiere", this.BookieName));
                _status = BookieStatusType.NAVTOSB;
                _mreWaitForAction.Set();
                return;
            }
            _searchCompleted = false;
            HtmlDocument doc = _webBrowser.Document;

            if (doc != null)
            {

                mshtml.IHTMLInputElement elemSearch = (mshtml.IHTMLInputElement)doc.GetElementById("query").DomElement;
                if (elemSearch != null)
                {
                    Thread.Sleep(Delayer.delay(2000, 10000));
                    elemSearch.value = tipp.BookieMatchName;

                    mshtml.IHTMLElement elemSearchButton = (mshtml.IHTMLElement)doc.GetElementById("search_button").DomElement;
                    if (elemSearchButton != null)
                    {
                        Thread.Sleep(Delayer.delay(900, 4000));

                        elemSearchButton.click();
                        //elemSearchButton.InvokeMember("click");

                        if (!_mreWaitForAction.WaitOne(10000)) //Here The Deadlock happens
                        {
                            //Now the click event and therefor the search will be executed
                            ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Suche ist auf Timeout gelaufen", this.BookieName));
                            throw new BookieTimeoutExcpetion(String.Format("Bookie {0}: Suche ist auf Timeout gelaufen", this.BookieName));
                        }

                        _mreWaitForAction.Reset();
                        HtmlElement spanResult = doc.GetElementById("total_ocs_count");
                        while (spanResult == null)
                        {
                            Thread.Sleep(500);
                            spanResult = doc.GetElementById("total_ocs_count");
                        }

                        int total_ocs_count = 0;
                        if (!Int32.TryParse(spanResult.InnerHtml, out total_ocs_count))
                        {
                            ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Tip {1} nicht gefunden", this.BookieName, tipp.BookieMatchName));
                            throw new BookieTippNotFoundExcpetion(String.Format("Bookie {0}: Tip {1} nicht gefunden", this.BookieName, tipp.BookieMatchName));
                        }

                        if (total_ocs_count <= 0)
                        {
                            ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Tip {1} nicht gefunden", this.BookieName, tipp.BookieMatchName));
                            throw new BookieTippNotFoundExcpetion(String.Format("Bookie {0}: Tip {1} nicht gefunden", this.BookieName, tipp.BookieMatchName));
                        }
                        /*
                    else if (total_ocs_count > 1)
                    {
                        throw new BookieMoreThanOneFoundExcpetion(String.Format("Bookie {0}: Tipp {1} nicht eindeutig", this.BookieName, tipp.BookieMatchName));
                    }
                    */
                        ConsoleWriter.writeToConsole(String.Format("Bookie {0}: Tip {1} gefunden", this.BookieName, tipp.BookieMatchName));
                        _status = BookieStatusType.GETMARKET;
                    }
                }
            }
            _mreWaitForAction.Set();
        }
    }

Has anybody an Idea what's happens here?
Thanks
lichtbringer

A: By doing _webBrowser.Invoke(new delegatePlaceBet(searchTipp), new object[] { tipp }), you make the searchTipp method be executed synchronously on the main UI thread. This is understood, as you cannot access WebBrowser API from any thread other than the original thread the control was created on.
However, by doing so, the _mreWaitForAction.WaitOne(10000) call will be too executed on the main UI thread, effectively blocking the message loop (which was started by Application.Run). WebBrowser needs a functional message loop, which is constantly pumping Windows messages, otherwise DocumentCompleted doesn't get fired, and you are getting a deadlock.
My understanding is, you only create another thread here to organize the workflow of your automation scenario. You really don't need another thread for that. Here's an example of how it can be done on the main UI thread asynchronously, using async/await, and here's an example of using WebBrowser in a console app.
Alternatively, as a workaround, you can use WaitWithDoEvents from here, like this: _mreWaitForAction.WaitWithDoEvents(10000). It waits for a handle while still pumping messages. You should be aware of potential implications of creating a nested message loop with Application.DoEvents().
Note, you still don't need a separate thread if you use a nested message loop. It will give you the linear code workflow on your main UI thread. Example:
private void buttonStart_Click(object sender, EventArgs e)
{
    using (var mre = new ManualResetEvent(false))
    {
        WebBrowserDocumentCompletedEventHandler handler = (s, args) =>
            mre.Set();
        this.webBrowser.DocumentCompleted += handler;
        try
        {
            this.webBrowser.Navigate("http://www.example.com");
            mre.WaitWithDoEvents(10000);
        }
        finally
        {
            this.webBrowser.DocumentCompleted -= handler;
        }
    }
    MessageBox.Show(this.webBrowser.Document.Body.OuterHtml);
}

Although as I've mentioned above, you can achieve the same more naturally and without nested message loops, using async/await, which is a preferred way of doing this, IMO.


text:
Q: How do Kryptonians know Earth languages? In Man of Steel, when General Zod & company arrived to Earth, they broadcast a message in many Earth languages. We've also seen them speaking English.
How do they know Earth languages?

A: The Kryptonians have had space travel and advanced technologies for 100,000 years. Consider in all of that time in space they surely have come across other species and utilized translation technology allowing them to broadcast in multiple languages simultaneously. Their ability to send data to multiple locations should have been little more than a party trick.
As far as their ability to speak English, we are not told how long they hovered above the Earth before they decided to tell Humanity to turn over Kal-El. They could have simply learned the language before arriving.
Canon precedents indicates Kal-El was capable of speaking every Earth language and able to learn languages extremely quickly. So having the intellectual capacity for language isn't beyond the scope of Kryptonian abilities, at least from a canon perspective.

A: They have ridiculously advanced technology, so they could have just listened in on our broadcasts for a little while and figured out the languages that way. Furthermore, we know that they aren't exclusively soldiers

 since one of them was going to dissect Superman to retrieve the Codex,

so it's conceivable that they had a space-linguist on board.
A better question would be 'why are they all speaking fluent English', but that could also be answered with 'alien technology' in the form of some kind of real-time translation device.

A: Two words: highly advanced technology and omnilingualism under a yellow star. This time was highly advanced technology, and surely they learned the language before arriving at Earth.
Though Kryptonians can learn omnilingualism, and speak or understand any language they come into contact with, this power has not yet been shown in the Man of Steel universe.

A: None of these really answer why they spoke it on Krypton also. Since a lot of other worldly figures in comics speak english, I like to think they all adopted the easiest language in the universe so that they could better communicate with others and Earth hasn't got the memo lol. But this is all just my imagination.


text:
Q: What is the lenght of a quadratic curve? The lenght of a curve $C$ is given by the integral:
$$L = \int_{C} \ ds = \int_{0}^{1} \left\|\dfrac{d\vec{p}(t)}{dt}\right\| \ dt$$
If $\vec{p}(t)$ is a quadratic curve, how can I compute $L$?
$$\vec{p}(t) = \vec{p}_0 + t \cdot \vec{p}_1 + t^2 \cdot \vec{p}_2$$
I'm struggling with the integral of the absolute function, cause I would rewrite:
$$\dfrac{d\vec{p}}{dt} = \vec{p}_1 + 2t \cdot \vec{p}_{2}$$
$$L = \int_{0}^{1} \left\|\vec{p}_1 + 2t \cdot \vec{p}_{2} \right\| \ dt$$
Any hint how I can compute it?


text:
Q: C++ Templated Delegates like Unity after saw Unity's delegates and events, i'm trying to code my own:
I want to create a class with a variadic template, to specify the return type of the functions, and optionals arguments.
template <typename Ret, typename... Args>
class MyDelegate{
    std::vector<Ret(*)(Args...)> vec;

    public:
    void operator+=( const Ret(*)(Args...)& newElement)
    {
        vec.push_back(newElement);
    }

    Ret operator()(const Args&... args)
    {
        for (auto i = vec.begin(); i != vec.end(); ++i)
            (*i)(args...);
    }
};

As you can see, i would like this class to be used this way:
MyDelegate<void> voidDelegate;
MyDelegate<void, int> intDelegate;
MyDelegate<int, char, boolt> miscDelegate;

and "adding" functions to each one using += operators, like:
voidDelegate += voidFunc;
//etc...

I'm having problem with the += operator for now, because VS don't accept this:
MyDelegate<void, int> delegate1;
delegate1 += [](const int a)->void{std::cout << a << std::endl; };

The lambda function is correct: it take an int and return void, so i don't understand whats' wrong.

A: The issue is that your std::vector stores function pointers. It doesn't store std::bind objects, it doesn't store member functions, it doesn't store functors and it doesn't store lambdas. You are trying to add a lambda to it, hence the failure.
If you want to store any kind of object which supports calling with the correct argument and return types, you want std::function:
using FunType = std::function<Ret(Args...)>;
std::vector<FunType> vec;

Demo
Incidentally, you could improve your solution by perfect-forwarding your operator() args and copying your newElement arg in the interface and moving it into the std::vector.

A: Your delegate accepts only function pointers. A lambda is not a function pointer. However, the lambda that you are trying to doesn't capture anything. Which means that it can be converted to a function pointer thanks to some sorcery:
MyDelegate<void, int> delegate1;
delegate1 += +[](const int a)->void{std::cout << a << std::endl; };
             ↑↑↑

However, once you want to allow functors that have member variables, the extra + won't work:
delegate1 += +[x](const int a) { ... }; // error: no match for operator+

At which point you'll definitely have to use TartanLlama's suggestions of std::function.

A: @TartanLlama's right, std::function is what you need.
And the calling loop can be folded to for (auto handler : vec) handler(args...);


text:
Q: About $\prod_{n\in\mathbb Z}\left[{\tanh\Big(\frac{\pi}{2}\sqrt{a^2n^2+ab}\Big)\over\tanh\Big(\frac{\pi}{2}\sqrt{n^2/a^2+b/a}\Big)}\right]^{(-1)^n}=1$ The infinite product in the title is invariant under the transformation $a\to 1/a$, however it is not a modular form because it is not a periodic function of $a$. Before asking the question one needs to explain some facts about this infinite product. Consider these two propositions
If $\cos\frac{\pi j}{n+1}+\cosh\alpha_j= \cos\frac{\pi k}{m+1}+\cosh\beta_k=x$ for all integers $1\le j\le n,\ 1\le k\le m$ then
$$
\prod_{j=1}^n\frac{\sinh(m+1)\alpha_j}{\sinh\alpha_j}=\prod_{k=1}^m\frac{\sinh(n+1)\beta_k}{\sinh\beta_k},\tag{1}
$$
If $\cos\frac{\pi (j-\frac{1}{2})}{n}+\cosh\alpha_j= \cos\frac{\pi (k-\frac{1}{2})}{m}+\cosh\beta_k=x$ for all integers $1\le j\le n,\ 1\le k\le m$ then
$$
\prod_{j=1}^n2\cosh m\alpha_j=\prod_{k=1}^m2\cosh n\beta_k.\tag{2}
$$
The formulas defining $\alpha_j$ and $\beta_k$ arise during solution of Helmholtz equation on a finite rectangular lattice with suitable boundary conditions (see e.g. Phillips, B.; Wiener, N. (1923). Nets and the Dirichlet problem. Journal of Math. and
Physics, Massachusetts Institute, 105–124). The proofs of these two identities are elementary in the sense that only elementary trigonometry is involved in the proof. There are also corresponding identities on hexagonal lattices as well.
When $m,n\to\infty$ with the ratio $m/n$ fixed they have continous analogues
$$
\prod_{n=1}^\infty\frac{1-e^{-2\pi\alpha\sqrt{n^2+\beta^2}}}{1-e^{-2\pi\sqrt{n^2/\alpha^2+\beta^2}}}=\sqrt{\frac{1-e^{-2\pi\beta}}{1-e^{-2\pi\alpha\beta}}}\cdot \exp\left\{\int_0^\infty\ln\frac{1-e^{-2\pi\alpha\sqrt{x^2+\beta^2}}}{1-e^{-2\pi\sqrt{x^2/\alpha^2+\beta^2}}}\ dx\right\},\tag{1a}
$$
$$
\prod_{n=0}^\infty\frac{1+e^{-\pi\alpha\sqrt{(2n+1)^2+\beta^2}}}{1+e^{-\pi\sqrt{(2n+1)^2/\alpha^2+\beta^2}}}=\exp\left\{\frac{1}{2}\int_0^\infty\ln\frac{1+e^{-\pi\alpha\sqrt{x^2+\beta^2}}}{1+e^{-\pi\sqrt{x^2/\alpha^2+\beta^2}}}\ dx\right\}.\tag{2a}
$$
It is possible to prove these formulas directly by contour integration. Now it turns out that there are other similar identities and in fact an infinite family of them. Here I give only two examples
$$
\prod_{n=1}^\infty\left(\frac{1-e^{-\pi\alpha\sqrt{n^2+\beta^2}}}{1+e^{-\pi\alpha\sqrt{n^2+\beta^2}}}\right)^{(-1)^n}=\sqrt{\frac{\tanh\frac{\pi\beta}{2}}{\tanh\frac{\pi\alpha\beta}{2}}}\prod_{n=1}^\infty\left(\frac{1-e^{-\pi\sqrt{n^2/\alpha^2+\beta^2}}}{1+e^{-\pi\sqrt{n^2/\alpha^2+\beta^2}}}\right)^{(-1)^n},\tag{3}
$$
$$
\prod_{n=1}^\infty\left(1-\tfrac{2\sqrt{5}}{1+\sqrt{5}+4\cosh{\frac{2\pi\alpha\sqrt{n^2+\beta^2}}{5}}}\right)^{\left(\frac{n}{5}\right)}=\prod_{n=1}^\infty\left(1-\tfrac{2\sqrt{5}}{1+\sqrt{5}+4\cosh{\frac{2\pi\sqrt{n^2/\alpha^2+\beta^2}}{5}}}\right)^{\left(\frac{n}{5}\right)}.\tag{4}
$$
Identity (3) is in fact the infinite product given in the title. Identity (4) containing the Legendre symbol was motivated by $\beta=0$ case given in the paper of Bryden Cais, "Transformations of infinite series". Note that all these identities can be reformulated in the form which reflects the symmetry $a\to 1/a$.

Q: Is there finite analogue of (3) similar to (1) and (2)?

A: The answer is yes and is given in this MO post:
If
$$\cosh\alpha_j+\cos\frac{\pi j}{2n}=\cosh\beta_k+\cos\frac{\pi k}{2m}=x\tag{3}$$
for all $1\le j\le 2n-1,\ 1\le k\le 2m-1$, then
$$
\prod_{j=1}^{2n-1}\left(\frac{\tanh m\alpha_j}{\sinh\alpha_j}\right)^{(-1)^j}=\prod_{k=1}^{2m-1}\left(\frac{\tanh n\beta_k}{\sinh\beta_k}\right)^{(-1)^k}.
$$


text:
Q: Multiple data values for label text in cytoscape.js I am trying to add multiple values to a label in cytoscape.js like so -
{
    "selector": "edge",
    "style": {
        "curve-style": "haystack",
        "text-wrap": "wrap",
        "label": "data(count)" + "data(edgevalue)",
        "font-size": "8px",
        "color": "black",
        "haystack-radius": "0.5",
        "opacity": "0.4",
        "line-color": "#bbb",
        "width": "mapData(weight, 0, 1, 1, 8)",
    }
},

However this is literally just displaying -
data(count)data(edgevalue)

As the label text. If I remove one or the other it prints the correct value for each.
I tried adding a '\n' for a line break, which created a line break but the values were just the same as above.
I also tried data(count + edgevalue) to no avail.
How can I achieve multiple data attributes in a label text?

A: You can use mappers to get the correct data into your styles: mappers
Also, I usually use template strings:
{
    label: function (element) {
        return `${element.data("attribute_01")} + ${element.data("attribute_02")}`
    }
}

Here you can see a simple example:

document.addEventListener("DOMContentLoaded", function() {
  var cy = (window.cy = cytoscape({
    container: document.getElementById("cy"),

    // demo your layout
    layout: {
      name: "klay"

      // some more options here...
    },

    style: [{
        selector: "node",
        style: {
          "background-color": "#dd4de2"
        }
      },
      {
        selector: ".leaf",
        style: {
          "background-color": "#000"
        }
      },
      {
        selector: "edge",
        style: {
          "curve-style": "bezier",
          "target-arrow-shape": "triangle",
          "line-color": "#dd4de2",
          "target-arrow-color": "#dd4de2",
          "opacity": "0.5",
          "label": function(node) {
            return `${node.data("source")} -> ${node.data("target")}`
          }
        }
      }
    ],
    elements: {
      nodes: [{
          data: {
            id: "n0"
          }
        },
        {
          data: {
            id: "n1"
          }
        },
        {
          data: {
            id: "n2"
          }
        },
        {
          data: {
            id: "n3"
          }
        },
        {
          data: {
            id: "n4"
          }
        },
        {
          data: {
            id: "n5"
          }
        },
        {
          data: {
            id: "n6"
          }
        },
        {
          data: {
            id: "n7"
          }
        },
        {
          data: {
            id: "n8"
          }
        },
        {
          data: {
            id: "n9"
          }
        },
        {
          data: {
            id: "n10"
          }
        },
        {
          data: {
            id: "n11"
          }
        },
        {
          data: {
            id: "n12"
          }
        },
        {
          data: {
            id: "n13"
          }
        },
        {
          data: {
            id: "n14"
          }
        },
        {
          data: {
            id: "n15"
          }
        }
      ],
      edges: [{
          data: {
            source: "n0",
            target: "n1"
          }
        },
        {
          data: {
            source: "n1",
            target: "n2"
          }
        },
        {
          data: {
            source: "n1",
            target: "n3"
          }
        },
        {
          data: {
            source: "n2",
            target: "n4"
          }
        },
        {
          data: {
            source: "n4",
            target: "n5"
          }
        },
        {
          data: {
            source: "n4",
            target: "n6"
          }
        },
        {
          data: {
            source: "n6",
            target: "n7"
          }
        },
        {
          data: {
            source: "n6",
            target: "n8"
          }
        },
        {
          data: {
            source: "n8",
            target: "n9"
          }
        },
        {
          data: {
            source: "n8",
            target: "n10"
          }
        },
        {
          data: {
            source: "n10",
            target: "n11"
          }
        },
        {
          data: {
            source: "n11",
            target: "n12"
          }
        },
        {
          data: {
            source: "n12",
            target: "n13"
          }
        },
        {
          data: {
            source: "n13",
            target: "n14"
          }
        },
        {
          data: {
            source: "n13",
            target: "n15"
          }
        }
      ]
    }
  }));

  cy.nodes().leaves().addClass("leaf");
});
body {
  font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
  font-size: 14px;
}

#cy {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 999;
}


text:
Q: If a matrix multiplied by its transpose equals the original matrix, is it symmetric? Here's the question:

Prove: If ATA = A, then A is symmetric and A = A2

I tried to solve this by using inference.

*

*Assume A is symmetric, prove A = A2

*

*If A is symmetric, then by definition ATA = A2. Since ATA = A, then A = A2.

*Assume A = A2, prove A is symmetric

*

*??

I wasn't sure what to put for the second part to prove 1. Is an idempotent matrix by definition symmetric? It would make sense, but I couldn't find anything definitive.
Am I going about this correctly, or should I take a different approach?

A: You seem to have misunderstood what you need to prove. You seem to be attempting to prove that

If $A^TA$, then ($A$ is symmetric if and only if $A=A^2$).

But that is not what you are being asked to prove! What you are being asked to prove is that

If $A^TA=A$, then ($A$ is symmetric and $A=A^2$).

So you are not allowed to just assume that $A$ is symmetric or that $A=A^2$; you need to prove these things from only the hypothesis that $A^TA=A$.
Your only assumption is that $A^TA=A$.

*

*To prove $A$ is symmetric, remember that $A$ is symmetric if and only if $A^T=A$. But if $A=A^TA$, then $A^T = (A^TA)^T = \cdots$

*To prove that $A=A^2$, argue like you did above, since you have now shown that $A$ is symmetric.
Note that in general, the two statements I wrote above in the grey boxes are not logically equivalent. If the second one holds, then the first one must (because both sides of the "if and only if" will be true whenever the premise is true); but you can have the former one be true and the latter one not be true. For example, "if $x$ is a real number, then ($x$ is positive if and only if $-x$ is negative)" is true, but "if $x$ is a real number, then ($x$ is positive and $-x$ is negative)" is false (as witnessed by $x=-1$).


text:
Q: Linker error "clang error linker command failed" There are quite a few posts like this on Stack Overflow, but most of them pertain to Xcode, and I cannot replicate their solutions. I have a Heap.h, Heap.cpp, and main.cpp file and whenever I try to run main.cpp with g++ main.cpp Heap.cpp, it gives me:

clang: error: linker command failed with exit code 1 (use -v to see invocation)

File Heap.h
#ifndef _HEAP_H_
#define _HEAP_H_

template<class T>
class Heap{
    private:
        struct Node{
            T *dist;
            T *v;

            bool operator==(const Node& a){
                return *dist == *(a -> dist);
            }

            bool operator!=(const Node& a){
                return (!(*dist == *(a -> dist)));
            }

        };

        Node *container;
        int size;
        int curSize;
        T sourceV;

    public:
        Heap();
        Heap(int inSize, T inSourceV);

};

#endif

File Heap.cpp
#include <iostream>
#include <vector>
#include <limits>
#include "Heap.h"

using namespace std;

template<class T>
Heap<T>::Heap(){
    cout << "hello" <<endl;
}

template<class T>
Heap<T>::Heap(int inSize, T inSourceV){
    size = inSize;
    container = new Node[size];
    curSize = 0;
    sourceV = inSourceV;

    int maxVal = numeric_limits<int>::max();
    for (int i = 1; i < size; i++){
        container[i].dist = &maxVal;
        container[i].v = &maxVal;
    }
}

File main.cpp
#include "Heap.h"
#include <iostream>

using namespace std;

int main(){
   Heap <int> h;
}

It is strange I have another project that contains bst.h, bst.cpp, and main.cpp, and those run fine. The difference between these two projects is that the bst I implemented is not a templated class.
I also saw another similar post that mentioned something about changing bitcode settings, but where can I access that from?
I'm running Xcode 7.1. Apple LLVM version 7.0.0 (clang-700.1.76).
Target: x86_64-apple-darwin14.5.0
Thread model: posix

A: You don't instantiate a Heap<int> in the Heap.cpp compilation. As a result the compiler doesn't bother generating any code for Heap.o.
You can see this if you do:
nm Heap.o

It tells you there's nothing there.
This is a typical behaviour of a C++ compiler - no template gets turned into code unless there's an instantiation of it.
Quick solutions are

*

*Move all the Heap.cpp code into the template class declaration of Heap.h

*create a dummy function in Heap.cpp that instantiates a Heap<int>


text:
Q: Process Coredumped but does not look like illegal reference in a multithreaded program Backtrace of the coredump:
#0  0x0000000000416228 in add_to_epoll (struct_fd=0x18d32760, lno=7901) at lbi.c:7092
#1  0x0000000000418b54 in connect_fc (struct_fd=0x18d32760, type=2) at lbi.c:7901
#2  0x0000000000418660 in poll_fc (arg=0x0) at lbi.c:7686
#3  0x00000030926064a7 in start_thread () from /lib64/libpthread.so.0
#4  0x0000003091ed3c2d in clone () from /lib64/libc.so.6

Code Snippet:
#define unExp(x) __builtin_expect((x),0)
...
7087 int add_to_epoll( struct fdStruct * struct_fd, int lno)
7088 {
7089    struct epoll_event ev;
7090    ev.events = EPOLLIN | EPOLLET | EPOLLPRI | EPOLLERR ;
7091    ev.data.fd = fd_st->fd;
7092    if (unExp(epoll_ctl(struct_fd->Hdr->info->epollfd, EPOLL_CTL_ADD,         struct_fd->fd,&ev) == -1))
7093    {
7094        perror("client FD  ADD to epoll error:");
7095        return -1;
7096    }
7097    else
7098    {
            ...
7109    }
7110    return 1;
7111 }

Disassembly of the offending line. I am not good at interpreting assembly code but have tried my best:
        if (unExp(epoll_ctl(struct_fd->Hdr->info->epollfd, EPOLL_CTL_ADD, stuct_fd->fd,&ev) == -1))
  416210:       48 8b 45 d8             mov    0xffffffffffffffd8(%rbp),%rax // Storing struct_fd->fd
  416214:       8b 10                   mov    (%rax),%edx                   //  to EDX
  416216:       48 8b 45 d8             mov    0xffffffffffffffd8(%rbp),%rax // Storing struct_fd->Hdr->info->epollfd
  41621a:       48 8b 80 e8 01 00 00    mov    0x1e8(%rax),%rax              // to EDI which failed
  416221:       48 8b 80 58 01 00 00    mov    0x158(%rax),%rax              // while trying to offset members of the structure
  416228:       8b 78 5c                mov    0x5c(%rax),%edi               // <--- failed here since Reg AX is 0x0
  41622b:       48 8d 4d e0             lea    0xffffffffffffffe0(%rbp),%rcx
  41622f:       be 01 00 00 00          mov    $0x1,%esi
  416234:       e8 b7 e1 fe ff          callq  4043f0 <epoll_ctl@plt>
  416239:       83 f8 ff                cmp    $0xffffffffffffffff,%eax
  41623c:       0f 94 c0                sete   %al
  41623f:       0f b6 c0                movzbl %al,%eax
  416242:       48 85 c0                test   %rax,%rax
  416245:       74 5e                   je     4162a5 <add_to_epoll+0xc9>

Printing out Registers and struct member values:
(gdb) i r $rax
rax            0x0      0
(gdb) p struct_fd
$3 = (struct fdStruct *) 0x18d32760
(gdb) p struct_fd->Hdr
$4 = (StHdr *) 0x3b990f30
(gdb) p struct_fd->Hdr->info
$5 = (struct Info *) 0x3b95b410    // Strangely, this is NOT NULL. Inconsistent with assembly dump.
(gdb) p ev
$6 = {events = 2147483659, data = {ptr = 0x573dc648000003d6, fd = 982, u32 = 982, u64= 6286398667419026390}}

Please let me know if my dis-assembly interpretation is OK. And if yes, would like to understand why gdb not showing NULL when it is printing out the structure members.
OR if the analysis is not perfect would like to know the actual reason of coredump. Please let me know if you need more info.

*

*Thanks

---- The following part has been added Later ----
The proxy is a multithreaded program. Doing more digging came to know that when the problem occurs the following two thread were running in parallel. And when I avoid the two functions to run parallely the problem never occurs. But, the thing is I cannot explain how this behavior results into the original problematic scene:
Thread 1:
------------------------------------------------------------
int new_connection() {
   ...
   struct_fd->Hdr->info=NULL; /* (line 1)  */
   ...
   <some code>
   ...
   struct_fd->Hdr->info=Golbal_InFo_Ptr; /* (line 2) */  // This is a malloced memory, once allocated never freed
   ...
   ...
}
------------------------------------------------------------

Thread 2 executing add_to_epoll():
------------------------------------------------------------
int add_to_epoll( struct fdStruct * struct_fd, int lno)
{
   ...
   if (unExp(epoll_ctl(struct_fd->Hdr->info->epollfd,...)  /* (line 3) */
   ...
}
------------------------------------------------------------

In the above snippets if execution is done in the order,
LIne 1,
Line 3,
Line 2,
the scene can occur. What I expect is whenever an illegal reference is encountered it should dump immediately without trying to execute LINE 3 which makes it NON NULL.
It is a definite behavior because till now I have got around 12 coredumps of the same problem, all showing the exact same thing.

A: It is clear that struct_fd->Hdr->info is NULL, as Per Johansson already answered.
However, GDB thinks that it is not. How could that be?
One common way this happens, is when

*

*you change the layout of struct fdStruct, struct StHdr (or both),
and

*you neglect to rebuild all objects that use these definitions

The disassembly shows that offsetof(struct fdStruct, Hdr) == 0x1e8 and offsetof(struct StHdr, info) == 0x158. See what GDB prints for the following:
(gdb) print/x (char*)&struct_fd->Hdr - (char*)struct_fd
(gdb) print/x (char*)&struct_fd->Hdr->info - (char*)struct_fd->Hdr

I bet it would print something other than 0x1e8 and 0x158.
If that's the case, make clean && make may fix the problem.
Update:
(gdb) print/x (char*)&struct_fd->Hdr - (char*)struct_fd
$1 = 0x1e8
(gdb) print/x (char*)&struct_fd->Hdr->info - (char*)struct_fd->Hdr
$3 = 0x158

This proves that GDB's idea of how objects are laid out in memory matches compiled code.
We still don't know whether GDB's idea of the value of struct_fd matches reality. What do these commands print?
(gdb) print struct_fd
(gdb) x/gx $rbp-40

They should produce the same value (0x18d32760). Assuming they do, the only other explanation I can think of is that you have multiple threads accessing struct_fd, and the other thread overwrites the value that used to be NULL with the new value.
I just noticed your update to the question ;-)

What I expect is whenever an illegal reference is encountered it should dump immediately without trying to execute LINE 3 which makes it NON NULL.

Your expectation is incorrect: on any modern CPU, you have multiple cores, and your threads are executing simultaneously. That is, you have this code (time goes down along Y axis):
char *p;  // global

Time     CPU0                  CPU1
0        p = NULL
1        if (*p)               p = malloc(1)
2                              *p = 'a';
...

At T1, CPU0 traps into the OS, but CPU1 continues. Eventually, the OS processes hardware trap, and dumps memory state at that time. On CPU1, hundreds of instructions may have executed after T1. The clocks between CPU0 and CPU1 aren't even synchronized, they don't necessarily go in lock-step.
Moral of the story: don't access global variables from multiple threads without proper locking.

A: The C line part of the disassembly does not match the one in the original code. But clearly
struct_fd->Hdr->info

is NULL. gdb shouldn't have a problem printing that, but it does sometimes get confused when the code is compiles with -O2 or higher.


text:
Q: Call function that's within ngAfterViewInit from outside ngAfterViewInit As the title suggests, I'm trying to call a function that is within ngAfterViewInit from outside of it. I can't move the function as it uses HTML elements that are only available once ngAfterViewInit has fired.
So, ideally this would work (but it doesn't):
ngAfterViewInit(): void {
  --stuff--
  function foo() {
    --do stuff--
  }
}

public DoSomething() {
  --more stuff--
  foo();
}

A: If you want to use the this keyword in the function, you'll want an arrow function:
foo?: () => void;

ngAfterViewInit(): void {
  --stuff--
  this.foo = () => {
    //`this` refers to the component
    --do stuff--
  }
}

public DoSomething() {
  --more stuff--
  if (this.foo) this.foo();
}

A: Make the reference to the function available outside of ngAfterViewInit
@Component()
export class SomeComponent {
 foo: Function;

 ngAfterViewInit() {
  // if you need to preserve the 'this' context simply use a lambda instead.
  this.foo = function() {
   // do things.
  }
 }
}


text:
Q: Python: Identifying a numeric string? I tried a couple of approaches, I am really only concerned with performance, not correctness. I noticed that the regex based implementation is about 3-4x slower than the one that uses type coercion. Is there another, more efficient way of doing this?
def IsNumber(x):
    try:
        _ = float(x)
    except ValueError:
        return False
    return True

 def IsNumber2(x):
     import re
     if re.match("^\d*.?\d*$", x) == None:
         return False
     return True

Thanks!

A: First of all, they're not doing the same thing.  Floats can be specified as "1e3", for example, and float() will accept that.  It's also not coercion, but conversion.
Secondly, don't import re in IsNumber2, especially if you're trying to use it with timeit.  Do the import outside of the function.
Finally, it doesn't surprise me that float() is faster.  It's a dedicated routine written in C for a very specific purpose, while regex must be converted into a form that's interpreted.
Is your first version, that uses float(), fast enough?  It should be, and I don't know of a better way to do the same thing in Python.

A: Not really. Coercion is the accepted way to do this.

A: The answer depends a lot on what you mean by 'numeric string'.  If your definition of numeric string is 'anything that float accepts', then it's difficult to improve on the try-except method.
But bear in mind that float may be more liberal than you want it to be:  on most machines, it'll accept strings representing infinities and nans.  On my machine, it accepts 'nan(dead!$#parrot)', for example.  It will also accept leading and trailing whitespace.  And depending on your application, you may want to exclude exponential representations of floats.  In these cases, using a regex would make sense.  To just exclude infinities and nans, it might be quicker to use the try-except method and then use math.isnan and math.isinf to check the result of the conversion.
Writing a correct regex for numeric strings is a surprisingly error-prone task.  Your IsNumber2 function accepts the string '.', for example.  You can find a battle-tested version of a numeric-string regex in the decimal module source.  Here it is (with some minor edits):
_parser = re.compile(r"""        # A numeric string consists of:
    (?P<sign>[-+])?              # an optional sign, followed by either...
    (
        (?=\d|\.\d)              # ...a number (with at least one digit)
        (?P<int>\d*)             # having a (possibly empty) integer part
        (\.(?P<frac>\d*))?       # followed by an optional fractional part
        (E(?P<exp>[-+]?\d+))?    # followed by an optional exponent, or...
    |
        Inf(inity)?              # ...an infinity, or...
    |
        (?P<signal>s)?           # ...an (optionally signaling)
        NaN                      # NaN
        (?P<diag>\d*)            # with (possibly empty) diagnostic info.
    )
    \Z
""", re.VERBOSE | re.IGNORECASE | re.UNICODE).match

This pretty much matches exactly what float accepts, except for the leading and trailing whitespace and some slight differences for nans (the extra 's' for signaling nans, and the diagnostic info).  When I need a numeric regex, I usually start with this one and edit out the bits I don't need.
N.B. It's conceivable that float could be slower than a regex, since it not only has to parse the string, but also turn it into a float, which is quite an involved computation;  it would still be a surprise if it were, though.

A: You might try compiling your regular expression first, but I'd imagine it would still be slower.
Also, if you want to know if your string is a number because you're going to do calculations with it, you'll have to coerce it anyway.


text:
Q: keras loss jumps to zero randomly at the start of a new epoch I'm training a network which has multiple losses and both creating and feeding the data into my network using a generator.
I've checked the structure of the data and it looks fine generally and it also trains pretty much as expected the majority of the time, however at a random epoch almost every time, the the training loss for every prediction suddenly jumps from say
# End of epoch 3
loss: 2.8845

to
# Beginning of epoch 4
loss: 1.1921e-07

I thought it could be the data, however, from what I can tell the data is generally fine and it's even more suspicious because this will happen at a random epoch (could be because of a random data point chosen during SGD?) but will persist throughout the rest of training. As in if at epoch 3, the training loss decreases to 1.1921e-07 then it will continue this way in epoch 4, epoch 5, etc.
However, there are times when it reaches epoch 5 and hasn't done this yet and then might do it at epoch 6 or 7.
Is there any viable reason outside of the data that could cause this? Could it even happen that a few fudgy data points causes this so fast?
Thanks
EDIT:
Results:
300/300 [==============================] - 339s - loss: 3.2912 - loss_1: 1.8683 - loss_2: 9.1352 - loss_3: 5.9845 -
val_loss: 1.1921e-07 - val_loss_1: 1.1921e-07 - val_loss_2: 1.1921e-07 - val_loss_3: 1.1921e-07

The next epochs after this all have trainig loss 1.1921e-07

A: Not entirely sure how satisfactory this is as an answer but my findings seem to show that using multiple categorical_crossentropy loss's together seems to result in a super unstable network? Swapping this out for other loss functions fixes the problem with the data remaining unchanged.


text:
Q: File input reading in C I am a student learning C programming and I am learning file input. Below is the code. I have data text file to read from. I am confused with what is the meaning of status here, the condition in which (status != 0) what is the meaning of 0 and use of return -1.
int main()
{
    FILE *inp;
    int status;
    int a, b, c, d, e;

    status = fopen_s(&inp, "data.txt", "r");

    if (status != 0)
    {
        printf("Error");
        return -1;
    }

    status = fscanf_s(inp, "%d %d %d %d %d", &a, &b, &c, &d, &e);`

    while (status != EOF)
    {
        printf("%d %d %d %d %d\n", a, b, c, d, e);`
        status = fscanf_s(inp, "%d %d %d %d %d", &a, &b, &c, &d, &e);
    }

    return 0;
}

A:
I am confused with what is the meaning of status here

It's just a variable to keep the return value of fopen_s() and later fscanf_s().

the condition in which (status != 0) what is the meaning of 0

A manual helps: fopen_s() returns error codes, or 0 on success. This just checks whether there was an error opening the file.

and use of return -1.

Whatever you return from main() is passed as the exit code to your operating system. Any value other than 0 means there was an error. See also exit() -- calling exit with a value has the same effect as returning this value from main().

Side note: Just use the standard functions (without _s suffix). Some of these _s functions are specific to Microsoft, others are a bit different on Microsoft compilers than specified by the standard -- just spare yourself the hassle. Using just fopen() and fscanf() (beware of the different signatures!) makes your program immediately portable.


text:
Q: Given $x>0,n\in \mathbb{N}$ prove there is a unique $y>0$ such that $y^n=x$.
Given $x>0,n\in \mathbb{N}$ prove there is a unique $y>0$ such that $y^n=x$.

Let $S=\{s\in\mathbb{R} : s^n\leq x\}$
Since $0=0^n<x$ then $0\in S$ thus $S$ is a nonempty subset of $\mathbb{R}$ and so there is a least upper bound of $S$
Let $y=lub(S)$
I want to prove that $y^n=x$
Suppose $y^n<x$
then for some $\epsilon>0$, $y^n<y^n+\epsilon<x$, Since there is no real number closest to $x$
then there exists a $\delta>0$ such that $\vert y+\frac{\delta}{2}-y\vert<\delta$
implies $\vert y^n - (y+\frac{\delta}{2})^n\vert<\epsilon$
then $(y+\frac{\delta}{2})^n<\epsilon+y^n<x$
so $y+\frac{\delta}{2}\in S$ but clearly $y<y+\frac{\delta}{2}$ thus $y\neq lub(S)$ a contradiction.

A: Firstly we have to prove $f(x)=$ $x^n$ is a 1-1 on interval (0,+$\infty$)
For $n=1$ it is trivial.
For $n>1$, we have to prove. Suppose f(a)=f(b). Then $a^n=b^n$. By factoring,
$(a-b)(a^{(n-1)}+a^{(n-2)}b...........b^{(n-1)})=0$.
As second factor can't be zero as $a,b>0$. So $a-b=0$, i.e., $a=b$.
Now we have to prove that every positive real no. has unique positive $n^{(th)}$ root., $y=(x_0)^{(1/n)}$.
If n=1, $y=x_0$, simply
Suppose $n>1$, and $x_0>0$. Consider a polynomial function $p(x)=x^n$. As $p(0)=0$ and $p(x)$ diverges to +$\infty$. So, there exist, $b$  s.t. $ p(b)>x_0$.
By intermediate value theorem, there exist $y$ belong to$(0,b)$ s.t. $ p(y)=x_0$. Uniqueness follows from first proof.

A: I can fix your approach. You want to find some $\epsilon>0$ such that $y^n<(y+\epsilon)^n<x$ in order to get a contradiction.
Well, this is the same as finding $\epsilon$ such that
$$(y+\epsilon)^n-y^n <x-y^n=\delta$$.
This is of course obvious, if we know continuity of functions, but what I understand is that you just want to prove this with just inequalities (trichotomy of real numbers) and the fact that the real numbers are complete (that your bounded sets have lower upper bounds).
Claim: $(y+\epsilon)^n-y^n<\epsilon n x^{n-1}$.
Indeed, $$(y+\epsilon)^n-y^n=((y+\epsilon)-y)((y+\epsilon)^{n-1}+(y+\epsilon)^{n-2}y+\dots +y^{n-1})<\epsilon(nx^{n-1})$$
Using the claim, then we just need to take $\epsilon=\delta/(nx^{n-1})$ and we are done.

A: The easiest way to solve this problem is to perform an analysis of the function $f : x \mapsto x^r$ on $\mathbb{R}_+$.
$f$ is differentiable, and $f'(x) = rx^{r-1}$. For any positive $x$, $f'(x)>0$ hence $f$ is sctrictly increasing, whence injective. So if we find $y$ such that $y^r = x$, it will be unique.
Let $S=\{s\in\mathbb{R} : s^n\leq x\}$, as in OP.
To prove the existence of such a $y$, use intermediate value theorem : it is easy to find $b$ such that $b^r > x$ (any $b > \sup(S)$ will do). Since $f$ is continuous and $f(0) = 0 < x$ and $f(b)>x$, there must be $y \in [0, b]$ such that $f(y) = x$.

A: Set
$f(y) = y^n; \tag 1$
note that $f(y)$ is continuous.  This follows from the fact that the function $y$ is continuous, and products of continuous functions are continuous; more formally, we may use induction, observing that for $k \in \Bbb N$,
$y^{k + 1} = yy^k; \tag 2$
then if $y^k$ is continuous, $y^{k + 1}$ is; the base case is simply the case $k = 1$, i.e.
$y^2 = yy. \tag 3$
It is easy to see that $f(y)$ is strictly monotonically increasing on $[0, \infty)$, that is
$y_2 > y_1 > 0 \Longrightarrow y_2^n > y_1^n; \tag 4$
this of course follows from the elementary property of multiplication
$0 < a < c, 0 < b < d \Longrightarrow ab < cd. \tag 5$
Next, we have
$f(0) = 0, \tag 6$
as is trivially obvious, and if we choose
$z > 0 \tag 7$
such that
$1 < z, x < z, \tag 8$
then repeated application of (5) yields
$x < z^n = f(z); \tag 9$
in light of (6) and (9) it follows from the intermediate value theorem that
$\exists y \in [0, z], y^n = f(y) = x; \tag{10}$
the uniqueness of $y$ follows easily from (4), which shows that $y_1 \ne y_2$ implies that $y_1^n \ne y_2^n$; one may also argue algebraically that
$y_1^n = y_2^n \Longrightarrow y_1^n - y_2^n = 0$
$\Longrightarrow (y_1 - y_2)(y_1^{n - 1} + y_1^{n - 1}y_2 + \ldots y_1y_2^{n - 2} + y_2^{n - 1}) = 0, \tag{11}$
and since, unless $y_1 = y_2 = 0$,
$y_1^{n - 1} + y_1^{n - 1}y_2 + \ldots y_1y_2^{n - 2} + y_2^{n - 1} > 0, \tag{12}$
we conclude that
$y_1 - y_2 = 0, \tag{13}$
or
$y_1 = y_2, \tag{14}$
that is, the solution to $y^n = x$ is unique.