text:
Q: custom marker for vue2-google-maps I am trying to add my own images for a custom marker in vue2-google-maps without success.
I know this is a bug and when I add an :icon="{url:'../assets/my_image'}" in  tag the marker disappears.
Has anyone managed to make it work?

A: Just in case if you like to scale the size of the custom marker to look better in retina screen:
in <template>
<GmapMarker
  v-for="(m, index) in markers"
  :key="index"
  :ref="`marker${index}`"
  :position="m.position"
  :clickable="true"
  :draggable="true"
  :icon="markerOptions" />

in script
const mapMarker = require('~/assets/images/layout/map-marker.png');
data() {
  return {
    markerOptions: {
      url: mapMarker,
      size: {width: 60, height: 90, f: 'px', b: 'px',},
      scaledSize: {width: 30, height: 45, f: 'px', b: 'px',},
    },
  };
},

A: You need to load the image in this case, like this:
:icon="{ url: require('../../assets/img/marker-a.png')}"

An example:
<GmapMarker
  v-for="(m, index) in markers"
  :key="index"
  :ref="`marker${index}`"
  :position="m.position"
  :clickable="true"
  :draggable="true"
  :icon="{ url: require('../../assets/img/marker-a.png')}" />


text:
Q: Distributing the Hodge map over the wedge product Let $(V,\langle,\rangle)$ be a finite dimensional inner product space, $V^{\wedge}$ it exterior algebra, and $\ast$ the Hodge star arising from $\langle,\rangle$. Does there exist any formula to "distribute" the Hodge map over the wedge product. For example, for the de Rham complex we have the Leibniz rule
$$
d(w \wedge v) = dw \wedge v + (-1)^kw \wedge dv?
$$
Is there any analogous formula for $\ast$. I would guess
$$
\ast_H(w \wedge v) = \ast(w) \# v \pm w \,\# \ast(v),
$$
where $\#$ is contraction.

A: I'm surprised this question has been only partially answered until now.  Abel Stern's answer generalizes nicely but it requires thinking about some things that are typically not mentioned in definitions of the Hodge star.  This thread is also a duplicate of https://math.stackexchange.com/questions/605448/the-hodge-operator-and-the-wedge-product which is older.
Let $V$ be a finite-dimensional oriented inner product space.  We think of the $k$-forms on $V$ as the space of alternating $k$-linear functionals $V^k \to \mathbb R$.  The space of $k$-linear alternating functionals on $V$ is denoted by various things, I would like to use the notation $\Lambda^k (V^*)$.  The star is put there to indicate we are talking about real-valued functions.  There is another reason for this notation, in that there is framework where one can talk about abstract wedge and tensor products of abstract vector spaces, and the answer to your question fits naturally in that language.
Precisely, if $V$ and $W$ are vector spaces, and if $f : V \times W \to U$ is a bi-linear function, there exists a unique linear functional $\tilde f : V \otimes W \to U$ factoring a certain canonical bi-linear map $V \times W \to V \otimes W$. This is called the universal property of the tensor product.
If $f : V \times V \to U$ is alternating and bi-linear, the same conclusion holds but replacing $V \otimes W$ with $V \wedge V$.   We denote $V \wedge V$ by $\Lambda^2 V$, and iterate this notation $\Lambda^k V = V \wedge V \wedge \cdots \wedge V$.
So in this language, $\Lambda^k(V^*)$ is canonically identified with the dual space of $V \wedge \cdots \wedge V$.
But now you can ask, is there a conflict of notation?  $V^*$ is a vector space, so $\Lambda^k(V^*)$ could now be given a 2nd meaning -- it is originally the alternating $k$-linear functionals on $V^k$ but it is now also $V^* \wedge V^* \wedge \cdots \wedge V^*$.  The wedge product of $1$-forms gives an alternating $k$-linear functional $V^* \times V^* \times \cdots \times V^* \to \Lambda^k(V^*)$  so by the universal property of wedge products of vector spaces, these two objects are canonically identified.
So now for the next step.  Contraction is typically viewed as a bi-linear operation
$$\Lambda^k(V^*) \times V \to \Lambda^{k-1}(V^*)$$
but clearly it makes sense to consider it as a bi-linear functional
$$\Lambda^k(V^*) \times \Lambda^j(V) \to \Lambda^{k-j}(V^*)$$
We have a canonical isomorphism between $\Lambda^k(V^*)$ and $\Lambda^k(V)^*$ given by the universal property.  Let's denote the isomorphism $V \to V^*$ by $c$.  This induces an isomorphism $\overline{c} : \Lambda^k(V^*) \to \Lambda^k(V)$.
The Hodge star is therefore the map that takes $\omega \in \Lambda^k(V^*)$
and sends it to the contraction:
$$(*\omega) = Det( \overline{\omega}, \cdot) \hskip 1cm \text{ (my notation for contraction)} $$
Where $Det \in \Lambda^{dim(V)}(V^*)$ is the canonical generator of your top-dimensional forms given by the orientation and inner product.
This gives
$$ *(\omega \wedge \eta) = (*\omega)(\overline{\eta}, \cdot) = (-1)^{jk}(*\eta)(\overline{\omega}, \cdot)$$
provided $\omega$ is a $j$-form and $\eta$ is a $k$-form.  So this is close to what you were looking for but there's only the one term.

A: When $w$ is of degree 1, $\ast(v \wedge w) = \iota_{w^\flat} \ast v$ because for the inner product, $\langle w \wedge v, u \rangle = \langle v, \iota_{w^\flat} u \rangle$. This can then be applied repeatedly.
As Ryan Budney explains in far superior detail, the generalization is straightforward. Explicitly, if we define $\iota_{\alpha \wedge \beta} = \iota_\beta \circ \iota_\alpha$ and if we define $w^\flat \in \Lambda^\bullet(V^*) \simeq (\Lambda^\bullet (V))^*$ to be such that $\langle w, u \rangle = w^\flat(u)$, the formula $\langle w \wedge v, u \rangle = \langle v, \iota_{w^\flat} u \rangle $ holds in general, so for all $v,w \in \Lambda^\bullet(V)$,
$$\ast(v \wedge w) = \iota_{w^\flat} \ast v$$
Note, by the way, that the Hodge star does not arise from $\langle,\rangle$ alone: one needs a choice of sign for the volume form.

redpajama_set_name: RedPajamaStackExchange


text: Q: Probability density function of the sum of uniform is a polynomial I have to proof that the pdf of the sum of n uniform in (0,1) it's an n degree polynomial, but I can't use characteristic function or the Irwin-Hall Distribution. I supouse it has to be proven with conditional probability.


text:
Q: How to set style-sheet for the QStacked Widget's page when the page is promoted widget using QT Designer?  QWidget#page
 {
     background-image: url(:/resources/img/NMS_Background.png);
 }

Here, the page is promoted widget as Splash Widget, I have a style-sheet in Splash Widget but I can not access this style-sheet using this code which is defined under the MainWindow style-sheet.

A: Add the stylesheet to SplashWidget directly.
means that select page and RightClick on this and choose change stylesheet and then just write this:
 background-image: url(:/resources/img/NMS_Background.png);

and set checked autoFillBackground option of widget :


text:
Q: How to update the pointer in the calling function? I have a linked list. In the calling function, I created the first node and I passed the pointer of that first node to a function for further processing. The additional nodes are created in that function. But for some reason, during the processing in the function that first node has to be deleted. So in the processing function, the linked list's first node address is changed to the next node. But when return to the calling function, that change is not reflected in the calling function. In the calling function, the linked list's first node is still the deleted first node, how can I update?
Inside calling function:
model_list *allmodelroot;

allmodelroot =  new model_list;
allmodelroot->next = NULL;
allmodelroot->modelIndex = -1;
processfunction(bmodelroot, wmodelroot, settings, featurePts, allmodelroot);

Inside process function;
int processfunction(model_list *bmodelroot, model_list *wmodelroot, set_setting &settings, calib_features &featurePts, model_list *allmodelroot)
{
    model_list *first_allmodelroot = allmodelroot;

    model_list *previous = allmodelroot;
   for(i = 0; i < allmodelrootSize; i++)
   {

       if(usemodel[i] == false)
       {
               //delete the first node
               first_allmodelroot = allmodelroot->next;
               previous = allmodelroot->next;
               delete allmodelroot;
               allmodelroot = previous;

       }else{
          previous = allmodelroot;
          allmodelroot = allmodelroot->next;
       }

   }

   allmodelroot = first_allmodelroot;

}

A: Pass the code a structure representing the linked list itself, not a pointer to the first node in the list. If you have no such structure, I'd say that's a pretty big defect in your code.

A: You should make a full understand about the pointer.
In short words: The pointer itself has an address in memory, but its value is the address of other variable.
#include <stdio.h>
void pointer_test(char *p) {
    printf("p addr \t:%d\n", (int)p);
    p = p + 1;
    printf("p addr \t:%d\n", (int)p);
}
int main() {
    char buf[3] = {'a', 'b', 'c'};
    printf("buf addr\t:%d\n", (int) buf);
    printf("buf[0] addr\t:%d\n", (int) &buf[0]);
    printf("buf[1] addr\t:%d\n", (int) &buf[1]);
    printf("buf[2] addr\t:%d\n", (int) &buf[2]);
    pointer_test(buf);
    printf("buf addr\t:%d\n", (int) buf);
    printf("buf[0] addr\t:%d\n", (int) &buf[0]);
    printf("buf[1] addr\t:%d\n", (int) &buf[1]);
    printf("buf[2] addr\t:%d\n", (int) &buf[2]);
    return 0;
}

