text:
Q: Is there anything special about the below finite metric space? See below for details. I am a high school student who has been playing around with certain mathematical ideas, most recently metric spaces, and I believe I have just "defined" if you will, the following metric space:
Metric space: $(X,d)$
Set: $X={(a,a),(a,b),(b,a),(b,b)}$
Metric:
$$
d((x_1,x_2),(y_1,y_2)) =\left\{ \begin{array}[ll]\\
0 & \text{if } x_1 = y_1 \text{ and } x_2 = y_2.\\
1 & \text{if } x_1 = y_1 \text{ xor } x_2 = y_2.\\
\sqrt{2} & \text{if } x_1 \ne y_1 \text{ and } x_2 \ne y_2.
\end{array}\right.
$$ This seems really interesting to me as it seems to describe the lengths of the sides and diagonals of a square. My questions are these, in no particular order:
1: Is this really a metric space? $d$ seems to fit the triangle inequality, but perhaps I'm missing something.
2: If this is a metric space, does it have any interesting properties? Also, are there any useful metric spaces like this (have any been used to prove/disprove conjectures?
3: Is this similar to any other idea/concept/example in metric spaces that I could look at to gain a deeper appreciation?
4: On a more general note, are there any good introductory texts to metric spaces, that don't require much in the way of current knowledge. I do know some set theory, and can read (some) proofs, if that helps.
Please remember I am only a novice in this area, so please do not assume any background knowledge, outside of the definition of a metric space.

A: *

*Yes, this is a metric space. It is (isomorphic to) the subspace of $\mathbb R^2$ consisting of the four points $(0, 0), (0, 1), (1, 0), (1, 1)$, with the metric inherited from the metric on $\mathbb R^2$.

2,3. Nothing particular that I can think of.

*Most texts for a first class in real analysis should give an overview of metric space theory. I personally like Charles Pugh's Real Mathematical Analysis quite a bit, but any such text will do.

A: 1) To test the triangle inequality there are only the following  situations with $X = (x_1,x_2), Y=(y_1,y_2), Z=(z_1,z_2)$
a.) X = Y.  Then $d(X,Y) + d(Y,Z) = 0 + d(X,Z) = d(X,Z) \le d(X,Y) + d(Y,Z)$.  It holds.
Symmetry assures it holds for $Y = Z$.
b) Otherwise $X \ne Y$ and $Y \ne Z$.
$d(X,Z) = \{0,1,$ or $\sqrt{2}\}$ so $d(X,Y) \le \sqrt{2}$; $d(X,Y) = \{1,$ or $\sqrt{2}\}$; $d(Y,Z) = \{1,$ or $\sqrt{2}\}$ so $d(X,Y) + d(Y,Z) = \{2, 1+\sqrt{2}, 2\sqrt{2}\}$. so $2 \le d(X,Y) + d(Y,Z)$
So $d(X,Z) \le \sqrt{2} < 2 \le d(X,Y) + d(Y,Z)$ so triangle inequality holds.
The other conditions of the metric space are obviously true.  ($d(X,Y) \in \mathbb R$; $d(X,Y) \ge 0$; $d(X,Y) = d(Y,X)$; $d(X,Y) = 0 \iff X = Y$).
2) Notice it isn't just a metric space on your set X.  It's a metric space on all $\mathbb R^2$.  Or on any cross product set $S \times S$.
I don't know if you know anything about topology of metric spaces but this makes all sets both open and closed.  (I'll explain that further if you like.)
3) Look at the discrete/trivial metric space which is the simplest most basic metric (on any set).  $d(x,y) = 1 \iff x \ne y; d(x,y) = 0 \iff x = y$.  It's very similar to yours but simpler.
Consider the paris railway metric:  Set: $X$ with a central element $c$.  If $x = y$ $d(x,y) = 0$.  Otherwise $d(c,x) = r_x$ where $r_x$ can be an arbitrary positive real number of each element $x$.  And if $x \ne c$ and $y \ne c$ then $d(x,y) = d(c,x) + d(c,y)$.  This is called a the paris railway metric becuase to get from any two points you must pass through the "main terminal" $c$.
It's not actually that interesting a metric space but I like it because it (and the discrete metric) shows us all the properties required of a metric while getting us away from our preconceptions of a "distance" being "as the crow flies".
Another metric space is Set: $\mathbb R^2$ and the metric is $d_2(X,Y) = \frac{d_1(X,Y)}{d_1(X,Y) + 1}$ where $d_1(X,Y)$ is the usual euclidean metric: $d_1((x_1,y_1),(x_2,y_2)) = \sqrt{(x_2 - x_1)^2 + (y_2-y_1)^2)}$.
Whats interesting about this metric is that it maintains nearly on the other properties of $R^2$ with euclidean metric and "shapes" in euclidean $R^2$ will be the equivalent "shapes" in this metric space to.  But this metric space is bounded.  All distances are less than 1 so there are no infinite distances and all sets are bounded.
Also to $d_2 = \frac{d_1}{d_1 + 1}$ can be applied to any metric space to make an equivalent but bounded new space.
4)  Hmmmm.... not off the top of my head.


text:
Q: how to display image in angular saved on node server I have a nodejs app running on localhost:3000, I uploaded images using multer, so they are in ./uploads/ folder. In the Angular app running on locahost:4200 I want to retrieve those images.
in my for loop:

    {{i+1}}
    {{data.emp_name}}

I have all data in following result variable:
this.emp.viewData().subscribe(
  res => {
    this.empData = res;
  },
  err => {
    console.log(err);
  },
)

A: In addition to the answer above by Software Person, ensure you include this to you node application to enable you access the uploads directory in your nodejs application.
const express   = require('express');
const app       = express();

app.use(express.static('uploads'));

Happy Coding.

A: You could include your full url like

    {{i+1}}
    {{data.emp_name}}

Or even better you could define a variable in component and use it like this:

    {{i+1}}
    {{data.emp_name}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve custom properties of Solr cores I'm bit new with Solr 7.0.
With Solr CoreAdmin APIs it is possible to create new cores with custom properties:
solr/admin/cores?action=CREATE&name=mycore&configSet=myconfigset&property.version=1.2.3

The command above creates a new core with a core.properties file containing the specified custom property "version" with value "1.2.3"
The defined custom properites may be used as replacement in Solr configuration files, but I could not be able to retrieve (and eventually update) a specific custom property using the Solr CoreAdmin APIs.
How is it possible to retrive or update a specific core custom property?
Thanks a lot

A: To create user defined property, you can use below command.
curl http://localhost:8983/solr/<core-name>/config -H'Content-type:application/json' -d '{
    "set-user-property" : {"custom_property":"some_value"}}'

And, to retrieve it.
    curl http://localhost:8983/solr//config/overlay?omitHeader=true
Though, these properties will be removed, once you have restarted the server. So I would suggest you to add these properties in core.properties file.
For more information :- https://lucene.apache.org/solr/guide/6_6/config-api.html#ConfigAPI-CreatingandUpdatingUser-DefinedProperties


text:
Q: Show that if each $B \in \mathcal{B}$ is the union of some members of $\mathcal{B}'$, then $\tau \subset \tau'$.
Let $\mathcal{B}$ and $\mathcal{B}'$ be bases of topologies $\tau$ and $\tau'$ on a space $X$ respectively. Show that if each $B \in \mathcal{B}$ is the union of some members of $\mathcal{B}'$, then $\tau \subset \tau'$.

I have two solutions for this and I'm wondering if they're both correct.
Firstly if $O \in \tau$, then I think that by definition there exists $B \in \mathcal{B}$ such that $B \subset O$. And since $B = B_1 \cup B_2 \cup \dots$ for $B_i$'s in $\mathcal{B}'$ we have that $O \in \tau'$.
Second is that if $O \in \tau$, then by definition $O$ is the union of the basis elements $B_i \in \mathcal{B}$. But since each $B_i$ is the union of elements in $\mathcal{B}'$ the set $O$ must also be an union of elements of $\mathcal{B}'$ and thus by definition $O \in \tau'$.
I'm convinced that the second one is correct, but I don't know if the first one is right? Isn't it true by definition that for any open set of $X$ there is a basis element contained in it?

A: The second one is correct (but could be more formalised), while the first has a gap and is handwavy about the union IMO.
Formalised second : Let $O \in \tau$. By the definition of a base, for some $\mathcal{O} \subseteq \mathcal{B}$ we have $\bigcup \mathcal O = O$. For each $B \in \mathcal{O}$ we know that (as it is in $\mathcal{B}$) we can write it as $B=\bigcup \mathcal O_B$ for some $\mathcal{O}_B \subseteq \mathcal B'$. So in fact $O=\bigcup \mathcal C$ where $\mathcal C = \bigcup \{\mathcal O_B\mid B \in \mathcal{O}\} \subseteq \mathcal B'$ and so $O$ is a union of sets from $\mathcal B'$ too and hence in $\tau'$.
It's however conceptually easier to just say: the assumption implies that $\mathcal B \subseteq \tau'$ (as $\mathcal B' \subseteq \tau'$ and a topology is closed under unions) and as $\tau$ is the minimal topology that contains $\mathcal B$ we have $\tau \subseteq \tau'$ QED. This is IMO by far the simplest and notation-minimal solution.


text:
Q: Composer works on console but not within a script This is really mysterious for me.. This lines are working, entered manually in a console:
cd /var/www/html/api
sudo composer install
sudo composer update
mysql -uhomestead -psecret -e "DROP DATABASE laravel"
mysql -uhomestead -psecret -e "CREATE DATABASE laravel CHARACTER SET utf8 COLLATE utf8_general_ci;"
php artisan migrate
php artisan db:seed --class DatabaseSeeder

But within a script, it is not working, and crashes CD command, even if I use sudo or try it as admin...
Any hint?

A: Sudo won't work with cd. You should check permission for user that executes your script.
Have a look here as an example.


text:
Q: Rails database boolean values Code first:
create_table :users do |t|
  ...
  t.boolean :is_active, :default => true
  ...
end

Now, here is my issue - I am creating a rake task to import a LARGE number of records (10,000+). I've done extensive testing and benchmarking and determined that the fastest and most efficient way to perform this task is to create one giant raw SQL statement. (I'm reading data from CSV). As an example:
inserts = Array.new
FasterCSV.foreach(...) do |row|
  inserts.push "(row[0], row[1]...)"
end
User.connection.execute "INSERT INTO users (...) VALUES #{inserts.join(", ")}"

