text:
Q: action not dispatching react native, state is coming out fine I am unable to dispatch an action to reducer.
State comes out just fine. Not sure where I have gone wrong.
For other user reducer, dispatch works just fine. my project has nested drawer navigation > tabs navigation > stack navigation and current page is the 3rd stack screen. Not sure if that is the issue or what.
Store.js
import { combineReducers, createStore } from '@reduxjs/toolkit';
import cartReducer from './cartSlice';
import userReducer from './userSlice';

const rootReducer = combineReducers({
    userReducer: userReducer,
    cartReducer: cartReducer,
})

const configureStore = () => createStore(rootReducer)

export default configureStore

cartSlice.js
const initialState = {
    cart: [{ key: 1, data: { freq: 'Daily', duration: 30 } }]
}

const cartReducer = (state = initialState, action) => {
    switch (action.types) {
        case "ADD_TO_CART":
            console.log(action)
            return {
                ...state,
                cart: [...state.cart, { key: 2, data: action.data }]
            }

        case "REMOVE_FROM_CART":
            const idx = state.cart.map((cartItem) => (
                cartItem.key === action.id
            ))

            const tempNewCart = [...state.cart]
            if (idx >= 0) {
                tempNewCart.splice(idx, 1)
            }
            return { ...state, cart: tempNewCart }

        case "CLEAR_CART":
            return {
                ...state,
                cart: []
            }
        default:
            return state
    }
}

export default cartReducer

SubscriptionQuantity Component
const mapStateToProps = (state) => {
    console.log(state)
    return {
        cart: state.cartReducer.cart
    }
}