In the above example, value of p is the address of buf, address of p is in the stack or just a register.
The address of buf is copped to function pointer_test as the value of p.
Changing the value of p, cannot affect buf for this case.
Output of the above code may be like below:
buf addr        :2686736
buf[0] addr     :2686736
buf[1] addr     :2686737
buf[2] addr     :2686738
p addr  :2686736
p addr  :2686737
buf addr        :2686736
buf[0] addr     :2686736
buf[1] addr     :2686737
buf[2] addr     :2686738

For your case, if you want to modify the value of allmodelroot, model_list **allmodelroot should be used, which means passing the address of pointer allmodelroot. Once you get the original address of pointer allmodelroot, then it's possible to change the value of pointer allmdelroot inside a function.


text:
Q: What do significance tests for adjusted means tell us? Many stats packages allow you to view the adjusted means/marginal means/predicted values of a model (e.g., R's lsmeans, Stata's 'margins', SPSS's 'Estimated Marginal Means'; for more info., see https://www3.nd.edu/~rwilliam/stats/Margins01.pdf).
Marginal means are often presented with a t/z value, a p value, and confidence intervals.
1) Are these one-sample tests?
2) What is their importance? If, for instance, I have a marginal mean which does not reach the threshold of significance, can I still use it to describe my data? What does it mean if it is not significant? (ignore the dubiousness of null hypothesis significance testing for the sake of the question, since they still dominate many journals in the psychological sciences).

A: There is no law that says you have to test anything; you can just report estimates. I suggest including confidence limits as well, and explaining exactly what you are showing.


text:
Q: How to provide efficient collision detection and response for spherical objects and triangular terrain? I've been trying to make efficient collision detection between objects and terrain. The objects are represented by mobile spheres and the terrain is made of static triangles.
So far, I managed to implement a collision algorithm, but it has some major issues:
1. It's very resource-consuming.
2. Collision only works on one side of the triangles.
3. Multiple, simultaneous collisions give bad results.
Below I've put the algorithm that I have. It's based on an article from realtimecollisiondetection.net, and it's using the GLM math library. I've simplified loops, variable names, unnecessary code and class members:
//Class definitions:
class Sphere
{
     public:
     float x;
     float y;
     float z;
     float radius;
     float sqradius;
     float xmov;
     float ymov;
     float zmov;
};
class TriangularWall
{
     public:
     float x[3];
     float y[3];
     float z[3];
     glm::vec3 Normal;
};

