text:
Q: VerificationTest for uncaught `Throw`? I want to demonstrate that Catch[x_] does not catch things thrown with a tag.
Catch[Throw[0, 0]]

gives

Throw::nocatch: Uncaught Throw[0,0] returned to top level.
Hold[Throw[0, 0]]

But I cannot put this behaviour into a VerificationTest that results in Success.
I tried
VerificationTest[Catch[Throw[0, 0]],
 Hold[Throw[0, 0]], {Throw::nocatch}, {}]

but this gives an Error TestResultObject.
Usually, using the third argument is the way to go with messages:
VerificationTest[Message[a::b], Null, {a::b}]

I guess I could use something like GeneralUtilities`CatchAll to construct the test manually, but I was under the impression that VerificationTest catches all Error conditions.
Any ideas?

I also seems to require manual work to catch Abort[].
VerificationTest[Abort[], $Aborted]

gives an Error-result too, but the Abort is shielded from the rest of the execution:
VerificationTest[Abort[], $Aborted]*2

does not give $Aborted like Abort[]*2 does.

A: On a rare occasion, something produces an uncaught Throw that must be tested for, and as you have noticed, checking for the message is insufficient. So, if I know the form, e.g. Throw[0, 0], I wrap the expression in another Catch, and then use the outer Catch to return the test result, e.g.
VerificationTest[
 Catch[  Catch[Throw[0, 0]]; (* or some other expression *)
   True, (* No uncaught Throw *)
   _, (* Catch all tagged Throws *)
   False&
 ]
]

The key is the last argument has to be a function, which normally would return
f[thrownValue, tag]

But, in this case we just want it to return False if the execution ever makes it to that branch.  For untagged Throw, we have to exercise some caution as Catch[Throw[...]] will return the value passed by Throw. So, the solution is to have Catch return a value that is not likely to be thrown, e.g.
VerificationTest[
 Catch[ (*throwing expression*); "Not Thrown"],
 "Not Thrown"
]

where Catch will produce "Not Thrown", if no uncaught, untagged Throw is produced. These two forms can be combined if the form is not known, as follows
VerificationTest[
 Catch[ Catch[ expr; "Not Thrown"], _, "Tagged expr Thrown"&]
 ,
 "Not Thrown"
]

A: You could use CheckAll to "catch" all "uncaught" control flow statements. Then wrap those statements with special head to make sure that they were not returned by ordinary evaluation of expression.
ClearAll[stoppedControlFlow, confineControlFlow]
stoppedControlFlow // Attributes = HoldAll;
confineControlFlow = Function[,
    CheckAll[#, Function[, Replace[HoldComplete@##, {
        HoldComplete[_, Hold@ctrlFlow__] :> stoppedControlFlow@ctrlFlow,
        HoldComplete[result_, Hold[]] :> result
    }], HoldAllComplete]],
    HoldAllComplete
];

Now all following VerificationTests are successful.
VerificationTest[2 + 3 // confineControlFlow, 5]
VerificationTest[Catch[Throw[0, 0]] // confineControlFlow, stoppedControlFlow@Throw[0, 0]]
VerificationTest[Abort[] // confineControlFlow, stoppedControlFlow@Abort[]]
VerificationTest[Goto[1] // confineControlFlow, stoppedControlFlow@Goto[1]]

A: A VerificationTest with Outcome Error cannot be fixed by changing the expected-messages argument. This only applies to MessagesFailure Outcome (orange versus yellow cross, a bit hard to distinguish).
Tests that result in Error must be fixed on a case-by-case basis: There could be an error in either of the expressions involved in the test or in some of the options (e.g. the SameTest not returning True or False).


text:
Q: ¿Cómo especificar días en los que se ejecutara un evento en MySQL? Tengo una gran duda acerca de los eventos que se pueden programar con phpmyadmin, lo que intento hacer es eliminar registros de una tabla los días 27 de cada mes.
CREATE EVENT limpieza
ON SCHEDULE AT now() + INTERVAL 1 HOUR
DO DELETE carrera WHERE carrera = Administracion

A: Intente configurar su evento de la siguiente forma:
mysql> DROP EVENT IF EXISTS `limpieza`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE EVENT IF NOT EXISTS `limpieza`
    ->   ON SCHEDULE
    ->     EVERY 1 MONTH
    ->     STARTS '2017-01-27 00:00:00'
    ->     DO
    ->       DELETE FROM `carrera`
    ->       WHERE `carrera` = 'Administracion';
Query OK, 0 rows affected (0.00 sec)

ACTUALIZACIÓN
Si bien la funcionalidad de EVENTOS en MySQL ofrece mucha flexibilidad, quizás no tiene toda la potencia expresiva y de opciones de, por ejemplo, cron de Unix.
Por ello, una opción para lograr lo que necesita puede ser:
mysql> DROP EVENT IF EXISTS `limpieza`;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> DELIMITER //

mysql> CREATE EVENT IF NOT EXISTS `limpieza`
    ->   ON SCHEDULE
    ->     EVERY 1 DAY
    ->     STARTS '2017-01-27 00:00:00'
    ->     COMMENT 'EVENTO ejecutado a diario. DELETE ejecutado primer lunes mes'
    ->     DO
    ->       BEGIN
    ->         IF (DAYOFMONTH(NOW()) BETWEEN 1 AND 7 AND
    ->             DAYOFWEEK(NOW()) = 2) THEN
    ->           DELETE FROM `carrera`
    ->           WHERE `carrera` = 'Administracion';
    ->         END IF;
    ->       END//
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

A: Puedes crear el evento de esta manera para que se ejecute todos los 27 a la 1 de la mañana.
CREATE OR REPLACE EVENT STAT
ON  SCHEDULE  EVERY  1  MONTH  STARTS DATE_ADD(DATE_ADD(DATE_SUB(CURDATE(),INTERVAL DAY(CURDATE())-1 DAY),INTERVAL 26 DAY),INTERVAL 1 HOUR)
ON  COMPLETION  PRESERVE  ENABLE
DO
BEGIN
DELETE FROM `carrera` WHERE `carrera` = 'Administracion';
CALL STAT();
END;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having issues getting images centered properly inside of square container I'm working on a redesign of my photography site and am setting up a simple slider for some of my photos. I'm having issues getting the images to be centered in divs with padding all around. I'm trying to mimic how photos look on my Instagram where they're centered in a square but keep their aspect ratio.
Here is a link to my Codepen.
Example of what I'm going for:
SCSS:
.slick-slider {
  .image_container {
    background: red;
    position: relative;
    overflow: hidden;
    height: 256px;
    padding: 20px;

    img {
      position: absolute;
      top: 0; bottom: 0;
      margin: 0 auto;
      max-height: 300px;
      left: 0; right: 0;
      padding: 15px;
    }
  }
}

HTML:

A: it automatically crops and fit to the div

.thumbnail {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}
.thumbnail img {
  position: absolute;
  left: 50%;
  top: 50%;
  height: 100%;
  width: auto;
  -webkit-transform: translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
          transform: translate(-50%,-50%);
}
.thumbnail img.portrait {
  width: 100%;
  height: auto;
}

A: I ended up messing around with it for a little while and figured out the correct css:
.image_container {
  margin: 0 10px;
  position: relative;
  overflow: hidden;
  height: 350px;
  background: rgba($offBlack, 0.05);

  img {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    max-height: 300px;
    max-width: 310px;
  }
}


text:
Q: I wanna hide this little white-thing on the JTable The picture shows a thin (1 pixel?) white margin (marked in blue) inside the border of a JTable.
How can the margin be eliminated, or the colour be changed?
I have tried:

*

*Changing the JTable

*Changing the ScrollPane

I set both to opaque without success.
Thanks for help.

A: The sides there are simply the border set by whatever JComponent its contained in.  Remove the border (or change it to a line border for instance) and that style will go away.  :)


text:
Q: Problem with Symfony routing with online project I have a Symfony project on a Win XP / IIS 7 machine with Isapi rewrite installed. When I go to the frontend (my main) application, it seems that the routing simply doesn't work. I always end up on my default module/action. However, if I turnno_script_name = off (in the app's settings.yml file) then everything works fine. I also have an admin app as part of the project (which also has no_script_name = off) and this works fine as well. This seems like it should be a simple problem, yet we've been working on this for 4 hours now. Any help would be greatly appreciated, thanks.
Edit: I changed the front controller's environment to dev in order to use the debug toolbar and found that no matter what my URL looks like, it always says
Match route "homepage" (/) for / with parameters array ( 'module' => 'default', 'action' => 'index',)
No matter what I do, module always equals default

A: IIS doesn't support URL rewriting very well, which is a requirement of Symfony's routing to work. Essentially, the webserver is supposed to redirect all requests to non-existing files/paths to Symfony's index.php, passing along with it the original URL requested. Symfony decodes this URL and applies its routing rules.
But, it's possible. You'll need to follow this: Symfony on IIS

A: I've found the solution. I added this code to the top of my index.php
$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];

I tried everything within the Symfony on IIS tutorial (http://trac.symfony-project.org/wiki/symfonyOnIIS) and nothing made a difference. If anyone else runs into this problem, please try adding the above code first before mucking with any settings or .htaccess rules.

A: Check out the new Url Rewrite module for IIS:
http://learn.iis.net/page.aspx/734/url-rewrite-module/
It even adds a tool to IIS manager which imports and converts mod_rewrite rules


text:
Q: Test statistic for regression slope in terms of correlation Consider two data series, $X = (x_1, x_2, ..., x_n)$ and $Y = (y_1, y_2, ..., y_n)$, both with mean zero. We use linear regression (ordinary least squares) to regress $Y$ against $X$ (without fitting any intercept), as in $Y = aX + ε$ where $ε$ denotes a series of error terms. Suppose $\rho_{XY}$ is the sample correlation.
Question: Derive a test statistic to test the significance of the regression slope $a$ in terms of the sample correlation $\rho_{XY}$ (Assuming that the sample size is sufficiently large such that this statistic is normal).


text:
Q: Using OpenGL for Image Processing - Setting up an OpenGL context I want to do image processing on a raw image without displaying it on screen (I want to do some calculations based on the image data and display some results on screen based on these calculations.) I found an interesting answer to this question, shown here:

Do your actual processing on the GPU: Set up an OpenGL context (OpenGL
  ES 2 tutorial), and create a SurfaceTexture object in that context.
  Then pass that object to setPreviewTexture, and start preview. Then,
  in your OpenGL code, you can call SurfaceTexture.updateTexImage, and
  the texture ID associated with the SurfaceTexture will be updated to
  the latest preview frame from the camera. You can also read back the
  RGB texture data to the CPU for further processing using glReadPixels,
  if desired.

I have a question on how to go about implementing it though.
Do I need to create a GLSurfaceView and a Renderer, I don't actually want to use OpenGL to draw anything on screen so I am not sure if I need them? From what I have read online though it seems very essential to have these in order to setup an OpenGL context? Any pointers anybody can give me on this?

A: You don't have to use a GLSurfaceView. GLSurfaceView is a convenience class written purely in Java. It simplifies the setup part for applications that want to use OpenGL rendering in Android, but all of its functionality is also available through lower level interfaces in the Android frameworks.
For purely offscreen rendering, you can use the EGL interfaces to create contexts, surfaces, etc. Somewhat confusingly, there are two versions in completely different parts of the Android frameworks:

*

*EGL10 and EGL11 in the javax.microedition.khronos.egl package, available since API level 1.

*EGL14 in the android.opengl package, available since API level 17.

They are fairly similar, but the newer EGL14 obviously has some more features. If you're targeting at least API level 17, I would go with the newer version.
Using the methods in the EGL14 class, you can then create contexts, surfaces, etc. For offscreen rendering, one option is to create a Pbuffer surface for rendering. To complete the setup, you will typically use functions like:
eglInitialize
eglChooseConfig
eglCreatePbufferSurface
eglCreateContext
eglMakeCurrent

The Android documentation does not really describe these functions, but you can find the actual documentation at the Khronos web site: https://www.khronos.org/registry/egl/sdk/docs/man/.


text:
Q: How do I get access to R&D sessions in F1 2010? I'm playing F1 2010 and am not long into my career.  In the garage before a race it says that you can participate in R&D sessions to get new modifications for your car to improve its performance.  However, I can't see how to start an R&D session.
Does anybody know how to start an R&D session?

A: It appears to be somewhat random in its availability, but the frequency depends on how good your team is. However, if you become the number 1 driver for your team where you can control the level of R&D taken on by your team, and setting it higher will bring about more opportunities.

The race engineer will likely not give you a new objective every race, at least initially, as you start with the lesser teams and an intermediate path setting by default. This can change however, when the players team promotes you into the number one drivers slot, giving you the choice to further your research & development or curtail it in favor of improving next years package

Source


text:
Q: Searching for a tag inconsistently redirects to the tag page Searching for a word that matches an existing tag should, I believe, redirect you to the tag page for that tag, instead of a regular search result.
This is happening inconsistently...
For example, a search for the word "search" doesn't redirect to the tag page:

https://meta.stackexchange.com/search?q=search

But a search for "support" does redirect to the tag page:

https://meta.stackexchange.com/search?q=support

I tested this on a few sites with a number of tags and can reproduce on at least three sites (I couldn't on one). It also seems to be more inconsistent on some sites than others.
Why do only some tags redirect to the tag page?


text:
Q: Requesting Manifest.permission.USE_SIP acts weird I'm requesting the Manifest.permission.USE_SIP permission. The strange thing is that even though it seems to be considered a dangerous permission, when I request it it seems to be already given so no popup appears and neither does it appear as a switch under Settings->Permission.
And another strange thing is that it seems there's another additional permission:
which is the CONFIGURE_SIP
which I am indeed specifying in the manifest that I need but that one's not a dangerous permission, so why is it in the list under Settings?

A: So, I figured it out (at least the first part, the important part). I was requesting multiple permissions at a time and before requesting the USE_SIP one I was requesting and granting the REA_PHONE_STATE permission. They both are part of the large group of permissions PHONE. Apparently, and this is what I did not know, is that once a permission group item receives the OK from the user, then all of its items are fine.
Now ... I still can't figure out why the CONFIGURE_SIP permission is visible under Settings, but I've noticed that on 7.0.0 it's not being displayed ... so in case anyone wants to open a question on that, be my guest.


text:
Q: Android Studio 2.3.3 Logcat "Unable to connect to the editor..." when using emulator; what to do? In Android Studio 2.3.3, I get dozens of this Logcat message OFTEN. Probably every 5th run:
    com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text... will retry later
    com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text... will retry later
    com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text... will retry later
    com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text... will retry later
    com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text... will retry later
    com.android.inputmethod.latin E/RichInputConnection: Unable to connect to the editor to retrieve text... will retry later

I get no output from Log. statements.
Debugging is then greatly hindered.
I am using an emulator 10.1 WXGA Tablet_API_19, Android 4.4.2. But it's happened with other emulators, too. It seems (not positive about this) that this never happens when I connect my Android device to USB and compile app to it.
I restart Logcat repeatedly, I clear it repeatedly, I've even exited Studio; same messages always return.
It's nothing I'm doing is it? One SO Answer about this was, "The error mentioned by you does not belongs specifically to the list view . this is the logcat error. Restart your Logcat hope it will work for you." It doesn't.
So is there a bug in Logcat, as another SO comment suggests?
Does anybody who's had this know of a workaround? Should I report this problem as a bug, 'cause it sure ain't right!

A: According with comment on file code:

For some reason the app thinks we are not connected to it. This looks like a framework bug... Fall back to ground state and return false. Link to code

What OS do you use?
It's possible that the error is caused by some process in your system or bad config. Try download again Android platform-tools.


text:
Q: How can I set the font of a textView in Android? I'm trying to set the font to a custom font. the font is in a subfolder of the assets folder called "fonts" . This is code in my onCreate() function. Eclipse suddendly brings up the debugger saying "source not found"
    Typeface centuryGothic = Typeface.createFromAsset(this.getAssets(), "fonts/Century_Gothic_Bold.ttf");
    TextView tv = (TextView) findViewById(R.id.TitleAct_title);
    tv.setTypeface(centuryGothic);
    setContentView(tv);

This is the xml in My main at the moment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">

    <TextView
    android:text="@string/TitleAct_title"
    android:id="@+id/TitleAct_title"
    android:textColor="#fff"
    android:gravity="center_horizontal"
    android:background="#347"
    android:textSize="15pt"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"/>

 </LinearLayout>
</LinearLayout>

I can't see anything wrong with this. Why is it bringing up the debugger and error "source not found"?

A: What you saw was the eclipse debugger looking for the source of the exception. next time, press continue and look ad the log of the exception in the Logcat window.
You should call setContentView(R.layout.main); before TextView tv = (TextView) findViewById(R.id.TitleAct_title);, and probably drop the call setContentView(tv);.


text:
Q: Can you help me solve a difficult kinematics problem? I've been working on this problem for a while now, but I still don't know how to solve it. It involves 2D kinematics, which aren't in themselves hard, but this one threw me for a loop.

A ball is thrown straight up from the edge of the roof of a building. A second ball is dropped from the roof 1.00 seconds later (ignore air resistance).
(a) If the height of the building is 20.00 meters, what must be the initial speed of the first ball if both are to hit the ground at the same time?
(b) Consider the same situation, but now let the initial speed of the first ball be given and treat the height of the of the building as an unknown. What would the height of the height of the building for both balls to reach the ground at the same time?

Now I know for (a) the initial position of each ball, the acceleration and velocity of the second ball (gravity), and final position of each ball, but that's it! I have no idea how to find out the velocity of the first ball. I'm pretty sure that you have to calculate the time it takes for the first ball to reach 20 meters in a second, to be dropped at the same time as the first ball, but I have no idea.
And in (b), the initial speed isn't given! How do I solve that?!

A: All you need for solve this problem is the equation for an uniformly accelerated motion:
$$x(t)=\frac{1}{2}at^2+v_0\cdot t+x_0$$
where the motion takes place on a straight line if the acceleration and the speed are collinear (i.e. on the same direction). $x_0$ and $v_0$ are the initial position (the roof) and the initial speed. Let me add different subscript (1 and 2) for the two balls:
$$\begin{cases}x_1(t_1)=\tfrac{1}{2}at_1^2+v_{1(0)}t_1+x_{1(0)}\\
x_2(t_2)=\tfrac{1}{2}at_2^2+x_{2(0)}\end{cases}.$$
$a=-g=-9.81...$ m/s$^2$, since the gravitational acceleration points down (I'm thinking that 'up' is positive and 'down' is negative, as a custom choice), $v_{2(0)}=0$, hence I will omit any subscript on the speed of the first ball, $v_{1(0)}=v_0$; $x_{1(0)}=x_{2(0)}=x_0=$ the eight of the roof, and $t_2=t_1-1$ sec. (since the second ball starts one second later than ball 1, i.e. it has one second less) then I simply call $t$ the time of the motion of the first ball and substitute $t_2=t-1$ sec. in the previous equation:
$$\begin{cases}x_1(t)=-\tfrac{1}{2}gt^2+v_0t+x_0\\
x_2(t)=-\tfrac{1}{2}g(t-1)^2+x_0\end{cases}.$$
You ask that a certain time $t$ your balls are in the same place, that is: $x_1(t)=x_2(t)$, or, more precisely, they are on the ground (which we can assume is at zero eight): $x_{1,2}(t)=0$. Then you have to solve this equations:
$$\begin{cases}0=-\tfrac{1}{2}gt^2+v_0t+x_0\\
0=-\tfrac{1}{2}g(t-1)^2+x_0\end{cases}$$
where both $t$ and $v_0$ are unknown. Some maths is all you need to solve this problem!
SOLUTIONS:
a) $v_0=\frac{1}{2}g\left(\sqrt{2x_0/g}+1\right)-x_0/\left(\sqrt{2x_0/g}+1\right)\simeq 8.17...$ m/s
b) You have to solve the previous equation for $x_0$...
$x_0=\left[\left({1\over2}g-v_0\right)/\left(\sqrt{2/g}-\sqrt{2\cdot g}\right)\right]$

A: Answer for a:
The second ball is released from rest and assumes going down is negative:
u=0  g=-9.81  v=? h=-20  t=?
By using the kinematics equation substitute the value in following equation:
$$ s=ut^2+\frac12 at^2$$
So:
$$-20=-\frac12 9.81 t^2 $$
Therefore: t=2.02 s.
It said it released after 1 s so: t=3.02 s.
The first ball is projected vertically upward:
u=? g=-9.81  h=-20  t=3.02.
Substitute the values:
$$-20=u (3.02) - \frac12(9.81)(3.02)^2 $$
Therefore: u=8.19 m/s.


text:
Q: Matching a variable with an object inside a nested array with JavaScript I am trying to find a match inside this JSON array but I find it a bit complicated since it's a nested array of objects.
I'm not sure what I am doing entire wrong here:
The idea is that I have an array with a set of permissions and I want to return only the set of permissions that match the role:
var data = [{
    "visitor": {
        "static": ["page-one:visit", "home-page:visit", "login"]
    }
}, {
    "users": {
        "static": ["posts:list", "posts:create", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
    }
}, {
    "admin": {
        "static": ["posts:list", "posts:create", "posts:edit", "posts:delete", "users:get", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
    }
}]

var role = "admin"

for(var x=0;x <data.length;x++){

  if(role === data[x]){
    console.log("OLE, we got a match!" + data[x])
  }

}

For some reason I just can't find a match. I just wanna return the full object like:
"admin":{
        "static": ["posts:list", "posts:create", "posts:edit", "posts:delete", "users:get", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
    }

Here is a JS Bin Link.

A: You could use the .find function like below:
data.find(function(x){ return Object.keys(x).indexOf(role) > -1; });
Given your role is the key of the object, you need to check if the object itself contains the role as a key, for this you'd use Object.keys(<object>).indexOf(role) where indexOf will return the value of -1 if it's not found and 0+ if found.

var data = [{"visitor":{"static":["page-one:visit","home-page:visit","login"]}},{"users":{"static":["posts:list","posts:create","users:getSelf","home-page:visit","dashboard-page:visit"]}},{"admin":{"static":["posts:list","posts:create","posts:edit","posts:delete","users:get","users:getSelf","home-page:visit","dashboard-page:visit"]}}]

var role = "admin"

var admins = data.find(function(x){ return Object.keys(x).indexOf(role) > -1; });

console.log(admins);

if you wanted to accommodate for an array of different roles, you can use the following, easy to follow example.

var data = [{"visitor":{"static":["page-one:visit","home-page:visit","login"]}},{"users":{"static":["posts:list","posts:create","users:getSelf","home-page:visit","dashboard-page:visit"]}},{"admin":{"static":["posts:list","posts:create","posts:edit","posts:delete","users:get","users:getSelf","home-page:visit","dashboard-page:visit"]}}]

var role = ["admin", "visitor"];

var admins = role.map(function(role) { return getObjectsForRole(role); })

function getObjectsForRole(role)
{

 return data.find(function(x){
  return Object.keys(x).indexOf(role) > -1;
  });

}

console.log(admins);

The above is pretty much the same as before, but we're mapping (.map) each role and calling a function which contains our call to the .find function.


text:
Q: Filling the intersection of paths I am aware that there is myriad of posts dealing with the intersection of objects in tikz, but I haven't found one that shows how to intersect two paths, so far. I would like to either shade or hatch the intersection of two blobs:
\documentclass{standalone}
\usepackage{tikz,pgfplots}
\usetikzlibrary{hobby,intersections,fillbetween,patterns}

\begin{document}

\begin{tikzpicture}
\path[name path = A,draw,use Hobby shortcut,closed=true, fill=blue]
(0,2) .. (3,3) .. (4,-3) .. (5,1);
\path[name path = B,draw,use Hobby shortcut,closed=true, fill=red,xshift=3cm, yshift=-1cm, fill opacity=.5]
(.5,.5) .. (2,4) .. (.5,4) .. (-1,2);
\end{tikzpicture}

\end{document}

Since couldn't see how to use \clip with \path, and following the examples on this post, I thought fillbetween might have been the answer, but adding
\tikzfillbetween[of=A and B,split] {pattern=north west lines};

produces

and I think I see why. How can I hatch/shade the intersection only?

A: If I understood correctly, a solution with \clip
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{hobby,patterns}
\begin{document}
\begin{tikzpicture}
\path[use Hobby shortcut,closed=true, fill=red,xshift=3cm, yshift=-1cm,fill opacity=0.5]
        (0.5,0.5) .. (2,4) .. (.5,4) .. (-1,2);
\path[use Hobby shortcut,closed=true, fill=blue]
        (0,2) .. (3,3) .. (4,-3) .. (5,1);
\begin{scope}
\clip[use Hobby shortcut, closed=true, xshift=3cm, yshift=-1cm]
        (0.5,0.5) .. (2,4) .. (.5,4) .. (-1,2);
\path[use Hobby shortcut,closed=true, pattern=north west lines,preaction={fill=red,opacity=0.5}]
        (0,2) .. (3,3) .. (4,-3) .. (5,1);
\end{scope}
\path[draw,use Hobby shortcut,closed=true]
        (0,2) .. (3,3) .. (4,-3) .. (5,1);
\path[draw,use Hobby shortcut,closed=true,xshift=3cm, yshift=-1cm]
        (0.5,0.5) .. (2,4) .. (.5,4) .. (-1,2);
\end{tikzpicture}
\end{document}


text:
Q: No encuentro el archivo draw9patch se me esta haciendo imposible encontrar el archivo draw9patch el en la carpeta tools del sdk. He buscado bastante info pero nada. Agradezco si me facilitan la data de como instalarlo, he buscado pero no he encontrado info detallada del problema.
Estoy trabajando con Ubuntu 19.10

A: La utilería para crear imagenes Draw9Patch

anteriormente se encontraba dentro de la instalación del Android SDK y dentro de /tools/draw9patch , ahora puedes descargar la utilería desde :
https://androidstudio.io/downloads/tools/download-the-latest-version-of-draw9patch.jar.html


text:
Q: Unsuccessful connection to the server makes it unusable I am facing a problem when multiple clients try to connect to the server with same credentials. Actually, when a client with a same credentials is already connected, a message to the client trying to connect with those credentials is going to be shown, but afterwards no more clients are able to connect. I am not getting any exceptions, nothing breaks, but once I check for client application status in task manager, there stands 'Not responding'.
Client function for connecting to the server:
    public TransferClass connectMe(TransferClass transfer)
    {
        try
        {
            if (!string.IsNullOrEmpty(transfer.ipAdr))
            {
                ipAdress = transfer.ipAdr.Trim();
            }
            client = new TcpClient(ipAdress, 10000);
            stream = client.GetStream();
            formatter = new BinaryFormatter();

            formatter.Serialize(stream, transfer);
            transfer = formatter.Deserialize(stream) as TransferClass;
            return transfer;
        }
        catch (Exception)
        {
            transfer.LoggedIn = false;
            return transfer;
        }
    }

Server listening for clients:
    void listen()
    {
        try
        {
            while (true)
            {
                socket.Listen(50);
                Socket client = socket.Accept();
                NetworkStream stream = new NetworkStream(client);
                BinaryFormatter formatter = new BinaryFormatter();

                TransferClass transfer = formatter.Deserialize(stream) as TransferClass;
                transfer.LoggedIn = true;
                if (connectedList.ContainsKey(transfer.ClientID))
                {
                    transfer.LoggedIn = false;
                    formater.Serialize(stream, transfer);
                    return;
                }
         //code which is executed if everything is OK
            }
         }
         catch (Exception)
         {
            throw;
         }
     }

I can successfully debug client and server side, but once a client tries to connect with same ClientID first it is checked on the server, and the message that he is not LoggedIn is going to be sent back to the client. But after I change the ClientID and try to connect again, and follow it with debug, it never enters server side, like formatter.Serialize is not working on the client.
ClientID is something client enters himself.
My guess is that in the part on the server where I am checking if client with same ClientID already exists I should also close the stream, or something like that, but I am not sure how to do it.


text:
Q: jQuery load() on large files within a loop leaves browser unresponsive. How to fix? I have a loop around the following:
$(document).ready(function() {
    $( "#" + divname[k]).load(documentname[k] + ".html", function(a, b) {
        console.log(documentname[k] + " was loaded");
    });
});

the loop is about 30-50 iterations, each file is different and weighs about 1mb.
I have tried on safari and chrome, both browsers become unresponsive for a good 1-2min until everything is loaded and control is given back to the user.
If the loop is only 10 items long, it works fine without freezing.
I did a lot of research and it seems that $().load should work asynchronously without freezing the UI.
What am I doing wrong?
Thank you!

A: If you have this placed at the top of your page, and that page has other HTML elements to it which don't need to be loaded in, consider placing the JavaScript at the bottom of the page, so it is the last thing to be loaded.
You could also place that code in a $( document ).ready() function.


text:
Q: A principal ideal domain that is not a Euclidean domain. Somebody can to help me in the following problem:

Let R be the following subring of the complex numbers: $$R = \left\{\frac{z_1}{2}+\frac{z_2\sqrt{-19}}{2} : z_1,z_2\in\mathbb{Z}, \;\text{with the same parity}\right\}.$$
  Then R is a principal ideal domain that is not a Euclidean domain.

Note: A ring for me is commutative and with identity.


text:
Q: getting multiple parameters separately (C# discord bot 0.9.6) So what I'm trying to do is that I want my bot to be able to have two different parameters. Like what I mean is something like I can extract like a certain part of it and then after there's a "," or another symbol I can extract the following separately. So I get two different strings from one input. So like I have two strings and I want one of them to be the first half and the second one to be the rest. And I am not planning on updating to 1.0 so tell me if it's not possible in 0.9.6.

A: Your question isn't very clear but I think I know what you are looking for.  This is a general answer for C# as I don't know how the Discord interface differs.  You seem to be taking input in the form of a string, for example: play *songname*,*channelname*.  To split this string into two inputs you want to use String.Split(',')
An example would be this:
string stringTakenFromDiscord = "play *songname*,*channelname*";
String[] input = stringTakenFromDiscord.Split(',');

//input[0] will be equal to what comes before the comma
//if you were to print it, it would be "play *songname*"

//input[1] will be  what comes after the comma
//if you were to print it, it would be "*channelname*"

Now you can do anything you want with either of the values of the array input[] and feed them through your code to parse them.  Do note that when it splits by the character, the character won't appear in either of the output strings.  This will only work for inputs that only have one instance of your chosen character.  You can change the character to whatever you want.
It occurs to me that it might be easier to just take the input on two separate lines instead.


text:
Q: Apple ID: How to avoid changing password? Whenever I try to log in to iCloud or https://appleid.apple.com/ from my PC I am getting forced to change my password ...

I do not want to change it. Is there any way to stop these messages?

A: This message is part of the security measures of iCloud. The only way to get rid of it is to actually set a new password adhering to the rules listed.


text:
Q: Application hangs when cropping image I have the below crop method. When I call cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); my screen hangs at 'saving image'. If I don't call it, the cropped image is not written to file.
private void crop() {
try {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");

    cropIntent.setDataAndType(mImageCaptureUri, "image/*");

    cropIntent.putExtra("crop", "true");
     cropIntent.putExtra("aspectX", 4);
    cropIntent.putExtra("aspectY", 3);
     cropIntent.putExtra("outputX", 500);
    cropIntent.putExtra("outputY", 300);
    File f = new File(Environment.getExternalStorageDirectory(),
            "/temporary_holder.jpg");
    try {
        f.createNewFile();
    } catch (IOException ex) {
        Log.e("io", ex.getMessage());
    }
    uri = Uri.fromFile(f);
    cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

    startActivityForResult(cropIntent, PIC_CROP);

} // respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
    // display an error message
    String errorMessage = "Your device doesn't support the crop action!";
    Toast toast = Toast
            .makeText(this, errorMessage, Toast.LENGTH_SHORT);
    toast.show();
}

}

A: I have the same problem, it stucks with:
cropIntent.putExtra("outputX", 500);
.. so badly that the only way to repair this is to remove the batterie..
but if I take
cropIntent.putExtra("outputX", 200); it works fine..
(device HTC Sensation Z710e Android 4.0.3 (API 15))


text:
Q: Регулярное выражение, которое берет предпоследнее слово из строки (слова разделены пробелами) Как будет выглядеть регулярное выражение, которое берет предпоследнее слово из строки. Слова в строке разделены пробелами.

A: Ну, на php, к примеру, вот так можно:
explode(" ", $str)[str_word_count($str)-2]
А регуляркой как-то так:
\w+(?=\s+\w+$)
regex101(dot)com
regex + php:
preg_match('~\w+(?=\s+\w+$)~',"Lorem ipsum dolor sit amet",$matches);
var_dump($matches);

UPD: с комментария @rvs, на python:
s.split(' ')[-2]


text:
Q: Rounded picturebox with antialias C# I used an advise from this topic: Rounded edges in picturebox C# to make my picturebox edges rounded. So, I claimed a new control using this code:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

class OvalPictureBox : PictureBox {
    public OvalPictureBox() {
        this.BackColor = Color.DarkGray;
    }
    protected override void OnResize(EventArgs e) {
        base.OnResize(e);
        using (var gp = new GraphicsPath()) {
            gp.AddEllipse(new Rectangle(0, 0, this.Width-1, this.Height-1));
            this.Region = new Region(gp);
        }
    }
}

But there is my question: how could I add antialias to my control? I read some topics like this: Possible to have anti-aliasing when drawing a clipped image? but there is just drawing functions are used, and I need to implement antialias in my own control, which parent is PictureBox.
I also tried to override OnPaint method to get PaintEventArgs to use the SmoothingMode, but my code sucked and didn`t work properly.
So I deleted it and this is what I have now:
protected override void OnPaint(PaintEventArgs pe)
{
    base.OnPaint(pe);

    using (var gp = new GraphicsPath())
    {
        gp.AddEllipse(new Rectangle(0, 0, this.Width - 1, this.Height - 1));
        this.Region = new Region(gp);
    }
}