const mapDispatchToProps = (dispatch) => {
    // console.log(dispatch)
    return {
        addtoCartStore: (freq, duration) => dispatch({
            type: 'ADD_TO_CART',
            data: {
                freq: freq,
                duration: duration
            }
        })
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(SubscriptionQuantity)

function call for dispatch
const addtoCart = () => {
addtoCartStore('Alternate', 30)
navigation.navigate("CartScreen")
}

A: The issue was with the switch statement!!!!
it should be switch(action.type) not action.types. that's why it was going in on the default route. changed the typo and works fine now.!


text:
Q: error: 150 en foreign key Al momento de crear esta tabla en mi database
me sale el siguiente error:

error: 150 "foreign key constraint is incorrectly formed"

¿Cuál es el problema?
create table iddistrito(
disnom varchar(30)
);

create table idcargo(
cargonom varchar(20)
);

create table idempleado(
nombres varchar(30),
apellidos varchar(30),
direccion varchar(30),
telefono char(9),
dni char(8),
sexo char(1),
estadocivil char(1),
sueldo FLOAT(5),
correo varchar(30),
disnom varchar(30),
cargonom varchar(20),
foreign key(disnom)
references iddistrito(disnom),
foreign key(cargonom)
references idcargo(cargonom)
);

A: *

*Tu referencia de FOREIGN KEY debe apuntar a una columna en otra tabla que este declarada de forma explícita como PRIMARY KEY

*Declara a las columnas disnom y cargonom como llaves primarias

Tus primeras 2 tablas deberían verse de este modo:
create table iddistrito(
disnom VARCHAR(30) PRIMARY KEY
);
create table idcargo(
cargonom VARCHAR(20) PRIMARY KEY
);

*

*Como punto final recomiendo que a tus llaves foráneas les asignes un nombre de tal modo que sean identificables; así:

Código
CONSTRAINT fk_idempleado_iddistrito FOREIGN KEY(disnom) references iddistrito(disnom),
CONSTRAINT fk_idempleado_idcargo FOREIGN key(cargonom) references idcargo(cargonom)

Tu script completo debería verse así:
create table iddistrito(
disnom VARCHAR(30) PRIMARY KEY
);
create table idcargo(
cargonom VARCHAR(20) PRIMARY KEY
);

create table idempleado(
nombres varchar(30),
apellidos varchar(30),
direccion varchar(30),
telefono char(9),
dni char(8),
sexo char(1),
estadocivil char(1),
sueldo FLOAT(5),
correo varchar(30),
disnom VARCHAR(30),
cargonom VARCHAR(20),
CONSTRAINT fk_idempleado_iddistrito FOREIGN KEY(disnom) references iddistrito(disnom),
CONSTRAINT fk_idempleado_idcargo FOREIGN key(cargonom) references idcargo(cargonom)
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closest plane to a point I'm working with a set of planes and a set of 3D points.
I want to find the closest plane to each one of the points in my set.
Right now I compute the disance of one point to each of the planes in my plane set and decide wich one is the closest, then I repeat the same process for every point in my point set. This works fine, but the computational cost depends a lot of the number of planes I have, so if I add more planes (usually I work with more than 500 planes) the processing time increase a lot.
Is there a more effcient way to know the closest plane to a point without having to compute the distance to each of the planes?
I'm implementing this using C++ and VTK libraries
The planes are precomputed using information from a 3D tracker and the points are defined by the user.
This block of code computes the point coordinates (voxel) and calls DistanceToPlane to calculate the distance from the voxel to all the planes. After running this the vnl_vector distances should have the closest plane to each point in the poin cloud.
vnl_vector<double> distances;

for(int i=0; i<volumeSize[0]; i++){

std::cout<<"."<<std::flush;

for(int j=0; j<volumeSize[1]; j++){
    for(int k=0; k<volumeSize[2]; k++){

        double voxel[3];
        voxel[0] = i*scale[0]*resolution + volumeOrigin[0];
        voxel[1] = j*scale[1]*resolution + volumeOrigin[1];
        voxel[2] = k*scale[1]*resolution + volumeOrigin[2];

        double distance = maxDistance;

        for(int plane=0; plane<volumeImageStack.size(); plane++){

            double d = imagePlaneStack.at(plane)->DistanceToPlane(voxel);

            if(d<distance)
                 distance = d;

        }

        distances.push_back(distance);
}

The DistanceToPlane() function computes the distance from a point to one plane, this function is called N time (N = number of planes) for each point.This function is implemented in the VTK library.
Thanks

A: UPDATE Updated the algorithm to work with any arbitrary planes
I was also looking for the solution to the exact same problem.
The solution requires a limited search space (min/max x/y/z). It is a 3D space partitioning data structure which you can query for closest planes more easily.
Pre-compute the partitioning data:

*

*Divide the search space into X/Y/Z buckets (choose the size reasonably, eg. 1/20 of the the given dimension - this gives you 8000 buckets).

*Now, to each each bucket we assign candidate planes to measure against if the point is inside this bucket.

*

*First assign all the planes that intersect the bucket as candidates.

*Now, for each plane that does not intersect the bucket, compute projections of the bucket corners (8 projections)

*Now, for each such plane check if any other plane is between  all the projections and the bucket (such plane is full covered by the other plane).

*Now, add all planes that are not covered to the bucket candidates.

Now the query part. Given a point:

*

*Find the bucket the point belongs to.

*Query linearly only the candidate planes in the bucket.

To understand this algorithm better, try following it on paper for a 2D equivalent (a rectangle surrounded and intersected by multiple lines).
Checking only for corner projections guarantees that a projection of any point inside the bucket will also be contained inside the projection area. If all vertices of the area are covered, so is the entire area.


text:
Q: Send POST request to Rest WS with JS Im trying to send a REST request to a WCF Service with javascript.
I have tried the service with a .net client and it works fine
this is my example method in the wcf service:
[OperationContract]
[WebInvoke(Method="POST",
   ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
bool GuardarJuan(Persona persona);

From javascript i have tried these methods:
function sendRequest3(){
var datos='{"IdPersona":2,"Nombre":"David BQ"}';
var parameters = JSON.stringify(datos);
        var req=$.ajax({
            url: 'http://localhost:8732/Design_Time_Addresses/RestTEST/GuardarJuan',
            type: 'POST',
            data: parameters,
            contentType: 'application/json',
            dataType: 'jsonp'
        });
    }

And also like this:
function sendPost(){
    var url = "http://localhost:8732/Design_Time_Addresses/RestTEST/GuardarJuan";
    var persona={
        IdPersona: 2,
        Nombre: 'David BQ'
    };
    var parameters = JSON.stringify(persona);
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");
    xmlHttp.send(parameters);
    xmlHttp.onreadystatechange= function X()
        {

             if(xmlHttp.readyState == 4)
             {
                  alert(xmlHttp.responseText);
             }
        }

but none of this work.
It always give me a 405 error Method not allowed or 0x80004005 (NS ERROR FAILURE)
Thanks
EDIT:
Problem solved.. It was the cross-domain problem.
I was doing it with the VS Server, so I changed to IIS and everything worked fine

A: First, is the "Service" on the same domain as the page you are attempting to talk to the service with?
Second, if you are attempting to use JSONP, you can only use "GET" not "POST" as JSONP simply creates a <script src="service...?callback=somerndmethod"> that wraps the response in somerndmethod(response) ... which executes your expected code.
You may need to use IIS/IISExpress and have both the main, and wcf application on the same host:port.


text:
Q: Menu and Text over a banner image, responsive I'm creating a webpage but I am having some problems with responsiveness.
Right under my logo, there is a large image. (1000 by 550 px) Over that image, I want to place a menu - and I think I've worked that out with position: absolute. However, I want to use an introduction text, and I cant figure out how to do that.
Could I just use a TextBox with absolute and z-index?  Otherwise, how can I add the image as a background image and make it responsive?

A: background-size: 100%;

That would make your background image responsive. But only if the container itself is responisve though. A more exact answer would require a fiddle or at least some html and css.


text:
Q: compiling a list using select elements from an external file in python okay, so I have 2 external files (GirlNames.txt and BoyNames.txt). Each file is a list of an entry number and a name.
example:
1.  Michael
2.  Ken
3.  Rebecca

About 300 names in total between the two files. I want to take the files, process them so that at the end of the process I have a single list of just names like so:
names = ['Michael','Ken','Rebecca']

I can see that in order to do this I need to open each file, read each line, and then pass that line to a list. using .split(.) will give me a series of lists formatted with the entry number at [0] and the name at [1]. Okay, so then I can just remove the first index value, and add the value to the final list.
So this is what I have come up with so far (just working with one file for the moment):
file_xy = open("BoyNames.txt", "r")
for aline in file_xy:
    value = aline.split('.')
    entry = value.pop(0)
    file_xy.append(entry)
print(file_xy)

Now quickie clarification because I'm not totally sure pop() is the right method for this. The explanations I found for it were somewhat contradictory. Does pop() remove the value from the index but leave the index effectively blank, or does it remove the index? I've found explanations that suggest either. If it doesn't remove the index, what method does? I tried every variant of del I could think of and every one threw up an invalid syntex error.
The particular error I can recieving at this point is:
Traceback (most recent call last): File "Names-7.py", line 20, in <module>
file_xy.append(entry)
AttributeError: '_io.TextIOWrapper' object has no attribute 'append'

did I pass entry incorrectly? If so, how do I need to pass it?

A: You are treating file_xy like a list, which it isn't. Instead you should declare a new list and append to it like so:
out_list = []
for aline in file_xy:
    value = aline.split('.')
    entry = value[0] #no reason to use pop here since value isn't used afterwards
    out_list.append(entry)
print(out_list)


text:
Q: References for Stiefel-Whitney class of Stiefel manifolds and Grassmannians Let $M$ be a manifold. The total Stiefel-Whitney class of $M$ is defined to be the Stiefel-Whitney class of the tangent bundle $TM$
$$
w(M)=1+w_1(TM)+w_2(TM)+\cdots
$$
I want to find references for
$$
w(SO(n)/SO(k)),(i.e. w(V_{n-k}(\mathbb{R}^n))), \\
w(U(n)/U(k)),(i.e. w(V_{n-k}(\mathbb{C}^n))), \\
w(Sp(n)/Sp(k)),(i.e. w(V_{n-k}(\mathbb{H}^n))),\\
w(SO(n)/(SO(k)\times SO(n-k))),(i.e. w(G_{n-k}(\mathbb{R}^n))), \\
w(U(n)/(U(k)\times U(n-k))),(i.e. w(G_{n-k}(\mathbb{C}^n))), \\
w(Sp(n)/(Sp(k)\times Sp(n-k))),(i.e. w(G_{n-k}(\mathbb{H}^n))).
$$
Which ones of the above are known? Where could I find these formulas?

A: The Stiefel manifolds are all parallelizable for $n-k\ge2$, so their total Stiefel-Whitney classes are equal to $1$. A reference is Theorem 3.1 of this paper by Kee Yuen Lam.
For the finite Grassmannians, things are a little more complicated. In the complex and symplectic cases you should be able to calculate these using the Wu formula. Partial results on the normal Stiefel-Whitney classes $\bar{w}(G_{n-k}(\mathbb{R}^n))$ are scattered throughout the literature, a recent reference being
Korbaš, J.; Novotny, P. On the dual Stiefel-Whitney classes of some Grassmann manifolds. Acta Math. Hungar. 123 (2009), no. 4, 319–330.
This article and the articles it references are content with showing non-triviality of some normal SW-class in order to deduce non-immersion results, and do not give formulae for $w(G_{n-k}(\mathbb{R}^n))$.
Most of the methods seem to use the vector bundle isomorphisms
\begin{align*}
T(G_{n-k}(\mathbb{R}^n)) & \cong \operatorname{Hom}(\gamma_k,\gamma_{n-k})\\
                          & \cong \gamma_k^*\otimes \gamma_{n-k} \\
                          & \cong \gamma_k\otimes \gamma_{n-k}\end{align*}
and the splitting principle.

A: In this note, the first two Stiefel-Whitney classes of unoriented, oriented, and complex grassmannians are determined in terms of the Stiefel-Whitney classes of their tautological bundles. This is achieved via the method mentioned at the end of Mark Grant's answer.
For the unoriented grassmannian $\operatorname{Gr}(m, m+n) = O(m+n)/(O(m)\times O(n))$, we have
\begin{align*}
w_1(\operatorname{Gr}(m, m+n)) &= (m + n)w_1(\gamma)\\
w_2(\operatorname{Gr}(m, m + n)) &= \left[\binom{m}{2} + \binom{n}{2} + m^2 + mn - 1\right]w_1(\gamma)^2 + (m^2 + n^2)w_2(\gamma)\\
&= \begin{cases}
0 & m - n \equiv 2 \bmod 4\\
w_2(\gamma) & m - n \equiv 1 \bmod 4\\
w_1(\gamma)^2 & m - n \equiv 0 \bmod 4\\
w_2(\gamma) + w_1(\gamma)^2 & m - n \equiv 3 \bmod 4.
\end{cases}
\end{align*}
For the oriented grassmannian $\operatorname{Gr}^+(m, m+n) = SO(m+n)/(SO(m)\times SO(n))$, we have
\begin{align*}
w_1(\operatorname{Gr}^+(m, m + n)) &= 0\\
w_2(\operatorname{Gr}^+(m, m + n)) &= \begin{cases}
0 & m - n \equiv 0 \bmod 2\\
w_2(\gamma_+) & m - n \equiv 1 \bmod 2.
\end{cases}
\end{align*}
For the complex grassmannian $\operatorname{Gr}^{\mathbb{C}}(m, m + n) = U(m + n)/(U(m)\times U(n))$, we have
\begin{align*}
w_1(\operatorname{Gr}^{\mathbb{C}}(m, m + n)) &= 0\\
w_2(\operatorname{Gr}^{\mathbb{C}}(m, m + n)) &= (m + n)w_2(\gamma_{\mathbb{C}}).
\end{align*}
As for the quaternionic grassmanian $\operatorname{Gr}^{\mathbb{H}}(m, m + n) = Sp(m + n)/(Sp(m)\times Sp(n))$, it is $2$-connected, so $w_1(\operatorname{Gr}^{\mathbb{H}}(m, m + n)) = 0$ and $w_2(\operatorname{Gr}^{\mathbb{H}}(m, m + n)) = 0$.
In principle, you can calculate all of the Stiefel-Whitney classes using the splitting principle argument, but the calculations get more and more complicated. A short cut for the third Stiefel-Whitney class is to use the fact that $\operatorname{Sq}^1(w_2) = w_3 + w_1w_2$. It follows that we have
\begin{align*}
w_3(\operatorname{Gr}(m, m + n)) &= \begin{cases}
0 & m - n \equiv 0, 2 \bmod 4\\
w_3(\gamma) & m - n \equiv 1 \bmod 4\\
w_3(\gamma) + w_1(\gamma)^3 & m - n \equiv 3 \bmod 4
\end{cases}\\
& \\
w_3(\operatorname{Gr}^+(m, m + n)) &= \begin{cases}
0 & m - n \equiv 0 \bmod 2\\
w_3(\gamma_+) & m - n \equiv 1 \bmod 2
\end{cases}\\
& \\
w_3(\operatorname{Gr}^{\mathbb{C}}) &= 0\\
& \\
w_3(\operatorname{Gr}^{\mathbb{H}}) &= 0.
\end{align*}


text:
Q: What is muieblackcat? I've recently installed ELMAH on a small .NET MVC site and I keep receiving error reports
System.Web.HttpException: A public action method 'muieblackcat' was not found on controller...

This is obviously an attempt to access a page that doesn't exist.  But why are there attempts to access this page?
Is this an attack or is it simply a bot scanning to see if I've been infected?  What exactly is 'muieblackcat' and why is there an attempt to access this URL?

A: I do it another way - redirect them on theirs IP on the same URI. Somethig like this:
redirect301 = http://hackerIP/muieblackcat

I think it's easier for the server to send a 301 redirect than to return a 404 page each time.

A: According to Daily Update Summary 6/24/2011 (Emerging Threat Pro blog), it's a scanner which is looking for some breaches in your server; it's definitely an intruder that you should block. Look for your access logs, you should get its IP address.

A: It is just a hole finder script. The requests made are typically the following ones, if your servers answers all with a 404 error, you do not have anything to worry about.
111.221.1.140 - - [20/Nov/2013:10:15:56 +0000] "GET //xampp/phpmyadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:55 +0000] "GET //websql/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:55 +0000] "GET //web/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:54 +0000] "GET //web/phpMyAdmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:53 +0000] "GET //typo3/phpmyadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:51 +0000] "GET //scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:50 +0000] "GET //pma/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:49 +0000] "GET //phpmyadmin2/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:48 +0000] "GET //phpmyadmin1/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:47 +0000] "GET //phpmyadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:47 +0000] "GET //phpadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:46 +0000] "GET //phpMyAdmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:45 +0000] "GET //phpMyAdmin-2/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:44 +0000] "GET //phpMyAdmin-2.5.5/index.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:44 +0000] "GET //phpMyAdmin-2.5.5-pl1/index.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:43 +0000] "GET //php-my-admin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:42 +0000] "GET //mysqladmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:41 +0000] "GET //mysql/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:41 +0000] "GET //myadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:40 +0000] "GET //dbadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:39 +0000] "GET //db/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:38 +0000] "GET //admin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:37 +0000] "GET //admin/pma/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:36 +0000] "GET //admin/phpmyadmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:35 +0000] "GET //MyAdmin/scripts/setup.php HTTP/1.1" 404 1787 "-" "-"
111.221.1.140 - - [20/Nov/2013:10:15:34 +0000] "GET /muieblackcat HTTP/1.1" 404 1787 "-" "-"

A: muieblackcat is script/bot, supposedly of Ukrainian origin, that attempts to exploit PHP vulnerabilities or misconfigurations. See SUC027: Muieblackcat setup.php Web Scanner/Robot for more detail.
If you are not using PHP and have deactivated mod_php, you're safe. However, a request for
/muieblackcat may mean that the bot has already, maybe successfully, visited your site. I
suggest you carefully check your configuration and web content (if possible, erase all and reinstall
from a trusted source set).
On the other hand, the originating IP address is likely to be useless. Most attacks come
from unaware infected Windows users.


text:
Q: Add pound sign to jquery range slider I have a jQuery range slider on my site, when it hasn't yet been used the £ signs show. But the moment you change the value by using the slider the £ signs are removed. Any way to get them to stay?
Here is the code so far:
JavaScript

HTML

Price Range: £<?php echo $priceFrom; ?> - £<?php echo $priceTo; ?>

         <input type="text" id="priceFrom" name="priceFrom" style="display:none;"/>
        <input type="text" id="priceTo" name="priceTo" style="display:none;"/>
         <input type="submit" class="btn btn-mini btn-success" id="priceGo" value="Search">

Live URL - http://bit.ly/Iol1jG

A: You must add the pound sign to the spans in the slide event as it follows:
$("#slider-range").slider({
    range: true,
    min: <?php echo $rootPriceFrom; ?>,
    max: <?php echo $rootPriceTo; ?>,
    values: [<?php echo $priceFrom; ?>, <?php echo $priceTo; ?>],
    slide: function(event, ui) {
        $("#priceFrom").val(ui.values[0]);
        $("#priceTo").val(ui.values[1]);
        $("#rangeval").html("£"+ui.values[0]+" - £"+ui.values[1]); //edited part
    },
    stop: function(event, ui) {
        //alert('a');
        $("#priceGo").click();
    }
});

A: try something like this
    $( "#slider-range" ).slider({
        orientation: "vertical",
        range: true,
        values: [ 17, 67 ],
        slide: function( event, ui ) {
        $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
        }
    });

REFERENCE
http://jqueryui.com/slider/#range-vertical
for your code it will be like FIDDLE
        slide: function( event, ui ) {
            $("#spanPriceFrom").html("£" + ui.values[0]);
            $("#spanPriceTo").html("£" + ui.values[1]);
        }


text:
Q: MeteorJS and Mongo: Initial collection count is always 0 I have a self project of creating sudoku grid using meteor js. In this code, i try to fill in the database first before initialising the template and the template will just read from the database for existing values. below is my code for client side js:
Cells = new Mongo.Collection("cells");

if(Meteor.isClient) {
  Session.setDefault("colMax", 9);
  Session.setDefault("rowMax", 9);

  Meteor.startup(function() {
    for(var i = 0; i < Session.get("rowMax"); i++) {
      for(var j = 0; j < Session.get("colMax"); j++) {
        if(Cells.find({row: i, col: j}).count() == 0) {
          Cells.insert({
            value: -1,
            row: i,
            col: j,
            createdAt: new Date()
          });
        }
      }
    }
  });

  Template.createSudoku.helpers({
    rows: function() {
      var _rows = [];
      for(var i = 0; i < Session.get("rowMax"); i++) {
        _rows.push(Cells.find({row: i}, {sort: {col: 1}}));
      }
      return _rows;
    }
  });
}

And below is my html code

Sudoku

    {{> createSudoku}}

  <button class="reset">reset</button>

<template name="createSudoku">
  {{#each rows}}
    {{> createRow cells=this}}
  {{/each}}
</template>

<template name="createRow">

    {{#each cells}}
      {{> createCell}}
    {{/each}}

</template>

<template name="createCell">
  {{value}}
</template>

The issue is that, the table keeps multiplying every time I refresh the page. For additional info, I turned on the autopublish. Any hints to help me on this matter? Thanks!

A: the behavior is correct. The initial count of client side collection will always be 0, given that actual DB is stored on server side. The client DB gets populated over the course of time.
If want to insert some fixture data only once, standard procedure is to do it on server side.
However, if I misunderstand your use case and you still feel that for some reason, you must do it on client side, then do it inside a callback in your subscribe method.
Meteor.subscribe('faq',
  /* onReady callback */
  function() {
    console.log(somecollection.find().count());
  }
)

See here: http://docs.meteor.com/#/full/meteor_subscribe


text:
Q: Android NullPointerException CipherInputStream to Bitmap I'm tryin to get encrypted files from assets folder,decrypt it in application and show it as a content in list view.I'm using a well known Fedor's Lazy List Loading implementation.As you can see, I changed his getBitmap method with my own method :
package com.custom.lazylist;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.fedorvlasov.lazylist.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoader extends Activity {

    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();

    private File cacheDir;

    public ImageLoader(Context context){
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    final int stub_id=R.drawable.stub;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url))
            imageView.setImageBitmap(cache.get(url));
        else
        {
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
        photosQueue.Clean(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }

        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }

    //MY METHOD
private Bitmap getBitmap(String src) {
    Bitmap myBitmap = null;
        //Decryption
        try {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        AssetManager is = this.getAssets();
        InputStream input = is.open(src); //open file in asset manager
        CipherInputStream cis = new CipherInputStream(input, cipher);

        myBitmap = BitmapFactory.decodeStream(cis);

        }
        catch(Exception e){
            e.printStackTrace();
            Log.v("ERROR","Error : "+e);
        }

        return myBitmap;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    PhotosQueue photosQueue=new PhotosQueue();

    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }

    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }

    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.url);
                        cache.put(photoToLoad.url, bmp);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                            Activity a=(Activity)photoToLoad.imageView.getContext();
                            a.runOnUiThread(bd);
                        }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }

    PhotosLoader photoLoaderThread=new PhotosLoader();

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();

        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}

.....but the problem is that I'm getting this Exception :
08-11 11:11:45.293: WARN/System.err(1073): java.lang.NullPointerException
08-11 11:11:45.293: WARN/System.err(1073):     at android.content.ContextWrapper.getAssets(ContextWrapper.java:74)
08-11 11:11:45.293: WARN/System.err(1073):     at com.custom.lazylist.ImageLoader.getBitmap(ImageLoader.java:79)
08-11 11:11:45.293: WARN/System.err(1073):     at com.custom.lazylist.ImageLoader.access$0(ImageLoader.java:70)
08-11 11:11:45.293: WARN/System.err(1073):     at com.custom.lazylist.ImageLoader$PhotosLoader.run(ImageLoader.java:200)

this is how I use LazyAdapter in my main class :
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this, mStrings);
        list.setAdapter(adapter);

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> a, View v, int position, long id)
            {
                Intent i = new Intent(v.getContext(), Cards.class);
                startActivity(i);

            }
        });

        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(listener);

/*          adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();*/

        }

    @Override
    public void onDestroy()
    {
        adapter.imageLoader.stopThread();
        list.setAdapter(null);
        super.onDestroy();
    }

    public OnClickListener listener=new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();
        }
    };

    private String[] mStrings={
            "card1_encrypted.jpg",
            "card1_encrypted.jpg",
            "card2_encrypted.jpg",
            "card1_encrypted.jpg",
            "card3_encrypted.jpg",
            "card1_encrypted.jpg",
            "card1_encrypted.jpg",
            "card3_encrypted.jpg",
            "card3_encrypted.jpg",
            "card2_encrypted.jpg",
            "card4_encrypted.jpg",
            "card5_encrypted.jpg",
            "card3_encrypted.jpg",
            "card2_encrypted.jpg",
            "card5_encrypted.jpg",
            "card1_encrypted.jpg"

    };