using namespace glm;
Sphere Obj;
TriangularWall Wall;
//Assume that the 2 objects above are constructed. I didn't include their constructors because they looked ugly.
float rr=Obj.sqradius;
vec3 A=vec3(Wall.x[0], Wall.y[0], Wall.z[0])-vec3(Obj.x, Obj.y, Obj.z);
vec3 B=vec3(Wall.x[1], Wall.y[1], Wall.z[1])-vec3(Obj.x, Obj.y, Obj.z);
vec3 C=vec3(Wall.x[2], Wall.y[2], Wall.z[2])-vec3(Obj.x, Obj.y, Obj.z);
vec3 V=cross(B-A, C-A);
float d=dot(A, V);
float e=dot(V, V);
float di=d;
float ei=e;
vec3 Ai;
vec3 Bi;
vec3 Ci;
vec3 Vi;
if(!(di*di>rr*ei))
{
      float aa=dot(A, A);
      float ab=dot(A, B);
      float ac=dot(A, C);
      float bb=dot(B, B);
      float bc=dot(B, C);
      float cc=dot(C, C);
      if(!(aa>rr && ab>aa && ac>aa))
      if(!(bb>rr && ab>bb && bc>bb))
      if(!(cc>rr && ac>cc && bc>cc))
      {
            vec3 AB=B-A;
            vec3 BC=C-B;
            vec3 CA=A-C;
            float d1=ab-aa;
            float d2=bc-bb;
            float d3=ac-cc;
            float e1=dot(AB, AB);
            float e2=dot(BC, BC);
            float e3=dot(CA, CA);
            vec3 Q1=A*e1-d1*AB;
            vec3 Q2=B*e2-d2*BC;
            vec3 Q3=C*e3-d3*CA;
            vec3 QC=C*e1-Q1;
            vec3 QA=A*e2-Q2;
            vec3 QB=B*e3-Q3;
            if(!(dot(Q1, Q1)>rr*e1*e1 && dot(Q1, QC)>0)
            if(!(dot(Q2, Q2)>rr*e2*e2 && dot(Q2, QA)>0)
            if(!(dot(Q3, Q3)>rr*e3*e3 && dot(Q3, QB)>0)
            {
                  vec3 ObjectMov=vec3(Obj.xmov, Obj.ymov, Obj.zmov);
                  if(dot(ObjectMov, Wall.Normal)<0)
                  ObjectMov-=dot(ObjectMov, Wall.Normal);
                  Obj.xmov=ObjectMov [0];
                  Obj.ymov=ObjectMov [1];
                  Obj.zmov=ObjectMov [2];
            }
      }
}

For the third issue, I re-made the above algorithm (simply stopping the object on the corresponding axis if a collision still takes place). However, this loads up the program significantly, and doesn't produce that nice effects.
I'm also aware that I could include a few performance tweaks to the algorithm above, but I don't see anything that could improve performance by a significant margin.
I know that I could also use octrees, however they seemed pretty complicated to me and I'm also worried that they could, in some situations, create a lot of latency.
Therefore, is there any way to improve the algorithm I used in order to fix its main issues? Or should I just try to use another one?

A: Assuming that what you call "resource consuming" is too high running-time, the number of triangles must be significant. So the first thing to do is to reduce the number of triangles to be tested against.
You mentioned oct-trees. More generally, a hierarchy of bounding volumes is the way to go. (https://en.wikipedia.org/wiki/Bounding_volume_hierarchy.) Speedups will be tremendous for million triangles. In your particular case, I would probably opt for a binary tree of bounding spheres.

Note that before implementing this, you will already obtain a speedup by precomputing the bounding sphere of every triangle (the center of the sphere is the center of the circumscribed circle, i.e. the intersection of the mediator planes and the plane of the triangle). Then non-intersecting triangles are detected by comparing the distance between the centers to the sum of radii.

Regarding the exact intersection test between the sphere and a triangle, I am afraid that there is no free lunch. Using the "inflating/deflating" method, the center of the sphere can be inside either the right prism over the triangle, one of three truncated cylindres around the edges or one of three spheres around the vertices.
Whatever approach you take, you will have to deal with that complexity of the case analysis.


text:
Q: How to get VS2010 not show useless information in the Methods dropdown? I have an app with a ton of UI components on the form.  As a result, when I drop down the Methods (?) combobox, there are a ton of irrelevant entries.

Is there a setting somewhere that limits the list to actual code constructs (e.g. methods/events/etc...)?

A: Don't know how to do this with the drop down but maybe an extension would help you out.
You could use something like the VS10x Code Map:

The Solution Navigator also groups items by type rather than alphabetically:

A: The only setting I can find that affects the "Navigation Bar" is to hide/show, located in Tools/Options/Text Editor/[Your Language]/General at the bottom under the display heading, "Navigation Bar" check box.
Some ideas:
1) You could define all of your event handlers and additional methods in a subclass, then a single method in your parent class to connect everything up to a private member of the subclass type.  When in the subclass, only the subclass methods would show up in the navigation bar.
2) You could derive a class from your main form class, setting anything you needed to see in the derived class as protected in the base class (such as the event handlers).  This would also effectively filter your navigation bar.
HTH


text:
Q: How can I programatically generate Html on the server, without a third party library? I asked a similar question, but before it got closed as a duplicate I forgot to mention I want to understand how to do this without using a third party library.
How can I dynamically generate Html content with Node.js?
So, how can I programatically generate Html content on the server side using Node.js? (I don't mean sending hard-coded Html, I mean generating it like you would on the client side).
(I have nothing against 3rd party libraries. I prefer to understand Node.js well before learning about libraries on top of it).

A: var http = require('http');
var html = '<!doctype html>
Hello, World!
';

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(html);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

A: Create your webserver listening on whatever port you want, then have it respond to requests to whatever endpoint you want with whatever html you want.
// Include the HTTP Node library
// http://nodejs.org/docs/latest/api/http.html
var http = require('http');

// define the IP and port number
var localIP = "127.0.0.1"; // 127.0.0.1 is used when running the server locally
var port = 8080; // port to run webserver on

function sayHello(req, res) {

    console.log("We've got a request for " + req.url);

    // HTTP response header - the content will be HTML MIME type
    res.writeHead(200, {'Content-Type': 'text/html'});

    // Write out the HTTP response body
    res.write('' +
    '
Hello Dynamic World Wide Web
'+
    '');

    // End of HTTP response
    res.end();

}

/************************/
/*  START THE SERVER    */
/************************/

// Create the HTTP server
var server = http.createServer(sayHello);

// Turn server on - now listening for requests on localIP and port
server.listen(port, localIP);

// print message to terminal that server is running
console.log('Server running at http://'+ localIP +':'+ port +'/');

the above code was taken from https://gist.github.com/johnschimmel/1759465


text:
Q: Your URL pattern [ ] is invalid. DJANGO Urls.py file I am getting this error:
ERRORS:
app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/static/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.

I don't know why I am getting this error. I have correctly added everything in my url patterns
urlpatterns = [
  path("admin/", admin.site.urls),
  path("api/v1/jobs/", include("jobs.urls")),
  path("api/v1/company/", include("company.urls")),
]

if settings.DEBUG:
  urlpatterns.extend(
     [
        static("/static/static/", document_root="/vol/web/static"),
        static("/static/media/", document_root="/vol/web/media"),
        path("__debug__/", include(debug_toolbar.urls)),
    ]
)

A: The function static() returns a list already, not a single pattern. It could be that the list contains a single path element, but it is a list nonetheless.
I suggest you change your code to:
if settings.DEBUG:
    # add multiple paths using 'extend()'
    urlpatterns.extend(static("/static/static/", document_root="/vol/web/static"))
    urlpatterns.extend(static("/static/media/", document_root="/vol/web/media"))

    # add a single path using 'append()'
    urlpatterns.append(path("__debug__/", include(debug_toolbar.urls)))


text: Q: Back button in server side render pages with React My use case is that i have two pages (let's call is A and B) and on those two pages i have two buttons each and each button redirects to the same page (let's call it C). Now, this page C has a back button, so in a server side rendering, with the fact that I can't access the Dom, how should I handle this? I am doing this all in a class component.


text:
Q: docker pull fails (not found) yet "number of pulls" increases I am running docker on CentOS 7 following the official documentation from https://docs.docker.com
When I try to pull a demo image I just created, I got this error:
FATA[0013] Repository not found

The strange thing is that the "Number of Pulls" increases every time I try to pull it. As if every pull is successful.

Every time I get this same error: FATA[0013] Repository not found
So what should I do now?
Lastest Update: Problem solved. Thanks to Jerry Baker, one of the Docker Staff.
Please refer to https://forums.docker.com/t/cant-find-or-pull-public-repos-on-docker-hub/1806/6

UPDATE: I am not running docker under a http_proxy.
UPDATE 2: @user2915097 After I run docker events:

UPDATE 3:
My repo was not even found by docker search:

UPDATE 4:
docker push failed, too.  I've already logged in (by docker login).

A: docker pull wings27/centos-web-dev is not working because it does not have the 'latest' tag. It tries to pull the 'latest' tag by default if you do not provide any tag in your pull command.

A: Login to your docker account before accessing private repos
docker login

A: If it still helps, short answer
docker login
docker tag <image_id> wings27/centos-web-dev:<your-tag>
docker pull wings27/centos-web-dev:<your-tag>


text:
Q: How can I get the index of a property inside a JS object using the property key not the value using Javascript? I am having a simple sample code as follows:
var sampleObj = [{prop1 : ""}, {prop2 : ""}, {propArr : [{key : "", value : ""}, {key : "", value : ""}]}];

This is a JSON Object that has some properties including a property that contains an array.
My Question
I need to use the JS method indexOf() to get the index of [propArr] using the key not the value.
for example
I need a way to implement this:
var index = sampleObj.indexOf(propArr);

A: Use findIndex:

var sampleObj=[{prop1:""},{prop2:""},{propArr:[{key:"",value:""},{key:"",value:""}]}];

const prop = "propArr"

const res = sampleObj.findIndex(e => Object.keys(e)[0] == prop)
console.log(res)

If you strictly need to use indexOf, you can map through the array to extract the first property of each object, then use indexOf:

var sampleObj=[{prop1:""},{prop2:""},{propArr:[{key:"",value:""},{key:"",value:""}]}];

const prop = "propArr"

const res = sampleObj.map(e => Object.keys(e)[0]).indexOf(prop)
console.log(res)


text:
Q: oracle SQL: selecting distinct value where it does not contain another certain value in all its record This is the current database record that I have, and I only want it to display all the name of students who have never been enrolled in Science.
Name        | Subject     | Year
-----------------------------------
Ian Lee     | Math        | 2008
Ian Lee     | Science     | 2008
Ian Lee     | Econs       | 2006
Marie-Ann   | Geography   | 2006
Marie-Ann   | Literature  | 2009
Natalie S.  | Geography   | 2006
Julienne    | Math        | 2008
Julienne    | Science     | 2008
Julienne    | Literature  | 2009
Liam        | Literature  | 2009
Liam        | Econs       | 2006

I also have a student record Emily Toh that has not been enrolled in any classes yet. But the correct output should be
Name
------------
Marie-Ann
Natalie S.
Emily Toh
Liam

This was what I used to call
SELECT DISTINCT en.Name
FROM ENROLLMENT en
WHERE NOT EXISTS (
    SELECT st.Name
    FROM STUDENT st
    WHERE en.Name = st.Name
    AND en.Subject = 'Science'
);

But it still gives me a display of all the student names.
The student table and enrollemnt table is as per:
CREATE TABLE STUDENT(
    Name       VARCHAR2(50),
    DOB        DATE,
    Address    VARCHAR(70),
CONSTRAINT STUDENT_PKEY PRIMARY KEY (Name)
);

CREATE TABLE ENROLLMENT(
    Name       VARCHAR2(50),
    Subject    VARCHAR2(70),
    Year       Number(4),
CONSTRAINT ENROLLMENT_PK PRIMARY KEY (Name, Subject)
CONSTRAINT ENROLLMENT_FKEY FOREIGN KEY (Name) REFERENCES TO STUDENT (Name)
);

A: The approach you made is right, just start with STUDENTS table, and look for the science enrollment using NOT EXISTS.
SELECT  st.Name
FROM STUDENT st
WHERE NOT EXISTS (
    SELECT st.Name
    FROM enrollment en
    WHERE en.Name = st.Name
    AND en.Subject = 'Science'
);

A: One option is to use a subquery to identify all students which you don't want in your result set (i.e. those who were enrolled in Science at some point), and then join to filter off these students.
SELECT s.Name      -- , s.Id
FROM STUDENT s
LEFT JOIN
(
    SELECT Name    -- , Id
    FROM ENROLLMENT
    WHERE Subject = 'Science'
) t
    ON s.Name = t.Name   -- AND s.Id = t.Id
WHERE t.Name IS NULL

This approach will capture both students who are enrolled in no classes and students who enrolled, but never enrolled in Science.
Ideally there should also be an Id column associated with each student in both tables.  Without this, joining in a meaningful way could be difficult if two or more students were to share the same name.

A: If you do not need to worry about students who have not enrolled in any classes then you can use GROUP BY ... HAVING ... like this:
SELECT   name
FROM     enrollment
GROUP BY name
HAVING   COUNT( CASE WHEN subject = 'Science' THEN 1 ELSE NULL END ) = 0;

If you have students who have not enrolled for any classes and you want to include them in your output then:
SELECT   s.name
FROM     student s
         LEFT OUTER JOIN
         enrollment e
         ON ( s.name = e.name AND e.subject = 'Science' )
GROUP BY s.name
HAVING   COUNT( e.subject ) = 0;

Since name and subject are the composite primary key for the table then the GROUP BY and HAVING clauses could be replaced with a subject IS NULL check:
SELECT   s.name
FROM     student s
         LEFT OUTER JOIN
         enrollment e
         ON ( s.name = e.name AND e.subject = 'Science' )
WHERE    e.subject IS NULL;


text:
Q: How to convert Series index into two columns as a DataFrame I have the following Pandas Series:
import pandas as pd
import io
from scipy import stats

test=u"""probegenes,sample1
1415777_at Pnliprp1,20
1415884_at Cela3b,47
1415805_at Clps,17
1115805_at Ckkk,77
"""
df_test = pd.read_csv(io.StringIO(test),index_col='probegenes')
my_series = df_test['sample1']
my_series

It looks like this:
In [62]: my_series
Out[62]:
probegenes
1415777_at Pnliprp1    20
1415884_at Cela3b      47
1415805_at Clps        17
1115805_at Ckkk        77
Name: sample1, dtype: int64

What I want to do is to split the 'probe genes' index so that I get new data frame:
  Probe      Genes      Score
0 1415777_at Pnliprp1    20
1 1415884_at Cela3b      47
2 1415805_at Clps        17
3 1115805_at Ckkk        77

How can I achieve that?

A: You can .str.split(expand=True) on the index after converting to Series, and .concat() the result with the first column:
df = pd.concat([my_series,my_series.index.to_series().str.split(expand=True)], axis=1).reset_index(drop=True)
df.rename(columns={'sample1': 'Score', 0: 'probe', 1: 'genes'})

yields:
     Score       Probe     Genes
0       20  1415777_at  Pnliprp1
1       47  1415884_at    Cela3b
2       17  1415805_at      Clps
3       77  1115805_at      Ckkk

A: df = pd.DataFrame([i.split(" ") for i in my_series.index], columns=['Probe', 'Genes'])
df['Score'] = my_series.values

>>> df
        Probe     Genes  Score
0  1415777_at  Pnliprp1     20
1  1415884_at    Cela3b     47
2  1415805_at      Clps     17
3  1115805_at      Ckkk     77


text:
Q: Why isn't the value of default-only variable added to an outbound URL as part of the query string? Why isn't the value of default-only variable myVar added to outbound URL as part of a query string:
    routes.MapRoute("MyRoute", "{controller}/{action}",
        new { myVar = 1 });

Index.cshtml:
         @Html.ActionLink("click me", "CustomVariable", "Home",
                  new { myVar = 1, newMyVar = 1000 }, null);

From the above routing system generates:
       click me

Thank you

A: In your routing rule you are stating that if the default value is not provided, then use this value.
So there is really no need to provide the value when it is the same as the default value, because it will simply use the default value.


text:
Q: How does -join ";" work? This answer includes a Powershell like of code that splits $env:path, applies a filter and puts the result together, to store it in $env:path.
$path = ($path.Split(';') | Where-Object { $_ -ne 'ValueToRemove' }) -join ';'

I was reading this code, and then, suddenly, a wild -join ';' appears. How does this work? What is the concept behind this? I would expect (<expression) would eventually become some object, but then this like reads <object> -join ';', so the join part would still be some independent token. How is it evaluated? I can see that it obviously does "the right thing", but how and why does it work? How exactly does Powershell evaluate this line? Looks like very dark magic to me.

A: As stated out by the docs the -Join Operator can be used mainly in two ways:
-Join <String[]>
<String[]> -Join <Delimiter>

Most of PowerShells operators work this way (and look similiar to method parameters). You got some values on the left side of an operator and execute an action (in this case joining) with the right-side-token, in your case the semicolon ;.
Take a look at the help (by typing Get-Help <section_name>) sections about_Join and about_Operators
Also a nice example copied from the docs (without the need of splitting beforehand) is:
PS> $a = "WIND", "S P", "ERSHELL"
PS> $a -join "OW"
WINDOWS POWERSHELL

A: To add to Clijsters' answer, it's an operator that acts on a string array (String[]). The character following the operator specifies the character to use to join each element of the array.
To break down the parts:
($path.Split(';')                        # take the *string* $path and split into an *array*.
                                         # do this on the ; character

Where-Object { $_ -ne 'ValueToRemove' }) # exclude the array element which is equal to
                                         # "ValueToRemove"

-join ';'                                # Join the *array* back into a *string*
                                         # Put ";" between each array element.


text:
Q: React sometimes not using updated source files Usually when I make a change in a source code file the server automatically updates. Though occasionally it does not, even if I reload the page, or even close the tab and load fresh from a new blank browser tab. I have to restart the server to finally see the change. I found this out upon changing a console.log message.
Is there a way to ensure that the server is using all of the latest source files without having to restart the server? (ya as I already mentioned usually it does this automatically, but at times it does not.)


text:
Q: What is the Quantum interference? Can someone please explain what is  Quantum interference and how it differs from classical interference

A: Here's the thing. Interference in Classical Physics is shown by waves only. Since waves are spread out in spae-time they tend to propagate along the space with their respective wave vectors. When two waves of slightly different amplitude and frequencies interfere they produce what we call interference effect. That is the waves in phase produce constructive interference and out of phase waves cancel each other out producing destructive interference.
Now whats funny in quantum realm, particles in motion exhibit wave nature.
Know more about matter wave here
When the classical two slit experiment is commenced on electrons(Quantum particles) surprisingly it produced the interference pattern on the screen. This is due to the wave nature of electrons.
So what happens exactly?
So what is it waving? Does the electron spread out in the spatial space and interact with itself? Well no. It's not the physical spread of material particle but the distribution of probability over space and time. The wave of material particle is actually its probability of finding that particle in that space.
The electron interferes with its probability distribution only. That is what happens in quantum interference. The new question arises that from which slit the electron went? To answer this if we install a measuring device at the slits, surprisingly the interference pattern vanish. That means the wave nature is suppressed.
So what do we conclude from it?
Prior to the measurement, the electron goes through every possible way it can to get to the screen, that is, throgh both the slits simultaneously, thus interfering with it's own probability distribution. That is the wave nature and particle nature is suppressed.
After installing the measurement device we measure that either the electron passed through one slit or the other. That is the particle nature and the wave nature is suppressed. So interference pattern vanishes. This is what we call the collapse of wave function.
That is why it is totally different from the classical wave interference. Hope it hepled :)


text:
Q: Java import error when writing code in Netbeans I'm writing some code and I'm getting errors on four different lines saying that packages don't exist. The errors are on lines 7 to 10, which say package org.web3d.x3d.sai does not exist. The code that I have for this project is:
package xj3dtest;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JFrame;
import org.web3d.x3d.sai.Browser;
import org.web3d.x3d.sai.BrowserFactory;
import org.web3d.x3d.sai.X3DComponent;
import org.web3d.x3d.sai.X3DScene;

public class Xj3DTest extends JFrame {

    public Xj3DTest(String title) {

        super(title);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        X3DComponent x3dComponent = BrowserFactory.createX3DComponent(null);

        Browser browser = x3dComponent.getBrowser();

        Component browserComponent = (Component)  x3dComponent.getImplementation();

        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());
        cp.add(browserComponent, BorderLayout.CENTER);

        X3DScene scene = browser.createX3DFromURL(new String[]   {"test.x3dv"});

        browser.replaceWorld(scene);
    }

    public static void main(String[] args) {
        Xj3DTest frame = new Xj3DTest("Xj3D test");
        frame.setSize(640, 480);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

And the code for the test.x3dv is:
#X3D V3.0 utf8

PROFILE Interactive

DEF TS TimeSensor {
  cycleInterval 3
  loop TRUE
}

DEF TG Transform {
  rotation 0 1 0 0
  children Shape {
    geometry Box {}
    appearance Appearance {
      material DEF MAT Material {
        diffuseColor 1 0 0
      }
    }
  }
}

DEF OI OrientationInterpolator {
  key [ 0 0.5 1 ]
  keyValue [
     0 1 0 0
     0 1 0 3.14
     0 1 0 6.28
  ]
}

ROUTE TS.fraction_changed TO OI.set_fraction
ROUTE OI.value_changed TO TG.rotation

The reason why I'm making this little project is because I need to display .x3d files through a Java project. I'm put -Xmx450M -Djava.library.path='F:\Uni\Uni work\Year Three\xj3d-code-12559-trunk\bin' in the project properties VM option and have put all the x3d jars in a library called Xj3D.
When I've written this code. I have the errors on lines 7 to 10 and I don't know why.
EDIT
I've looked through all the Xj3D code trunk file that I have that has got the .jars in but I don't think it has the org.web3d.x3d.sai jar in.
EDIT 2
I've downloaded the org.web3d.x3d.sai and I've put it in the JARS lib folder that I've made in Netbeans. But I'm still getting the errors.
EDIT 3
I've moved things round and I've only used that one jar. I've unzipped the file and used the jar itself and the errors have gone. However, a new problem has occurred while I run the piece of code and it's giving me a NotSupportedException.

A: Google -> org.web3d.x3d.sai -> first link -> find download -> Put it netbeans /lib folder -> Profit


text:
Q: What is a StringIndexOutOfBoundsException? How can I fix it? This is my code:
    private void bringData() {
    final TextView mTextView = (TextView) findViewById(R.id.textView);

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://192.168.4.1:8080/";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    mTextView.setText("Response is: "+ response.substring(0,500));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

It's the default given from the android documentation. I only changed the url.
This is my error message:

java.lang.StringIndexOutOfBoundsException: length=28; regionStart=1;
  regionLength=499
                        at java.lang.String.substring(String.java:1931)
                        at com.example.my.app.MainActivity$2.onResponse(MainActivity.java:50)
                        at com.example.my.app.MainActivity$2.onResponse(MainActivity.java:46)
                        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                        at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                        at android.os.Handler.handleCallback(Handler.java:751)
                        at android.os.Handler.dispatchMessage(Handler.java:95)
                        at android.os.Looper.loop(Looper.java:154)
                        at android.app.ActivityThread.main(ActivityThread.java:6077)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

During debugging I see that at mTextView.setText("Response is: "+ response.substring(0,500)); my message is delivered to me but the textview is never updated and the app crashes.
Specifically, it crashes here inside the Looper.Java file:
finally {
if (traceTag != 0) {
   Trace.traceEnd(traceTag);
}

traceTag is 0.
I read that some string bounds are wrong but I cannot find out how to fix it.

A: Error Message:
    java.lang.StringIndexOutOfBoundsException: length=28; regionStart=1;
    regionLength=499 at java.lang.String.substring(String.java:1931) at
    com.example.my.app.MainActivity$2.onResponse(MainActivity.java:50) at
    com.example.my.app.MainActivity$2.onResponse(MainActivity.java:46) at
    com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60) at
    com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30) at
    com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) at android.os.Handler.handleCallback(Handler.java:751) at
    android.os.Handler.dispatchMessage(Handler.java:95) at
    android.os.Looper.loop(Looper.java:154) at
    android.app.ActivityThread.main(ActivityThread.java:6077) at
    java.lang.reflect.Method.invoke(Native Method) at
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) at
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Error Description
There is an IndexOutOfBound exception occurred in your MainActivity class
Inside second inner class's OnResponse function as shown MainActivity$2onResponse
on line 46 which basically occurred during substring operation in String.java line 1931
which was invoked from StringRequest.deliverResponse at line 60,
which was invoked from StringRequest.deliverResponse at line 30,
which was invoked from ExecutorDelivery.java at line 99,
which intially started from ZygoteInit$MethodAndArgsCaller's run function
and reached up-to main thread of ActivityThread.main=>looper=>handler

Actual Reason
Your code trying to create a substring with
starting index = 0
ending index = 500

though your actual response string length is = 28, so String length is not long enough to create a substring of 500 characters.
Solutions :

*

*Validate length using ternary operator ?:
mTextView.setText("Response is: "+
   ((response.length()>499) ? response.substring(0,500) : "length is too short"));

Note : Ternary operator (?:) is a short expression of if else but it is not a statement mean it cannot occur as an atomic statement as this is INVALID because there is no assignment
((someString.length()>499) ? someString.substring(0,500):"Invalid length");

*if-else enhances the visibility
String msg="Invalid Response";
if(response.length()>499){
    msg=response.substring(0,500);
}
mTextView.setText("Response is: "+msg);

//or     mTextView.setText("Response is: "+response);

What is IndexOutOfBoundsException?

IndexOutOfBoundsException is a subclass of RuntimeException mean
  it is an unchecked exception which is thrown to indicate that an index
  of some sort (such as to an array, to a string, or to a vector) is out
  of range.e.g using List.

as shown in the Documentation

List<String> ls=new ArrayList<>();
      ls.add("a");
      ls.add("b");
      ls.get(3); // will throw IndexOutOfBoundsException , list length is 2

Prevention :
String str = "";
int index =3;
if(index < ls.size())    // check, list size must be greater than index
    str = ls.get(index);
else
    // print invalid index or other stuff

Class Constructor usage with index or string message
public IndexOutOfBoundsException() {
    super();
}

public IndexOutOfBoundsException(String s) {
    super(s);
}

Which are other variations/sub-classes of IndexOutOfBoundsException?

*

*ArrayIndexOutOfBoundsException : This indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array for e.g

int arr = {1,2,3}
int error = arr[-1]; // no negative index allowed
int error2 = arr[4]; // arr length is 3 as index range is 0-2

Prevention :
int num = "";
int index=4;
if(index < arr.length)     // check, array length must be greater than index
    num = arr[index];
else
    // print invalid index or other stuff

*

*StringIndexOutOfBoundsException : This is thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string.

String str = "foobar";       // length = 6
char error = str.charAt(7);  // index input should be less than or equal to length-1
char error = str.charAt(-1); // cannot use negative indexes

Prevention :
String name = "FooBar";
int index = 7;
char holder = '';
if(index < name.length())     // check, String length must be greater than index
    holder = name.charAt(index) ;
else
    // print invalid index or other stuff

Note: length() is a function of String class and length is a associative field of an array.
Why these exception occur?

*

*Usage of Negative index with arrays or charAt , substring functions

*BeginIndex is less than 0 or endIndex is greater than the length of input string to create substring  or beginIndex is larger than the endIndex

*When endIndex - beginIndex result is less than 0

*When input string/array is empty

INFO : It is job of JVM to create the object of appropriate exception and pass it to the place of , where it occurred using throw keyword like or you can also do it manually using throw keyword too.
if (s == null) {
    throw new IndexOutOfBoundsException("null");
}

How can I fix this ?

*

*Analyzing StackTrace

*Validating input string against nullity , length or valid indexes

*Using Debugging or Logs

*Using Generic Exception catch block

1.) Analyzing StackTrace
As shown at the beginning of this post , stacktrace provides the necessary information in the initial messages about where it happen , why it happen so you can simply trace that code and apply the required solution .
for e.g the reason  StringIndexOutOfBoundsException and then look for your package name indicating your class file then  go to that line and keeping the reason in mind , simply apply the solution
It's a head start if you study about the exception and its cause as well in documentation.
2.) Validating input string against nullity , length or valid indexes
In case of uncertainty when you don't know about the actual input like response is coming from server (or maybe it's an error or nothing) or user then it's always better to cover all the unexpected cases though believe me few users always like to push the limits of testing so use input!=null && input.length()>0 or for indexes, you can use the ternary operator or if-else boundary check conditions
3.) Using Debugging or Logs
You can test the running environment of your project in debug mode by adding break-points in your project and system will stop there to wait for your next action and meanwhile you can look into the values of variables and other details.
Logs are just like check-points so when your control cross this point they generate details , basically they are informative messages given by wither system or user can also put logging messages using either Logs or Println messages
4.) Using Generic Exception catch block
Try-catch blocks are always useful to handle RuntimeExceptions so you can use multiple catch block along to handle your possible issues and to give appropriate details
try {
     mTextView.setText("Response is: "+ response.substring(0,500));
} catch (IndexOutOfBoundsException e) {
    e.printStackTrace();
    System.out,println("Invalid indexes or empty string");
}
  catch (NullPointerException e) { // mTextView or response can be null
    e.printStackTrace();
    System.out,println("Something went wrong ,missed initialization");
}
catch (Exception e) {
    e.printStackTrace();
    System.out,println("Something unexpected happened , move on or can see stacktrace ");
}