What should I add to this method?


text:
Q: Send db-query-result to client Trying to send results from a node-mysql database query to the client.
Code:
io.on('connection', function(socket){
    socket.on('admin', function() {
        [...]
        locations = getUserInfo(function(e,c){...});
        [...]
    });
});

function getUserInfo(callback) {
    var json = '';
    connection.query('SELECT * from locations WHERE loc_id = 1', function(err, results, fields) {
        if(err)
           return callback(err, null);

        console.log('The query-result is: ', results[0]);

        json = JSON.stringify(results);

        console.log('JSON-result: ', json);
        callback(null, json);
    });
};

getUserInfo(function(e,c){
    console.log(c);
});

This is working as expected.
But I don't want to write it to the console but send it to the client (with socket.io). How can I do this? All my attempts ended in getting undefined as result.

A: You might be sending the locations object back, which is always undefined. Try:
io.on('connection', function(socket){
  socket.on('admin', function() {
      getUserInfo(function(e,c){
        if(!e){
            socket.emit('locations', c);
        }
      });
  });
});


text:
Q: How to prevent Netbeans 8 from stopping on the first line when debugging a PHP Application I'm working on a PHP application for a web server in Netbeans 8.0.1. I've installed XAMP/Apache Server/XDebug and can run and debug the application. When I debug the project in Netbeans, the debugger breaks at the beginning of each php file. This is very annoying and interrupts the process of debugging. How can I disable this feature?