So any ideas how to fix that?An last thing: at line 79 I have this:
AssetManager is = this.getAssets();

Thanks in advance!

A: You need an onCreate() method.
  @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        AssetManager am = getAssets();//this should not get a nullpointerexception
  }

Or do the following:
In your Activity (whichever one calls image loader) write this:
ImageLoader il = new ImageLoader(this);//this being the context.

Then in your ImageLoader class you can use
AssetManager am = context.getAssets();//context being the activity which called this class.

A: If the first class is not really an activity, doen't extend activity just to use this.getAssets(), pass the context (i.e. your activity) when instantiating the class, and use this instance to call getAssets()


text:
Q: React map values duplicating firebase i use firebase as my database and the data added to the firebase is correct however the mapped value on realtime data is duplicating.[here is the mapped datas][1]
[1]: https://i.stack.imgur.com/MhKo5.png
as you can see the value why is repeating but i already inputted different values and also i added a function to prevent the user from entering the same value as you can see on the image there is a error message
here is my code
my useEffect and firebase code to fetch data in realtime
useEffect(() => {
    const unsubscribe = onSnapshot(docCollection, (snapshot) => {
      const data = [];
      snapshot.docs.map((val) => {
        data.push({
          docID: val.id,
          label: val.data().labelName,
          created_at: val.data().created_at,
        });
      });
      dispatch(setLabels(data));
    });
    return () => unsubscribe();
  }, []);

mapped data
{labels.map((val, i) => {
              return (
                <LabelComp
                  key={i}
                  setActiveText={setActiveText}
                  labelName={val.label}
                  docID={val.docID}
                />
              );
            })}

and also my redux code
export const label = createSlice({
  name: "label",
  initialState: {
    currentLabel: "",
    labels: [],
  },
  reducers: {
    setCurrentLabel: (state, action) => {
      state.currentLabel = action.payload;
    },
    setLabels: (state, action) => {
      state.labels = action.payload;
    },
  },
});


text:
Q: FBSDKShareDialog not showing and returning error 2 Hi I've been this week adapting my app to iOs11 and since yesterday to today trying to do repare the share video to facebook button in iOs 11 but without success. I've tried everything, googled, tried everything in stackOverflow but i'm stuck with this.
The point is everything stopped to work since I changed the way I save my video. I was using ALAsset and changed to PHAsset.
I don't know if this is the reason but it's imposible to get the facebook prompt to share my video. I've tried every bit of code I seen around here.
My video url is "file:///var/mobile/Media/DCIM/100APPLE/IMG_0233.MP4" and except the name of the file, I think everything is okay. My app check if the user is logged and if it has publish permissions to yes. And then it configures the prompt, to display it. But always end up in the error method of the delegate:
/**
 Sent to the delegate when the sharer encounters an error.
 - Parameter sharer: The FBSDKSharing that completed.
 - Parameter error: The error.
 */