Further References
What is a NullPointerException, and how do I fix it?


text:
Q: How to get HTTPS response
Possible Duplicate:
How to get a response from a https server using android sdk?

hi,
I am doing a https post and I'm getting an exception of ssl exception Not trusted server certificate. If i do normal http it is working perfectly fine. Do I have to accept the server certificate somehow?

A: try this...
Https Connection Android

A: Can you access that HTTPS URL directly from your web browser? Or do you also get an error in that situation? Access it directly first to ascertain that the certificate is actually valid for that domain.


text:
Q: How to refactor the deprecated method .exchange()? I have next method that uses in AbstractWebClient. How can I refactor it to get rid of deprecated .exchange() and save availability to work in abstract way?

    private ClientResponse executeRequest(WebClient.RequestHeadersSpec<?> spec,
                                          RequestContext requestContext,
                                          String requestBody) {
        logRequest(requestContext, requestBody);
        return spec
                .exchange()
                .blockOptional()
                .orElseThrow(() -> new InternalException(String.format("%s: can't extract response from method \"%s\"", externalServiceName, requestContext.getApiMethodName())));
    }

A: You can use retrieve() method as suggested in exchange() documentation something like below:
return
spec.retrieve().bodyToMono(ClientResponse.class).blockOptional()
                .orElseThrow(() -> new InternalException(String.format("%s: can't extract response from method \"%s\"",
                        externalServiceName, requestContext.getApiMethodName())));