Everything works great. The entire process completes in (literally) seconds instead of the 1.5 hours using ActiveRecord. However, my problem lies with the boolean field. I develop locally on SQLite, but MySQL on production. When using ActiveRecord, Rails determines what to put in the "boolean" field (since almost all databases are different). I'm writing custom SQL and I want to know if there is a way I can do something like...
INSERT INTO users(..., is_active, ...) VALUES (..., ActiveRecord::Base.connection.boolean.true, ...)

...that correctly returns the database-specific boolean value.
Anyone who answers "just using ActiveRecord" will be down-voted. It's simply NOT feasible in this situation. I'm also not willing to use a tinyint(1) field and use 1's or 0's.
In summary, the value for is_active needs to change based on the current database connection...
Is this even possible?

A: I believe that you might be looking for ActiveRecord::Base.connection.quoted_true
This returns native boolean values in quotes, e.g. '1' for SQL Server or MySQL, and 't' for PostgreSQL or SQLite


text:
Q: Constraining raster calculator results This is in ArcGIS Pro.
I will be performing a raster calculation to determine how much a given raster might change over time by multiplying the current raster by the percent projected change and then adding back to the current raster to give the 'new' raster
The problem is that the values for the raster need to be constrained to -17 (the worst case) to +17 and this approach could make me fall outside of those values.  So, I know I need something that works sort of like an if then statement - if >17 then =17 and if < - 17 = -17  This is the step that is tripping me up.  I have never been able to really come to grips with the CON statement and I think this may be what is needed here so could you provide any examples?

A: There's two different syntaxes for using Con:
Con("raster", true_value_or_raster, false_value_or_raster, "where_clause")

And
Con(in_conditional_raster, true_value_or_raster, {false_value_or_raster})

I always use the 2nd, it's easier to understand for me.  You can generate the conditional raster on the fly in the function. i.e. Con("raster" > 1, etc...)
For your question, a nested Con function can be used:
Con("raster" > 17, 17, Con("raster" < -17, -17, "raster"))

What this does in pseudo code (for each pixel value):
if "raster" > 17   <-- in_conditional_raster
    output = 17    <-- true_value_or_raster
else               <--- false_value_or_raster using another Con
    if "raster" < -17   <-- in_conditional_raster
        output = -17    <-- true_value_or_raster
    else
        output = "raster"    <-- false_value_or_raster


text:
Q: Deformation of integration paths First of all: I'm more of an algebraic person. So happily differentials/integrals are not what I deal with a lot. However, I got this exercise to solve:
Let $\Omega \subset \mathbb{R}^n$ open, $K: \Omega \rightarrow \mathbb{R}^n$ a $C^1$ vector field with $\partial_iK_j  = \partial_j K_i$ for $i, j= 1, ..., n$.
Let $\gamma, \gamma ' \in C^1([0,1]; \Omega)$ be curves with $\gamma(0) = \gamma'(0)$ and $\gamma(1) = \gamma' (1)$. Let $\Phi \in C^2 ( [0,1] \times [0,1]; \mathbb{R}^n)$ be a homotopy between $\gamma$ and $\gamma'$.
Then it is to show that $\int_{\gamma} K d x= \int_{\gamma '} K d x$.
I know this holds for continous homotopies already, but I have to present the solution to a group of first years and the proof for general case seems a bit lengthy. But, here I have a $C^2$ homotopy, and I'd like to use it by showing
$\frac{\partial}{\partial s} \int_{\Phi(s, -)} K dx = 0$
How can I do this?

A: Pull back the vector field $K$ to the domain $Q=[0,1]^2$ of $\Phi$ as follows: For a given point $u\in Q$ the function
$$\psi(U):=K\bigl(\Phi(u)\bigr)\cdot \bigl(d\Phi(u).U\bigr)$$
is a linear functional on the tangent space $T_u$. Therefore there is a unique vector $a\in T_u$ such that $\psi(U)=a\cdot U$. This vector $a$ is called the pullback of $K$ at $u$ and will be denoted by $K^*(u)$. From the defining equality
$$K^*(u)\cdot U=K\bigl(\Phi(u)\bigr)\cdot \bigl(d\Phi(u).U\bigr)$$
one easily deduces that (a) for any curve $\gamma^*$ in $Q$ with image curve $\Phi(\gamma^*)=:\gamma$ one has
$$\int\nolimits_\gamma K\cdot dx=\int\nolimits_{\gamma^*} K^*\cdot du\ ,$$
and that (b) one has
$${\partial K_2^*\over\partial u_1}-{\partial K_1^*\over\partial u_2}\equiv0$$
when $\partial_iK_j-\partial_jK_i\equiv0$ in $\Omega$.
Now apply Green's theorem to $K^*$, $Q$ and $\partial Q$.

A: Let $\gamma_s(t)$ be the path $\Phi(s,\cdot)$, and let its derivatives be $\gamma'$ (w.r.t. $t$) and $\dot\gamma$ (w.r.t. $s$). We know that $\dot\gamma(0)=\dot\gamma(1)=0$. We also know that $((a\nabla)K,b) = ((b\nabla)K,a)$.
Now,
$$\begin{aligned}
\frac{d}{ds}\int_{\gamma_s}K &=
 \int_0^1dt\,\frac{d}{ds}(K(\gamma_s(t)), \gamma_s'(t))
\\&= \int_0^1 ((\dot \gamma\nabla)K, \gamma') + (K, \dot\gamma')
\\&= \int_0^1 ((\gamma'\nabla)K, \dot\gamma) + (K, \dot\gamma')
\\&= \int_0^1 -(K, \dot\gamma') + (K,\dot\gamma')
\\& = 0,
\end{aligned}$$
where $(\gamma'\nabla)K = \frac{d}{dt}K(\gamma_s(t))$, and the second last line is obtained from integration by parts ($\dot\gamma$ vanishes at $t=0,1$).

A: The proof can be done as follows:
$$\frac{d}{d s}\int_{\Phi(s,-)}K(x)\cdot dx = \frac{d}{d s}\int_0^1K(\Phi(s,t))\cdot \frac{\partial\Phi}{\partial t}(s,t)dt$$
We use one of the classical results of measure theory to exchange integral and derivative:
$$\int_0^1\frac{d}{d s}\left(K(\Phi(s,t))\cdot \frac{\partial\Phi}{\partial t}(s,t)\right)dt =$$
$$=\int_0^1\left(DK(\Phi(s,t))\frac{\partial\Phi}{\partial s}\right)\cdot \frac{\partial\Phi}{\partial t}(s,t) + K(\Phi(s,t))\cdot \frac{\partial^2\Phi}{\partial s\partial t}(s,t)dt$$
Now we use partial integration on the second term, notice that the boundary terms vanish since $\frac{\partial \Phi}{\partial s}(s,t)$ vanishes for $t=0$ and $t=1$:
$$\int_0^1K(\Phi(s,t))\cdot \frac{\partial^2\Phi}{\partial s\partial t}(s,t)dt =$$
$$=\int_0^1\left(\frac{d}{dt}K(\Phi(s,t))\right)\cdot \frac{\partial\Phi}{\partial s}(s,t)dt =$$
$$=\int_0^1\left(DK(\Phi(s,t))\frac{\partial\Phi}{\partial t}(s,t)\right)\cdot \frac{\partial\Phi}{\partial s}(s,t)dt=$$
$$=\int_0^1\left(DK(\Phi(s,t))\frac{\partial\Phi}{\partial s}(s,t)\right)\cdot \frac{\partial\Phi}{\partial t}(s,t)dt$$
Where in the last line we use that $DK$ is symmetric (i.e. the assumption that $\frac{\partial K^i}{\partial x^j} = \frac{\partial K^j}{\partial x^i}$) and that $(Au)\cdot v = (A^tv)\cdot u$. In conclusion we obtain that
$$\frac{d}{d s}\int_{\Phi(s,-)}K(x)\cdot dx =0$$
As you wanted.


text:
Q: setOnItemClickListener on Gridview having listview inside not working properly I am having a listview inside the Gridview and trying to set the OnitemClickListener on gridview. It works when clicked outside the listview, but on clicking the listview part of gridview item its not working.
Following xml code i am inflating in gridview item.
      <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:descendantFocusability="blocksDescendants">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="6dp"
    android:background="@drawable/card_background"
    android:elevation="5dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/dashlet_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:fontFamily="sans-serif-bold"
            android:gravity="center"
            android:paddingLeft="15dp" />

        <ImageView
            android:id="@+id/dashlet_settings"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:paddingRight="15dp"
            android:src="@drawable/settings" />

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_margin="10dp"
        android:background="#c3c3c3" />

    <ListView
        android:id="@+id/dashlet_settings_items_list"
        android:layout_width="wrap_content"
        android:layout_height="90dp"
        android:divider="@null"
        android:listSelector="@android:color/transparent" />

</LinearLayout>

A: It is because of the listview component has no click listener.If you want to get click listener for listview,you may need to put it.
Commonly we are using setOnItemclickListener for listview.
The clicking position has listview only. That is why you get nothing while clicking.


text:
Q: How to send a message to SNS topic through the test event of an AWS lambda function? I have an AWS lambda function that triggers an SNS topic on failure.

I'm wondering why the SNS topic is not triggered why I run "Test" in the AWS console.

As you can see in the above picture, the python lambda function raises an error at line 4.
I've subscribed to the SNS topic with my e-mail address. And I have clicked the "Confirm subscription" link. So there should be no problem receiving messages from the SNS topic.
I've also confirmed that the role of my AWS lambda function has "AmazonSNSFullAccess" permission.
Why can't I trigger SNS topic through the "Test" in AWS lambda function?

A: Thanks to pyzor's information, I use the following python script to asynchronously trigger my AWS lambda function so that it can send messages to SNS topic.
import boto3

client = boto3.client('lambda')
response = client.invoke(
    FunctionName='my-function',
    InvocationType='Event'
)
print(f"response: {response}")


text:
Q: kubespray deployment Failed to download key at https://apt.dockerproject.org/gpg: HTTP Error 404: Not Found In Ubuntu 16.04 I'm trying to deploy Kubespray2.5 using Ansible Playbook(2.9.7) command and getting error:
I have deployed kubespray many times with version 2.5 but this time only i am getting this error.
Please help to me.
ansible-playbook -i inventory/mycluster/hosts.ini cluster.yml
    TASK [docker : ensure docker-engine repository public key is installed] *******************************************************
Friday 08 May 2020  16:28:44 +0530 (0:00:20.450)       0:04:46.454 ************
FAILED - RETRYING: ensure docker-engine repository public key is installed (4 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (4 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (4 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (3 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (3 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (3 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (2 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (2 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (2 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (1 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (1 retries left).
FAILED - RETRYING: ensure docker-engine repository public key is installed (1 retries left).
failed: [node2] (item=58118E89F3A912897C070ADBF76221572C52609D) => {"attempts": 4, "changed": false, "item": "58118E89F3A912897C070ADBF76221572C52609D", "msg": "Failed to download key at https://apt.dockerproject.org/gpg: HTTP Error 404: Not Found"}
failed: [node3] (item=58118E89F3A912897C070ADBF76221572C52609D) => {"attempts": 4, "changed": false, "item": "58118E89F3A912897C070ADBF76221572C52609D", "msg": "Failed to download key at https://apt.dockerproject.org/gpg: HTTP Error 404: Not Found"}
failed: [node1] (item=58118E89F3A912897C070ADBF76221572C52609D) => {"attempts": 4, "changed": false, "item": "58118E89F3A912897C070ADBF76221572C52609D", "msg": "Failed to download key at https://apt.dockerproject.org/gpg: HTTP Error 404: Not Found"}

NO MORE HOSTS LEFT ************************************************************************************************************
        to retry, use: --limit @/root/kubespray/cluster.retry

PLAY RECAP ********************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0
node1                      : ok=62   changed=0    unreachable=0    failed=1
node2                      : ok=64   changed=0    unreachable=0    failed=1
node3                      : ok=62   changed=9    unreachable=0    failed=1

A: The https://apt.dockerproject.org/ repository has been shut down on March 31, 2020.
Your playbook is outdated; acquire a newer version or adjust it according to the linked instructions yourself.


text:
Q: Restful request body return wrong JSON format when using getRawBody() in Zend framework I'm testing the restful service built with zend framework. I'm using the command below to test it (learned from this post).

curl -v -H "Content-Type: application/json" -X GET -d '{"locationId":"33","limit":"5","offset":"0"}' \ http://localhost/api/review

But when I fetch the request body in Zend using $payload = $this->getRequest()->getRawBody();, the var_dump($payload) returns "'{locationId:33,limit:5,offset:0}'", where the double quotation marks are removed so that I can't decode it into array.
What's reason of it? Please help. Thank s in advance.

A: The Windows command line is removing the double quotes. It also does not recognize single quotes. You can try double quoting the entire thing and escaping the quotes use internally like this:
curl -v -H "Content-Type: application/json" -X GET -d "{\"locationId\":\"33\",\"limit\":\"5\",\"offset\":\"0\"}" http://localhost/api/review


text:
Q: Plot a wave on a surface Say I'm plotting a 3d-ring with
ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]),
  Sin[u]}, {t, 0, 2 Pi}, {u, 0, 2 Pi}, Boxed -> False, Axes -> False,
 Mesh -> None]

I need to plot a wave, like a sin-function, which runs over the surface of the ring. Something like a mesh line, which is not straight, but oscillates?
Is it possible to plot?

A: Perhaps this?
Show[
 ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]), Sin[u]},
  {t, 0, 2 Pi}, {u, 0, 2 Pi},
  Boxed -> False, Axes -> False, Mesh -> None],
 ParametricPlot3D[
  With[{t = v, u = 0.5 Sin[20 v]},
    {Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]), Sin[u]}
   ],
  {v, 0, 2 Pi},
  PlotStyle -> Thick]
 ]

A: Edit
You can draw a Sin like curve in the parametric domain,see f[t,u] as below.
f[t_, u_] := 2 u - 1 - Sin[15 t];
ContourPlot[f[t, u] == 0, {t, 0, 2 π}, {u, 0, 2 π},
 PlotPoints -> 80, FrameLabel -> {t, u}]

and then use the MeshFunctions to lift it to the surface.
ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]),
  Sin[u]}, {t, 0, 2 Pi}, {u, 0, 2 Pi}, Boxed -> False, Axes -> False,
 MeshStyle -> Directive[Thick, Cyan],
 MeshFunctions -> Function[{x, y, z, t, u}, f[t, u]], Mesh -> {{0}},
 PlotPoints -> 80]