A: Go to Netbeans -> Tools -> Options -> PHP -> Debugging, and uncheck the 'Stop at First Line' checkbox.


text:
Q: Failed to fetch with Docker, MySQL, Express and TypeScript I tried to create a todo-app with Node.js, TypeScript, MySQL.
This app works well. There is no issue.
However, when I tried to have this app on Docker Container, I have the following error.
Failed to load resource: net::ERR_NAME_NOT_RESOLVED
TypeError: Failed to fetch
    at getTodos (ListTodo.tsx:16)
    at ListTodo.tsx:25
    at invokePassiveEffectCreate (react-dom.development.js:23487)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
    at invokeGuardedCallback (react-dom.development.js:4056)
    at flushPassiveEffectsImpl (react-dom.development.js:23574)
    at unstable_runWithPriority (scheduler.development.js:468)
    at runWithPriority$1 (react-dom.development.js:11276)
    at flushPassiveEffects (react-dom.development.js:23447)
    at react-dom.development.js:23324
    at workLoop (scheduler.development.js:417)
    at flushWork (scheduler.development.js:390)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:157)

I failed to fetch data.

The backend code is:
//index.ts
import express from 'express';
import cors from 'cors';
import { Express, Request, Response } from 'express';
import { createPool, RowDataPacket } from 'mysql2';