text:
Q: Audio front panel noise? I want to use the front-panel audio connections for my headphones, but when I use it, it makes a static noise like my HDD.
There is no problem with the wires. This sound starts only when Windows starts.
If I am in BIOS, and my HDD is on, when Windows is loading, there is no sound.
I have Windows 7 and I deactivated the Beep from my device manager already.
I have an integrated 5.1 Realtek audio card. My motherboard is Gigabyte GA-H55M-UD2H.
Thank you very much!

A: I don't think the motherboard is to blame.
If your front panel has a USB I/O try to disconnect the USB cable from the motherboard to the front panel. If the static noise is gone try modifying the circuitboard so the ground connectors are no longer connected to the headphone ground pin (HDD use + front panel audio = static noise - Tom's Hardware) (the front panel shares the same ground for USB and audio I/O).

A: My laptop's audio output also has some background noise, only apparent when playing into a big amp or using earbuds.  The fact is, most audio circuits in PCs are practically afterthoughts, not designed to isolate properly from the system's electrical noise, especially integrated chipsets.
Most likely, when you hear no noise, it's before the audio driver has been loaded, and so there's no output at all.
If you want better sound without noise, invest in a good sound card, maybe a Turtle Beach one, or even a good (not a cheap) external USB sound card.


text:
Q: Android Tab Issue throwing up runtime (looks fine to me though) Tabhost throwing up a runtime error - code seems fine to me - but obviously not. I have 2 activities that I want to show in some tabs.
Error

(java.lang.IllegalArgumentException: you must specify a way to create the tab content)

MainActivity
public class MainActivity extends TabActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabHost tabHost = getTabHost();

        // Tab 1
        TabHost.TabSpec tab1 = tabHost.newTabSpec("tab1");
        // setting Title and Icon for the Tab

        tab1.setIndicator("", getApplicationContext().getResources().getDrawable(R.drawable.drawtab1));
        Intent tab1Intent = new Intent(this, Tab1Activity.class);
        tab1Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab1.setContent(tab1Intent);

        // Tab 2
        TabHost.TabSpec tab2 = tabHost.newTabSpec("tab2");
        // setting Title and Icon for the Tab

        tab2.setIndicator("", getApplicationContext().getResources().getDrawable(R.drawable.drawtab1));
        Intent tab2Intent = new Intent(this, Tab2Activity.class);
        tab1Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab1.setContent(tab2Intent);

        tabHost.addTab(tab1);
        tabHost.addTab(tab2);

    }
}

XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/LinearLayout1"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:paddingBottom="@dimen/activity_vertical_margin"
              android:paddingLeft="@dimen/activity_horizontal_margin"
              android:paddingRight="@dimen/activity_horizontal_margin"
              android:paddingTop="@dimen/activity_vertical_margin"
              tools:context="com.example.dawnlp.innertab.MainActivity"
              android:background="#00547d"
              android:textColor="#FFFFFF"

    >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"

            >

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                >

            </TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent"

                >

            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>

Dont think it has anything to do with the other activities I have.

A: change last tab code as :
You are using tab1 instead of tab2 for indicator
 // Tab 2
        TabHost.TabSpec tab2 = tabHost.newTabSpec("tab2");
        // setting Title and Icon for the Tab

        tab2.setIndicator("", getApplicationContext().getResources().getDrawable(R.drawable.drawtab1));
        Intent tab2Intent = new Intent(this, Tab2Activity.class);
        tab2Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tab2.setContent(tab2Intent);