Original
Like this?
f[x_, y_, k_] := 4 Cos[Sqrt[x^2 + y^2] - k]*Exp[-Sqrt[x^2 + y^2]/6];
Manipulate[
 ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]),
   Sin[u]}, {t, 0, 2 Pi}, {u, 0, 2 Pi}, Boxed -> False, Axes -> False,
   MeshStyle -> Directive[Thick, Cyan],
  MeshFunctions -> Function[{x, y, u, v}, f[u, v, k]], Mesh -> 40,
  PerformanceGoal -> "Quality"], {k, 0, 8/π, 1/(50 π)}]


text:
Q: Child not re rendering when child state changed I'm using model in child components and I would like to manage visibility by child state variable, but when I click on button(it's also on child) child state variable is update successfully but child render function not called?
Please review my code and let me correct where i'm wrong.
      //Main Parent class

        export default class ChatMessageComponent extends Component {
            renderItem = ({ index, item }) => {
                return (
                  <ChatMessageView
                    {...this.props}
                  />
                )
              };
            }

    //ChatMessageView child
    export default class ChatMessageView extends PureComponent {
    render() {
        return (
          <View style={[styles.container, isMinimize ? { width: screenWidth - scale(20) } : null]}>
                <ChatNoticeView
                  {...this.props}

                />
          </View>
        )
      }
    }
    }
    //ChatNoticeView child
    export default class ChatNoticeView extends Component {
constructor(props) {
    super(props);
    this.state = {
      visibleModal: this.props.isVisible
    }
  }
 renderModAL = () => {
    return (
      <Modal
        visible={this.state.visibleModal}
      >
        <RejectReason
        />
      </Modal>
    )
  }
render() {
    return (
      <View style={styles.container}>
    {this.renderModAL()}
      </View>
    )
  }
}

//Model
export default class RejectReason extends Component {
    componentDidMount() {
    }

    render() {
        return (
            <View style={styles.container}>

            </View>
        )
    }
}

A: This is because your child's function is bonded with the state which won't get updates when the button is clicked. Either need to use the getderivedstatefromprops method to update state or bind the visibility with props. I have update your child component which should show the modal.
export default class ChatNoticeView extends Component {
constructor(props) {
    super(props);
    this.state = {
      visibleModal: this.props.isVisible
    }
  }
 renderModAL = () => {
    return (
      <Modal
        visible={this.props.isVisible}
      >
        <RejectReason
        />
      </Modal>
    )
  }

You can read more about getDerivedStateFromProps here


text:
Q: Start MyAppPool using iisapp.vbs I have a batch file that uses the following script to recycle MyAppPool.
cscript.exe %windir%\system32\iisapp.vbs /a MyAppPool /r

However when MyAppPool is Stopped, then I am not able to recycle it. What I want is to check weather MyAppPool is Stopped, if stopped , then Start it, recycle it and then Stop again.
Well I am a complete newbie in this IIS thing and have never worked in it. I am using Window Server 2003 and IIS6.

A: You can write your own .vbs script, to lookup the .State of the AppPool, and start it when it's stopped. Something like:
//EDIT:
Option Explicit

If WScript.Arguments.Count <> 1 Then
    Wscript.Echo "No AppPoolName provided. Iterate through all AppPools"
    iterate_and_start_all_apps()
Else
    Dim AppPoolName
    AppPoolName = Wscript.Arguments(0)
    '
    ' Choose what to do here and uncomment that Sub
    '
    ' start_given_app(AppPoolName)
    ' start_one_app_if_stopped(AppPoolName)
    ' start_recycle_stop_app(AppPoolName)
End If

' This Sub is runs if no argument is passed to the script
Sub iterate_and_start_all_apps()
        Dim objAppPools, objAppPool
        Set objAppPools = GetObject("IIS://Localhost/W3SVC/AppPools")
        For Each objAppPool in objAppPools
          Set objAppPool = GetObject("IIS://Localhost/W3SVC/AppPools/" & objAppPool.Name )
            If objAppPool.AppPoolState <> 2 Then
              Wscript.Echo objAppPool.Name & " is not running."
                  WScript.Echo objAppPool.Name & ", AppPoolState: " & objAppPool.AppPoolState & _
                        ", Win32Error: " & objAppPool.Win32Error & " ("& hex(objAppPool.Win32Error)&")"
                  Wscript.Echo State2Desc(objAppPool.AppPoolState)
                  objAppPool.Start
                  If Err.Number = 0 Then
                    Wscript.Echo objAppPool.Name & " started."
                  End If
                End If
        Next
        Set objAppPool = Nothing
        Set objAppPools = Nothing
End Sub

'
' start an application pool if the .State is stopped
'
Sub start_one_app_if_stopped(applicationpool)
        Dim iisObjectPath : iisObjectPath = ("IIS://Localhost/W3SVC/AppPools/" & applicationpool)
        Dim iisObject : Set iisObject = GetObject(iisObjectPath)
                If iisObject.AppPoolState <> 2 Then
                  iisObject.Start
                  If (Err.Number <> 0) Then
                    WScript.Echo "Error starting: " & ObjectPath
                    WScript.Quit (Err.Number)
                  Else
                    WScript.Echo applicationpool & " started."
                  End If
                End If
        Set iisObject = nothing
        Set iisObjectPath = nothing
End Sub

'
' if an application pool is stopped, start + recycle + stop it
'
Sub start_recycle_stop_app(applicationpool)
        Dim iisObjectPath : iisObjectPath = ("IIS://Localhost/W3SVC/AppPools/" & applicationpool)
        Dim iisObject : Set iisObject = GetObject(iisObjectPath)
                If iisObject.AppPoolState <> 2 Then
                  iisObject.Start
                  If (Err.Number <> 0) Then
                    WScript.Echo "Error starting: " & ObjectPath
                    WScript.Quit (Err.Number)
                  Else
                    WScript.Echo applicationpool & " started."
                 End If

                  iisObject.recycle
                  ' we need to sleep for some time because recyle takes some time
                  wscript.sleep(3000)