func sharer(_ sharer: FBSDKSharing!, didFailWithError error: Error!) {
    print(error.localizedDescription)
}

This is the error:
The operation couldn't be completed. (com.facebook.sdk.share error 2.)

Here is my code. I don't see what can be happening except that the saved video from phAsset is not compatible with facebook, which I doubt. But maybe somebody here knows more about this than me and can help.
Many thanks in advance!
Here the code I run after the facebook button is pressed:
//save video with PHAsset
    self.avHandler.saveWithPHAsset { (void) -> () in

//get url of the video
                        guard let urlToShare = self.avHandler.self.mergedLocalAssetVideoURL else {
                            return
                        }

                        if FBSDKAccessToken.current() != nil
                        {

                            if FBSDKAccessToken.current().hasGranted("publish_actions")
                            {
                                print("permission granted")
                                let video = FBSDKShareVideo(videoURL: urlToShare)
                                let dialog = FBSDKShareDialog()
                                DispatchQueue.main.async{
                                    if UIApplication.shared.canOpenURL(URL.init(string: "fbauth2://")!)
                                    {
                                        dialog.mode = FBSDKShareDialogMode.native
                                    }
                                    else{
                                        dialog.mode = FBSDKShareDialogMode.browser
                                    }
                                }

                                let content : FBSDKShareVideoContent = FBSDKShareVideoContent()
    //                                content.contentURL = NSURL.init(string: urlToShare.absoluteString) as! URL
                                let image = UIImage(data: self.recordingInfo.thumbData)
                                let fbimage = FBSDKSharePhoto(image: image, userGenerated: false)
                                content.previewPhoto = fbimage!
                                content.video = video!
                                content.contentURL = urlToShare
                                dialog.delegate = self
                                dialog.shareContent = content
                                dialog.fromViewController = self
    //                            FBSDKShareDialog.show(from: self, with: content, delegate: self)
                                dialog.show()

                            }
                            else
                            {
                                print("don't have permission")

                            }
                        }
                        else
                        {
                            "Please login to facebook in the tab menu".displayInfo()
                        }
                    }


text:
Q: How to change boot options on Linux I am attending a robotics camp in a week and was given a USB and was told to set up my computer by booting it through the USB so that I can use Linux. I did this, and it worked successfully. But the camp isn't until next week and I want my normal Windows computer back. When I try to change the boot in Linux through the restart screen it doesn't give me an option to return to my original one, it only asks questions about whether I want my USB to be "active" and such. How do I return to my original operating system from Linux? Is it as simple as removing the USB?
I'm on an Acer laptop with Windows 10, trying to escape Linux.

A: The way I fixed it is going through the Linux booting screen at the restart, pressing escape, and then typing 'reboot.' It took me back to Windows. To go back to Linux, I just restart my computer again and go through the basic booting route. I'm not sure if this is the best or correct way to solve this, but it's the way I did and it's fairly simple.


text:
Q: Using $_SERVER['HTTP_REFERER'];, but modify for www I'm using some code like this to grab the URL from an inbound link:
$inbound_url = $_SERVER['HTTP_REFERER'];

//then do some stuff writing the url to a database table, but....
//ONLY IF the url doesn't already exist in the table

Let's say the link comes in from the same website, same webpage, but different only in the www.  So I get this:
1) http://www.mysite.com/page.html
2) http://mysite.com/page.html
This shows up twice in my table since one has the www and one doesn't.
Is there a way to parse the results of $_SERVER['HTTP_REFERER']; to either:
1) add www. where it's missing, OR
2) strip everything of ...http://...www. or ..http://
Thanks in advance as always.

A: Sure you can. Some simple string manipulation and replacement should be all you need to remove the www from any URL -
$inbound_url = str_replace('http://www','http://',$inbound_url);

As defined in the documentation -

str_replace() - Replace all occurrences of the search string with the replacement string

Notice that I'm including the http:// in the search so that any other occurrence of the string www  URL will remain untouched.

A: Use this
$url = 'http://stackoverflow.com';
$d = array_shift( explode( '.', str_replace('www.', '', parse_url( $url, PHP_URL_HOST )) ) );
echo $d; //stackoverflow

or you can also use
http://php.net/manual/en/function.parse-url.php function


text:
Q: Laravel 5 environment config arrays? In Laravel 4, you could set an environment based config folder structure:
/config/app.php
/config/dev/app.php
/config/staging/app.php
/config/testing/app.php