const pool = createPool({
  host: 'mysqldb',
  port: 3306,
  user: 'root',
  password: 'pass123',
  database: 'todo',
});

const app: Express = express();
app.use(cors());
app.use(express.json());

app.get("/todos", async (req: Request, res: Response) => {
  try{
    const resp = await pool.promise().query<RowDataPacket[]>(
      'SELECT * FROM todo'
    );
    res.json(resp[0]);
  } catch (error) {
    throw error;
  }
});

app.listen(5000);

The frontend code is:
import React, { useState, useEffect } from 'react';

export const ListTodo = () => {
  const [todos, setTodos] = useState([]);
  const getTodos = async () => {
    try {
      //fetch data
      const response = await fetch('http://api-prod:5000/todos');
      const jsondata = await response.json();
      setTodos(jsondata);
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    getTodos()
  }, []);

  return (
    //list data
  );
};

docker-compose file is:
//docker-compose.yml
version: "3"

services:
  mysqldb:
    platform: linux/x86_64
    image: mysql:8.0
    hostname: mysqldb
    environment:
      - MYSQL_ROOT_PASSWORD=pass123
      - MYSQL_DATABASE=todo
    ports:
      - 3306:3306
    command: --default-authentication-plugin=mysql_native_password
    networks:
      - shared-network
    volumes:
      - db-config:/etc/mysql
      - db-data:/var/lib/mysql
      - ./db/backup/files:/data_backup/data

  nginx:
    image: nginx
    container_name: nginx_prod
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
    ports:
      - 80:80
    depends_on:
      api-prod:
        condition: service_healthy
      app-prod:
        condition: service_started
    networks:
      - shared-network

  api-prod:
    container_name: server_api_prod
    build:
      context: server
      dockerfile: Dockerfile
    hostname: api-prod
    depends_on:
      - mysqldb
    networks:
      - shared-network
    ports:
      - 5000:5000
    restart:
      unless-stopped
    healthcheck:
      test: ["CMD", "curl", "http://api-prod:5000"]
      interval: 5s
      timeout: 3s
      retries: 6

  app-prod:
    container_name: client_app_prod
    build:
      context: client
      dockerfile: Dockerfile
    hostname: app-prod
    ports:
      - 3000:3000
    networks:
      - shared-network
    restart:
      unless-stopped

networks:
  shared-network:

volumes:
  db-config:
  db-data:

Why I fail to fetch data?
I think I have a correct database connection(host:mysqldb, port:3306).

A: Your React app runs in your browser, where you can't use the Docker hostnames. Those are only available on the Docker bridge network.
So your React app can't resolve the name api-prod. You need to use a name that can be resolved from the browser. If you run the app locally, you can use localhost. If you want to deploy it and use it from other computers, you need to use a name that can be resolved from those computers.
But for running locally
fetch('http://localhost:5000/todos')

should do the trick.