                  iisObject.Stop
                End If
        Set iisObject = nothing
        Set iisObjectPath = nothing
End Sub

'
' just issue a start command to start an application pool
'
Sub start_given_app(applicationpool)
        Dim iisObjectPath : iisObjectPath = ("IIS://Localhost/W3SVC/AppPools/" & applicationpool)
        Dim iisObject : Set iisObject = GetObject(iisObjectPath)
                IIsObject.Start
                If (Err.Number <> 0) Then
                        WScript.Echo "Error starting: " & ObjectPath
                        WScript.Quit (Err.Number)
                Else
                        WScript.Echo applicationpool & " started."
                End If
        Set iisObject = nothing
        Set iisObjectPath = nothing
End Sub

'
' support function
'
Function State2Desc(nState)
    Select Case nState
    Case 1
        State2Desc = "Starting"
    Case 2
        State2Desc = "Started"
    Case 3
        State2Desc = "Stopping"
    Case 4
        State2Desc = "Stopped"
    Case Else
        State2Desc = "Unknown state"
    End Select
End Function

(part taken from http://www.saotn.org/iis-60-start-gestopte-application-pools/, which is a script to start all application pools).
Save as 'startapp.vbs' and run with:
cscript.exe /nologo startapp.vbs name_of_appPool

if you start it without an argument, then the script will iterate through all applications pools in the the metabase and start them if they're not running.
I think you'll need the "start_one_app_if_stopped" Sub, so uncoment that line (line 13) and run the .vbs script with an command line argument:
cscript.exe /nologo startapp.vbs name_of_appPool

HTH


text:
Q: Quaternion rotations strange behavior I'm currently working on my own small game engine (I am learning OpenGL). I made camera mechanism that can rotate vectors with Euler angles, and now I'm working on rotations with quaternions. Now I'm stuck because my quaternions rotations behave very strangely (flipping objects, not rotating camera as it should). Please, help me find out what is wrong with my algorithm. Could you suggest some fixes to my camera code? Below is my source code, and here is some marks to it: target I want to look at is at coordinates (0.0f, 0.0f, 0.0f). I want my position from which I am look at the target to be glm::vec3 position = glm::vec3(0.0f, 0.0f, 3.0f)
My camera class:
class Camera {
private:
    bool eulerMode = false;
    float m_mouseSensitivity;
    float m_velocity;
    glm::vec3 m_rightAxis{};
    glm::vec3 m_upAxis;
    glm::vec3 m_position;
    glm::vec3 m_target{};
    glm::vec3 m_r{};
    glm::vec3 m_direction{};

    static glm::vec3 rotateVector(float angle, glm::vec3 rotationAxis, glm::vec3 vectorToRotate);
    static glm::quat quaternion(float angle, glm::vec3 vec);

public:
    static Camera *s_context;
    float m_yaw;
    float m_pitch;
    float m_mouseLastX;
    float m_mouseLastY;
    bool m_firstMouse;
    glm::vec3 m_frontAxis;

    Camera(float speed,
           int width,
           int height,
           glm::vec3 position = glm::vec3(0.0f, 0.0f, 3.0f),
           glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f),
           glm::vec3 target = glm::vec3(0.0f, 0.0f, 0.0f)
    );

    glm::mat4 getLookAtMatrix();

    static void quaternionRotate(GLFWwindow *window, double x, double y);
};

Camera::Camera(
        float speed,
        int width,
        int height,
        glm::vec3 position,
        glm::vec3 up,
        glm::vec3 target
)
        : m_pitch(0.0f), m_yaw(-90.0f), m_mouseLastX((float) width / 2),
          m_mouseLastY((float) height / 2), m_mouseSensitivity(0.1f), m_upAxis(up), m_position(position),
          m_frontAxis(glm::vec3(0.0f, 0.0f, -1.0f)), m_firstMouse(true) {
    m_velocity = speed;
    m_direction = glm::normalize(position - target);
    m_rightAxis = glm::normalize(glm::cross(up, m_direction));
    m_upAxis = glm::cross(m_direction, m_rightAxis);

    s_context = this;
    glfwSetWindowUserPointer(g_Window->getOpenGLWindow(), this);

    if (eulerMode) {
        glfwSetCursorPosCallback(g_Window->getOpenGLWindow(), eulerRotate);
    } else {
        glfwSetCursorPosCallback(g_Window->getOpenGLWindow(), quaternionRotate);
    }
}

glm::mat4 Camera::getLookAtMatrix() {
    glm::mat4 view = glm::lookAt(m_position, m_r, m_upAxis);
    return view;
}

// for the sake of brevity, I skipped some class methods that are unnecessary for quaternions rotations

void Camera::quaternionRotate(GLFWwindow *window, double x, double y) {
    if (s_context->m_firstMouse) {
        s_context->m_mouseLastX = (float) x;
        s_context->m_mouseLastY = (float) y;
        s_context->m_firstMouse = false;
    }

    auto xoffset = (float) (x - s_context->m_mouseLastX);
    auto yoffset = (float) (s_context->m_mouseLastY - y);
    s_context->m_mouseLastX = (float) x;
    s_context->m_mouseLastY = (float) y;

    float sensitivity = 0.1f;
    xoffset *= sensitivity;
    yoffset *= sensitivity;

    s_context->m_yaw += xoffset;
    s_context->m_pitch += yoffset;

    glm::vec3 yAxis = glm::vec3(0, 1, 0);

    // Rotate the view vector by the horizontal angle around the vertical axis
    glm::vec3 view = s_context->m_direction;
    view = glm::normalize(rotateVector(s_context->m_yaw, yAxis, view));

    // Rotate the view vector by the vertical angle around the horizontal axis
    glm::vec3 xAxis = glm::normalize(glm::cross(yAxis, view));
    view = glm::normalize(rotateVector(s_context->m_pitch, xAxis, view));

    s_context->m_r = view;
    s_context->m_upAxis = glm::normalize(glm::cross(s_context->m_r, xAxis));
}

glm::vec3 Camera::rotateVector(float angle, const glm::vec3 rotationAxis, const glm::vec3 vectorToRotate) {
    glm::quat rotationQ = quaternion(angle, rotationAxis);
    glm::quat conjugateQ = glm::conjugate(rotationQ);
    glm::quat result = rotationQ * vectorToRotate * conjugateQ;
    return {result.x, result.y, result.z};
}

glm::quat Camera::quaternion(float angle, const glm::vec3 vec) {
    float HalfAngleInRadians = glm::radians(angle / 2);
    float SineHalfAngle = sinf(HalfAngleInRadians);
    float CosHalfAngle = cosf(HalfAngleInRadians);
    float xC = vec.x * SineHalfAngle;
    float yC = vec.y * SineHalfAngle;
    float zC = vec.z * SineHalfAngle;
    float wC = CosHalfAngle;
    return {wC, xC, yC, zC};
}


text:
Q: Prevent Javascript Facebook SDK Conflicts in plugin I have plugin that uses Facebook's Javascript SDK to display a Facebook's Customer Chat Plugin.
I've been getting feedback that it doesn't work well with other Wordpress plugins that load the Facebook Javascript SDK.
This is the code Facebook provides to use for my Facebook SDK plugin: Customer Chat for Facebook
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId            : 'your-app-id',
      autoLogAppEvents : true,
      xfbml            : true,
      version          : 'v2.11'
    });
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "https://connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

This is an example of a plugin that breaks mine: Simple Facebook Plugin
<script>
    (function(d){
        var js, id = 'facebook-jssdk';
        if (d.getElementById(id)) {return;}
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));
</script>

Question:
How can protect my Facebook SDK plugin from any other Facebook SDK plugins that loaded before it AND not interfere with any plugins that load after it?
Live Example


text:
Q: JSON , how to parse variable with "-" name I have below json data. Here i m not able to parse "user-1" using script. Its returning null values. any ideas please..
JSON Data:
{
   "users":[
      {
         "unique_id":1122774,
         "user-1":"Alpha",
         "user-2":"Beta",
         "location":"ABC",

      }
   ]
}

SCRIPT :
for (var key in parsed.users) {
 gs.log("unique_id "+parsed.matches[key].unique_id);
 gs.log("user 1 "+parsed.matches[key].user-1);
}


text:
Q: What is an easy way to replace duplicated object serialisations by the ID in jackson I have a nested data structure, where somewhere down the hierarchy the same objects are used several times. What I want as a result is, that when serializing this via Jackson, it is somehow detected than an object has already been written to the output and instead of serializing the object again, its ID is used.
Is Jackson able to do this for me, or do I have to implement this manually?
Example:
AddressBook
  |
  Person
    |
    Tag

A lot of Persons can have the same Tag. I only want each Tag object once in the JSON output.

A: It seems pretty trivial to implement manually - just have a HashSet containing all the Tag objects. Then, as you're serializing, if an object's tag is already contained in the set, you know it's already been serialized.


text:
Q: Transparent layout - not transparent on Android 2.3 I have a transparent layout used for holding a banner advert in my app. The layout sits on top of my game area constantly, but the ads only appear once in a while. The code works as follows:
transparent_linearlayout_to_hold_banner.setBackgroundColor(Color.TRANSPARENT);
game_frame_layout.addView(transparent_linearlayout_to_hold_banner);
setContentView(game_frame_layout);

When I want an ad to be shown I do a
transparent_linearlayout_to_hold_banner.addView(adView);

When I want the ad to disappear I do a
transparent_linearlayout_to_hold_banner.removeView(adView);

This works perfectly on my Galaxy S !! with 4.0.3, but on my Galaxy tab with 2.3 I find that my transparent_linearlayout_to_hold_banner turns black as soon as the add appears, and remains black forever more, even when the ad is removed.
Any idea what is happening?... and how to fix it?
EDIT: after some experimentation, I worked out that the colour of the layout is not changing, but the alpha channel is. My guess is that perhaps the SDK of the banner ad system is calling some function(s) to make sure that the banner itself is not transparent, and then (depending on the OS version) this is having the side effect of making its parent layout non-transparent.

A: Try making the layout non transparent before adding the ad banner.
When you want to remove the ad, remove the ad banner view and make the layout transparent again.
Can you try adding this line again after you remove the ad.
transparent_linearlayout_to_hold_banner.setBackgroundColor(Color.TRANSPARENT);

A: If you're using admob, try latest 6.0 library, it has several improvements (as I can see) in control over the look of ad, it seems to pay more attention to the attributes described in Best Practices: Specifying ad colors. I had similar problem with previous release of the library. Yet, it doesn't allow alpha-channel, so you wouldn't be able to specify transparent background of the ad, but it may solve your problem.

A: try to make the layout that you want to be transparent in XML, not dynamically. I had such problems on dynamically added ListView with transparent Items.
You have a game here, so of course what I suggested might not work, or will be hard to do, but you can Use a FrameLayout to put your layout on which you draw, and the transparent one on top of it. Also note, in such case the touches will go to the ad layout. It can be prevented, but is a bit like of a hack (I did it by the way once).
I don't know if this will work, but give a try.

A: some ideas:
can you simply remove the line of setting the background to the lineraLayout :
transparent_linearlayout_to_hold_banner.setBackgroundColor(Color.TRANSPARENT);

?
also , instead of removing and adding the adView , can you instead toggle the visibility of the linearLayout (or the adView ) ?


text:
Q: Select every second row mysql without auto_increment or data of table How can I select even numbered records in MySQL, without using any column id or auto_increment?
I have now this for the ODD rows:
SET @inc = 0;
SELECT * FROM
(SELECT *,@inc:=1-@inc autoinc
FROM mytable) A
WHERE autoinc = 1 ORDER BY id;