Can you do this with Laravel 5? I understand the .env concept and I'm using that to define which environment I'm in. But I need to define a config value that is an array of arbitrary length, and you can't do that with .env files.
An example of what I'm trying to achieve:
if (in_array($request->input('value'), config('app.valid_values')) {
  // do something
}

This valid_values is simply an array of values. It's of arbitrary length, so you can't just set them in your .env file like:
VALID_VALUE1=...
VALID_VALUE2=...
etc.

AND the array needs to be different for each environment.
This was easy to do in Laravel 4 with environment configuration folders. But how do you do this with Laravel 5?

A: Generally for Phpdotenv
Phpdotenv is about storing values in environment, not general purpose config library. Environment is UNIX concept and the values are always interpreted as character strings. Converting to different datatypes such as arrays or booleans even though convenient would be outside the scope of this class.
Laravel config system
Laravel's config system is already separated. phpdotenv does environment, laravel does config. Then once config is done, environment is ignored. The concern of parsing environment variables from strings into whatever is passed on to laravel (weather that be their env function, or exploding inside your config files).
Good practice
In other words, use Config::get() to get a specific conf file with your desired structure and you have what you need.
You should never use env() in the code directly when it is outside of the config folder according to the Laravel guidelines. It's a good practice to use config(). In config files use env() to get the data from .env file.

A: If you need to create an array on values, you can create on string format and when you need you can parse them
MY_ARRAY_VALUE=1,2,house,cat,34234

When you need them
$myArrayValue  = explode(',', env('MY_ARRAY_VALUE'));

Or save your values in JSON and get them with json_decode()
$myArrayValue  = json_decode(env('MY_ARRAY_VALUE'), true);

Extra info:
On Laravel 5, you need to translate all your configs files in one .env file.
On each environment your .env file will be diferent with values for this environment.
To set your environment, you need to change the value of APP_ENV in your .env file
APP_ENV=local

And you can create your own variables in that file
https://laravel.com/docs/5.2/configuration#environment-configuration
This is an extract of the upgrade guide to Laravel 5.0
https://laravel.com/docs/5.2/releases#laravel-5.0

Instead of a variety of confusing, nested environment configuration directories, Laravel 5 now utilizes DotEnv by Vance Lucas. This library provides a super simple way to manage your environment configuration, and makes environment detection in Laravel 5 a breeze. For more details, check out the full configuration documentation.

You can find a default .env file here: https://github.com/laravel/laravel/blob/master/.env.example

It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use a different cache driver locally than you do on your production server. It's easy using environment based configuration.
To make this a cinch, Laravel utilizes the DotEnv PHP library by Vance Lucas. In a fresh Laravel installation, the root directory of your application will contain a .env.example file. If you install Laravel via Composer, this file will automatically be renamed to .env. Otherwise, you should rename the file manually.


text:
Q: Ensuring div are placed below each other after the top div grows in size I have two divs that represent a list of elements the user can click on on a search bar, followed by a "Done" button.

  <input type="text" class="form-control dropdown-toggle" id="inputSearch" placeholder="Search for a term ">

        <button type="submit" class="btn btn-primary">Done</button>

Whenever the user starts typing, there are a number of
 elements that appear with an autocomplete function (that is, they are appended between the
 tag,  but the position of the "Done" button is messed up, as it does not stay at the bottom, that is, below the list elements.

How can I keep the button always at the bottom of the list, regardless of how many elements there are?

A: See example below. I used your code, added a few
 items, the data-bs-toggle and a class on the
 list so no bullets appear, and the buttons is where it should be.
So if your problem isn't solved with my example, post the full example of the dropdown, with the search results and including any custom CSS.
Other options:

*

*Use the helper class float-end instead of using flex.

*Place the btn inside the list:

..

<btn>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

  <input type="text" class="form-control dropdown-toggle" id="inputSesarch" data-bs-toggle="dropdown" aria-expanded="false" placeholder="Search for a term ">

First result

Another result

Some other result

      <button type="submit" class="btn btn-primary">Done</button>


text:
Q: Who policed the civilian population of the Galactic Empire? I know that stormtroopers did a significant amount of policing for the Empire, but surely they could not have been the only organisation providing law enforcement.
Who acted as law enforcement in the Galactic Empire (apart from stormtroopers)?

A: One example from Legends at least is CorSec, or the Corellian Security Force, which acted as the primary police force for Corellia with an imperial intelligence liasion officer to keep an eye on them.

A: Local (planetary) police forces served as law enforcement on many systems in the Empire. An example in canon is the Coruscant Security Force, which was composed of police droids:

(Image from Wookieepedia)
as well as non-droid officers:

(Image from Wookieepedia, taken from the canon short story "One Thousand Levels Down" which takes place during the Imperial era)
Another example from canon is the Royal Naboo Security Forces, an organization which we know existed during the Imperial era because it appeared in Shattered Empire, Part II which took place after Episode VI Return of the Jedi. Many of these police forces had existed since the Republic. The Empire also had a secret police force, the Imperial Security Bureau. The Imperial military (including stormtroopers) acted as law enforcement on more rebellious planets such as Ryloth (where the Empire used slave labor).

A: It is important to note that security forces were planet-specific. For example, we have: Coruscant Security Force,  Royal Naboo Security Forces, Telos Security Force (TSF).
All the planet specific security forces were more or less obedient to the Empire (Imperial Security Bureau and/or Imperial Intelligence).
Additionally to these, on many planets there were other private security forces (like the Security of the Exchange or Czerka Corporation) also mostly compliant to Imperial rules and were pretty powerful on the locations of interest. So in case the local forces were resilient to comply with what's needed, the private ones made sure that thing go a little more the Empire's way.


text:
Q: in Rails how do I grab an element with a dynamically created id? So I have an index page with multiple divs of listings.  each div has a dynamically created id, in this case edit_<%= address.id%>.  I'm trying to write some jquery so that as I hover over an individual div, some hidden links are shown, or as I click on the edit link for this individual listing, a form pops up.  I'm able to do it inline like this:
onclick="$('#edit_<%= address.id %>').dialog();"

but once in my application.js file like this:
$(document).ready(function() {
$('#edit_<%= @address.id%>').dialog();
});

It doesn't work.  now I'm assuming it's because I'm using it outside of the view/controller where this variable actually has meaning.  Is there a solution to this?

A: You're trying to get a rails variable in your JavaScript file, and that is not how it works. I think the easiest solution for you is simply to use the gon gem.

A: Use a specific class name for all of the target DIVs. Even though they will have a dynamic ID if you use a pre-defined class name you will be able to locate them using a simple jQuery. You can then write code in your application JS files and target only those specific class names.
Update: Here is an example that gives you what you want. This is straight HTML/Javascript but the container DIVs use a unique ID but common class name. You can easily move this into your Rails app:

      Hover over me to reveal my hidden fields

A hidden field

A hidden field

A hidden field

A hidden field

      Hover over me to reveal my hidden fields

A hidden field

A hidden field

A hidden field

A hidden field

      Hover over me to reveal my hidden fields

A hidden field

A hidden field

A hidden field

A hidden field

A: Make sure that all your css elements have the same starting id or class and then you can select them using some jquery similar to this, which selects all divs with edit at the beginning of their id $('div[id^="#edit_"]').hover.dialog();
below is some documentation on how to use this selector
http://api.jquery.com/attribute-starts-with-selector/


text:
Q: Need to change Datagridview row color if checkbox is checked on Form Load i have problem with dataset gridview on Form load procedure. I hava dataset as datagridview source and when I'm trying to change datagrid row color based on if statement if checkbox is checked nothing happens. If I used same code on some button-click procedure it all works fine.
Can anyone help me with this problem.
 da.Fill(ds, "customer")
    cnn.Close()
    DataGridView1.DataSource = ds.Tables("customer")

    For i = 0 To DataGridView1.Rows.Count - 1

        If DataGridView1.Rows(i).Cells(3).Value = True Then

            DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.MediumAquamarine
        Else
            DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.MistyRose
        End If

    Next

A: You cant have this code in Form_Load. This only occur when the form starts the first time. Try instead to put the code in the DataGridView1.Paint event handler. That should do the trick.


text:
Q: Issues with repeated key checking with getch() I am having issues with repeating key checking using a function that utilizes getch().
Here is a code example:
static char g_keybuffer[256];
_Bool IsKeyDown(char c)
{
    char ch;
    if(kbhit())
        ch = getch();

    if(ch == -32 || ch == 224)
    {
        ch = getch();
    }

    g_keybuffer[ch] = 1;
    if(g_keybuffer[c] == 1)
    {
        g_keybuffer[c] = 0;
        return 1;
    }

    return 0;
}

/*
 *
 */
int main(int argc, char** argv) {
    while(1)
    {
        if(IsKeyDown('a'))
        {
            printf("Test\n");
        }
        if(IsKeyDown('a'))
        {
            printf("Hello\n");
        }
        else if(IsKeyDown('b'))
        {
            printf("World\n");
        }
        Sleep(100);
    }
    return (EXIT_SUCCESS);
}

I know why the problem occurs.  When a key is pressed, kbhit is true once per loop, and sets ch to the character retrieved from the buffer.  When IsKeyDown is used, if it is equal to the parameter, the key in the buffer g_keybuffer is set equal to zero to avoid having a key be "down" infinitely.  The problem with this is if you want to check if the same key is down more than once, only the first instance of IsKeyDown will be ran, with the rest being invalid due to the g_keybuffer of the key now being 0.
Does anyone know how I can change IsKeyDown to give it the ability to check the same key multiple times per looping?  I'm stuck.

A: Your problem is because you are setting g_keybuffer[c] to 0 after you get a hit for the key state. I'm guessing you have done this to avoid getting the same result twice - but that is just a workaround. The only way to do what you want to do properly is to choose a library that is actually made to capture the keyboard state.
Most graphics libraries have functions for capturing keyboard states. I don't know of any solutions thought that don't involve a little overhead if you are just writing a small program.


text:
Q: How to make a stripe charge in rails form BEFORE form is submitted I have a form that is filled out by a userA. IF userA says that they will pay then I want a charge button to appear within the form (BEFORE THE FORM IS SUBMITTED) next to the drop down menu that userA chose that they would pay(Im guessing javascript?). Also, the form itself will NOT submit if the charge for payment does NOT complete. If the dropdown menu is set to userB will pay (the other user type) then the form will submit.
I am unsure what I can use to do this I think javascript but I know ruby not too much javascript. Also, the charge MUST get the amount of the charge from within a 2nd dropdown menu on the form. So the charge button would need to pull that amount from the pre-submitted form. Once again puts me in the mind that this can be accomplished with javascript.
I have javascript for my stripe button but need some code to get the button to appear from when the dropdown is selected and also to pull the amount from the other dropdown in the form.
Here is an example of the actual flow:
Submit Form -> Check Attrs :x -> If Attrs X False, Create Record || Elsif Attr True -> Get payment Amount from Attrs: Y, Render Payment View showing Attrs Y as amount due -> Submit Payment Form -> Upon Successful charge -> Create Original Record

A: You should not rely on javascript if you need things to be authorized in your application. Users can easily circumvent this.
I think you are thinking about this a bit wrong - you are not going to have two users in the same browser session or have somebody sit and wait with the browser window open until a supervisor approves their request. This is not the timesharing era.

Instead you would have the unprivileged user create a PurchaseRequest when they submit the form. The supervisor would get a notification and can approve or cancel the PurchaseRequest.
Whether you want the ball to roll back to user 1 in this case depends on the exact use case but in my experience the supervisor is usually the one holding onto the company card.
When using stripe or any other payment system you submit a payment and your then get a callback request which tells you if the payment was a success.

*

*Joe submits form to create a request

*Jane (supervisor) is out playing golf and approves it 3 days later.

*Joe receives a notification that he now can pay the request. He clicks the pay button and the request is forwarded to the payment portal.

*He submits the payment, and is redirected back to your app. In this action your need to check the state of the payment and render a view accordingly.

This is a generic example and you should check out the Stripe docs for what flow they recommend.


text:
Q: How do I set Secondary Preferred reads on Mongo Database from Parse Server? We created 10 nodes with Parse Server and they killed our Mongo database's Primary.
Is there a way we can set up Secondary Preferred for the reads on Parse servers otherwise the load will be put in the primary node?

A: You should read this article about read preferences in MongoDB
If you use MongoDB Native driver or Mongoose you can achieve a read preference read this

A: By setting secondaryPreferred as the read preference.
The documentation statues for secondaryPreferred in most situations, operations read from secondary members but if no secondary members are available, operations read from the primary
Also you can tweak your secondary read preference by configuring maxStaleTimeout
Please go through the documentation for understanding more about read preference
https://docs.mongodb.com/manual/core/read-preference/

A: The Parse Server docs you are looking for are here.
Example:
const query = new Parse.Query("MyClass");
query.readPreference("SECONDARY");


text:
Q: How to convert points to lines? I want to convert these points to lines, however they are not sorted sequentially along a line (by ID or FID), i.e. the converted lines zig-zag across the obvious trail of points.
How can I join these point trails based on proximity to points?
I don't have access to the Near (Analysis) tool, which I thought might help me move froward.

A: *

*One approach is to convert this to raster and then extract contours

*Another is to find the buffer for each point;Dissolve those buffers to get a narrow polygon;Find the center line of each dissolved polygon.

A: First you need a line identifier.
A buffer will probably do what you need, with dissolve. Then you can spatially join the buffer polys back to the points and transfer the buffer fid across.
Then you need to sequence them in some way.
The points all seem to go NE-SW, so perhaps ordering on the Y coord will get you a sequence. Apply this as an index to the points. Then use the Points To Lines tool.

A: we have once Geoprocessing tool Point to Line in arcgis use once i think this is useful to you
http://resources.arcgis.com/en/help/main/10.1/index.html#//00170000003s000000


text:
Q: constraining type in Seq.scan I am not sure why this happens
   //fine, type of xs is Set<int>
   let e = Seq.scan (fun xs         x -> Set.add x xs) Set.empty [1..2]

   //bad, type of xs is Set<obj>,  no type check no good
   let e = Seq.scan (fun(xs:Set<_>) x -> Set.add x xs) Set.empty [1..2]

Must be my eyes but what gives ?

A: As precised in the comment, I was opening the namespace of some other library further up in my file.
Being a C# library, it redefines its own Set (poor folks)
Doing so, writing Set<_> induced the compiler in picking up their version, whilst Set.add still refered to the trusted FSharp Set<_>.
Eventually, the two came in brutal head to head conflict with each other.


text:
Q: Cypress e2e test with stripe js I am writing an e2e test on cypress to a online store and after click the confirm purchase button it redirects to stripe page to input credit card and then redirects back to our store to show the receipt.
Does anyone one what should be the best way to perform this test? Should be by API?
 How to use stripe api to do the payment using cy.request in order to avoid redirecting to their page?
Thank you very much


text:
Q: Creating Visual Displays of Calculations and Solutions In the late 80s or 90s, I remember watching video online of a series of lectures in a college physics course at UCAL. One of the sponsors was the Annenberg Foundation. Most of the time the video was shots in the lecture hall, but there were also cutaways to an empty black space in which an equation or calculation would appear and as the voiceover articulated the operations necessary to solve the original equation it would change in time to reflect the effects of each step; one could watch as numbers, variables, signs were struck through, faded in or out, moved around, etc.; thus, "showing your work" was being done fluidly in time instead of frozen in space the way it would be if one were doing the math on paper.
So, to my questions: 1. Does anybody know the video I'm talking about and where to find it? (I've been looking on and off for years and never have); 2. Does anybody understand what I've tried to describe going on in the cutaways and what I need to make my own?

A: 1)
Could it be "The Mechanical Universe" series? See here for an example of the kind of manipulations used in the series. Sponsored by Annenberg, but produced by Caltech, not UCLA.