text:
Q: Search Multiple sites with one input field how about when you down vote something you leave a comment on why you down voted so the poster has an idea how they can improve on the way they asked something
So I have an input field like so:
<form action="search.php?do=process" method="post">
 <input type="hidden" name="do" value="process" />
 <input type="hidden" name="quicksearch" value="1" />
 <input type="hidden" name="childforums" value="1" />
 <input type="hidden" name="exactname" value="1" />
 <input type="hidden" name="s" value="$session[sessionhash]" />
 <input type="hidden" name="securitytoken" value="$bbuserinfo[securitytoken]" />
 <input type="text" name="query" tabindex="1001" id="overlay-search" class="no-border overlay-search bg-transparent" placeholder="Search..." autocomplete="off" spellcheck="false" />
</form>

what I'm trying to accomplish is alternative buttons that will search the text in the input on say google.com but I have had no success in finding a solution to this =/
the way I'm trying to get it to work is like:
Not happy with your results? Try searching on google.

I have searched and searched and have found nothing related to this, although I doubt I'm searching the right thing.  Any help in achieving this would be greatly appreciated =)
searches I'm considering on including:

*

*Facebook

*Google

*Bing

*Yahoo

*and more

A: A simple solution will be getting the value of the posted input field and just echoing out .Before that you must add a submit button at the end of your form.
<input type="submit" name="submit" value="Search"/>

And then do something like below in your search.php file.
        <?php
            // Check if the submit button is clicked
            if(isset($_POST['submit'])) {
            // And then do something

                echo 'Not happy with your results?Try searching on google.";

            }
        ?>


text:
Q: How to set up the same Terraform formatting style in VSCode and Intellij I am setting up an environment to develop Terraform in VSCode.
I'm collaborating with another developer, who uses Intellij and I use VSCode.
enter image description here
The red part on the left is the code written in Intellij, and the green part on the right is the code written in VSCode.
I want to set the ESLint to be the same for each other to set a consistent format. How can I do that?
And I already set up setting.json
enter image description here
Now i use extension
HashiCorp Terraform https://marketplace.visualstudio.com/items?itemName=HashiCorp.terraform
Terraform (forked) https://marketplace.visualstudio.com/items?itemName=l2fprod.terraform-fork
Thanks a lot.

A: The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style. This command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability.
https://www.terraform.io/cli/commands/fmt
Rather than changing the formatting in your IDE's you should run the terraform fmt command which will format your code to correct formatting.


text:
Q: Change domain of images that webpack generates for imported images Although my dev server is running on localhost:3000, I have set up my host file to point www.mysite.com to localhost. In my JavaScript, I have code like:
import myImage from '../assets/my-image.jpg'

const MyCmp => <img src={myImage} />

Using Webpack's file-loader, it transforms that import into a URL to the hosted image. However, it uses the localhost path to that image, but I'd like it to use the www.mysite.com domain. I looked at both the publicPath and postTransformPublicPath options for file-loader, but those only appear to allow you to modify the part of the path that comes after the domain.

A: I personally don't like the notion of defining host-information statically in the build output. This is something that should be determined in runtime based on where you actually put your files.
If you are like me then there are two options here.
Both involve you calling a global method that you have defined on i.e. window / global scope.
The purpose of the global method is to resolve the root path (the domain, etc) in runtime.
Define a global method
So lets say you define a method on the global scope somewhere in your startup code like so:
(<any>window).getWebpackBundleRootPath = function (webpackLibraryId) {
   if (webpackLibraryId == null) return throw "OOOPS DO SOMETHING HERE!";

   // Preferably these variables should be loaded from a config-file of sorts.
   if(webpackLibraryId == "yourwebpacklibrary1") return "https://www.yoursite.com/";
   // If you have other libraries that are hosted somewhere else, put them here...

   return "...some default path for all other libraries...";
};

The next step is to configure webpack to call this global method when it tries to resolve the path.
As I mentioned there are two ways, one that manipulates the output of the webpack and one that is more integrated in webpacks configuration (although only for file-loader but I think it should suffice).
It's worth mentioning that you don't need a global method if you only have one bundle or if you host all your bundles in one place. Then it would be enough to use a global variable instead. It should be quite easy to modify the example below to accommodate this.
First option: configure webpack file-loader to call your method when resolving path
This solution will not require something to be done post build. If this fits your need and covers all scenarios I would go for this option.
Edit your webpack config file
var path = require('path');