And for even:
SET @inc = 0;
SELECT * FROM
(SELECT *,@inc:=1-@inc autoinc
FROM mytable) A
WHERE autoinc = 1 ORDER BY id;

This works good. But on large tables it is too slow.
Please suggest me any alternatives.

A: maybe you look forsomething like this by MOD
try this
    select * from Table1 where mod(id, 2) <> '1'

DEMO HERE
if you want to output odd rows 1,3,5,...
then use this
       select * from Table1 where mod(id, 2) <> '0'

A: Assuming you're using a version of MySQL new enough to support subqueries -- and if not, what are you still doing on MySQL 3? -- here's an example of how it's done, using a temporary table with meaningless contents:
 mysql> create temporary table t (n text);
 Query OK, 0 rows affected (0.00 sec)

 mysql> insert into t (n) values ('a'), ('b'), ('c'), ('d'), ('e');
 Query OK, 5 rows affected (0.00 sec)
 Records: 5  Duplicates: 0  Warnings: 0

 mysql> select * from t;
 +------+
 | n    |
 +------+
 | a    |
 | b    |
 | c    |
 | d    |
 | e    |
 +------+

 mysql> SET @i = 0; SELECT i, n FROM (SELECT @i := @i + 1 AS i, n FROM t) a WHERE MOD(a.i, 2) = 0;
 Query OK, 0 rows affected (0.00 sec)

 +------+------+
 | i    | n    |
 +------+------+
 |    2 | b    |
 |    4 | d    |
 +------+------+
 2 rows in set (0.00 sec)

 mysql> SET @i = 0; SELECT i, n FROM (SELECT @i := @i + 1 AS i, n FROM t) a WHERE MOD(a.i, 2) = 1;
 Query OK, 0 rows affected (0.00 sec)

 +------+------+
 | i    | n    |
 +------+------+
 |    1 | a    |
 |    3 | c    |
 |    5 | e    |
 +------+------+
 2 rows in set (0.00 sec)

See how that works? You're setting session variable @i to zero, then, in the subquery, doing the equivalent of a preincrement on it to give you an index column along with your data rows. Then, in the outer query, you're selecting rows based on whether @i mod 2 is 0 (for even-numbered rows) or 1 (for odd-numbered rows).
I've selected the 'i' column in the outer query for purposes of illustration, but you don't need to do the same for the technique to work -- or, of course, if you're selecting * in the outer query, you can just ignore the 'i' column values in the result. (If you already have a column 'i' in your data table, just use a different alias in the subquery.)
The technique generalizes pretty well, too; for WHERE MOD(a.i, N) = 0, you get back every Nth row.


text:
Q: marginals of Dirichlet distribution (using Gamma definition) Let be $X=(X_1,\cdots,X_k)\sim \operatorname{Dirichlet}(\alpha_1,\cdots,\alpha_k).$ Find the distribution of any marginal vector $(X_r,\cdots,X_h)$, $1\leq r\leq h\leq k.$
I found the following definition of Dirichlet distribution:
Let  $X=(\frac{Y_1}{\sum_{i=1}^kY_i},\cdots,\frac{Y_k}{\sum_{i=1}^kY_i});$ $Y_i\sim \Gamma (\alpha _i,1)$. Then $X\sim \operatorname{Dirichlet}(\alpha_1,\cdots,\alpha_k).$
Can I use this definition to find the marginal distributions?
There is other easier method to find the distributions or marginals?


text:
Q: How to detect what device the user is using? I know there was a thread about this already, but I'm asking this because it isn't working for me.
I put this code outside of my class, and it has no closures around it.
public extension UIDevice {

var modelName: String {
    var systemInfo = utsname()
    uname(&systemInfo)
    let machineMirror = Mirror(reflecting: systemInfo.machine)
    let identifier = machineMirror.children.reduce("") { identifier, element in
        guard let value = element.value as? Int8 where value != 0 else { return identifier }
        return identifier + String(UnicodeScalar(UInt8(value)))
    }

    switch identifier {
    case "iPod5,1":                                 return "iPod Touch 5"
    case "iPod7,1":                                 return "iPod Touch 6"
    case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
    case "iPhone4,1":                               return "iPhone 4s"
    case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
    case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
    case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
    case "iPhone7,2":                               return "iPhone 6"
    case "iPhone7,1":                               return "iPhone 6 Plus"
    case "iPhone8,1":                               return "iPhone 6s"
    case "iPhone8,2":                               return "iPhone 6s Plus"
    case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
    case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
    case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
    case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
    case "iPad5,1", "iPad5,3", "iPad5,4":           return "iPad Air 2"
    case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
    case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
    case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
    case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
    case "i386", "x86_64":                          return "Simulator"
    default:                                        return identifier
    }
 }
}

So, up in my didMoveToView, I ran this code:
if UIDevice.currentDevice().modelName == "iPhone4,1" {
        print("yes")
    repeatObstaclesOnPhone()

    }

I ran the app then on the iPhone 4S simulator and nothing happened. Can someone help me figure this out?


text:
Q: How to handle cross thread error in C sharp windows application? I'm having an application with a progress bar and a buttom.
When the button clicked the progress bar value will get increased, here is the source code,
private void Run()
        {
                progressBar1.Maximum = 1000;
                progressBar1.Minimum = 0;
                progressBar1.Step = 1;

                for (int l_nIndex = 0; l_nIndex < 1000; l_nIndex++)
                {
                        progressBar1.Value++;
                        Thread.Sleep(10);
                }
            }

private void button1_Click(object sender, EventArgs e)
        {
                Run();
    }

so when i run the application, the progress bar value is getting increased, but when i try to move the window its not responding.
I can not run it in a normay thread way - it will throw Cross-Thread error.
so i changed the code like,
private void Run()
        {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(this.Run));
                }
                else
                {
                    progressBar1.Maximum = 1000;
                    progressBar1.Minimum = 0;
                    progressBar1.Step = 1;
                    for (int l_nIndex = 0; l_nIndex < 1000; l_nIndex++)
                    {
                            progressBar1.Value++;
                            Thread.Sleep(10);
                    }
                }
        }

 private void button1_Click(object sender, EventArgs e)
        {
                Thread myThread = new Thread(new ThreadStart( Run));
              myThread.Start();
        }

Now i can able to move the winodow, but when i move the progress bar is stopped, and when i release the mouse button its resuming. So still the execution is in UI Thread.
How to handle it in a better way.Please help me to do this .

A: Invoke() works by running the given delegate from the UI thread.  So if you use Invoke() to run your entire method, then your entire method runs from the UI thread.
Instead, you should be doing your actual work in the other thread, and just performing UI updates in the UI thread, by just Invoke()ing the little bits of code that perform the updates.
One easy way to do this is to use the BackgroundWorker class built into the standard library.

A: This has been answered here - in your case the code should look something like:
this.BeginInvoke((Action)(() => progressBar1.Value++));


text:
Q: Помогите синтаксически правильно обновить счетчик в стейте React Вообщем ситуация следующая:
state = {
    ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
    }
}

addIngredientHandler = type => {
    this.setState(prevState => {
        ingredients: {
            [type]: prevState.ingredients.[type] + 1
        }
    })
}

В методе addIngredientHandler я хочу в зависимости от передаваемого параметра увеличить соответствующий счетчик в стейте. Помогите написать правильно синтаксически данную функцию.