text:
Q: Wordpress site moved to new server, permalinks work but homepage redirects and creates a WP 404 error I apologise if this has been asked, I was unable to find clear information anywhere on it.
We've recently been forced into moving to a VPS hosting package.
Thewre were a few issues with links that I managed to fix but now the issue lies with the home page. Every page apart from the home page works as should and at the correct address. I.e. website.co.uk/contact instead of /blog/contact.
I assume this has either something to do with the .htaccess file and/or mod rewrite being disabled on the new server.
Most solutions I`ve found all relate to the homepage working and the other pages not. I'm having basically the opposite of this problem.
See http://www.crowdwifi.co.uk it redirects to the /blog/ and creates the 404 Error within Wordpress. You can see from there the other pages and permalinks are fine.
Im on tablet at the moment but can post htaccess code for the root in here in an hour if it helps. I contacted host support but theyve been rather slow so I figure it may be easier for me to try and resolve it.
Added the .htaccess from the "/blog/" subdirectory below.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

A: Can you post up a copy of your .htaccess file?
EDIT:
Set both WordPress Address (URL) and Site Address (URL) to http://www.crowdwifi.co.uk if that doesn't work then try changing your htaccess to this as well:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

# END WordPress

A: Have you checked your Front page settings are not pointing to a specific page?

*

*Dashboard => Settings => Reading => A static page (select below) => Front page
Have you also checked your General Settings do not have the wrong URL?

*

*Dashboard => Settings => General => WordPress Address (URL)

*Dashboard => Settings => General => Site Address (URL)


text:
Q: AJAX Mailchimp signup form integration Is there any way to integrate mailchimp simple (one email input) with AJAX, so there is no page refresh and no redirection to default mailchimp page.
This solution doesn't work jQuery Ajax POST not working with MailChimp
Thanks

A: Based on gbinflames' answer, this is what worked for me:
Generate a simple mailchimp list sign up form , copy the action URL and method (post) to your custom form. Also rename your form field names to all capital ( name='EMAIL' as in original mailchimp code, EMAIL,FNAME,LNAME,... ), then use this:
      $form=$('#your-subscribe-form'); // use any lookup method at your convenience

      $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action').replace('/post?', '/post-json?').concat('&c=?'),
      data: $form.serialize(),
      timeout: 5000, // Set timeout value, 5 seconds
      cache       : false,
      dataType    : 'jsonp',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { // put user friendly connection error message  },
      success     : function(data) {
          if (data.result != "success") {
              // mailchimp returned error, check data.msg
          } else {
              // It worked, carry on...
          }
      }

A: As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!

A: Use jquery.ajaxchimp plugin to achieve that. It's dead easy!
<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />

</form>

JavaScript:
$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})

A: Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.
<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
  <input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
  <input type="hidden" name="id" value="XXXXXXXXX">
  <input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
  <input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>

Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.
$('.myform').submit(function(e) {
  var $this = $(this);
  $.ajax({
      type: "GET", // GET & url for json slightly different
      url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
      data: $this.serialize(),
      dataType    : 'json',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { alert("Could not connect to the registration server."); },
      success     : function(data) {
          if (data.result != "success") {
              // Something went wrong, parse data.msg string and display message
          } else {
              // It worked, so hide form and display thank-you message.
          }
      }
  });
  return false;
});

A: You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.
Your form tag will look something like this by default:
<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >

change it to look something like this
<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.
I submit my forms with this bit of jQuery:
$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }
        });
    }
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...
            }
        }
    });
}

A: You should use the server-side code in order to secure your MailChimp account.
The following is an updated version of this answer which uses PHP:
The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.
1)  Download the PHP 5 jQuery example here...
http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip
If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.
http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip
2)  Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.
3)  You may also want to gather your users' name and/or other information.  You have to add an array to the store-address.php file using the corresponding Merge Variables.
Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:
<?php

function storeAddress(){

    require_once('MCAPI.class.php');  // same directory as store-address.php

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('123456789-us2');

    $merge_vars = Array(
        'EMAIL' => $_GET['email'],
        'FNAME' => $_GET['fname'],
        'LNAME' => $_GET['lname']
    );

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page.
    $list_id = "123456a";

    if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
        // It worked!
        return 'Success!  Check your inbox or spam folder for a message containing a confirmation link.';
    }else{
        // An error ocurred, return error message
        return 'Error:  ' . $api->errorMessage;
    }

}

// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>

4)  Create your HTML/CSS/jQuery form.  It is not required to be on a PHP page.
Here is something like what my index.html file looks like:
<form id="signup" action="index.html" method="get">
    <input type="hidden" name="ajax" value="true" />
    First Name: <input type="text" name="fname" id="fname" />
    Last Name: <input type="text" name="lname" id="lname" />
    email Address (required): <input type="email" name="email" id="email" />
    HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
    Text: <input type="radio" name="emailtype" value="text" />
    <input type="submit" id="SendButton" name="submit" value="Submit" />
</form>

Required pieces...

*

*index.html constructed as above or similar.  With jQuery, the appearance and options are endless.

*store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID.  You need to add your other optional fields to the array.

*MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4).  Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.

A: For anyone looking for a solution on a modern stack:
import jsonp from 'jsonp';
import queryString from 'query-string';

// formData being an object with your form data like:
// { EMAIL: 'emailofyouruser@gmail.com' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});

A: This Github code works perfectly for me. This has a detailed explanation of how to use it. I use it on my WP site. Here is the link -
https://gist.github.com/DmitriyRF/34f659dbbc02637cf7465e2efdd37ef5

A: In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):
https://github.com/cgarnier/angular-mailchimp-subscribe

A: I wasn't able to get this working with fetch so had to combine a few answers here using GET and parsing form inputs into the query string for the URL. It also wasn't necessary for the name of the input to be EMAIL but I guess it makes it more legible and doesn't break the code (in this simple case. Play around if you have other form fields).
Here's my code;
<form action="https://me.usxx.list-manage.com/subscribe/post-json?" id="signup" method="GET">
  <input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxx"/>
  <input type="hidden" name="id" value="xxxxxxxxx"/>
  <input type="hidden" name="c" value="?"/>
  <input name="EMAIL" type="text" />
</form>

// Form submission handler
const formData = new FormData(signup);

fetch(signup.action + new URLSearchParams(formData).toString(), {
  mode: 'no-cors',
  method: signup.method,
})
.then((res) => {
  // Success
})
.catch((e) => {
  // Error
})

You could make it no-js friendly with...
<form action="https://me.usxx.list-manage.com/subscribe/post" id="signup">

fetch(signup.action + '-json?' + new URLSearchParams(formData).toString(), {

And just to save those who fumbled around as I did needlessly, you must create a signup form for an Audience within Mailchimp and by visiting that page you can get your u value and id as well as the action. Maybe this was just me but I thought that wasn't explicitly clear.


text:
Q: Invoking method via selector I am writing  a function in objective C.
That is what I got:
int rndValue = (((int)arc4random()/0x100000000)*width);
timer1 = [NSTimer scheduledTimerWithTimeInterval:.01
                                          target:self
                           [self performSelector:@selector(doItAgain1:)
                                      withObject:rndValue]
                                        userInfo:nil
                                         repeats:YES];

The selector invokes this method and passes parameter:
-(void)doItAgain1:(int)xValuex{
}

At this stage the top code produces syntax error. Syntax error: 'Expected ] before performSelector' What is the prob?
Best regards

A: That line should probably read
timer1 = [NSTimer scheduledTimerWithTimeInterval:.01
         target:self selector:@selector(doItAgain1:)
         userInfo:nil repeats:YES];

You can't send a method argument with this call, in order to do that you have to do something like:
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:
    [self methodSignatureForSelector:@selector(doItAgain1:)]];

[inv setSelector:@selector(doItAgain1:)];
[inv setTarget:self];
[inv setArgument:&rndValue atIndex:2];

timer1 = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval).01
         invocation:inv
         repeats:YES];

A: This would be more correct:
[NSTimer scheduledTimerWithTimeInterval:.01 target:self
                 selector:@selector(doItAgain1:)
                 userInfo:[NSNumber numberWithInt:rndValue] repeats:YES];

Also notice that the syntax for the selector you call in this way must be:
- (void)doItAgain1:(NSTimer*)timer {

   int rndValue = [timer.userInfo intValue];
   ...
}

It is not possible to specify an int argument to such a timer selector, thus the trick to convert it into a NSNumber object.


text:
Q: How do I prevent users from running applications using invalid shortcuts? I work in an environment where my department maintains various in-house applications used by our company users with varying computer skill level.
We've had numerous problems in the past where users copy shortcuts from one machine to another, or worse, use shortcuts to applications they've had emailed to them from other users.
For the most part, it doesn't really cause any problems. However, we do get support tickets occasionally because someone is trying to run a shortcut where the path is incorrect, or points to another machine on the network and loads the wrong files.
We're working on some new applications, and I'd love to find a method to prevent that from happening.
My initial thought is to somehow find a way to read how the program was executed and somehow backtrack to the location of the shortcut and find out where it was running from. At that point I could validate the shortcut and/or restrict shortcut. i.e. somehow force the program to be launched directly by exe or from a desktop shortcut only. I don't really know how to find out the shortcut-that-called-the-exe-path however...
Thoughts? Ideas?

A: Your implementation would be left up to you, but a great preliminary check would be to examine the path property of the shortcut file. For example, if someone emailed another user a shortcut and had it placed on the desktop, the path would contain the user of the person who emailed the shortcut rather than the current user. Other than that you could try:
File.Exists(shortcutPath);

You could bundle up some simple rules like these into a console application that recursively checks all the shortcuts on a machine and if they are invalid, delete them.


text:
Q: CGAL compile error I installed all the required libraries of CGAL, and added all the library path to my makefile while compiling my program on linux, but it still occured compiling error.
This is the content of my makefile
//--------------------------------------------------

FLAGS = -Wall -g -std=c++11 -O3

BOOST_LIB_PATH = -I /usr/include/include/

CGAL_LIB_PATH = -I /usr/local/include/

all :
    g++ $(FLAGS) $(BOOST) $(CGAL) main.cpp -o main
clean :
    rm main

//--------------------------------------------------

Bellow is the error message while compiling, Please help !
//----------------------------------------------------

g++ -Wall -g -std=c++11 -O3  -I /usr/include/include/ -I /usr/local/include/ main.cpp -o main
/usr/local/include/CGAL/Interval_nt.h:208: undefined reference to `CGAL::assertion_fail(char const*, char const*, int, char const*)'
/usr/local/include/CGAL/Interval_nt.h:210: undefined reference to `CGAL::assertion_fail(char const*, char const*, int, char const*)'
/tmp/cc5WX5dM.o: In function `~Gmpz_rep':
/usr/local/include/CGAL/GMP/Gmpz_type.h:57: undefined reference to `__gmpz_clear'
/usr/local/include/CGAL/GMP/Gmpz_type.h:57: undefined reference to `__gmpz_clear'
/usr/local/include/CGAL/GMP/Gmpz_type.h:57: undefined reference to `__gmpz_clear'
/tmp/cc5WX5dM.o: In function `CGAL::Gmpz::operator==(CGAL::Gmpz const&) const':
/usr/local/include/CGAL/GMP/Gmpz_type.h:154: undefined reference to `__gmpz_cmp'
/usr/local/include/CGAL/GMP/Gmpz_type.h:154: undefined reference to `__gmpz_cmp'
/tmp/cc5WX5dM.o: In function `CGAL::Quadratic_program_solution<CGAL::Gmpz>::optimality_certificate_numerators_begin() const':
/usr/local/include/CGAL/QP_solution.h:460: undefined reference to `CGAL::assertion_fail(char const*, char const*, int, char const*)'
/tmp/cc5WX5dM.o: In function `CGAL::Gmpz::operator<(CGAL::Gmpz const&) const':
/usr/local/include/CGAL/GMP/Gmpz_type.h:152: undefined reference to `__gmpz_cmp'
/usr/local/include/CGAL/GMP/Gmpz_type.h:152: undefined reference to `__gmpz_cmp'
/usr/local/include/CGAL/GMP/Gmpz_type.h:152: undefined reference to `__gmpz_cmp'
/tmCGAL::assertion_fail(char const*, char const*, int, char const*)'
collect2: error: ld returned 1 exit status
make: *** [all] Error 1