let config = {
    entry: {
        'index': path.join(__dirname, '/public/index.js')
    },
    output: {
        path: path.join(__dirname, '/dist/'),
        filename: 'index-bundle.js',
        publicPath: 'https://localhost:3000/',
        library: 'yourwebpacklibrary1',
        ...
    },
    module: {
        rules: [{
            // Please note that this only defines the resolve behavior for ttf. If you want to resolve other files you need to configure the postTransformPublicPath for those too. This is a big caveat in my opinion and might be a reason for using second option.
            test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
            use: [{
                loader: 'file-loader',
                options: {
                    outputPath: 'assets/fonts', // The folder where you store your fonts.
                    name: '[name].[ext]',
                    // This is where the magic happens. This lets you override the output of webpack file resolves.
                    postTransformPublicPath: function (p) {

                        // Because of the way webpack file-loader works the input from to this method will look something like this: __webpack_public_path__ + "/assets/fonts/yourfont.ttf"
                        // But we are not interested in using the __webpack_public_path__ variable so lets remove that.
                        p = p.replace('__webpack_public_path__ + ', '');

                        // Return a stringified call to our global method and append the relative path to the root path returned.
                        return `getWebpackBundleRootPath("${config.output.library}") + ${p}`;
                    }
                }
            }]
        },
    },
    ...
};

module.exports = config;

As you might have noticed in the comments in the webpack config file you need to specify the resolve behavior for each file-loader that you add (if someone knows a better way, please let me know). This is why I still use the second option.
Second option: manipulate the output of the webpack in a postbuild step
Example webpack.config.js file
For completeness sake here is an example of a webpack.config.js file that contains the variables used in the postbuild script.
var path = require('path');

module.exports = {
    entry: {
        'index': path.join(__dirname, '/public/index.js')
    },
    output: {
        path: path.join(__dirname, '/dist/'),
        filename: 'index-bundle.js',
        publicPath: 'https://localhost:3000/',
        library: 'yourwebpacklibrary1',
        ...
    },
    ...
}

Create a postbuild.js file
Create a file postbuild.js next to your package.json with the following content:
const fs = require('fs');

// We take the path to the webpack config file as input so that we can read settings from it.
const webpackConfigFile = process.argv[2];

// Read the webpack config file into memory.
const config = require(webpackConfigFile);

// The file to manipulate is the output javascript bundle that webpack produces.
const inputFile = config.output.path + config.output.filename;

// Load the file into memory.
let fileContent = fs.readFileSync(inputFile, 'utf8');

// Replace the default public path with the call to the method. Please note that if you specify a publicPath as '/' or something very common you might end up with a problem so make sure it is unique in the file to avoid other unrelated stuff being replaced as well.
fileContent = fileContent.replace('"' + config.output.publicPath + '"', 'getWebpackBundleRootPath("' + config.output.library + '")');

// Save the manipulated file back to disk.
fs.writeFileSync(inputFile, fileContent, 'utf8');

Call the postbuild.js automatically on build
Next step is to actually call the postbuild.js script after each build.
This can be done in a postscript in package.json like so (in the script section in your package.json):
{
    "scripts": {
        "build": "webpack",
        "postbuild": "node postbuild.js ./webpack.config.js"
    }
}

From now on whenever you run the build script it will also run the postbuild script (from npm or yarn, etc).
You can of course also manually run the postbuild.js script manually after each build instead.

A:
but those only appear to allow you to modify the part of the path that comes after the domain.

Not really, you can give it an URL that includes the domain.
In your case, assuming your images are under the assets directory, you will have something like this in your webpack.config.js
...
module: {
  rules: [
    ...
    {
      test: /\.(png|jpe?g|gif|svg)$/,
      use: {
        loader: 'file-loader',
        options: {
          publicPath: 'https://www.example.com/assets',
          outputPath: 'assets'
        }
      }
    },
    ...
  ]
}
...


text:
Q: Do assembly languages differ among CPUs? I'm interested in learning assembly. Basically I want to know if there are different languages (assembly) between different CPUs. If I had a modern Intel x86 processor, and an Intel x86 processor from a year ago would the assembly code by compatible across those two machines? Could I run that code on both machines without having to learn an entire other book of assembly instructions?

A:
If I had a modern Intel x86 processor, and an Intel x86 processor from a year ago would the assembly code by compatible across those two machines?

Yes, almost certainly.  Silicon vendors try to keep their instruction sets relatively stable in order to make life easier on the compiler writers and software developers in general.  Every once in a while some new instructions crop up, or some old ones stop working.  But it doesn't happen very often, especially on Intel.

Could I run that code on both machines without having to learn an entire other book of assembly instructions?

Again, almost certainly yes.  But there are always exceptions.  You might find the Intel Software Developers Manuals to be interesting reading.

A: Yes and no.
The assemblers for the Linux operating system for wildly differing processors all lean on GNU convention, and so are the same. They "only" differ in the actual CPU instructions. They have the same conventions regarding labels, comment and directives.
Now the opposite view is that the actual CPU instructions are the essential difference between assembler languages. This hinges on the properties of the cpu such as the names of registers and what operations are provided. The description of a modern Intel processor is a multi tome book, running thousands of pages in total. Likewise the description of Risc V is hundreds of pages, and there is no coordination with Intel. For an other processor you can expect an unrelated point of view and even conflicting terms.
If you think this is silly, I can tell you that it is not really less effort to rework an assembler program for Linux from say i86 to arm, than to rework an assembler program for Linux i86 (gas) to MS-Windows i86 (masm). See also an extensive family of non-trivial programs in
https://github.com/albertvanderhorst/ciforth.


text:
Q: Pytest <> Apache airflow ImportError The project structure for airflow looks like this (with init.py in each folder):

/dags
    /dagA.py
    /dagB.py
    /utils
        /custom_operator.py
        ...
/tests
    /test1.py
    ...

The imports within dags look like this:
from utils.A.B import C
Which works fine for airflow, but when running pytest:
python3 -m pytest tests/*
I get import/ModuleNotFound errors within the dags. But when I switch to these imports:
from dags.utils.A.B import C
the pytests run without any errors but I get similar errors in the airflow environment.
How can I run pytest differently so that these import issues do not occur (without changing actual airflow code in the dags)?
I tried relative imports, but that has it's own set of errors when importing from parent directories, and no solution online worked completely (other than some saying to use absolute imports, which brought me back to square one).

A: Move your tests to 'dags' and exclude the tests folder from scanning with .airflowignore


text:
Q: Can not edit font on drawing tool I am simply trying to add some text to a plot via the drawing tool, but it seems the text style options are fixed at some default setting and will not change. You can see in the following picture that I have set totally wild text settings, but they do not show in the text I just entered. Any help?
I am using v.11.2.0 for Linux x86.

A: after you're done inserting the text, select the text by clicking it (text will be surrounded by resizable orange frame), you can use Alt-minus and Alt-plus to make the text smaller or bigger.


text:
Q: How to generate all possible 64 bit random values in java? Does Java SecureRandom.nextLong() return all possible values given it inherits from Random which uses only 48 bits? If not, can I still do it in Java maybe by modifying the Random class and how to do it? I just want to use an all random long number generator where all possible long values can be returned, if possible.

A: While SecureRandom inherits from Random, it doesn't use the same maths or have the same limitation. It will produce all possible 64-bit values eventually.

This class provides a cryptographically strong random number generator (RNG).

This class delegates to one of many possible implementations. You can select one by calling SecureRandom.getInstance(algorithm)
Note: some implementations use entropy in your computer to make the results random, rather than purely pseudo random.

this uses s 48 bit algorighm

SecureRandom doesn't use any of the methods of it's parent e.g.
/**
 * The provider implementation.
 */
private SecureRandomSpi secureRandomSpi = null;

public void nextBytes(byte[] bytes) {
    secureRandomSpi.engineNextBytes(bytes);
}

This method delegates to a completely different implementation.
Related link How to solve slow Java `SecureRandom`? due to using /dev/random


text:
Q: Regular Expression With Mask I have a regular expression for phone numbers as follows:
 ^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$
I have a mask on the phone number textbox in the following format: (___)___-____
How can I modify the regular expression so that it accommodates the mask?

A: The expression for the (placeholder) mask is
^\(_{3}\)_{3}-_{4}$

The expression for a valid phone number is
^\(\d{3}\)\d{3}-\d{4}$

The mask uses _ in place of digits, so you'll need to use [\d_] as your character class to match as the user is typing.
^\([\d_]{3}\)[\d_]{3}-[\d_]{4}$

Obviously, if the user switches fields, you'll want to return an error if your phone field as any remaining _ in it. phone.match(/_/) == null should do the trick here :)

A: Your question is a little unclear; if you want a regular expression that matches that mask, it's:
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

A: ValidationExpression="\([2-9]\d{2}\)\d{3}-\d{4}$|^\(_{3}\)\ _{3}-_{4}$"
This will validate the mask and (234)432-4322 but won't allow the user to enter (434)88_-____

A: this expression will work for you
^[( ][0-9][1-9][0-9][) ]?[0-9]{3}[- ]?[0-9]{4}$
 this expression defines that except second digit of phone number every digit will consider
{0}


text:
Q: key of Container "vanishes" when trying to get its size I am trying to get the size of a container whith a function that typically works. Now it fails according to the debugger because it cannot find the container's key in the widget tree. The error is The method 'findRenderObject' was called on null. Receiver: null I do see the key in getSize() but when stepping into the error throwing line, I find the explanation that it cannot find the widget if null is returned. Any idea why this is so?
import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
 @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget>  {
  GlobalKey _keyScreenContainer = GlobalKey(); // <-------- key declared
   @override
  Widget build(BuildContext context) {
    return SafeArea(
          child: Container(
            key: _keyScreenContainer,         // <--------- key allocated
            width: 20, height: 20,
            child: Text("${getSize(_keyScreenContainer, context)}"),
            )
      );
  }

  Size getSize(GlobalKey _key, BuildContext context) {
    final RenderBox renderBox = _key.currentContext.findRenderObject(); // <---- error
    final boxSize = renderBox.size;
    print (boxSize);
    return boxSize;
  }
}

A: The error is because you are calling the getSize function even before the build is complete. You may call the function once widget layout is complete either in initState with WidgetsBinding.instance
.addPostFrameCallback((_) => someFunction()) or from with something like a button. Please see the code below :
import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
 @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget>  {
  GlobalKey _keyScreenContainer = GlobalKey();

  @override
  void initState(){

            super.initState();

    WidgetsBinding.instance
        .addPostFrameCallback((_) => print("${getSize(_keyScreenContainer, context)}"));

  }
   @override
  Widget build(BuildContext context) {
    return Column(children: [
          Container(
            key: _keyScreenContainer,
            width: 20, height: 20,
            child: Text("abc"),
      ), RaisedButton(onPressed:(){
            print("${getSize(_keyScreenContainer, context)}");

          },child:Text("Get size"))]);
  }

  Size getSize(GlobalKey key, BuildContext context) {
    final RenderBox renderBox = key.currentContext.findRenderObject(); // <---- error
    final boxSize = renderBox.size;
    print (boxSize);
    return boxSize;
  }
}


text:
Q: Python app IAM service account authentication via Cloud SQL Proxy Bug Description
Hi! I'd like to authenticate as a service account to Google Cloud SQL locally using the CloudSQL Proxy.
This is done via a Kubernetes sidecar container pattern with the serviceaccount JSON credentials mounted and in GKE with the workload identity feature.
However whenever I connect to my Cloud SQL postgresql server via the proxy from my app, it still requests a username and password?
My serviceaccount has the following roles: roles/cloudsql.client, roles/cloudsql.instanceUser and roles/cloudsql.connect.
My Cloud SQL database has the IAM permissions flag enabled.
The following does not work and results in the following psycopg2 error:
fe_sendauth: no password supplied

e.g. in Python:
    def getDBConnection(self, dbHost: str, dbPort: int, dbName: str, dbUser: str):
        dbConn = None
        try:
            dbConn = psycopg2.connect(host=dbHost, port=dbPort, database=dbName, user=dbUser)
            dbConn.execute('SELECT 1')
        except Exception as e:
            ...
        return dbConn

I've also tried without user.
Example code (or command)
        imagePullPolicy: Always
        image: gcr.io/cloudsql-docker/gce-proxy:latest
        name: cloudsql-proxy
        command: ['/cloud_sql_proxy', '-instances=xxx:europe-west1:yyy=tcp:3126']

        livenessProbe:
          tcpSocket:
            host: '127.0.0.1'
            port: 3126
          failureThreshold: 5
          initialDelaySeconds: 5
          periodSeconds: 3

        env:
        -
          name: GOOGLE_APPLICATION_CREDENTIALS
          value: /sa.json

        volumeMounts:
        -
          mountPath: /sa.json
          name: sajson
          readOnly: true

        resources:
          requests:
            cpu: 0.5
            memory: 0.5Gi
          limits:
            cpu: 0.5
            memory: 0.5Gi

        securityContext:
          readOnlyRootFilesystem: true
          privileged: false
          runAsNonRoot: true
          allowPrivilegeEscalation: false
          capabilities:
            drop: [all]
          seccompProfile:
            type: RuntimeDefault

How should I authenticate to Cloud SQL via the IAM service account that is assigned to my Pod?
I see examples using username and password authentication but that defeats the point of Workload Identity and IAM service account authentication?

A: You can use Cloud SQL's IAM Database Authentication feature to create a database account that can only be accessed by a specific IAM identity. It's compatible with the Cloud SQL Auth proxy, so you can modify your existing setup to use it with Workload Identity.


text:
Q: How to have a strict order in queued listeners? Is this possible in Laravel? Currently, I'm firing an event, when a user needs to be deleted. For example:
'App\Events\DeleteUserWasCalled' => [
   'App\Listeners\User\DeleteUserImages',
   'App\Listeners\User\RemoveFromMailchimp',
   'App\Listeners\User\RemoveFromStripe',
   'App\Listeners\User\RemoveOffers',
   'App\Listeners\User\UpdateRelatedTablesToNull',
   'App\Listeners\User\SoftDeleteUser',
],

All those listeners are implementing ShouldQueue. But my problem is that the queue is not in the correct order. For example 'App\Listeners\User\SoftDeleteUser' is processed before 'App\Listeners\User\RemoveFromMailchimp'.
RemoveFromMailchimpneeds the user's email but in SoftDeleteUser it is set to Null.
One solution comes into my mind is to use a job class and put everything in one class. But it feels not nice for me.
Any idea how to fix it? The order that I have listed is important (especially the last two listeners)
Edit
class DeleteUserWasCalled
{
    use SerializesModels;

    public $user;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }
}