A: Набросал для примера вот такой вариант:
import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
      }
    };

    this.addIngredientHandler = this.addIngredientHandler.bind(this);
  }

  addIngredientHandler(e) {
    const { name } = e.target;
    this.setState({
      ingredients: {
        ...this.state.ingredients,
        [name]: this.state.ingredients[name] + 1
      }
    });
  }

  render() {
    const { bacon, salad, cheese, meat } = this.state.ingredients;
    return (

Ingredients!

        <button onClick={this.addIngredientHandler} name="bacon">bacon {bacon}/button>
        <button onClick={this.addIngredientHandler} name="salad">salad {salad}</button>
        <button onClick={this.addIngredientHandler} name="cheese">cheese {cheese}</button>
        <button onClick={this.addIngredientHandler} name="meat">meat {meat}</button>

    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

Использовал так называемый spread syntax для копирования свойств объекта. Вариант рабочий, просто нужно переписать немного под ваши нужды. Смысл думаю ясен. Результат:

Spread syntax позволяет повторить итерацию, такую как выражение
  массива или строк, в местах, где ожидается ноль или больше аргументов
  (для вызовов функций) или элементы (для литералов массива), или
  выражение объекта, которое должно быть расширено в местах, где пары
  ключ-значение ноль или больше (для объектных литералов).

В данном случае, в приведенном примере, spread syntax (...) копирует собственные перечисляемые свойства данного объекта в новый объект.

A: Предлагаю использовать спред опреатор ... для получения текущего стейта. Далее модифицируем стейт и вызываем this.setState.
state = {
    ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
    }
};

addIngredientHandler = type => {
    const { ingredients } = this.state;
    const newIngredients = { ...ingredients, [type]: ingredients[type] + 1 };
    this.setState({ ingredients: newIngredients });
};

A: Object.assign() еще для копирования обьекта по ссылке. Определить в методе что менять и менять через this.setState()


text:
Q: Reading with setw: to eof or not to eof? Consider the following simple example
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

int main() {
  string str = "string";
  istringstream is(str);
  is >> setw(6) >> str;
  return is.eof();
}

At the first sight, since the explicit width is specified by the setw manipulator, I'd expect the >> operator to finish reading the string after successfully extracting the requested number of characters from the input stream. I don't see any immediate reason for it to try to extract the seventh character, which means that I don't expect the stream to enter eof state.
When I run this example under MSVC++, it works as I expect it to: the stream remains in good state after reading. However, in GCC the behavior is different: the stream ends up in eof state.
The language standard, it gives the following list of completion conditions for this version of >> operator

*

*n characters are stored;

*end-of-file occurs on the input sequence;

*isspace(c,is.getloc()) is true for the next available input character c.

Given the above, I don't see any reason for the >> operator to drive the stream into the eof state in the above code.
However, this is what the >> operator implementation in GCC library looks like
...
__int_type __c = __in.rdbuf()->sgetc();

while (__extracted < __n
       && !_Traits::eq_int_type(__c, __eof)
       && !__ct.is(__ctype_base::space,
                   _Traits::to_char_type(__c)))
{
  if (__len == sizeof(__buf) / sizeof(_CharT))
  {
    __str.append(__buf, sizeof(__buf) / sizeof(_CharT));
    __len = 0;
  }
  __buf[__len++] = _Traits::to_char_type(__c);
  ++__extracted;
  __c = __in.rdbuf()->snextc();
}
__str.append(__buf, __len);

if (_Traits::eq_int_type(__c, __eof))
  __err |= __ios_base::eofbit;
__in.width(0);
...

As you can see, at the end of each successful iteration, it attempts to prepare the next __c character for the next iteration, even though the next iteration might never occur. And after the cycle it analyzes the last value of that __c character and sets the eofbit accordingly.
So, my question is: triggering the eof stream state in the above situation, as GCC does - is it legal from the standard point of view? I don't see it explicitly specified in the document. Is both MSVC's and GCC's behavior compliant? Or is only one of them behaving correctly?

A: The definition for that particular operator>> is not relevant to the setting of the eofbit, as it only describes when the operation terminates, but not what triggers a particular bit.
The description for the eofbit in the standard (draft) says:

eofbit  - indicates that an input operation reached the end of an input sequence;

I guess here it depends on how you want to interpret "reached". Note that gcc implementation correctly does not set failbit, which is defined as

failbit - indicates that an input operation failed to read the expected characters, or
  that an output operation failed to generate the desired characters.

So I think eofbit does not necessarily mean that the end of file impeded the extractions of any new characters, just that the end of file has been "reached".
I can't seem to find a more accurate description for "reached", so I guess that would be implementation defined. If this logic is correct, then both MSVC and gcc behaviors are correct.

EDIT: In particular, it seems that eofbit gets set when sgetc() would return eof. This is described both in the istreambuf_iterator section and in the basic_istream::sentry section. So now the question is: when is the current position of the stream allowed to advance?

FINAL EDIT: It turns out that probably g++ has the correct behavior.
Every character scan passes through <locale>, in order to allow different character sets, money formats, time descriptions and number formats to be parsed. While there does not seem to be a through description on how the operator>> works for strings, there are very specific descriptions on how do_get functions for numbers, time and money are supposed to operate. You can find them from page 687 of the draft forward.
All of these start off by reading a ctype (the "global" version of a character, as read through locales) from a istreambuf_iterator (for numbers, you can find the call definitions at page 1018 of the draft). Then the ctype is processed, and finally the iterator is advanced.
So, in general, this requires the internal iterator to always point to the next character after the last one read; if that was not the case you could in theory extract more than you wanted:
string str = "strin1";
istringstream is(str);
is >> setw(6) >> str;
int x;
is >> x;

If the current character for is after the extraction for str was not on the eof, then the standard would require that x gets the value 1, since for numeric extraction the standard explicitly requires that the iterator is advanced after the first read.
Since this does not make much sense, and given that all complex extractions described in the standard behave in the same way, it makes sense that for strings the same would happen. Thus, as the pointer for is after reading 6 characters falls on the eof, the eofbit needs to be set.


text:
Q: How to install python imagemagick at windows 7. I followed these instruction To install python IMagick binding wand api on windows 64 bit (python 2.6)
This is what I did:

*

*downloaded and installed ImageMagick-6.5.8-7-Q16-windows-dll.exe

*downloaded wand module from http://pypi.python.org/pypi/Wand

*after that i ran python setup.py install from wand directory,

*then i executed step6. but i got the import error: magickband librarry not found

*downloaded magickwand' module and executed 'python setup.py install' from magickwand directory.

*then agian i tried this code
from wand.image import Image
from wand.display import display

with Image(filename='mona-lisa.png') as img:
    print img.size
    for r in 1, 2, 3:
        with img.clone() as i:
            i.resize(int(i.width * r * 0.25), int(i.height * r * 0.25))
            i.rotate(90 * r)
            i.save(filename='mona-lisa-{0}.png'.format(r))
            display(i)

*but thereafter again i am getting the same import error magickband library not found
i am fed up with this coz i have done with all the installation. but not able to execute the code. coz everytime i am getting magickband libraray..import error.

A: You have to set MAGICK_HOME environment variable first.  See the last part of this section.

(source: wand-py.org)

>

Lastly you have to set MAGICK_HOME environment variable to the path of ImageMagick (e.g. C:\Program Files\ImageMagick-6.7.7-Q16).  You can set it in Computer ‣ Properties ‣ Advanced system settings ‣ Advanced ‣ Environment Variables....

A: First i had to install ImageMagic and set Envrioment Variable MAGIC_HOME ,just after i was able to install Wand from pip


text:
Q: Angular-translate Unknown provider Im using angular translate in my app, this is my app.js
var formApp = angular.module('formApp', [
  'ngRoute',
  'ui.bootstrap',
  'pascalprecht.translate'
]).config(function($translateProvider) {
    $translateProvider.translations('en', {
       HEADLINE: 'Hello there, This is my awesome app!',
       INTRO_TEXT: 'And it has i18n support!'
    });
});

Im fallowing tutorial I fond on the internet.
This is how I loaded libraries in my html file

And this is how i print values

{{ 'HEADLINE' | translate }}

{{ 'INTRO_TEXT' | translate }}

But when i open my app im getting this msg in console :
Error: [$injector:unpr] Unknown provider: translateFilterProvider <- translateFilter

Does anyone knows how to fix this? Im absolute beginner in angular, sorry if error is stupid :)

A: In your controller, you need to add $translate as a dependency.
formApp.controller('myCtrl', function ($scope, $translate) {
 //code
});

So for example in the html, you must have a ng-controller at some point before those elements, thats the controller that needs the dependency injected as a parameter.

  ...

HEADLINE

INTRO_TEXT

  ...

Also in the config block you need to set the prefered language:
$translateProvider.preferredLanguage('en');


text:
Q: How to get average of each player in recent 5 games I have a table containing player name, total on court time, and date of that game.

Given a list of players, I want to calculate the average on court time of each player in recent 5 games.
This is how I get average on court time of Aaron Brooks.
select `Player Name`, AVG(TIME_TO_SEC(`Total on Court`))
from
    (SELECT * FROM nba.`player stat total`
    where `Player Name`='Aaron Brooks'
    order by `date` desc
    limit 5) as t

But I have a list of players, it is possible to do in pure sql rather than executing sql in a for-loop in my program?
The players may be in the form ('Aaron Brooks', 'Chris Bosh', 'Andre Miller') or any other form you like.

A: You can use user-defined variables to get 5 recent records per player group
SELECT t.`Player Name` ,
AVG(TIME_TO_SEC(t.`Total on Court`))
 FROM (
SELECT s.*,
@rank:= CASE WHEN @group = s.`Player Name` THEN @rank +1 ELSE 1 END rank ,
@group:= s.`Player Name` g
 FROM
`player stat total` s
JOIN (SELECT @group:='',@rank:='') t
 WHERE s.`Player Name` IN('Aaron Brooks', 'Chris Bosh', 'Andre Miller')
ORDER BY `Player Name`  ,`date` DESC
) t WHERE t.rank <=5
GROUP BY t.`Player Name`

A: Give this a try
SELECT *
FROM
    (SELECT `Player Name`, SUM(AVG(TIME_TO_SEC(`Total on Court`))) AS Avg FROM nba.`player stat total`
    GROUP BY `Player Name`
    ORDER BY `date` desc
    LIMIT 5) AS t


text:
Q: Script that will merge changes from the master to my branch I'm trying to write a script that will merge changes from the master to my branch that will be built in Azure DevOps
git config –global user.email "My Email"
git config –global user.name "My User Name"
REPO="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_git/$(Build.Repository.Name)"
EXTRAHEADER="Authorization: Bearer $env:SYSTEM_ACCESSTOKEN"
git -c http.extraheader="$EXTRAHEADER" clone $REPO
cd $(Build.Repository.Name)
# ls

git config http.$REPO.extraHeader "$EXTRAHEADER"

git checkout $(Build.SourceBranchName)
git status
ls -la
git merge --no-ff --no-edit origin/automatecitest
ls -la

I have configured the rights that are described in this article.
but I am getting errors
*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: empty ident name (for <vsts@fv.fx.internal.cloudapp.net>) not allowed

Could you please help me. Thanks.

A: Based on your actual script, you are merging origin/automatecitest to main.
I archive via below code:
trigger: none

pool:
  vmImage: Ubuntu-latest

steps:
- checkout: none

- script: |
    REPO="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_git/$(Build.Repository.Name)"
    git clone -c http.extraheader="AUTHORIZATION: bearer $(System.AccessToken)" $REPO
    cd $(Build.Repository.Name)
    ls
    git config user.email "tester1@hotmail.com"
    git config user.name "tester1"
    git merge --no-ff --no-edit origin/automatecitest
    ls -la

I enabled in project setting:

Note:

*

*You can change the branch, from main to other..

*The change will not push back to main branch since you need to add extra step to push. if you cat file change afte merge in the task, you can see the merge result.


text:
Q: Show figures two at a time by default I'm writing a document that has a lot of figures, and as a result is quickly growing in size. I want to bring the page count down if possible, and I'd like to do it by placing the figures side by side.
I know I can do it manually by using two minipages inside a figure, but I want latex to place them for me, since I don't really care what figures are placed side by side.
Setting width=0.45\textwidth made it smaller, but it didn't get the figures to go side by side, even without centering them.
Is there any way to set this up by default?
The environment I'm using:
\documentclass{article}

\usepackage{graphicx}