A: I had a similar problem. I fix it by adding
find_library( GMP_LIB     NAMES "gmp"          PATHS ${CMAKE_LIBRARY_PATH} )
and add it to the target_link_libraries


text:
Q: Update the data of an existing table in PHP I need to make a table of searches made by the user in php. My code fails to encapsulate every new result in the table. I'd like you not to create a new table every time and delete the data, but to gradually add to the data already in the table. Also I have a problem with highlighting accents or special characters in php, how can I fix it? All my data is taken from a column (MySQL database = cherubini, table = lemmi) where it has already been normalized and therefore it works. In my code I have already tried both php and js, but in both cases they conflict with the search results. I am learning web development on my own by asking many questions about my problems, I hope they are useful. My PHP code doesn't work because there isn't my table in your own. You've to just to change database and table and two queries. The new table data must be added after the last element in the table. This is my code - it contains PHP code and MySQL connection - :

    <link rel="icon" href="https://icons.iconarchive.com/icons/custom-icon-design/flatastic-1/512/search-icon.png">
    <title>Vocabulary searching</title>

    <form class="form" action="main.php" method="GET">
      <input type="text" name="text" id="text" placeholder="Premi invio per cercare nel vocabolario Cherubini">
      <button type="submit" name="button" id="button"></button>
      <button type="submit" name="reset" id="reset">Pulisci la tabella</button>
    </form>

Cronologia delle ricerche

    <?php
      error_reporting(0);
      ini_set('display_errors', 0);
      $conn = mysqli_connect('localhost', 'root', '', 'cherubini');
      $c = 0; $text2 = "";
      if(isset($_GET['button'])) {
        $text2 = $_GET['text'];
        $result = $conn->query("SELECT * FROM lemmi WHERE LemmaNo LIKE '%".$text2."%' ORDER BY LemmaNo");
        $count=$result->num_rows;
        if(empty($count)) {
          $r = $conn -> query("SELECT * FROM history ORDER BY ID");
          while($row = mysqli_fetch_assoc($r)) {
            $history[$c] = $row['Parola'];
            echo "
".$history[$c]."
"."
"; $c++;
          } $c = 0; echo "
";
        }
        else {
        $stmt = $conn->prepare("INSERT INTO history (Parola) VALUES (?)");
        $stmt->bind_param("s", $text2);
        $stmt->execute(); $stmt->close();
        $r = $conn -> query("SELECT * FROM history ORDER BY ID");
        while($row = mysqli_fetch_assoc($r)) {
          $history[$c] = $row['Parola'];
          echo "
".$history[$c]."
"."
"; $c++;
        } $c = 0; echo "
"; }
        while($row = mysqli_fetch_assoc($result)) {
          $modifiedrawData = preg_replace('/'.implode('|', array($text2)).'/i', '$0', $row['LemmaNo']);
          echo "Lemma: ".$modifiedrawData."
";
          $modifiedrawData = preg_replace('/'.implode('|', array($text2)).'/i', '$0', $row['Definizione']);
          echo "Definizione: ".$modifiedrawData."

";
          $c++; } }
        if(isset($_GET['reset'])) { $conn->prepare("DELETE FROM history")->execute()->close(); }
     ?>

A: You can use something like follows;
 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
";
  }
} else {
  echo "0 results";
}
$conn->close();
?>

Source : https://www.w3schools.com/php/php_mysql_select.asp
You can modify this to match with your table name, columns etc.


text:
Q: How to paste/equalize specific range value in one sheets into another? I have named "FormEntry" in Range("E7,F11,H12,I8,E16") in Sheet1.

and picture above is Sheet2.
Is that possible to copy Range "FormEntry" from Sheet1 and paste/equalize into the same Range in Sheets2 without other cells range in Sheet2 being replaced?
I've tried this syntax but the values on Sheets2 are A's
Sub test()

 Sheets("Sheet2").Range("E7,F11,H12,I8,E16").Value = Sheets("Sheet1").Range("E7,F11,H12,I8,E16").Value

End Sub

A: You can use:
For Each cell In Range("FormEntry")
    Sheets("Sheet2").Cells(cell.Row, cell.Column).Value = cell.Value
Next


text:
Q: Serializing Django model objects: Referencing to self I have implemented natural keys on my objects and they worked. Except for one model that reference to itself.
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('self')

    def natural_key(self):
        return (self.name)

Calling
serializers.serialize('json', Person.objects.all(), use_natural_keys=True)

Gives me an error "DoesNotExist... No exception supplied"
-Thanks in advance!

A: If you want a list of lists, this would work:
from django.utils import simplejson

people = People.objects.all().values_list('name', 'id')
simplejson.dumps(list(people))


text:
Q: Maven pom version inheritance I have 3 projects Parent,Child,SubChild.
Project  Parent pom is as follows:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.3.RELEASE</version>
</parent>

<groupId>mu.parent</groupId>
<artifactId>parent-system</artifactId>
<version>1.0</version>
<packaging>pom</packaging>

....
Project Child pom is defined below and its Parent is defined follows:
<modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>mu.parent</groupId>
        <artifactId>parent-system</artifactId>
        <version>1.0</version>
    </parent>

    <groupId>mu.dummy.child</groupId>
    <artifactId>child-backend</artifactId>
    <name>child-backend</name>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

  <modules>
        <module>subChild-app</module>

    </modules>

...

Now subChild pom is as follows and the child is defined as parent for subChild :
 <parent>
            <groupId>mu.dummy.child</groupId>
           <artifactId>child-backend</artifactId>
          <version>0.0.1-SNAPSHOT</version>
    </parent>
 <groupId>mu.dummy.subchild</groupId>
    <artifactId>subchild-backend</artifactId>
    <name>subchild-backend</name>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

  <dependencies>
        <dependency>
            <groupId>org.project.test</groupId>
            <artifactId>project</artifactId>
       <version></version> --version of parent-system???
        </dependency>

    </dependencies>

Is it possible to get version of parent-system(1.0) in subchild-backend please without hardcoding it?

A: You can use CI-friendly versions and write ${revision} for the versions, setting this property in the main pom (from which you build everything).
You need to use the flatten Maven plugin, though, to get proper POMs in the repository.

A: I asked a similar question a while back and determined that tthe groovy-maven-plugin works for this. See this answer.


text:
Q: Pandas: Same indices for each column. Is there a better way to solve this? Sorry for the lousy text in the question? I can't come up with a summarized way to ask this question.
I have a dataframe (variable df) such as the below:
df

ID
A
B
C

1
m
nan
nan

2
n
nan
nan

3
b
nan
nan

1
nan
t
nan

2
nan
e
nan

3
nan
r
nan

1
nan
nan
y

2
nan
nan
u

3
nan
nan
i

The desired output is:

ID
A
B
C

1
m
t
y

2
n
e
u

3
b
r
i

I solved this by running the following lines:
new_df = pd.DataFrame()
for column in df.columns:
    new_df = pd.concat([new_df, df[column].dropna()], join='outer', axis=1)

And then I figured this would be faster:
empty_dict = {}
for column in df.columns:
    empty_dict[column] = df[column].dropna()
new_df = pd.DataFrame.from_dict(empty_dict)

However, the dropna could represent a problem if, for example, there is a missing value in the rows that have the values to be used in each column. E.g. if df.loc[2,'A'] = nan, then that key in the dictionary will only have 2 values causing a misalignment with the rest of the columns. I'm not convinced.
I have the feeling pandas must have a builtin function that will do a better job and either of my two solutions. Is there? If not, is there any better way of solving this?

A: Looks like you only need groupby().first():
df.groupby('ID', as_index=False).first()

Output:
   ID  A  B  C
0   1  m  t  y
1   2  n  e  u
2   3  b  r  i

A: Use stack_unstack() as suggested by @QuangHoang if ID is the index:
>>> df.stack().unstack().reset_index()
    A  B  C
ID
1   m  t  y
2   n  e  u
3   b  r  i

You can use melt and pivot:
>>> df.melt('ID').dropna().pivot('ID', 'variable', 'value') \
      .rename_axis(columns=None).reset_index()

   ID  A  B  C
0   1  m  t  y
1   2  n  e  u
2   3  b  r  i


text:
Q: Copy from Vim to VSCode causing extra tab Having copied normaly indented text from Vim into the system clipboard using "+y, I paste it VSCode. Each line that is tab-indented will be indented two-tab width as the picture shows.
Code in Vim:

Code in VSCode copied from Vim:

shiftwidth is set to 4 in my .vimrc and tab size is set to 4 in VSCode.
Below is my full .vimrc:
call plug#begin('~/.vim/plugged')
Plug 'tpope/vim-surround'
Plug 'tpope/vim-repeat'
Plug 'jiangmiao/auto-pairs'

" Theme
Plug 'phanviet/vim-monokai-pro'
Plug 'sainnhe/sonokai'
Plug 'crusoexia/vim-monokai'
Plug 'chriskempson/base16-vim'

" Syntax highlighting
Plug 'sheerun/vim-polyglot'

" Master Vim
Plug 'takac/vim-hardtime'

" Autocomplete
Plug 'ycm-core/YouCompleteMe'

" Full path fuzzy file, buffer, mru, tag, ... finder
Plug 'ctrlpvim/ctrlp.vim'

" Move line
Plug 'matze/vim-move'

" Window
Plug 'tpope/vim-vinegar'

" Status bar
Plug 'vim-airline/vim-airline'

" Git tool
Plug 'tpope/vim-fugitive'

" Comment stuff
Plug 'tpope/vim-commentary'

" Syntax checking
Plug 'vim-syntastic/syntastic'
call plug#end()

" Basics
set nocompatible
filetype plugin on
syntax on
set encoding=utf-8
set fileencoding=utf-8
set shiftwidth=4

" Enable autocompletion
set wildmode=longest,list,full