text:
Q: Is it possible to run VMWare Server on a Linux VPS? I want to run a Windows Server 2003 under a Debian Linux VPS I have.  Is this possible using VMware Server?

A: Almost certainly no: Most VPS solutions are /already/ virtualized (Virtual Private Server), many of them using Xen or similar.  Even if it "worked" (that is the hypervisor actually started) performance would be abysmal - likely to the point of being unusable.


text:
Q: Why am I getting an System.InvalidOperationException when I assign "SelectedIndex = 0" to a DataGrid? I've got a problem that keeps my app crashing and I can't figure out why.
My code is like this:

Private Sub SelectedFieldFK_TextChanged() Handles SelectedFieldFK.TextChanged
  RefreshSelections()
End Sub

Private Sub RefreshSelections()
  If Selections Is Nothing Then Exit Sub
  Selections.SetBinding(DataGrid.ItemsSourceProperty, New Binding With {.XPath = "..."})
  m_SelectionSorter.Refresh()
  If Selections.HasItems Then Selections.SelectedIndex = 0 '*)
End Sub

I'm skipping down a ListBox using the arrow keys. Via binding the "SelectedFieldFK" keeps changing its value, and the DataGrid named "Selections" keeps getting updated. After that, the first row of the DataGrid is selected. This works for the first occurence when 2 selections are to be shown. Then I continue pressing the down arrow and eventually land on an item that has one selection. As soon as the function "RefreshSelctions()" ends, the app crashes with:

System.InvalidOperationException: Can only change SelectedItems collection in multiple selection modes. Use SelectedItem in single select modes.

and StackTrace
at System.Windows.Controls.Primitives.Selector.OnSelectedItemsCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
at System.Windows.Controls.SelectedItemCollection.InsertItem(Int32 index, Object item)
at System.Collections.ObjectModel.Collection`1.Add(T item)
at System.Collections.ObjectModel.Collection`1.System.Collections.IList.Add(Object value)
at System.Windows.Controls.Primitives.Selector.UpdateSelectedItems(InternalSelectedItemsStorage toAdd, InternalSelectedItemsStorage toRemove)
at System.Windows.Controls.Primitives.Selector.UpdateSelectedItems()
at System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(ItemInfo info, Boolean assumeInItemsCollection)
at System.Windows.Controls.ListBox.MakeSingleSelection(ListBoxItem listItem)
at System.Windows.Controls.ListBox.MakeKeyboardSelection(ListBoxItem item)
at System.Windows.Controls.ListBox.OnGotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
at System.Windows.Input.KeyboardFocusChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.KeyboardDevice.ChangeFocus(DependencyObject focus, Int32 timestamp)
at System.Windows.Input.KeyboardDevice.TryChangeFocus(DependencyObject newFocus, IKeyboardInputProvider keyboardInputProvider, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
at System.Windows.Input.KeyboardDevice.Focus(DependencyObject focus, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
at System.Windows.Input.KeyboardDevice.Focus(IInputElement element)
at System.Windows.UIElement.Focus()
at System.Windows.Controls.ItemsControl.FocusItem(ItemInfo info, ItemNavigateArgs itemNavigateArgs)
at System.Windows.Controls.ListBox.FocusItem(ItemInfo info, ItemNavigateArgs itemNavigateArgs)
at System.Windows.Controls.ItemsControl.NavigateByLineInternal(Object startingItem, FocusNavigationDirection direction, FrameworkElement startingElement, ItemNavigateArgs itemNavigateArgs, Boolean shouldFocus, FrameworkElement& container)
at System.Windows.Controls.ItemsControl.NavigateByLine(ItemInfo startingInfo, FrameworkElement startingElement, FocusNavigationDirection direction, ItemNavigateArgs itemNavigateArgs)
at System.Windows.Controls.ItemsControl.NavigateByLine(FocusNavigationDirection direction, ItemNavigateArgs itemNavigateArgs)
at System.Windows.Controls.ListBox.OnKeyDown(KeyEventArgs e)
at System.Windows.UIElement.OnKeyDownThunk(Object sender, KeyEventArgs e)
at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey)
at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled)
at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers)
at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at DatenfKatCreator.Application.Main() in C:\Users\Christoph\Documents\Visual Studio 2010\Projects\DatenfKatCreator\DatenfKatCreator\obj\x86\Debug\Resource\XAML\Application.g.vb:Zeile 66.
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

When I comment line *) out, it works, but of course the first entry is not selected.
Am I missing something?

A: You need to set the property SelectionMode to Extended on your grid
 grid.SelectionMode = DataGridSelectionMode.Extended;

However this should be the default, so check if your code (or XAML) changes it to Single


text:
Q: Accelerometer-based gesture recognition I'm developing an embedded accelerometer-based hand gesture recognition. Does anybody know about some free libraries to employ or to start from? I'm working with embedded linux and I'm looking for something not too much computation-heavy. I couldn't find much on google apart from dozens of theoretical papers, youtube videos or "closed" applications.
I understand it's a pretty broad question, but I think it can help everybody in the same situation.
Thank you!

A: If you haven't already seen these...
There are two projects started as academic projects:
http://www.dfki.de/~rnessel/tools/gesture_recognition/gesture_recognition.htm
(with source code)
and
the gRmobile framework:
all I can find is a paper:
http://www.ic.uff.br/~esteban/files/papers/SBGames09_Mark_A.pdf
Hope that helps! There doesn't seem to be much out there. But, if you are looking to do a little more work, not necessarily relying on a library, definitely be sure to read through the gesture information from the Android Dev site (the Gesture Recognition API):
http://developer.android.com/resources/articles/gestures.html

A: This question is already answered, but for the sake of posterity, here goes:
http://www.wiigee.org/
Meant for use with the Wiimote, wiigee is an open-source Java based implementation for pattern matching based on accelerometer readings. It accomplishes this using Hidden Markov Models[1].
It was apparently used to great effect by a company, Thorn Technologies, and they've mentioned their experience here : http://www.thorntech.com/2013/07/mobile-device-3d-accelerometer-based-gesture-recognition/