text:
Q: Android: Adding View inflated from XML Layout to Viewgroup which has not defined any width yet I have a layout problem with my custom viewgroup class.
I call init() in the constructor. In my init() function I inflate the viewgroups layout from an xml file, which contains a LinearLayout to which I add several other views.
I am using spacer (View layout_width="0" and layout_weight="1") to distribute the items equaly.
The problem lies here: the layout still has not defined any width when i add the children. So the spacer all have the size 0, and wont actually place the "line_dot" items equally. How can i somehow update their size?
public class SliderSwitch extends FrameLayout {

...
    public SliderSwitch(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context)
    {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.slider_switch,this);

        sliderLayout = (LinearLayout) findViewById(R.id.sliderLayout);
        labelLayout = (LinearLayout) findViewById(R.id.labelLayout);

        // add one spacer
        View spacer = (View) inflate(context,R.layout.spacer, null);
        sliderLayout.addView(spacer);

        // setup the view depending on how many elements there are
        for (int i=1;i<numberOfElements-1;i++) {

            ImageView lineDot = (ImageView) inflater.inflate(R.layout.slider_switch_line_dot, null);
            sliderLayout.addView(lineDot);

            View spacer = (View) inflate(context,R.layout.spacer, null);
            sliderLayout.addView(spacer);
        }

    }
...
}

this is the xml file for the spacer:
<View
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_weight="1" />

and this is the one for my viewgroup layout
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="3dp"
            android:orientation="horizontal" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/left_bg" />

            <LinearLayout
                android:id="@+id/sliderLayout"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="@drawable/middle_bg"
                android:gravity="center"
                android:orientation="horizontal" >

               <!-- <include layout="@layout/spacer"/> -->

            </LinearLayout>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/right_bg" />
        </LinearLayout>

        <ImageButton
            android:id="@+id/sliderKnob"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="0dp"
            android:background="@null"
            android:src="@drawable/knob" />
    </RelativeLayout>

</LinearLayout>

A: I found the solution now. You have to set the LayoutParams in the code again (even if they are already defined in the xml file), then everything is neatly spaced, how its supposed to. seems to be a bug. But this solution works:
    // add one spacer
    View spacer = (View) inflate(context,R.layout.spacer, null);
    spacer.setLayoutParams(new LinearLayout.LayoutParams(1,LayoutParams.WRAP_CONTENT,1.0F));
    sliderLayout.addView(spacer);

    // setup the view depending on how many elements there are

    for (int i=1;i<numberOfElements-1;i++) {

        ImageView lineDot = (ImageView) inflater.inflate(R.layout.slider_switch_line_dot, null);

        sliderLayout.addView(lineDot);

        spacer = (View) inflate(context,R.layout.spacer, null);
        spacer.setLayoutParams(new LinearLayout.LayoutParams(1,LayoutParams.WRAP_CONTENT,1.0F));
        sliderLayout.addView(spacer);
    }

A: You can call init() on onSizeChanged callback. Remember to set and keep a flag in order to avoid calling it twice, since this callback may run more than once.


text:
Q: Регулярное выражение, пропускающее логины, состоящие только из определённых символов, PHP Пытаюсь написать регулярное выражение на PHP, чтобы пропускало только логины, состоящие из букв русского и латинского алфавита, цифр, символов _-*#!~. и пробела. Запутался с русскими символами [а-я], а также с пробелом (использовал модификатор x)
Вот моё регулярное выражение:
if (!preg_match('/^[а-яa-z0-9_-]+$/ix', $login))
   $errors[] = 'Недопустимые символы в имени';

Тут, конечно, не все разрешённые символы. Подскажите, пожалуйста!

A: Дополненный ответ из комментариев:
$login = "Vova_#! .Putin~";
if (!preg_match('/^[\s*\#!\~\.А-Яа-яЁёA-Za-z0-9_-]+$/i', $login)) {
  echo 'Недопустимые символы в имени';
}


text:
Q: Text nodes in XQuery Creating a text node in XQuery is done like so
text { 'foo' }

Can someone explain the syntax here? Is a function being invoked? If so, I would expect to see text('foo').

A: That's a computed constructor; XQuery syntax for creating nodes. The same syntax works for creating (for example) elements and attributes:
element hello {
  attribute target { "world" }
}

See The XQuery spec for full details.


text:
Q: PHP get the table data row input value using loop I am having a issue in getting the correct value from the table.
The issue I encountered:

*

*When I choose the second checkbox the and input a quantity, it is Undefined offset: 0
But the value of the checkbox is working and correct.
What I am expecting is when I choose the second or other checkbox (exclude first checkbox), I should get the value of that input field.
HTML
<?php foreach($results as $row) { ?>

    <input type="checkbox" name="products[]" value="<?php echo $row->items_id; ?>">
    <?php echo $row->item_name; ?>
    <input type="number" name="quantity[]" class="form-control">

<?php } ?>
<input type="submit" name="process" class="btn btn-primary" value="Process">

PHP
$quantity = $_POST['quantity'];
$products = $_POST['products'];
$count_selected = count($products);

for($i=0; $i< $count_selected; $i++){
    var_dump($quantity[$i]); exit;
}

A: The problem with checkboxes is that an unchecked one submits no value so your $_POST['products'] and $_POST['quantity'] arrays may have different lengths.
I'd combine using a hidden input with specific array indexes.
For example
<?php foreach($results as $row) : ?>

        <input type="hidden" name="products[<?= $row->items_id ?>]" value="0">
        <input type="checkbox" name="products[<?= $row->items_id ?>]" value="1">

    <?= htmlspecialchars($row->item_name) ?>
    <input type="number" name="quantity[<?= $row->items_id ?>]" class="form-control">

<?php endforeach ?>

Then the arrays will have the same indexes and you can iterate them with a foreach
foreach ($_POST['products'] as $itemId => $checked) {
    // $checked represents the state of the checkbox
    // you can access quantity via $_POST['quantity'][$itemId]
}

You could even create a nice filtered array of quantities via
$selections = $_POST['products'];
$quantities = array_filter($_POST['quantity', function($itemId) use ($selections) {
    return $selections[$itemId];
}, ARRAY_FILTER_USE_KEY);

A: first, define array variable.
    $products =array( );
    $quantity=array( );
other wise every thing seems fine.


text:
Q: Java unable to read variables from pom I have the following line in my maven.properties file.
   MY_VARIABLE = www.google.com

My pom file code looks like this
    <build>

    <pluginManagement>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.16</version>

                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>read-project-properties</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>**/*Test*.java</include>
                                <include>**/*Tests*.java</include>
                                <include>**/Test*.java</include>
                            </includes>
                            <files>
                                <file>src/test/resources/maven.properties</file>
                            </files>

                            <systemPropertyVariables>
                                <message>${MY_VARIABLE}</message>
                            </systemPropertyVariables>

                        </configuration>
                    </execution>
                </executions>

            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.16</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

And finally i have a piece of code to retrieve the value in the message variable.
   public static String getMsg()
   {
      final String msg = System.getProperty("message");
      if (StringUtils.isEmpty(msg) || url.startsWith("${"))
      {
          return "Empty message";
      }
      return msg;
   }

So when i am calling the getMsg() method, it always returns the value of msg as Empty Message.
Is it some error in the pom.xml declaration or is it some problem in the getMsg() function that is being used.
It would be nice of someone could throw some light on this.
Thanks in advance ....

A: If I'm not mistaken, you need to use the following syntax
<properties>
  <message>${MY_VARIABLE}</message>
</properties>

systemPropertyVariables are for the Surefire pluging, for unit testing

A: I faced this problem some time ago. I don't know if it is a failsafe/maven bug or limitation. The solution I found was to set the variable as a VM argument. Here is how it currently works for me:
Update you pom as follows:
                   <plugin>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <version>2.17</version>
                        <configuration>
                            <argLine>-DMY_VARIABLE=${MY_VARIABLE}</argLine>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>test</phase>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

Then, you can invoke maven to get your integration tests running as follows:
    mvn integration-test -DMY_VARIABLE=www.google.com

A: Thanks Guys for helping ..
I found a way to get this done.
Before i start the tests, in my java file i am using
 System.setProperty("message" , "welcome message");

And this is finally printing out the value instead of null.
Cheers


text:
Q: when there are 2 array results in sql and each result containing 5 answers..then how to compare the 2 arrays element by element.? here "user" is a table name and a_i are the answers to the 5 questions answered in the quiz...
now if i want to compare these two results like comparing the ans1  of the user 1 and user 2 what is the code i need to write...
basically what i am thinking of is i will store all the coorrect answers in the users table under the user_id=1 and when other users play the quiz i will
manage to store the results in the same table.. while evaluating i will compare the every user with user_id=1.... so now how to compare....
$sql="select a_1,a_2,a_3,a_4,a_5  from
                   users
           where user_id=1";
$result1=mysql_query($sql);
$sql="select a_1,a_2,a_3,a_4,a_5  from
                   users
           where user_id=2";
$result2=mysql_query($sql);

A: Do a self join on the user table and use aliases like so
    FROM USER answer, USER contestant
   WHERE answer.id = 1
     and contestant.id = 2

Then use the If function in your select clause to output correctness such as
SELECT IF(answer.a_1 = contestant.a_1, 'Yes', 'No') as A_1_Successful

This should allow you to reduce your sql calls.

A: You're almost there.  You can now do this:
compare($result1[a_1], $result2[a_1]);

The compare function can be done any way you need.