" Comment stuff
autocmd FileType apache setlocal commentstring=#\ %s
autocmd FileType c,cpp,java,lisp setlocal commentstring=//\ %s

" Relative number
set number relativenumber
set nu rnu

" Disable automatic commenting on newline
autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o

" Splits open at the bottom and the right
set splitbelow splitright

" Shortcutting split navigation
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l

" Treat numbers as decimals
set nrformats-=octal

" Theme
set t_Co=256
set background=dark
let g:sonokai_style = 'shusia'
let g:sonokai_enable_italic = 1
let g:sonokai_disable_italic_comment = 1
colorscheme monokai_pro
let g:airline_theme = 'sonokai'

" NERDTree
nmap <F6> :NERDTreeToggle<CR>

" Arrow keys are dead, stupid
noremap <Up> :echo "Arrow keys are dead, stupid!"<CR>
noremap <Down> :echo "Arrow keys are dead, stupid!"<CR>
noremap <Left> :echo "Arrow keys are dead, stupid!"<CR>
noremap <Right> :echo "Arrow keys are dead, stupid!"<CR>

inoremap <Up> <esc>:echo "Arrow keys are dead, stupid!"<CR>
inoremap <Up> <nop>
inoremap <Down> <esc>:echo "Arrow keys are dead, stupid!"<CR>
inoremap <Left> <esc>:echo "Arrow keys are dead, stupid!"<CR>
inoremap <Right> <esc>:echo "Arrow keys are dead, stupid!"<CR>

nnoremap ∆ :m .+1<CR>==
nnoremap ˚ :m .-2<CR>==

inoremap ∆ <Esc>:m .+1<CR>==gi
inoremap ˚ <Esc>:m .-2<CR>==gi

vnoremap ∆ :m '>+1<CR>gv=gv
vnoremap ˚ :m '<-2<CR>gv=gv
" Master Vim
let g:hardtime_default_on = 0

" ctrlp
let g:ctrlp_map = '<c-p>'

My computer's system version is macOS Catalina 10.15.7.

A: there are 3 settings actually you should use for vim if you want all files with tabs  with width 4 spaces
:set shiftwidth=4
:set tabstop=4
:retab


text:
Q: Вывод сырого HTML на странице Как можно вывести сырой HTML на страницу?
В базе у меня есть текст, который нужно вывести в таком виде на страницу

Patient Name: {{patient_name}}

При рендере {{patient_name}} удаляется. Мне нужно, чтобы он остался.
Пробую вывести вот так:
>{{html_entity_decode($template->content)}}</textarea>
>{!! $template->content !!}</textarea>

Оба варианта не работают.

A: Разобрался. Так как у меня подключён VUE на странице. Нужно было добавить атрибут к textarea v-pre


text:
Q: How to use where condition for two conditions in same column in SQL Server I have two tables, Customer and Sales.
I have to select customer and salesperson in the query. I have combined both the tables with the primary key with customer ID .
I also have to filter the selected data where salesperson name is ' John' and 'jack ,
When I use
where salesperson = 'John' and 'jack'

I am getting no results.
Please help me on how to get salesperson with names from jack and John .

A: You would use in:
where salesperson in ('John', 'Jack')

This is logically equivalent to:
where salesperson = 'John' or salesperson = 'Jack'

But in is simpler to write and less error-prone.
If you want customers that have been associated  with both John and Jack, then you would combine this with aggregation:
select customerid
from sales
where salesperson in ('John', 'Jack')
group by customerid
having count(distinct salesperson) = 2;

That is, look for customers that have either saleperson.  Aggregate and return only the customers that have had both.

A: AND is correct. Using OR as wouter suggests will output the result if 1 condition is matched so probably not what you want. Perhaps paste the full code here for better help. Have you tested just 1 name or OR just to ensure your query is working?


text:
Q: Problem with CakePHP model joins, missing fields from joined table. Im probably missing something painfully obvious here. Im trying to join multiple tables together in Cake, but Im only getting the fields from the first table. Consider the following code..
$joins = array();
$joins[] =  array(
            'table' => 'products',
            'alias' => 'Product',
            'type' => 'LEFT',
            'conditions' => array(
                'Device.id = Product.device_id'
            )
    );

$joins[] =  array(
            'table' => 'pricepoints',
            'alias' => 'Pricepoints',
            'type' => 'LEFT',
            'conditions' => array(
                'Pricepoints.product_id = Product.id'
            )
    );