\begin{document}
    \begin{figure}[htbp]
        \includegraphics[width=0.45\textwidth]{example-image-a}
    \end{figure
\end{document}

I don't want someone to write code for me, I just need a starting point for where to look.

A: Something like this, i.e., a macro named \twofigures?

\documentclass{article}
\usepackage{graphicx} % for "\includegraphics" macro
\usepackage{caption}

\newcommand\twofigures[6]{%
\begin{figure}[htbp]
\captionsetup{skip=0.5\baselineskip}
   \begin{minipage}{0.45\textwidth}
     \includegraphics[width=\textwidth]{#1}
     \caption{#2}\label{#3}
   \end{minipage}\hfill
   \begin{minipage}{0.45\textwidth}
     \includegraphics[width=\textwidth]{#4}
     \caption{#5}\label{#6}
   \end{minipage}
\end{figure}}

\begin{document}
\twofigures%
     {example-image-a}       % name of image file
     {Left-hand-side figure} % caption
     {fig:left}              % argument for "\label"
     {example-image-b}
     {Right-hand-side figure}
     {fig:right}
\end{document}


text:
Q: How to show and hide react .tsx file? I have a button. When button is clicked, I want to show table and when click again i want hide data. First data visible = false
Jsx file does not recognize state.
The div block name I'm trying to hide is apis.
function css() {

}

const myfunc= () => {
return (

     <button id="veriGoster" onClick={css}>
       Show
     </button>

      < Apidata/> // this component import another page.

  )
}

A: I'm not really sure what you want to do but i try to help you
//import of Apidata
import React, { useState } from "react";

const myFunc = () => {
    const [toggle, setToggle] = useState(false);

    const handleHideData = () => {
        setToggle(!toggle);
    };

    return (

            <button id="veriGoster" onClick={handleHideData}>
                Show
            </button>

            {toggle && (

                    <Apidata />

            )}

    );
};

export default myFunc;


text:
Q: Determine if perl script was launched from terminal or by gui on Windows I'm writing perl scripts on Windows, and need to determine if the a perl script was launched manually from a terminal (e.g., 'C:\Users\me\bin tst.pl') or via a gui (e.g., double-click on 'tst.pl'). In the former case, the script runs to completion, and any output generated is seen in the terminal window. In the latter case, the script is run, does its thing, may produce output (don't know...), and immediately is dismissed. I'd like to detect whether or not the script was run by the gui, so that I can have the option to have the script wait for user input. (E.g., 'print "$0: enter  to exit... "; $_ = <STDIN>;)
Of course, I could always prompt the user for input, but that wouldn't work for scripts that got its input from a pipe. I guess I'd have the same issue on Linux for scripts that are launched from gui as well, but most all the (many...) scripts I've written are command-line driven. I'm new to running perl scripts on Windows, and am really curious as to how to properly do this.
Any suggestions? Thanx!


text:
Q: Virtualbox Windows 7 guest, Ubuntu host, no internet connection -- working prior to upgrade I tried to install the new Virtualbox 5.0 (upgrading from 4.3.10) on Ubuntu 14.04.  I have successfully run Virtualbox (4.3.10 and earlier versions) for years on Ubuntu 14.04 (and earlier), but I could get no connection with Virtualbox 5.0.  I read threads for 6 hours and tried NAT and Bridged and everything imaginable.
One other variable:  I had just copied my VM vdi to my new Seagate Expansion 5TB USB external drive and I was at first trying to run from there.
But now:  even after completely removing VB 5.0 and reinstalling VirtualBox 4.3.10, and going back to a vdi on one of my regular SATA drives, I can get no internet connection in my Win7 guest.  I cannot ping any IP at all.
In the Win7 Device Manager, under Network Adapters, I have 4 items, all starting out with yellow exclamation points:
Intel(R) PRO/1000 MT Desktop Adapter   (this is also set in the vb settings)
WAN Miniport (IP)
WAN Miniport (IPv6)
WAN Miniport (Network Monitor)
When I uninstall the Intel Desktop Adapter, then reinstall it, the yellow exclamation point goes away, as if its working properly, but there is no change in my non-working internet connection.
Here is ifconfig from my Ubuntu host (note:  some entries are from a previously unfinished VPN setup but they never caused any problems with my VM and nothing else has changed besides what I've mentioned):
ifconfig
eth0      Link encap:Ethernet  HWaddr f4:6d:04:25:67:7f
          inet addr:192.168.0.100  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::f66d:4ff:fe25:677f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1383682 errors:0 dropped:0 overruns:0 frame:0
          TX packets:988203 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1148303939 (1.1 GB)  TX bytes:240381867 (240.3 MB)
          Interrupt:18

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:568 errors:0 dropped:0 overruns:0 frame:0
          TX packets:568 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:69229 (69.2 KB)  TX bytes:69229 (69.2 KB)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.9.0.1  P-t-P:10.9.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

tun1      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

virbr0    Link encap:Ethernet  HWaddr 2e:2a:79:b5:5c:15
          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

And here's the ipconfig from the Windows 7 guest:
Here too is the result of ipconfig from the win7 guest:  `
:\Users\Chris>ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : Chris-Win7-Ult
   Primary Dns Suffix  . . . . . . . :
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No

Tunnel adapter Local Area Connection* 11:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.monkeybrains.net:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

C:\Users\Chris>

Lastly, shouldn't be an issue but I am running everything behind the D-link Dir-601 router and have been for many years.

A: ipconfig shows that there are no any network adapters visible to Windows guest. AFAIK, VirtualBox generate a new MAC for every new network adapter, so, maybe, MAC for your "Intel(R) PRO/1000 MT Desktop Adapter" was regenerated. Windows expects NIC with old MAC address. Easy way to solve a problem: delete "Intel(R) PRO/1000 MT Desktop Adapter" from VM config and add a new one, but another model. Should help.

A: apt-get purge-ing everything and completely reinstalling  VB 4.3.10 again seems to have solved the problem.  Sorry, I have no explanation.


text:
Q: Add configurations for Connectors in Microsoft Teams How do i add configurations for users, when they want to add my connector?
F.x. if I add the GitHub connector, I have to sign in, and then select which repository it should work using.
I cannot find any examples in the manifest for where to define these.

A: Please have a look at Build your own Connector documentation. All your configurations can be added in the landing(configuration) page. Please check sample connector code given in Microsoft Teams documentation.


text:
Q: Почему изменение одной ячейки в матрице (списке списков) изменяет значения во всем столбце? tab1 = [[1, 1, 1, 2, 2, 2, 9, 9, 9],
        [3, 3, 3, 1, 1, 1, 2, 2, 2],
        [5, 5, 5, 3, 3, 3, 1, 1, 1],
        [4, 4, 4, 5, 5, 5, 3, 3, 3],
        [6, 6, 6, 4, 4, 4, 5, 5, 5],
        [8, 8, 8, 6, 6, 6, 4, 4, 4],
        [7, 7, 7, 8, 8, 8, 6, 6, 6],
        [9, 9, 9, 7, 7, 7, 8, 8, 8],
        [2, 2, 2, 9, 9, 9, 7, 7, 7]]

tab1z = [[0]*9]*9

for i in range(0,9):

    for j in range(0,9):

        if tab1[i][j] == 1:

            tab1z[0][j] = [i,j]
print(tab1z)

Выводит:
[[[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],
 [[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]]]

Хотя, по-идее должно быть так:
 [[[0, 0], [0, 1], [0, 2], [1, 3], [1, 4], [1, 5], [2, 6], [2, 7], [2, 8]],

А дальше нули.

A: Проблема в том как вы создали:
tab1z = [[0]*9]*9

вы реплицируете один и тот же объект (внутренний список) 9 раз. В итоге получите 9 ссылок на один и тот же список в памяти:
In [16]: list(map(id, tab1z))
Out[16]:
[277357384,
 277357384,
 277357384,
 277357384,
 277357384,
 277357384,
 277357384,
 277357384,
 277357384]

измение любого элемента вызовет следующий эффект:
In [20]: tab1z[0][2] = [1,1]

In [21]: tab1z
Out[21]:
[[0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0],
 [0, 0, [1, 1], 0, 0, 0, 0, 0, 0]]

т.к. вы изменяете элемент одного и того же списка в памяти (в моем случае id этого списка: 277357384)


text:
Q: Sqoop job to import data drom SQL server stuck at Map 0% I have a pseudo distributed hadoop cluster running CDH5.0.2. I'm running a sqoop import command:
sudo -u sqoop sqoop import --connect "jdbc:sqlserver://x.x.x.x:1433;databaseName=yyyyy" --username x --password y --table table_name

I'm just importing a very small table that has 12 rows and 2 columns for testing. The job has been running for half hour. On My resource manager, the mapper tasks' status are listed as NEW and their state are listed as SCHEDULED. I don't think it ever runs!
When i list the job on yarn using:
yarn application -list

i'm getting:
14/07/01 15:55:06 INFO client.RMProxy: Connecting to ResourceManager at host/x.x.x.x:8032
Total number of applications (application-types: [] and states: [SUBMITTED, ACCEPTED, RUNNING]):1
Application-Id      Application-Name        Application-Type          User           Queue                   State             Final-State             Progress                        Tracking-URL
application_1404252440376_0001      ActivityType.jar               MAPREDUCE         sqoop                   root.sqoop        RUNNING               UNDEFINED                   5%                  http://host:42583

this is the Application Master log im seeing. How do i fix this?
2014-07-01 15:14:12,880 WARN [main] org.apache.hadoop.conf.Configuration: job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
2014-07-01 15:14:12,885 WARN [main] org.apache.hadoop.conf.Configuration: job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
2014-07-01 15:14:12,888 INFO [main] org.apache.hadoop.yarn.client.RMProxy: Connecting to ResourceManager at host/x.x.x.x:8030
2014-07-01 15:14:12,973 INFO [main] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerAllocator: maxContainerCapability: 1024
2014-07-01 15:14:12,973 INFO [main] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerAllocator: queue: root.sqoop
2014-07-01 15:14:12,977 INFO [main] org.apache.hadoop.mapreduce.v2.app.launcher.ContainerLauncherImpl: Upper limit on the thread pool size is 500
2014-07-01 15:14:12,979 INFO [main] org.apache.hadoop.yarn.client.api.impl.ContainerManagementProtocolProxy: yarn.client.max-nodemanagers-proxies : 500
2014-07-01 15:14:12,985 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.JobImpl: job_1404252440376_0001Job Transitioned from INITED to SETUP
2014-07-01 15:14:12,987 INFO [CommitterEvent Processor #0] org.apache.hadoop.mapreduce.v2.app.commit.CommitterEventHandler: Processing the event EventType: JOB_SETUP
2014-07-01 15:14:12,997 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.JobImpl: job_1404252440376_0001Job Transitioned from SETUP to RUNNING
2014-07-01 15:14:13,018 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskImpl: task_1404252440376_0001_m_000000 Task Transitioned from NEW to SCHEDULED
2014-07-01 15:14:13,019 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskImpl: task_1404252440376_0001_m_000001 Task Transitioned from NEW to SCHEDULED
2014-07-01 15:14:13,019 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskImpl: task_1404252440376_0001_m_000002 Task Transitioned from NEW to SCHEDULED
2014-07-01 15:14:13,019 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskImpl: task_1404252440376_0001_m_000003 Task Transitioned from NEW to SCHEDULED
2014-07-01 15:14:13,021 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1404252440376_0001_m_000000_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2014-07-01 15:14:13,021 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1404252440376_0001_m_000001_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2014-07-01 15:14:13,021 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1404252440376_0001_m_000002_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2014-07-01 15:14:13,021 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1404252440376_0001_m_000003_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2014-07-01 15:14:13,022 INFO [Thread-51] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerAllocator: mapResourceReqt:1024
2014-07-01 15:14:13,066 INFO [eventHandlingThread] org.apache.hadoop.mapreduce.jobhistory.JobHistoryEventHandler: Event Writer setup for JobId: job_1404252440376_0001, File: hdfs://host:8020/user/sqoop/.staging/job_1404252440376_0001/job_1404252440376_0001_1.jhist
2014-07-01 15:14:13,976 INFO [RMCommunicator Allocator] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerAllocator: Before Scheduling: PendingReds:0 ScheduledMaps:4 ScheduledReds:0 AssignedMaps:0 AssignedReds:0 CompletedMaps:0 CompletedReds:0 ContAlloc:0 ContRel:0 HostLocal:0 RackLocal:0
2014-07-01 15:14:14,054 INFO [RMCommunicator Allocator] org.apache.hadoop.mapreduce.v2.app.rm.RMContainerRequestor: getResources() for application_1404252440376_0001: ask=1 release= 0 newContainers=0 finishedContainers=0 resourcelimit=<memory:0, vCores:0> knownNMs=1

A: The main problem I saw when this happened to me is that there were not enough resources for executing sqoop.
When I was executing Sqoop along with other YARN applications it usually didn't have enough resources so map tasks was always stuck at 0%. I went to the driver logs and the last lines of the logs had something like:
2017-02-01 14:54:48,638 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1484947659248_0500_m_000000_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2017-02-01 14:54:48,638 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1484947659248_0500_m_000001_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2017-02-01 14:54:48,638 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1484947659248_0500_m_000002_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2017-02-01 14:54:48,638 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1484947659248_0500_m_000003_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2017-02-01 14:54:48,639 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1484947659248_0500_m_000004_0 TaskAttempt Transitioned from NEW to UNASSIGNED
2017-02-01 14:54:48,639 INFO [AsyncDispatcher event handler] org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl: attempt_1484947659248_0500_m_000005_0 TaskAttempt Transitioned from NEW to UNASSIGNED

After this, nothing is logged and sqoop is still at 0%.
When there was nothing else running on YARN, Sqoop executed without any problem.

A: this is not the most helpful answer, but I ended up reinstalling the whole thing.


text:
Q: Equivalent of Matlab filter2(filter, image, 'valid') in python I want to know what will be the equivalent of Matlab's filter2(filter, image, 'valid') function in python OpenCV or scikit-image library. I am mainly concerned with the valid argument which allows to calculate the convolution of filter and image without zero padding the image. I am aware of the fact that similar question is posted on this forum but the equivalent of filter2 function with valid argument has not been described properly.

A: The documentation for filter2 says that filter2(H, X, shape) is equivalent to conv2(X,rot90(H,2),shape);
A python equivalent to conv2 is signal.convolve2d. So the equivalent you're looking for is:
signal.convolve2d(X, np.rot90(H), mode='valid')

A: In matlab
a=[[1, 2, 0, 0];[5, 3, 0, 4];[0, 0, 0, 7]; [9, 3, 0, 0]];
k=[[1,1,1];[1,1,0];[1,0,0]];
a_k=filter2(k, a, 'valid')
ak=conv2(a,rot90(k,2), 'valid')

a_k =

11     5
17    10

ak =

11     5
17    10

In python
a = np.array([[1, 2, 0, 0],[5, 3, 0, 4],[0, 0, 0, 7], [9, 3, 0, 0]])
k = np.array([[1,1,1],[1,1,0],[1,0,0]])
from scipy import signal
print(signal.convolve2d(a, np.rot90(k,2), mode='valid'))

[[11  5]
     [17 10]]


text:
Q: android studio showing error Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at
https://docs.gradle.org/2.10/userguide/gradle_daemon.html
Please read the following process output to find out more:
Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap

A: I suggest invalidating Android Studio caches through going to File->Invalidate Caches/Restart

A: Like Omar said, the usual procedure is to clear any traces of cache on Android Studio.
Can be done with : File->Invalidate Caches/Restart
Additionally, you can increase gradle's JVM memory. I noticed a huge leap in performance when I did this for the first time on my main development machine (which has a rough 16gb of RAM)
Just uncomment the line your gradle.properties file and alter the values to your liking.
\# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

Regards


text:
Q: calling subclass method after initialising to parent java This might (most certainly will) sound stupid, but I am stuck and I cant find a proper solution to my problem.
I have a superclass and two sub classes extend it. On the parent class based on a condition I want to call the method from either of the two classes. This is inside a loop, so instead of doing the same check I decided to do the check once, create an object from the super class and then change the object to either one of the two sub classes. i.e.
public class Parent{
    public void method() {
        Parent object=new Parent();
        if(a==b) {
            object=new Child_A();
        }else {
            object=new Child_B();
        }
        for() {
            object.method();
        }
    }
    public void method() {
        //empty method. need it just to compile
    }
}

public class Child_A extends Parent{
    public void method() {
        //do something useful
    }
}

public class Child_A extends Parent{
    public void method() {
        //do something useful
    }
}

I had to write the Parent.method(), cos otherwise the compile would complain that there is no method() method on class Parent.
So with this, the method called is not one of the children,but the parents method.
I have read that objects need to be assigned directly to the class, like Childen_A object=new Childen_A. The thing is that I would like to use the same command for both cases (object.method()) no matter which class it refers to. Strange thing is that during debug, i see that object is of type Child_A, nevertheless the super method is called.
I know that the solution would be to create two different objects, one for each sub class, but that would make my code a bit more ugly and i would have to use the if statement inside the loop.So the correct way of doing it must be
public void method() {
   for() {
       if(a=b) {
            Child_A object=new Child_A();
            object.method();
       }else {
            Child_B() object=new Child_B();
            object.method();
        }
    }
}

Is there a way to avoid the if statement inside the loop? Thanks

A: Your code should be
public class Parent {

    public void method() {

    }

    // OR

    public abstract void method(); // and make the class abstract as well
}

public class Child_A extends Parent {

    @Override
    public void method() {
        //do something useful
    }
}

// same with Child_B


text:
Q: Converting int to char? ref void init_board (ref int side, ref char[][] board)  //make empty symbol chessboard
{
    const char black = ' ';
    const char white = 0xB0;

    board[0][0] = ' ';
    for (int i = 1; i <= side; i++)
    {
        board[i][0] = 0x30 + i;  //Setting nums; "Error: Cannot convert int to char"
        board[0][i] = 0x40 + i;  //Setting letters; same here
        for (int j = 1; j <= side; j++)
            board[i][j] = (i+j)%2 == 0 ? black : white; //making black-white board
    }
}

I'm trying to make a simple symbol chessboard. How do I set nums and letters depending or number of row/column correctly? board[i][0] = 0x30 + i; (or 0x40) works in C++, but not in D.

A: You already have what you need in the std.conv module. - The best is to use the std.conv.to.
import std.conv;
import std.stdio;

void main() {
  int i = 68;
  char a = to!char(i);
  writeln(a);
}

Output:
D

A: board[i][0] = cast(char)(0x30 + i);

Keep in mind that when converting like this, it could overflow.


text:
Q: Mysql / Hql running total needs single result but cannot get due to subselect limitation I am using a running total to find the median of a weighted set.  This works fine in sql, but not in hql due to Hibernate not supporting subselects in the FROM clause.  I cannot easily drop to sql because the actual code involves a lot of dynamic query building already in place in hql.
Here's the sample table:
score  weight
2      1
5      1
5      1
6      1
7      1
10     2
10     2

The total scores are 9 (I know this before this query).  9/2 = 4.5, so this query should return 6 as the weighted median score.
Here's the sample query:
SET @runtot:=0;
SELECT
    q1.score
FROM
    (SELECT
        score, (@runtot:=@runtot + weight) AS rt
    FROM
        tmp_stddev
    ORDER BY score) as q1
WHERE
    q1.rt <= (9 / 2)
ORDER BY q1.score DESC
LIMIT 1;

Ordering by the score ASC in the subselect enables me to keep adding weights until I get to the halfway point.  Ordering DESC in the outer query enables me to use the LIMIT to return just the single result for best performance (there can be a lot of data here, so I really only want to return one result).
This works in SQL, but not in HQL.  I can create a custom dialect I believe to support the setting of the user variable inside the query (the clearing it to 0 part would be in a separate sql query against the same connection).  The problem is the subselect.
I could do this:
SET @runtot:=0;
SET @runtot2:=0;

SELECT
    score,
   (@runtot := @runtot + weight) AS rt
FROM
    tmp_stddev
WHERE (@runtot2 := @runtot2 + weight) <= (9/2)
ORDER BY score;

but this would return me all the scores, and I really just want the one (the dataset can be very large and speed is important).
Any suggestions how to re-write this to return a single result, be fast, and be in a form of sql that hql can generate?
UPDATE:
Based on Mosty Mostacho's suggestions below, and some other research, this seems to work consistently:
SET @runtot:=0;
SELECT
    score, weight, @val := score
FROM
    tmp_stddev
WHERE
    (@runtot := @runtot + weight) <= (9 / 2)
ORDER BY score;

Here by selecting the last matched score into a variable, I can use it later in the same connection by selecting it's value, and get the last item in the sort list, which is what I want.  Also, I have reduced the scope of the read/write for the User Defined variable, that seemed to be inconsistent when I changed the data around.
Questions:

*

*Is this a safe usage of User Defined variables?  I've been reading a lot about how unsafe it is to read/write them in the same statement, but doesn't this have to evaluate in order since the read/write are both part of a single expression in the HAVING clause?  In other words, is this reliable?

*How can I get this to work in HQL?  If I use a Custom Dialect and create a custom function that does the '@val := score' portion, I get an 'Invalid filter-parameter name format' exception (I think because of the colon, but shouldn't that just be a direct pass-through substitution from the HQL to the SQL by Hibernate?  Why would it care that there's a colon?)

*Are there any better solutions that my query above that I haven't considered?

A: Ok, I got absolutely lost in the math :)
Anyway, I tried to turn your first query into something that doesn't use the FROM clause that way. This is what I got:
SELECT score, (@runtot := @runtot + weight) rt
FROM t, (SELECT @runtot := 0) init
HAVING rt = FLOOR(9 / 2)
ORDER BY score

Using the having clause that way is really a mess but it seems the only way not to need a derived table in there. The only issue is that, although this would answer this question it won't help you with a decimal field.
Now, the solution might not be as simple as changing the having clause into
HAVING rt <= 9 / 2

Check this fiddle to see how that messes with the results. That's what you make when you mess with User Defined Variables and don't user a derived table.
The second thing to try is if you can have a derived table in a JOIN. I mean:
SELECT * FROM t
JOIN (
  SELECT id FROM r
) s ON t.id = s.id

This is how far I can get but probably gave you a couple of ideas to try :)
Edit (last try):
After the following query I'll have to ask for forgiveness to the SQL language:
SELECT score
FROM t, (SELECT @runtot := 0.0) init
WHERE (@runtot := @runtot + weight) AND (9 / 2 >= @runtot)
ORDER BY score DESC
LIMIT 1

Fiddle here.