Alternatively, you could consider FastDTW (https://code.google.com/p/fastdtw/). It's less accurate than regular DTW[2], but also computationally less expensive, which is a big deal when it comes to embedded systems or mobile devices.
[1] https://en.wikipedia.org/wiki/Hidden_Markov_model

[2] https://en.wikipedia.org/wiki/Dynamic_time_warping


text:
Q: Virtualbox doesn't transmit `Control+Alt+A` I'm using Emacs inside of Virtualbox, and realized that Control+Alt+A does not work. Control+Alt+E does work.  It does not work inside the X Server or without it running (CLI).
I have my host key set to Right Control, so I don't think that is conflicting.

A: What do you mean ? Control+Alt+A in emacs sets a Mark. To set a mark there are other ways in Emacs too, you can use Control+Space to set a mark.


text:
Q: How to simple put button value to jQuery Datatables search input? I cannot simple create buttons for put value to jQuery datatable search input, because cannot find the input ID name!
I using "jquery-1.11.3.min.js" & "jquery.dataTables.min.js (v1.10.23)", help me, please!

A: You don't have to target the search input directly. You should instead use datatable's .search() api. Example
var table = $('#table-id').DataTable();
$('button').click(function(){
    table.search( $(this).text() ).draw();
});


text:
Q: Need Pyspark String to Date Conversion Pattern I have a string field with datetime in this format:
Thu Jul 01 09:26:47 UTC 2021

I have gone through spark documentation for date_format function and tried this one:
E L dd hh:mm:ss UTC yyyy

Still I get NULL and cant parse the string into datetime. any help would be appreciated.
df.select('Created Time', F.to_timestamp(F.col('Created Time'), 'E L dd hh:mm:ss UTC yyyy'))
  .show(1, False)

A: You need to escape UTC and consider it as "text", not part of the date pattern.
from pyspark.sql.functions import unix_timestamp

df = spark.createDataFrame(["Thu Jul 01 09:26:47 UTC 2021"], "string").toDF("TS_String")

df\
  .withColumn("TS_Converted", unix_timestamp(df.TS_String, "E MMM d h:m:s 'UTC' yyyy")\
  .cast("timestamp"))\
  .show()


text:
Q: Why isn't -Contains returning true for this? Here's my code:
while ($looper){
    [array]$destfiles = Get-ChildItem "C:\Users\{redacted}\Documents\test powershell\DEST"
    [array]$srcfiles = Get-ChildItem "C:\Users\{redacted}\Documents\test powershell\SRC" -File -Recurse
    Write-Host $destfiles
    Write-Host $srcfiles

    $matchcount = 0
    $matchfiles = ""

    $list = "a.txt","b.txt"

    foreach ($file in $destfiles){
        Write-Host "foreach " $file
        if ($list -contains $file){
            Write-Host "match iteration"
            $matchcount += 1
            # $matchfiles += $file + " "
        }
    }

    if ($matchcount -eq 0){
        Write-Host "break loop"
        break
    }
    else{
        Write-Host "loop"
        Start-Sleep -s 30
    }

    $loopcounter += 1
}

I have identical files in both directories. For the if statement, if I hardcode it (like in the above example) to this:
if ($list -contains $file){

It works as expected. But as soon as I try to actually compare against srcfiles, it doesn't enter the if loop:
if ($srcfiles -contains $file){

What am I doing wrong?

A: You're comparing to a [FileInfo] object, not a file name.
Change this if condition:
$list -contains $file

to:
$list -contains $file.Name

A: Two objects usually aren't equal unless they're the same object (they're pointers).  But comparing string values works.  Pay attention to the type of the left operand (the right side gets converted).
$a = get-childitem file
$b = get-childitem file

$a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     FileInfo                                 System.IO.FileSystemInfo

"$a".gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

$a -eq $a

True

$a -eq $b

False

"$a" -eq $b

True


text:
Q: Space of polynomially growing harmonic functions on a Lie group There is a recent theorem by Kleiner (based on previous work by Colding & Minicozzi), that reads:
If $G$ is a finitely generated group of polynomial growth, then for every $d$ the space of harmonic functions with polynomial growth of at most $d$ is finite dimensional. Kleiner later uses this to obtain a non-trivial representation of $G$.
Is an analogue for the setting of Lie groups known? that is, is it known whether for a polynomially growing (equivalently, type (R)) Lie group, the space of polynomially growing harmonic functions of some fixed rate is finite dimensional?
Edit: the measure setting is a probability measure $\mu$ such that:

*

*$\mu$ is adapted, in the sense that there is no proper subgroup $H$ such that $\mu(H)=1$.

*$\mu$ is compactly supported.

*$\mu$ is absolutely continuous w.r.t. the Haar measure.

*$\mu$ is symmetric.


text:
Q: What are the values of $k$ when $kx^2+x+k$, has equal zeroes? Show that the quadratic equation $kx^2 + 2(x+1)=k$ has real roots for all the values of $k\in \mathbb{R}$
what i did
$kx^2+2x+2-k=0$
$4-4(2-k)(k)>0$
$4-8k+4k^2>0$
$(64±64)÷ 4(2)>0$
$128÷ 8>0$
$16>0$
please help me check

A: I would say just:
$kx^2+2x+2-k=0$
$4-4(2-k)(k)\ge0$
$4-8k+4k^2\ge0$
$4(k-1)^2\ge0$
which is obviously true.
Also you have to consider $k=0$ separately, when your equation is not quadratic, in which case it has the real root $x=-1$

A: Hint: write the equation as:
$$0= k(x^2-1) + 2(x+1)=k(x-1)(x+1)+2(x+1) = (x+1)(kx-k+2)$$

A: $$kx^2+2x+2-k=0$$
Consider the discriminant:
$$ b^2-4ac=4-4(k)(2-k)$$
$$b^2-4ac=4k^2-8k+4$$
$$ b^2-4ac=4(k^2-2k+1)$$
$$ b^2-4ac=4(k-1)^2$$
This mean $$ b^2-4ac \ge 0 $$
So when you plug in any value for $k$ $(k \neq 0)$the discriminat will always be $(\ge0)$ hence you will always have real roots
Another case is $k=0$ where $2x+2=0 \Leftrightarrow x=1$

A: We can just compute the roots using factorization:
$$
kx^2+2(x+1) = k \\
kx^2 +2x + 2 - k = 0 \\
kx^2 -x^2 + x^2 +2x + 1 + 1-k = 0 \\
(k-1)x^2 + (x+1)^2 + 1-k = 0 \\
(k-1)(x^2 - 1) + (x+1)^2  = 0 \\
(k-1)(x+1)(x - 1) + (x+1)^2  = 0 \\
(x+1)((k-1)(x - 1) + (x+1))  = 0 \\
(x+1)(kx - k - x + 1 + x+1)  = 0 \\
(x+1)(kx - k + 2)  = 0 \\
$$
Hence the roots are $-1$ and, if $k$ is non-zero, $1-2/k$ .


text:
Q: Magick++ get pixel color. pixelpacket doesnt seem to exist anymore I'm trying to get the color of a pixel in a jpg image and all the tutorials I can find online say to use pixelpacket which doesnt exist anymore. searching and searching through google i've found that getvirtualpixels might be the new way but that doesnt seem to exist in the newest version either. so how do I get the color of pixels from an image with an image cache? I do not need to set any pixels btw.
Using windows10 and visual studio 2015

A: PixelPacket structures have been replaced with a pointer to Quantum data type. From Porting to ImageMagick Version 7, the key thing to understand is that a pixel can now have dynamic parts (or "traits" previously called as "channels").

ImageMagick version 7 supports any number of channels from 1 to 32 (and beyond) and simplifies access with a single method that returns an array of pixel channels of type Quantum.

You are now responsible for authoring code that handles deterministic (is that the right term?) pixel channels. For example...
Magick::Image rose("rose:");
const Magick::Quantum * q = rose.getConstPixels(5, 5, 1, 1);
size_t channel_length = rose.channels();
for (size_t k = 0; k < channel_length; k++ ) {
    std::cout << "Channel " << k << " = ";
    std::cout << q[k] << " of " << QuantumRange << std::endl;
}
/** Outputs
    -------
    Channel 0 = 13107 of 65535
    Channel 1 = 12079 of 65535
    Channel 2 = 11308 of 65535
 */

Without seeing your code, or understanding what your finial goal would be, I would guess that you really just want RGB info. If that's the case, the Magick::Image.getColor will work,
Magick::Image rose("rose:");
Magick::Color pixelColor = rose.pixelColor(5, 5);

std::cout << "Channel 0 = ";
std::cout << pixelColor.quantumRed() << " of " << QuantumRange << std::endl;
std::cout << "Channel 1 = ";
std::cout << pixelColor.quantumGreen() << " of " << QuantumRange << std::endl;
std::cout << "Channel 2 = ";
std::cout << pixelColor.quantumBlue() << " of " << QuantumRange << std::endl;
/** Outputs
    -------
    Channel 0 = 13107 of 65535
    Channel 1 = 12079 of 65535
    Channel 2 = 11308 of 65535
 */

But! Sometimes it's just easier to export the image data into a format you're already working with. For example, I might only need Green values as single-point float list.
Magick::Image rose("rose:");
Magick::PixelData pixelBlob(rose, "G", Magick::FloatPixel);
float * buffer = (float *)pixelBlob.data();
// ...


text:
Q: USB 2.0 Host PC enumeration requirement I am looking into USB 2.0 Ports in Host PC and LapTop computers. I am designing a device that will need to draw as much current as possible. Does anyone know how common these ports require enumeration and limit the current to 100mA before allowing the full 500mA+ supply ?

A: Limiting host current to 100 mA never occurs in "self-powered" "high-powered" USB hosts, be it a desktop PC (being powered from AC mains) or laptop PC (powered either from a big internal battery of from AC-DC adapter). In fact, this would be a gross violation of main USB 2.0 Specifications. The specifications can be found on USB.org/developers website (free, within a big zip file), or here, from UCSD.edu and several other places.
USB specifications 2.0 mandate that these categories of USB hosts must supply AT LEAST 5 "units" of load, each "unit" being defined as 100 mA in case of USB 2.0 port, or 150 mA for USB 3.x port. See Section 7.2.1 (page 171) of USB 2.0 Specifications. Therefore, all USB ports in big devices should be and are designed to provide "at least" 500 mA or 900 mA, or typically quite a bit more, 2- 2.5 A. Exceptions are for small gadgets like MP3 players, etc.
However, a USB device must be designed not to draw more than "1 unit" (100-150 mA) of current upon initial "connect" event, until it gets enumerated by host software and receives the final "set_configuration" command. Only if the host determines that everything is OK and issues the "set_configuration()" command, the device may start drawing full power from VBUS. During the enumeration the host determines the required power for the particular device (reading its descriptors), and in cases when the device demands more power than a particular USB segment (say, remote hub) can afford, the host may refuse the device connection by not completing the enumeration process. People frequently refer to this process as "negotiation", but in fact it is rather be "admitted" or "not admitted".
In short, USB ports don't limit the initial port power to 100/150 mA. But a device that doesn't exercise this limit can't be USB compliant and won't pass any official USB certification. This requirement has nothing to do with any Battery Charging specifications or else, this is in the original USB framework.

A: This will depend on if and how your device uses data.
The very old standard was 100mA by default, however in my personal experience, data ports made since 2010 will likely deliver 500mA if a data connection is detected, and more than 500mA if there is no data.
This can be observed by plugging a phone into a computer and measuring the current. A standard USB cable will pass-through all 4 pins, and the data connection will be detected, resulting in 500mA current.
BUT, reconfiguring the data pins can allow for more current. Observe three configurations below:

Charging at higher current whilst also using data can thus depend on the configuration of host and client, and also the cable in between.
See this page for in-depth details:
https://www.maximintegrated.com/en/app-notes/index.mvp/id/5801
"Dumb" devices with no data (such as a USB fan) either don't have a connection to the data pins, or have them tied together in some way.
Some ports, again those in computers, will detect overcurrent and be automatically disabled. Cheap wall chargers will not have this function, and may instead allow the voltage to drop, and may eventually burn out, sometimes in a dangerous fashion.


text:
Q: Using Struct to pass a variable Swift I'm trying to use a Struct to pass some variables that I get from a Facebook Graph Request such as email, name, gender, etc.
I've created the Struct ('fbDemographics') and the variables in 'ViewController' but I get an error when I try to call the struct and one of the variables in 'SecondViewController' (Type 'ViewController' has no member 'fbDemographics'). I've never used struct before so a bit baffled why I am getting this error. Thanks for any thoughts. The code for both view controllers is below:
class ViewController: UIViewController, FBSDKLoginButtonDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    struct fbDemographics {

        static var relationship_status: String?
        static var gender: String?
        static var user_education_history: String?
        static var user_location: String?
        static var email: String?
        static var name: String?

    }

    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, relationship_status, gender, user_location, user_education_history, email"]).start(completionHandler: { (connection, result, error) -> Void in
        if (error == nil){
            //let fbDetails = result as! NSDictionary
            //print(fbDetails)

            if let userDataDict = result as? NSDictionary {
                fbDemographics.gender = userDataDict["gender"] as? String
                fbDemographics.email = userDataDict["email"] as? String
                fbDemographics.name = userDataDict["name"] as? String
                fbDemographics.user_location = userDataDict["user_location"] as? String
                fbDemographics.user_education_history = userDataDict["user_education_history"] as? String
                fbDemographics.relationship_status = userDataDict["relationship_status"] as? String

                let myEducation = fbDemographics.user_education_history
                let myEmail = fbDemographics.email
                let myGender = fbDemographics.gender
                let myName = fbDemographics.name
                let myStatus = fbDemographics.relationship_status
                let myLocation = fbDemographics.user_location

                self.performSegue(withIdentifier: "LoginToHome", sender: (Any).self)

            }

        }

SECOND VIEW CONTROLLER
class SecondViewController: UIViewController {

@IBAction func verticalSliderChanged(_ sender: UISlider) {

        let currentValue = String(sender.value);

        sliderLabel.text = "\(currentValue)"

    func viewDidLoad() {
        super.viewDidLoad()

        ***ViewController.fbDemographics.myEmail***

    }
}

A: The problem is that you've defined your struct inside viewDidLoad. So the scope is limited to that method. Move it out of viewDidLoad, but still in ViewController, and you should be able to access it from the SecondViewController. Obviously, you'll have to fix that reference to myEmail, too, because it's called email. Also, in your SecondViewController you should pull viewDidLoad implementation out of the verticalSliderChanged method; the viewDidLoad should be a top-level instance method of SecondViewController, not defined inside another method.
There are deeper problems here, though. Rather than using struct with static variables, you really should make those simple instance variables, create an instance of your FbDemographics type (note, start struct types with uppercase letter), and then pass this instance in prepare(for:sender:).

For example, the right way to pass data would be to:

*

*eliminate static variables;

*give your struct a name that starts with uppercase letter;

*create instance of your struct; and

*pass this instance to the destination view controller in prepare(for:sender:).

E.g.
struct FbDemographics {
    var relationshipStatus: String?
    var gender: String?
    var userEducationHistory: String?
    var userLocation: String?
    var email: String?
    var name: String?
}

class ViewController: UIViewController {

    var demographics: FbDemographics?

    override func viewDidLoad() {
        super.viewDidLoad()

        performRequest()   // I actually don't think you should be initiating this in `viewDidLoad` ... perhaps in `viewDidAppear`
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? SecondViewController {
            destination.demographics = demographics
        }
    }

    func performRequest() {
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, relationship_status, gender, user_location, user_education_history, email"]).start { connection, result, error in
            guard let userDataDict = result as? NSDictionary, error == nil else {
                print("\(error)")
                return
            }

            self.demographics = FbDemographics(
                relationshipStatus: userDataDict["relationship_status"] as? String,
                gender: userDataDict["gender"] as? String,
                userEducationHistory: userDataDict["user_education_history"] as? String,
                userLocation: userDataDict["user_location"] as? String,
                email: userDataDict["email"] as? String,
                name: userDataDict["name"] as? String
            )

            self.performSegue(withIdentifier: "LoginToHome", sender: self)
        }
    }

}

And then SecondViewController could:
class SecondViewController: UIViewController {

    var demographics: FbDemographics!

    override func viewDidLoad() {
        super.viewDidLoad()

        let value = demographics.email  // this should work fine here
    }

}


text:
Q: How to extract/install android-ndk-r10c-linux-x86_64.bin I downloaded Android NDK from https://developer.android.com/tools/sdk/ndk/index.html but I am not able to extract it.
If I double-click it I get an error:

Could not display "android-ndk-r10c-linux-x86_64.bin". The file is of an unknown type

I have selected the option in permissions to "Allow executing file as program".
When I attempt to execute it with terminal (sudo ./android-ndk-r10c-linux-x86_64.bin) I get this error:

sudo: unable to execute ./android-ndk-r10c-linux-x86_64.bin: No such file or directory

I have 64 bit Ubuntu 14.10 running on VirtualBox. Any help would be appreciated.

A: Use 7z x *bin as workaround as all r10c packages are 7z archive.
To install 7z, do sudo apt-get install p7zip-full.
Found that from here: https://code.google.com/p/android/issues/detail?id=78148

A: Running
sudo apt-get install p7zip-full
7z x android-ndk-r10c-linux-x86_64.bin

will extract the ndk.

A: Android's NDK now ships as an self extracting executable. You likely need to set the executable bit, however:
$ chmod +x android-ndk-r10c-linux-x86_64.bin
 $ ./android-ndk-r10c-linux-x86_64.bin


text:
Q: How to call two actions in same method? I have 2 actions which are :
This is first
I insert person here :
export const InsertOrUpdate = (person) => {

    return (dispatch) => {
        var instance = Axios.create({
            baseURL: 'url',
            // timeout: 1000,
            headers: {
                "Content-Type": "application/json"
            }
        });
        instance.get("/InsertWorker", {
            params: {
                Name: person.Name,
                Surname: person.Surname,
                Duty: person.Duty,
                DateOfDay: person.Date.substring(0, person.Date.length - 9),
                Shift: person.Shift,
                WorkDayCount: person.WorkDayCount,
                Equipment: person.Equipment,
                Sicil: person.Sicil,
                Ship: person.Ship
            }
        });

    }
}

This is second
I call workers here :
export const getSignedWorkers = (collection) => {
    return (dispatch) => {
        var instance = Axios.create({
            baseURL: 'url',
            // timeout: 1000,
            headers: {
                "Content-Type": "application/json"
            }
        });

        instance.get('/GetWorkers', {
            params: {
                DateOfDay: collection.Tarih,
                Shift: collection.Vardiya
            }
        })
            .then((response) => response.data)
            .then(x => {
                const Signed = str3.filter(x => x.Ship != "" && x.Shift != "H");
                console.warn('signed', Signed);

                const UnSigned = str3.filter(x => x.Ship == "" || null);
                const RemoveOnHolidays = UnSigned.filter(x => x.Shift != "H");

                const OnHoliday = str3.filter(x => x.Shift == "H");

                const AllWorkers = {};
                AllWorkers.signed = Signed;
                AllWorkers.Unsigned = RemoveOnHolidays;
                AllWorkers.OnHoliday = OnHoliday;

                dispatch({ type: FETCH_SIGNED_WORKERS_SIGNED, payload: AllWorkers });

            })
            .catch((error) => {
                console.warn('error', error);
            })

    }
}

I call this actions here :
_Insert = (person) => {
        person.Ship = this.props.gemi_Sefer_No;

        this.props.InsertOrUpdate(item);    <------- Here I call first action

        var date = new Date().getDate(); //Current Date
        var month = new Date().getMonth() + 1; //Current Month
        var year = new Date().getFullYear(); //Current Year
        var tarih = year + "/" + month + "/" + date;

        let collection = {};
        collection.Tarih = tarih;
        collection.Vardiya = this.props.vardiya == 0 ? "S" : this.props.vardiya == 1 ? "A" : this.props.vardiya == 2 ? "G" : null

        this.props.getSignedWorkers(collection);   <--- Here I call second action

    }

I try to insert workers to database then call  all workers from database and use another component with redux. However, sometimes it works correctly sometimes not.
I mean , when I insert to database and call back again, insert worker works right however calling all workers come without worker which I insert last one. As I said, it works sometimes right. What should I do ?. Is that wrong to call two actions in same method ? if it is, what should I do ?


text:
Q: No setter/field for while trying to populate a listview on firebase I am trying to retrieve data from firebase and display it on my listview using firebase-ui. The code runs fine but nothing is displayed on the list view. This is what I get from my logs:

W/ClassMapper: No setter/field for -KNRXdDOlA9nV6qxXvOl found on class com.example.sammie.coreteccontacts.Sacco

Here is my FirebaselistAdapter
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
FirebaseListAdapter<Sacco> adapter = new FirebaseListAdapter<Sacco>(getActivity(), Sacco.class, android.R.layout.simple_list_item_1, mDatabaseReference) {
 @Override
protected void populateView(View view, Sacco sacco, int i) {
((TextView)view.findViewById(android.R.id.text1)).setText(Sacco.getName());
}
};
contactList.setAdapter(adapter);

Here is my Sacco class:
package com.example.sammie.coreteccontacts;

public class Sacco {

    String description;
    String location;
    static String name;

    public Sacco() {
    }

    public Sacco(String description, String location, String name) {
        this.name = name;
        this.description = description;
        this.location = location;
    }

    public static String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getLocation() {
        return location;
    }
}

Here is a sample of the data from firebase

KNRWnG6BTkbGJQJVq9Qaddclose
description:"test description"
location: "test location"
name: "test name"

A: There are no setter methods in your class.
public void setName(String name) {
    this.name = name;
}

public void setDescription(String description) {
    this.description = description;
}

public void setLocation(String location) {
    this.location = location;
}

BUT

-KNRWnG6BTkbGJQJVq9Qaddclose

This is a unique key which is to be obtained as an object containing your description, location and name.

W/ClassMapper: No setter/field for -KNRXdDOlA9nV6qxXvOl found on class
  com.example.sammie.coreteccontacts.Sacco

This shows that there is an error with your database listener's positioning. It is reading -KNRWnG6BTkbGJQJVq9Qaddclose as a variable to your Sacco class instead of an object of it.
Please check the JSON file and DatabaseReference. Most probably it should be like this:

*

*UnderChilds <----- (ON CHILD LISTENER).

*

*-KNRWnG6BTkbGJQJVq9Qaddclose

*-KNRWnSYnuojkbGJQJVq9Qaddclos

A: You have to get reference to your node:
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Your Node Name");