$all_products = $this->Device->find('all', array("joins" => $joins);

And this returns the following SQL
SELECT `Device`.`id`, `Device`.`manufacturer_id`, `Device`.`name`, `Device`.`type_id`, `Manufacturer`.`id`, `Manufacturer`.`name` FROM `devices` AS `Device` LEFT JOIN products AS `Product` ON (`Device`.`id` = `Product`.`device_id`) LEFT JOIN pricepoints AS `Pricepoints` ON (`Pricepoints`.`product_id` = `Product`.`id`) LEFT JOIN `manufacturers` AS `Manufacturer` ON (`Device`.`manufacturer_id` = `Manufacturer`.`id`)

ie. it only returns the fields from the parent Model ie. Device. How do I get  it to select ALL fields from the join? Im presuming its to do with the way I have my Model relationships set up, but I think I have these set up correctly.
Anyone any advice?

A: you can specify the fields in the find query:
$all_products = $this->Device->find('all', array("fields" => array('Device.*','Product.*','Pricepoints.*')
                                                 "joins" => $joins
);

Hope this helps

A: Do your join by calling bindModel() instead of manually specifying the join. See the cookbook for the details on creating and destroying associations on the fly


text:
Q: Bandwidth parameters in multivariate KDE using scipy.stats.gaussian_kde I am working on a project which involves implementing in Python two different density estimation functions over multivariate data; one using N-d histograms and the other using kernel density estimation (KDE).
I used scipy.stats.gaussian_kde, and realised that as the dimensions differed in variance in my underlying data, the KDE function was less able to accurately estimate the underlying probability density.
It seems that we need to have a different bandwidth parameter for each dimension (manifest, I gather, as a bandwidth matrix). scipy.stats.gaussian_kde does not appear to support bandwidth matrix arguments, so my questions are:

*

*Am I right in thinking that this function is flawed/useless without performing some normalisation-type operation on the data to ensure SD is somehow the same for each dimension? If so, it seems like a glaring problem in the implementation.

*What is the simplest Python alternative to plug into my code, to calculate KDE given a bandwidth matrix? (Ideally with a similar interface to avoid much refactoring)

A: Multivariate kernel density estimation can be defined in terms of

*

*product of univariate kernels $K^P(\mathrm{x}) = \prod_{i=1}^{d} \kappa(x_i)$,

*as a symmetric kernel $K^S(\mathrm{x}) \propto\kappa\{(\mathrm{x}'\mathrm{x})^{1/2}\}$,

*or in terms of standalone multivariate kernel, e.g. multivariate Gaussian distribution.

There are also different possible choices of bandwidth matrix,

*

*it can have equal bandwidth for each of the variables $\mathrm{H} = h^2\mathrm{I}_d$,

*different for different variables $\mathrm{H} = \mathrm{diag}(h_1^2, h_2^2, \dots, h_d^2)$,

*or it could be a covariance matrix.

The three choices are illustrated by Wand and Jones in their Kernel Smoothing book using the following figure of two-dimensional case.

The first choice is "symmetric", it assumes no correlation and equal variances. Second allows for unequal variances. Third allows additionally for correlation between variables.
The scipy documentation does not tell us much about the kind of multivariate kernel that they are using. It only tells us that it uses Scotts or Silvermans rules of thumb for selecting the bandwidth, so it estimates some constant $h^2$ and the covariance matrix is either same for all variables or is a scaling factor for covariance matrix (more likely, but you'd need to check the source code). Nonetheless, scipy is using rule of a thumb for choosing the bandwidth, so this does not have to be optimal choice and I'd encourage you to look for packages that implement more sophisticted approaches (R has several, I can't tell for python).

A: You can provide your own covariance matrix by inheriting from the gaussian_kde class as follows:
from scipy.stats._kde import gaussian_kde
import numpy as np

class custom_kde(gaussian_kde):
    def __init__(self, dataset, bw_method=None, weights=None, covariance=None):
        self.covariance = covariance
        super().__init__(dataset, bw_method=bw_method, weights=weights)

    def _compute_covariance(self):
        # Copied from the base gaussian_kde class, except for the covariance part
        self.factor = self.covariance_factor()
        if not hasattr(self, '_data_inv_cov'):
            self._data_covariance = np.atleast_2d(np.cov(self.dataset, rowvar=1, bias=False, aweights=self.weights))
            self._data_inv_cov = np.linalg.inv(self._data_covariance)

        if self.covariance is None:
            self.covariance = self._data_covariance * self.factor**2
        self.inv_cov = np.linalg.inv(self.covariance)
        L = np.linalg.cholesky(self.covariance*2*np.pi)
        self.log_det = 2*np.log(np.diag(L)).sum()

Example usage:
kernel = custom_kde(X_arr, Y_arr, covariance=np.array([[1.0, 0.5], [0.5, 1.0]]))

A: I was looking for an answer to this bandwidth matrix optimisation problem and I found this excellent other thread, so I thought I'd drop it here:
Difference in bandwidth for scikit-learn KDE and multivariate KDE of statsmodels.
In short, it says that the sklearn KernelDensity() implementation uses bandwidth as a multiplier of the diagonal matrix (so second case of Tim's answer), while statsmodel's KDEMultivariate() estimates different multipliers (so third picture, I believe). I am not sure how this compares to scipy which multiplies the covariance matrix by the single scalar. It looks to fall in the same case as KDEMultivariate(), but with a little less control over the dimension-specific toggling. From what I understand (again from that other stackoverflow answer), they both use rule of thumb for coming up with the covariance matrix.

A: This will allow you to manually specify a covariance matrix for your kernel, made by stripping Joe's answer down to the bare bones.
from scipy.stats import gaussian_kde as kde

class custom_kde(kde):
    def __init__(self, dataset, covariance):
        self.covariance = covariance
        super().__init__(dataset, bw_method=1.0, weights=None)

    def _compute_covariance(self):
        self.inv_cov = np.linalg.inv(self.covariance)

Example use
from scipy.stats import multivariate_normal as mvn
from matplotlib import pyplot as plt
plt.ion()

# covariance matrix with std devs of 10 and 1 in the x and y
# and a correlation coefficient of 5/(10*1) = 0.5
covariance = np.array([[100, 5], [5, 1]])

# compute KDE on a grid based on a single data point
# with the manually set covariance
data = [[0], [0]]
kernel = custom_kde(data, covariance)
x, y = np.mgrid[-30:30:100j, -3:3:100j]
xy = np.vstack([x.ravel(), y.ravel()])
density = kernel(xy)
density = density.reshape(x.shape)

# plot it up
plt.imshow(np.rot90(density), cmap=plt.get_cmap('YlOrRd'),
              extent=(-30, 30, -3, 3))
plt.gca().set_aspect('auto')

A multivariate Gaussian with the covariances we specified is what we get.


text:
Q: How do I back out of sudo privileges in OS X Is there a command to de-elevate the user from sudo permissions after I execute a command such as sudo pmset sleep 0 so that when I try to execute another sudo command it asks for my password again?
Currently after one sudo command it will execute any others without asking for my password. The command exit doesn't seem to work.

A: sudo -k will do what you want; it invalidates the sudo timestamp, effectively revoking your sudo permissions so that you will be prompted for a password again next time you use sudo.
sudo doesn't (by default at least) open another terminal, so exit won't help; it will just quit the shell you were already using.
Source.

A: You should also be able to do this (at least you can on Linux, it may be different on OSX) by setting the timestamp_timeout to 0 in /etc/sudoers. This is the time for which the password is remembered  . On most Linux distributions, the default is set at 15 minutes. Setting it to 0 means that sudo will prompt for a password every time it is run. To change it do the following:

*

*Run sudo visudo, this will open a vim session allowing you to edit /etc/sudoers.

*Hit i to enter INSERT mode

*Add this line
Defaults        timestamp_timeout=0

*Hit Esc to exit INSERT mode

*Hit :wqEnter to save the file and exit.
Now, sudo will always ask for a password, even if you have just given it one. If you think this is too strict, you can use a higher value, say 5 for five minutes or 0.5 for 30 seconds.


text:
Q: JWT::InvalidIatError at /user/auth/google_oauth2/callback Invalid iat I get this error when I try to log in using Google oauth2 locally. Googling the error doesn't give me any indication. On Heroku I don't have any issues
This is my omniauth controller function for google:
  def google_oauth2
      # You need to implement the method below in your model (e.g. app/models/user.rb)
      @user = User.from_omniauth(request.env["omniauth.auth"])

      if @user.persisted? # Check if the user exits
        sign_in_and_redirect @user, event: :authentication
        # flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
      else
        session["devise.google_data"] = request.env["omniauth.auth"].except('extra')
        redirect_to new_user_registration_url
      end
  end

This is the server log output:
Started GET "/user/auth/google_oauth2" for 10.0.2.2 at 2015-10-04 17:11:23 -0400
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
I, [2015-10-04T17:11:23.278558 #8203]  INFO -- omniauth: (google_oauth2) Request phase initiated.

Started GET "/user/auth/google_oauth2/callback?state=7080deaf5a52603044da3856898c08a89722f57e4dc9e75d&code=4/vWA-kcX2_P8JF6i10VIMRtYO81crG5vyPMRyknGs3q4" for 10.0.2.2 at 2015-10-04 17:11:26 -0400
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
I, [2015-10-04T17:11:26.065521 #8203]  INFO -- omniauth: (google_oauth2) Callback phase initiated.

JWT::InvalidIatError - Invalid iat:
  jwt (1.5.1) lib/jwt.rb:170:in `decode'
  omniauth-google-oauth2 (0.2.7) lib/omniauth/strategies/google_oauth2.rb:63:in `block in <class:GoogleOauth2>'
  omniauth (1.2.2) lib/omniauth/strategy.rb:105:in `block in compile_stack'
  omniauth (1.2.2) lib/omniauth/strategy.rb:104:in `compile_stack'
  (eval):7:in `extra_stack'
  omniauth (1.2.2) lib/omniauth/strategy.rb:329:in `extra'
  omniauth (1.2.2) lib/omniauth/strategy.rb:336:in `auth_hash'
  omniauth (1.2.2) lib/omniauth/strategy.rb:361:in `callback_phase'
  omniauth-oauth2 (1.3.1) lib/omniauth/strategies/oauth2.rb:79:in `callback_phase'
  omniauth (1.2.2) lib/omniauth/strategy.rb:227:in `callback_call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:184:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
  bullet (4.14.7) lib/bullet/rack.rb:12:in `call'
  meta_request (0.3.4) lib/meta_request/middlewares/app_request_handler.rb:13:in `call'
  meta_request (0.3.4) lib/meta_request/middlewares/meta_request_handler.rb:13:in `call'
  rails-dev-boost (0.3.0) lib/rails_development_boost/async.rb:14:in `call'
  jquery-fileupload-rails (0.4.6) lib/jquery/fileupload/rails/middleware.rb:14:in `_call'
  jquery-fileupload-rails (0.4.6) lib/jquery/fileupload/rails/middleware.rb:10:in `call'
  warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.3) lib/warden/manager.rb:34:in `call'
  rack (1.6.4) lib/rack/etag.rb:24:in `call'
  rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'
  rack (1.6.4) lib/rack/head.rb:13:in `call'
  remotipart (1.2.1) lib/remotipart/middleware.rb:27:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.4) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
  activerecord (4.2.4) lib/active_record/migration.rb:377:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.4) lib/active_support/callbacks.rb:88:in `__run_callbacks__'
  activesupport (4.2.4) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'
  activesupport (4.2.4) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.4) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
  rack-contrib (1.4.0) lib/rack/contrib/response_headers.rb:17:in `call'
  meta_request (0.3.4) lib/meta_request/middlewares/headers.rb:16:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.2.1) lib/web_console/middleware.rb:31:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.4) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.4) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.4) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.4) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.4) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.4) lib/rails/rack/logger.rb:20:in `call'
  quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets'
  actionpack (4.2.4) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.4) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.4) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.4) lib/action_dispatch/middleware/static.rb:116:in `call'
  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
  rack-mini-profiler (0.9.7) lib/mini_profiler/profiler.rb:276:in `call'
  railties (4.2.4) lib/rails/engine.rb:518:in `call'
  railties (4.2.4) lib/rails/application.rb:165:in `call'
  rack (1.6.4) lib/rack/content_length.rb:15:in `call'
  puma (2.11.1) lib/puma/server.rb:507:in `handle_request'
  puma (2.11.1) lib/puma/server.rb:375:in `process_client'
  puma (2.11.1) lib/puma/server.rb:262:in `block in run'
  puma (2.11.1) lib/puma/thread_pool.rb:104:in `block in spawn_thread'

A: skip_jwt: true is not always the best way to do that. The problem seems to lie in the hardware clock of my server in this case. It was off by 72 seconds in my case and if i recall by default JWT allows 60 seconds. You can check that and fix it by doing the following.
sudo ntpdate ntp.ubuntu.com

setup cronjob to check every hour and fix it

sudo nano /etc/cron.hourly/ntpdate

add

#! /bin/sh

ntpdate ntp.ubuntu.com

save file and change permissions

sudo chmod +x /etc/cron.hourly/ntpdate

A: based on the answer by @imsinu9 :
use OmniAuth::Builder do
  provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"], skip_jwt: true
end

A: Recently google_oauth2 released a way where we can ByPass JWT decoding.
use option :skip_jwt => true in file where you have configured OmniAuth.
use OmniAuth::Builder do
  provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"],ENV["GOOGLE_CLIENT_SECRET"], skip_jwt: true
end

For More details check Fix Steps By Gem Author

A: Combine with other params if any
provider :google_oauth2, ENV['GOOGLE_KEY'],   ENV['GOOGLE_SECRET'], { access_type: 'online', skip_jwt: true }


text:
Q: Calling RPC success from another RPC success I have done a rpc in my code. On the success side, i have some code as trigger to this rpc call.
I have a second rpc in my code. On the success side of this another call, I want to execute the code that is in the first rpc success side.
Without copying the code that is into the first rpc success, is it any way to call this first successful rpc code from the second rpc success?.
Thank you in advance for your time,
Kind regards,

A: Sure, either put your interesting code in a separate method, e.g.
service.doX(..., new AsyncCallback<String> {
  void onSuccess(String str) {
    awesomeness(...);
  }
});

service.doY(..., new AsyncCallback<String> {
  void onSuccess(String str) {
    awesomeness(...);
  }
});

void awesomeness(...) {
  // magic stuff
}

Or re-use the AsyncCallback:
final AsyncCallback<String> sweetCallback = new AsyncCallback<String> {
  void onSuccess(String str) {
    // magic stuff
  }
}

service.doX(..., sweetCallback);

service.doY(..., new AsyncCallback<String> {
  void onSuccess(String str) {

    if (whatever)
      sweetCallback.onSuccess(str);
  }
}

(Please note, that the code samples are schematic, and missing e.g. the onFailure methods)

A: Thank you for the response and for the time taken answering it. This is what i was looking for and therefore missing. Yes, i understand that the code samples are schematic but very explainable by themselves. :)
Kind regards,


text:
Q: Centering inputs with css and bootstrap 4 I have a form that I want to center on the page. The labels are centered but for some reason, I can't center the input with the form-control class.
It is rendering like this right now...
[EDIT: the display: block; inside form-control is causing the issue. Not sure why, how can I disable it]

#centered {
  text-align: center;
}

Email

            <input class="form-control" id="ex2" type="text">

Name

          <input class="form-control" id="ex2" type="text">

Create A Password

          <input class="form-control" id="ex2" type="text">

Confirm Password

          <input class="form-control" id="ex2" type="text">

        <input class="form-group-check-input" type="checkbox" value="" id="confirm_terms"> Agree to terms

A: You can try to change the display property of all form-control inside that div:
 #centered .form-control {
  display: inline;
}

A: Use the class mx-auto

/* CSS used here will be applied after bootstrap.css */
#centered {
  text-align: center;
  width:100px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Email

            <input class="form-control" id="ex2" type="text">

Name

          <input class="form-control" id="ex2" type="text">

Create A Password

          <input class="form-control" id="ex2" type="text">

Confirm Password

          <input class="form-control" id="ex2" type="text">

        <input class="form-group-check-input" type="checkbox" value="" id="confirm_terms"> Agree to terms