text:
Q: React Native - (0, _redux.combineReducers) is not a function I'm currently learning some redux in React Native. But i keep stumbling on one error if i try to combine my reducers in a index.js file.
(0, _redux.combineReducers) is not a function

I watched some tutorials for how to use this and I follow with every step but it's keep coming on my screen.
My App.js looks like this:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers/reducers';
import { Header } from './components/common/Header';

let store   = createStore(reducers, applyMiddleware(ReduxThunk));

export default class App extends Component {
    render() {
        return (
            <Provider store={ store }>
                <View style={ styles.container }>
                    <Header title="Tech Stack"/>
                </View>
            </Provider>
        );
    }
}

My reducers.js in the folder src/reducers:
console.log('HELLO');
import { combineReducers } from 'redux';
console.log( combineReducers );
import LibraryReducer from './LibraryReducer';

const reducers = combineReducers({
    libraries: LibraryReducer
});

export default reducers;

// Fixed the log. When i'm loggin combineReducers i get undefined.

LibraryReducer.js
import data from '../data/LibraryList.json';

export default () => data;

Console errors:
[Error log][1]

data json:
[
    {
        "id": 0,
        "title": "React",
        "description": "JS framework"
    },
    {
        "id": 1,
        "title": "Vue",
        "description": "JS framework"
    },
    {
        "id": 2,
        "title": "Angular",
        "description": "JS framework"
    }
]

package.json
{
  "name": "redux",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.6.1",
    "react-native": "0.57.5",
    "react-redux": "^5.1.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.49.2",
    "react-test-renderer": "16.6.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

THANK YOU ALL for your suggestions!
SOLVED:
Started a new project but don't gave it the name redux itself.

A: It looks like you have the same issue as here.
TLDR: rename the folder you have called redux to something else, wipe your node_modules and reinstall and it should work.

A: We looked at a lot of different things, but the problem was one with module resolution. import { combineReducers } from 'redux' was not working, apparently because the project, itself, was given the name 'redux' in its package.json file and/or because a folder in the project's root was named 'redux'.

A: I'm going to add this here as I came across this same issue today and luckily I quickly figured out the issue! The reason this error appeared in my builds was because I use the babel module resolver plugin and I named one of my module resolvers redux  If anyone comes across this answer, make sure you don't name any of your babel module resolvers the same as an NPM package.

A: So first of all i would install ReduxThunk on your project folder, so run following:
npm i redux-thunk --save

next in your App.js import this lib like so
import ReduxThunk from 'redux-thunk'

then create the Redux Store
const store = createStore(reducers, applyMiddleware(ReduxThunk))

the Method for creating the reducers functions should be at the end of your reducers.js file like so.
const reducers  = combineReducers({
    libraries,
    //otherFunctions...
});

export default reducers;

don´t forget to import the combineReducers method from redux in your reducers.js file.
import { combineReducers } from 'redux';

combineReducers method accept functions that you previously declared in your reducers.js for expample following ( im writing...)
const INITIAL_STATE = { isLoggedIn: false }
function libraries(state = INITIAL_STATE, action){
   switch (action.type) {

     default:
      return state
   }
 }

you should be able to write many cases for the switch statement as you want. for example..
const INITIAL_STATE = { isLoggedIn: false }
function libraries(state = INITIAL_STATE, action){
   switch (action.type) {

     case "isLogginSuccess":
      return {...state, isLoggedIn: action.payload}

     default:
      return state
   }
 }

the reducer case "isLogginSuccess" should be trigered by calling another funcion inse your desired component.


text:
Q: Programmatically Position Image on RDLC using Database Values I have an image that I'd like to programmatically position on an RDLC based on the X and Y values from the database. I originally thought I could just apply an expression to the Left and Top properties of the Location property, however it doesn't seem like there's an option to do that.
Is there anything I can do?
EDIT:
Fortunately the padding property allows expressions, however it seems I have another issue on my hands.
Here's my code for the "Left" property within the "Padding" property group.
=((Sum(Fields!intDessinX.Value, "dsRapport_uspReportCommandeInhumation") * 2.54) / 96) & "cm"

Essentially I'm converting the intDessinX value from the database from pixel to cm using the formula "cm = (pixel * 2.54) / 96" and finally appending "cm" to the end of the expression.
This does not work. I've done some research and can't seem to find how to take the value from a dataset and translate it into a measurement.
Does anyone know how to do this?
Thanks,
Mikael

A: Solved!! Since we're developing the website in French we had previously set the culture to "fr-CA" and this causes the decimal character to be replaced by a comma character.
As such, when it came time for the reporting engine to evaluate the value (with the comma), it wasn't positioning my image as it simply didn't understand that the value was in fact numeric.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this next.js project rendering the component? I'm trying to understand how React.memo works and created the following next.js project. I was expecting the Test component to render only once as I'm passing it the same prop, but it renders every time.
I added the const txt = `${msg}${Math.random()}`; line for testing purpose, but I get the same behavior if I remove it - the component renders three times at every page. With it, I get the something similar to the lines below:
Test: test0.22056845903240596
Test: test0.15269599756070829
Test: test0.8253090140192767

I was expecting:
Test: test0.22056845903240596
Test: test0.22056845903240596
Test: test0.22056845903240596

Also it looks like the areEqual function defined at /components/test.tsx never gets called.
codesandbox link
/components/test.tsx
import React from "react";

type TestProps = {
  msg: string;
};

function areEqual(prevProps: any, nextProps: any) {
  console.log(prevProps, nextProps);
  return prevProps === nextProps;
}

export default React.memo<TestProps>(({ msg }) => {
  console.log("Test rendered");
  const txt = `${msg}${Math.random()}`;
  return
Test: {txt}
;
}, areEqual);

/pages/index.tsx
import React from "react";
import Link from "next/link";
import dynamic from "next/dynamic";

const DynamicTest = dynamic(() => import("../components/test"), { ssr: false });

export default () => (

    <DynamicTest msg="test"></DynamicTest>
    <DynamicTest msg="test"></DynamicTest>
    <DynamicTest msg="test"></DynamicTest>
    <Link href="/second">
      Go to second page
    </Link>

);

/pages/second.tsx
import Link from "next/link";
import dynamic from "next/dynamic";

const DynamicTest = dynamic(() => import("../components/test"), { ssr: false });

export default () => (

    <DynamicTest msg="test"></DynamicTest>
    <DynamicTest msg="test"></DynamicTest>
    <DynamicTest msg="test"></DynamicTest>
    <Link href="/">
      Go to first page
    </Link>

);


text:
Q: NodeJS + ExpressJS wait 2 minutes before sending .js files I'm having problems loading .js files with my NodeJS project. In this project I'm currently running NodeJS 0.6.15 and Express 2.5.6.
The problem is that when I make a request for a .js file, it takes exactly 2 minutes.
Any idea?!
It's quite strange because it has been working for a long time, and now without changing anything it gets this error. After 2 minutes it returns the files perfectly.

A: Most likely, you are not calling response.end(), so the connection times out in about 2 minutes (typical of HTTP/1.1), gets flushed and closed, and you get your content back in the browser.

A: I had a similar issue on Ajax requests instead of .js files. And it turns out that it is caused by the browser itself. By mistake, I installed 32bit Chrome/Firefox in my Windows8 x64 system.
Issue detail
The issue is that any Ajax requests with Content-Type application/json with a small or almost empty response will hang for 2 minutes even though in the Developer Tool you can see the response has returned. And after 2 minutes, the browser marked that request as finished with exact 2 minutes of Content Download in the request's Timing result.
However, this didn't happen for requests with large response. Weird indeed.
Environment

*

*Nodejs v4.2.4 or Nodejs v0.12.9

*Expressjs 4.13.3

A: app.use(session({
    secret: config.secrets.session,
    saveUninitialized: false,
    resave: false,
    store: new mongoStore({
    mongooseConnection: mongoose.connection,
      db: 'freport'
    })
 }));

set saveUninitialized: false solve the problem, but don't know why yet


text:
Q: How to run multiple t.test in a data.frame? I have a data,
temp_data <- as.data.frame(matrix(rbinom(9*9, 1, 0.5), ncol=9, nrow =9))
colnames(temp_data) <- paste(rep(c("a","b","c"), each=3), rep(c(1,2,3), 3), sep = "")

I want to run multiple t.test on the factors of the data.frame and get an output file that shows this
     factor.1 factor.2 p.value
[1,] "a1"     "c1"     "value 1 "
[2,] "a2"     "c2"     "value 2 "
[3,] "a3"     "c3"     "value 3 "
[4,] "b1"     "c1"     "value 4 "
[5,] "b2"     "c2"     "value 5 "
[6,] "b3"     "c3"     "value 6 "

How can I get this results?

A: You could do this:
pa <- unlist(lapply(1:3, function(i) t.test(temp_data[, i], temp_data[, i + 6])$p.value))
pb <- unlist(lapply(1:3, function(i) t.test(temp_data[, i + 3], temp_data[, i + 6])$p.value))
p <- c(pa, pb)
p.table <- as.matrix(data.frame(factor.1 = colnames(temp_data[1:6]),
           factor.2 = rep(colnames(temp_data[7:9]), 2),
           p.value = p))
p.table
#      factor.1 factor.2 p.value
# [1,] "a1"     "c1"     "0.652543514"
# [2,] "a2"     "c2"     "0.176463197"
# [3,] "a3"     "c3"     "0.176463197"
# [4,] "b1"     "c1"     "0.372458894"
# [5,] "b2"     "c2"     "0.003949773"
# [6,] "b3"     "c3"     "0.652543514"


text:
Q: Unique determination of displacement gradients in structural physics? I am working on a 2-D planar problem in the x-y direction, dealing with stresses, strain, displacements. Under the linear elastic relation and after substitution I can write the following:
$$
\begin{bmatrix}
    \sigma_{xx} & \sigma_{xy} \\
    \sigma_{xy} & \sigma_{yy}
\end{bmatrix} = \mu
\begin{bmatrix}
\frac{\partial u}{\partial x} & \frac{\partial u}{\partial y} \\
\frac{\partial v}{\partial x} & \frac{\partial v}{\partial y}
\end{bmatrix}
 + \mu
\begin{bmatrix}
\frac{\partial u}{\partial x} &  \frac{\partial v}{\partial x}\\
\frac{\partial u}{\partial y} & \frac{\partial v}{\partial y}
\end{bmatrix}
 + \lambda\begin{bmatrix}
 \frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} & 0\\
 0 &  \frac{\partial u}{\partial x} + \frac{\partial v}{\partial y}
 \end{bmatrix}
$$
I need to obtain the unknowns, which are the 4 displacement gradients
$$
\frac{du}{dx}; \frac{du}{dy}; \frac{dv}{dx}; \frac{dv}{dy}
$$
However, since the stress matrix is symmetrical, I only have 3 knowns. In structural problems, where does this 4th condition come from?

A: You need to apply "Compatibility" conditions to the strain field. For small deformations, these conditions ensure that the displacement gradient components that you are looking for result from the gradient of a true displacement field. For this to be true, the "curl of the curl of strain" must disappear everywhere.
$$
\nabla \times (\nabla \times \epsilon) = \mathbf{0}
$$
where $\epsilon = \frac{1}{2}\left(\nabla \mathbf{u} + (\nabla \mathbf{u})^T\right)$ is the infinitesimal strain tensor.
For your two-dimensional problem, this condition takes the form:
\begin{align*}
\frac{\partial^2 \epsilon_{11}}{\partial x_1^2} - 2\frac{\partial^2 \epsilon_{12}}{\partial x_1 \partial x_2} + \frac{\partial^2 \epsilon_{22}}{\partial x_2^2} = 0
\end{align*}
This is the last equation that you need in order to solve for the components of the displacement gradient.
As a point of interest, it is usually easier to solve for the actual displacement field and to post-process this field for the stresses and strains. This is the procedure used in finite element software packages, and indeed in most analytical approaches as well. I'd recommend that you look up "variational methods" for elasticity
https://en.wikipedia.org/wiki/Compatibility_(mechanics)


text:
Q: Pick elements from list "separately" I have the following list I want to pick elements from:
mylist = {1, 5, 7, 3, 4, 7, 2, 9, 9, 1, 10, 12, 2, 64, 34, 64}

I have another list with 0's and 1's which is my selector:
selector = {1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1}

I want to select all the entries from mylist where selector has a 1. I know I can do this via:
Pick[mylist,selector,1]

BUT: Pick gives me all the selected elements from mylist together like this:
{1, 5, 7, 7, 2, 9, 1, 10, 34, 64}

I want the elements which are separated in selector by a 0 to be separate lists. That is, as a result I want to have a list of lists like this:
{{1,5,7},{7,2},{9,1,10},{34,64}}

Any help appreciated!

A: Map[Take[mylist, #] &,
 Map[Flatten[#] &,
   FindClusters[Position[selector, 1]]] //. {w___, {q_, __, x_},
    k___} :> {w, {q, x}, k}]

{{1, 5, 7}, {7, 2}, {9, 1, 10}, {34, 64}}

A: mylist = {1, 5, 7, 3, 4, 7, 2, 9, 9, 1, 10, 12, 2, 64, 34, 64};
selector = {1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1};

pick = Pick[mylist, selector, 1];

split = Length /@ Cases[Split[selector], {1 ...}]

{3, 2, 3, 2}

Internal`PartitionRagged[pick, split]

{{1, 5, 7}, {7, 2}, {9, 1, 10}, {34, 64}}

A: Because your selector is 0 or 1, SplitBy can be used as follows.
Select[SplitBy[mylist*selector, Positive], #[[1]] > 0 &]

A: You can combine Map, Take, and SequencePosition:
Map[Take[mylist, #] &,
 SequencePosition[selector, {1 ..}, Overlaps -> False]]

(* {{1, 5, 7}, {7, 2}, {9, 1, 10}, {34, 64}} *)

A: You can find positions where differences of selector is nonzero. Then you can take corresponding sublists. This straightforward solution is relatively fast (two times faster then eldo's solution, which is already very efficient)
list = {1, 5, 7, 3, 4, 7, 2, 9, 9, 1, 10, 12, 2, 64, 34, 64};
selector = {1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1};

pick[list_, sel_] :=
  Take[list, #] & /@ Transpose@{#[[;; ;; 2]], #[[2 ;; ;; 2]] - 1} &@
     Pick[Range@Length@#, #, 1] &@Abs@Differences@Join[{0}, sel, {0}];

pick[list, selector]
(* {{1, 5, 7}, {7, 2}, {9, 1, 10}, {34, 64}} *)

n = 1000000;
list = RandomInteger[100, n];
selector = RandomInteger[1, n];

pick[list, selector]; // RepeatedTiming
(* {0.706, Null} *)

A: Lots of nice answers already but coming to this question late here are my ideas.
Application of Szabolcs's How to efficiently find positions of duplicates? with adaptations:
fn1[a_, b_] :=
  a[[#]] & /@ SplitBy[Range@Length@a, b[[#]] &][[2 - b[[1]] ;; ;; 2]]

Application of my intervals from Find continuous sequences inside a list (load it first)
fn2[a_, b_] :=
  Take[a, #] & /@ intervals @ SparseArray[b]["AdjacencyLists"]

Test:
fn1[mylist, selector]

fn2[mylist, selector]

{{1, 5, 7}, {7, 2}, {9, 1, 10}, {34, 64}}

{{1, 5, 7}, {7, 2}, {9, 1, 10}, {34, 64}}


text:
Q: Getting Error too many indices for tensor of dimension 3 I am trying to Read an Image using GeneralizedRCNN, Input shape is given as a comment with code. The problem is I am getting an error while tracing the model with input shape. The error is :
> trace = torch.jit.trace(model, input_batch) line Providing the error
> "/usr/local/lib/python3.7/dist-packages/torch/tensor.py:467:
> RuntimeWarning: Iterating over a tensor might cause the trace to be
> incorrect. Passing a tensor of different shape won't change the number
> of iterations executed (and might lead to errors or silently give
> incorrect results).   'incorrect results).', category=RuntimeWarning)
> --------------------------------------------------------------------------- IndexError                                Traceback (most recent call
> last) <ipython-input-25-52ff7ef794de> in <module>()
>       1 #First attempt at tracing
> ----> 2 trace = torch.jit.trace(model, input_batch)
>
> 7 frames
> /usr/local/lib/python3.7/dist-packages/detectron2/modeling/meta_arch/rcnn.py
> in <listcomp>(.0)
>     182         Normalize, pad and batch the input images.
>     183         """
> --> 184         images = [x["image"].to(self.device) for x in batched_inputs]
>     185         images = [(x - self.pixel_mean) / self.pixel_std for x in images]
>     186         images = ImageList.from_tensors(images, self.backbone.size_divisibility)
>
> IndexError: too many indices for tensor of dimension 3

model = build_model(cfg)
model.eval()
# print(model)
input_image = Image.open("model/xxx.jpg")
display(input_image)
to_tensor = transforms.ToTensor()
input_tensor = to_tensor(input_image)
# input_tensor.size = torch.Size([3, 519, 1038])
input_batch = input_tensor.unsqueeze(0)
# input_batch.size = torch.Size([1, 3, 519, 1038])
trace = torch.jit.trace(model, input_batch)

A: This error occurred because input_batch.size = torch.Size([1, 3, 519, 1038])  has 4 dimensions and trace = torch.jit.trace(model, input_batch) expected to get a 3 dimensions as input.
you don't need input_batch = input_tensor.unsqueeze(0). delete or comment this line.

A: By default
..
The torch.jit.trace function cannot be used directly. However, it does provide a wrapper called that the model can take a tensor or a tuple of tensors as input. You can find a way to use it because of them.
The code for tracing the Mask RCNN model looks like this:
import torch
import torchvision
from detectron2.export.flatten import TracingAdapter
def inference_func(model, image):
    inputs= [{"image": image}]
    return model.inference(inputs, do_postprocess=False)[0]
print("cfg.MODEL.WEIGHTS: ",cfg.MODEL.WEIGHTS)   ## RETURNS : cfg.MODEL.WEIGHTS:  drive/Detectron2/model_final.pth
model= build_model(cfg)
example= torch.rand(1, 3, 224, 224)
wrapper= TracingAdapter(model, example, inference_func)
wrapper.eval()
traced_script_module= torch.jit.trace(wrapper, (example,))
traced_script_module.save("drive/Detectron2/model-final.pt")


text:
Q: Is 'git reset --hard Head~1' enough to undo a git pull? I am a git newbie, I am trying to understand to undo changes in git. Say I have two branches
1: master
2: work
I am working in work branch and I want to pull the latest changes from my teammates in work branch, so I am supposed to give the command
git pull origin work

But instead, I gave the command
 git pull origin master

It fetches a bunch of commits from master branch.Now, I want to undo the last pull(assuming no local uncommited changes), will this command be sufficient
git reset --hard HEAD~1

Will the above command accomplish undoing git pull? Is there any scenario where it might not work?
Edit
After reading the answers, Do HEAD~1 and ORIG-HEAD refer to the same commit after a pull/merge?

A: First of all, git reset does not take --head option, I think you mean --hard.  Second, no, it's not enough as git reset --head HEAD~1 will take your repository to the state of the previous commit. If git pull resulted in many new commits, it would not be enough. You need to do:
$ git reset --hard ORIG_HEAD

It works because before doing merge, rebase and other potentially dangerous operations Git sets a special reference called ORIG_HEAD equal to the SHA1 of current HEAD before this operation. Next time before doing git pull note SHA1 of the current HEAD and after git pull see yourself that ORIG_HEAD points the previous HEAD:
$  cat .git/ORIG_HEAD

A: I would recommend you to use git gui and gitk to see the history and do the resets.
But if you want to use the terminal:
To see where the HEAD was before the pull
git reflog

You should see the SHA1 of the previous position of the HEAD.
Then ( As suggested by Kenney ):
git reset --hard <previousSHA1>

or:
git branch -f master <previousSHA1>


text:
Q: Как создавать ребусы в С++? Нужно отгадать ребус, где вместо буков будут числа от 0 до 9(разные буквы, разные числа). Нужен пример для А, дальше разберусь. Какую команду использовать?

A: Ну, проще всего - перебор. Если под конкретное количество букв - что-то типа
for(int A = 1; A <= 9; ++A)
{
    for(int B = 1; B <= 9; ++B)
    {
        if (A == B) continue;
        for(int C = 0; C <= 9; ++C)
        {
            if (A == C) continue;
            if (B == C) continue;
            // расписываю подробное выражение для понятности :)
            if (A*100+B*10+С + A*100+C*10+B == B*100+C*10+A)
                cout << A << " " << B << " " << С << endl;
        }
    }
}

(Ну, или от 0 - если такой вариант проходит. В вашем первом задании он годится только для C).
Если букв много - можно перестановками "01234565789", но тогда нужно несколько править перестановку, так как нужны не все 10! вариантов, а только для определенного количества букв. Боюсь, что рассказать, как это делать - явно выходит за рамки вопроса, и требует квалификации, которой, судя по вопросу, вы пока не обладаете...
И в общем же случае имеет смысл писать свой синтаксический анализатор таких выражений.
Я как-то такой написал для себя, с тех пор для меня все эти задачки - так, набрать в командной строке и получить ответ :)


text:
Q: When the excess electrons move to equalise themselves in a negatively charged conductor, can it result in positively charged atoms? i am a beginner in physics and am currently studying electrical engineering. I was wondering when the excess electrons move to equalize themselves, can it result in some atoms being positively charged due to the spacing between the electrons causing the majority of the electrons to be outside the atoms.
An example would be the picture below whereby the force F1 has the same magnitude as F2 and thus the middle electron is in an equilibrium. However, in its equilibrium position it has been pushed out of its atom thus resulting in the atom being positively charged in a conductor that is negatively charged.

A: When atoms come together to form a solid (like the metal) all of the electrons and nuclei would in principle have to be considered together. However, in solid state physics we mostly assume that the lower lying electrons remain closely bound to their respective nuclei. The valence electrons and in this case the excess electrons however, move freely in the underlying potential of the lattice. This means that we don't assign them to specific atoms anymore. You will find that there are different charge densities, i.e. locations with a more positive charge and locations with a more net negative charge.


text:
Q: Create random uniform vector Given gunction float frand(), that generates uniformly-distributed random floating point value, in range [0.0, 1.0)
How can I create uniformly-distributed random 3D unit vector, and 4D unit quaternion?
(so that a 3D vector lies on a unit sphere, and 4D - on a unit hypersphere, and vectors are uniformly-distributed among correspoiding surface)

A: You should pick components of your vector from Gaussian distribution (mean = 0, deviation = 1) using your frand() function and then normalize it.
Another simpler approach is to generate random vector (x, y, z...) as x = frand(); y = frand(); ... and discard it (generate new one), if it is longer than 1. Then normalize this vector. This will eliminate the cases that skew the distribution. I however find this method ugly, because it's unnecessary example of Las Vegas algorithm, which might not terminate.
Check out this answer to similar question: random unit vector in multi-dimensional space


text:
Q: Is it normal for 4 chickens to spawn from one egg? So the chickens I have laid 2 eggs. The first egg was a success while the second one was a failure.
But when I looked down it isn't one chicken that spawned, it was four.

All my other chickens were grown and 2 eggs yielded me 4 chickens.
Is this a normal Minecraft probability that is coded where multiple babies come out of an egg or did Minecraft just glitch on me?

A: According to the game wiki:

When thrown by a dispenser or by pressing the use button, an egg has a 1⁄8 (12.5%) chance of spawning a chick. If this occurs, there is a 1⁄32 (3.125%) chance of spawning three additional chicks (on average, 1 out of every 256 eggs spawns 4 chicks). In other words, whenever an egg is thrown, there is a 31⁄256 chance of spawning 1 chick and a 1⁄256 chance of spawning four chicks.

Is it normal? Yes - it is not a glitch.  It is just uncommon.


text:
Q: Login with hashed password c# Will I be able to login with password which is hashed in a database if I have code like this:
string queryLog = "SELECT username, password FROM users WHERE username = @username and password = @password";
                using (SqlCommand command = new SqlCommand(queryLog, con))
                {
                    command.Parameters.AddWithValue("@username", LoginUsername_txt.Text);
                    command.Parameters.AddWithValue("@password", LoginPassword_txt.Text);

                    con.Open();
                    SqlDataAdapter adpt = new SqlDataAdapter(command);
                    DataSet dts = new DataSet();
                    adpt.Fill(dts);
                    con.Close();

                    if (dts.Tables[0].Rows.Count >= 1)
                    {
                        passingText = LoginUsername_txt.Text;
                        this.Hide();
                        Work_Orders d = new Work_Orders();
                        d.ShowDialog();
                    }
                    else MessageBox.Show("Invalid username or password!", "Error signing in!");
                }

As you can see I'm checking if I get at least 1 result back from database. But what happens if password is hashed in the database.

A: The password is [rightly so] stored as a hash for security reasons; but once hashed, it is stored as a string, and comparable directly to that exact string. Your code would currently require you to use the hashed password string as the password - not an ideal scenario...
What needs to happen is an intermediary step:
command.Parameters.AddWithValue("@password", Hash(LoginPassword_txt.Text));

Where string Hash(string password) is a function that will hash the password using the same hashing algorithm that was used at the time the account was created (and password stored in the database).

A: To be able to Login with the Hashed password, you need to Hash the password you received from the Password TextBox using the same algorithm you used to hash the password stored in the database before and then pass the it to the sql query.
string hasedPassword = Hash(PasswordTextBox.Text);  // TODO: Make a Hash() function
command.Parameters.AddWithValue("@geslo", hasedPassword );


text:
Q: Printing Only Theorem Environments, each on a new page I am currently revising for my exams, and I need to remember the proofs of a lot of theorems. One of my ideas was to have each theorem on a new page so that I can try to replicate the proof below it. My notes are currently in LaTeX and it would be great if there was a way to print only the Theorems, Lemmas, and so on (all the theorem environments) each on a new page.  Ideally I would like to have this done automatically since I have over 500 pages of notes. Does anybody know how can I do this or if it is possible to do it with scraping?
Thank you in advance.


text:
Q: How to make React Suspense work with a promise? I don't quite get how Suspense works in React.  I see Relay uses it, and even in code from another team at the company, only when I ask them how it works, they cannot really answer it (it seems they copied the code from somewhere).
For example, if I have the code:
import {Suspense} from "react";

function App() {
  return (
    <div className="App">
      <Suspense fallback="loading...">
        hello world
      </Suspense>
    </div>
  );
}

Is it possible to convert it to some kind of promise, using setTimeout() so that 3 or 5 seconds later, the loading... phrase would disappear and the resolved promise that gives "success!" would show up?  Is it by the mechanism of a promise?
So far, I see the lazy() being used, and the current docs says:

Today, Suspense only supports one use case: loading components dynamically with React.lazy. In the future, it will support other use cases like data fetching.

In the future we plan to let Suspense handle more scenarios such as data fetching. You can read about this in our roadmap.

And the roadmap above mentioned the data fetching part:

React 16.x (~mid 2019): The One with Suspense for Data Fetching

and it is using unstable_createResource to fetch data... so it seems it is supporting data fetching already in 2019, and now is already November 2022.  Is it data fetching by some kind of "flag", "state" mechanism but not by promise? It seems somewhat mysterious.
Together with Relay, it only makes it harder to understand, because I tried to understand Suspense well first, and then Relay, but it seems I can't understand Suspense that well to begin with.  When I ask coworkers who have used Relay and Suspense in their code, they don't understand it either. They just copied and pasted the code from some where else, which may not be a good scene for software engineering: people do something and they don't know what's really happening.
So the simple question is, how does Suspense work? Is it by making use of promise or something else?  And to understand how it works with something else, like lazy() or Relay, should we consider it "an abstraction" or some kind of "magic", as stated in SICP?
To make the best guess, I am wondering if it is like:
const [isLoading_react_internal__, setIsLoading_react_internal__] = useState(true);

and the setIsLoading_react_internal__ is passed down to the children components, so that they can call setIsLoading_react_internal__(), and the Suspense is no more than
{isLoading_react_internal__ && {fallback}}

If this really is the case, I hope Facebook or Meta can make it more transparent and perhaps state it in their docs or in StackOverflow so that developers know what is going on. Can any React open source developer confirm how it works here?


text:
Q: Proving the existence of an inverse of a matrix. (Linear algebra) Suppose that $A$ has no inverse. Prove that there exists a vector $b$ such that $Ax = b$ has no solution
My try
Proving by contradiction ,
Assume that for all vector $b$, $Ax = b$ have at least one solution.
This implies
$$A^{-1}Ax = A^{-1}b$$ which then gives $$x=A^{-1}b$$ but this means that $A^{-1}$ exists and hence contradicting our assumption that $A$ has no inverse, hence proving our original statement. Is my prove correct.Could anyone explain Thanks. Also lets say if i would to use a direct proof instead. How would i go about doing it.

A: Use the contrapositive.
If $Ax=b$ has at least one solution for each $b$, then you can solve $Ax=e_i$ for each $e_i$, where $e_i$ is a vector in the canonical basis. But then the solutions $x_i$ can be put as columns in a matrix $X$ and get $AX=I$. We have then found an inverse for $A$. (At least, a right inverse.)

A: If the determinant is zero then the rows and columns of A are linearly dependent!
look at this: What does it mean to have a determinant equal to zero?
This means that the sets of equations you get from $Ax=b$ are linearly dependent! Then the number of equations $Ax$ might be less than the number unknowns $b$! In which case a solution does not exist!

A: Elementary matrices can be used for a proof. If $A$ is not invertible, then there are elementary matrices $E_r,...,E_1$ such that
$$E_r...E_1A=A_{red}$$
where the reduced matrix $A_{red}$'s bottom row is zero row. Let $\vec v=[0\;0 ...0\;0\;1]^{T}$. Then $A_{red}\vec x=\vec v$ has no solution. Hence,
$$E_r...E_1A\vec x=\vec v$$
$$A\vec x=E_1^{-1}...E_r^{-1}\vec v=\vec {w}$$
has no solution.


text:
Q: C++/CLI: functions inherited from template class are not visible in C# I've a hard time figuring out how to make the parent class functions visible in C#.
Assume I've a template class, which defines a function foo()
template <int Dim, typename Type>
public ref class FixedNP
{
public:
  float foo() {return 1;};
};

Then I've a class which inherits from the FixedNP template:
public ref class Vector3fP : public FixedNP<3, float>
{
}

When I try to call the foo() function from the C#, eg.
Vector3fP bar = new Vector3fP();
bar.foo();

it says the function Vector3fP doesn't contain a definition for foo.
When I move the definition of foo() to the Vector3fP class, it works fine. However this is not viable in real code, because the FixedNP template contains quite a lot of functions which should be inherited from approximately 4 different classes.
After some search on the Internet I found that adding the
using FixedNP<3, float>::foo;

to the Vector3fP fixed a similar problem for someone. However in my case it just results in another error, this time when compiling the C++/CLI code:

error C3182: 'Vector3fP' : a member using-declaration or access declaration is illegal within a managed type

Any suggestions how to make my functions visible in C#?

A: I think they key is in this claim from Managed Templates on MSDN:

If a template is not instantiated, it's not emitted in the metadata. If a template is instantiated, only referenced member functions will appear in metadata.

That means that functions that aren't used in the C++ code won't be in the generated DLL and you won't be able to use them from C#. To fix this, you could add a phony function to your C++ code, which references the function:
void phony()
{
    auto vec = gcnew Vector3fP();
    vec->foo();
}

A: You can instantiate the whole template class without adding phony method by adding the following line.
template ref class FixedNP<3, float>;


text:
Q: How do I restore Xubuntu desktop to default? Before, I was using Gnome desktop on Ubuntu 14.04. Then, I installed Xubuntu desktop and, just recently, when I login it does not work. I don't know what's wrong.
When I drag something, its' image repeats many times (see below) and stays on the desktop and nothing works. Gnome is still ok.
How can I restore Xubuntu desktop to its' defaults?

A: If you want to revert back to Gnome, then you should first remove XFCE desktop then reinstall Gnome desktop.
Removing XFCE:
sudo apt-get purge xfce4
sudo apt-get autoclean
sudo apt-get autoremove

reinstalling Gnome desktop:
sudo apt-get install --reinstall gnome-shell
sudo dpkg-reconfigure gdm
sudo apt-get update && sudo apt-get upgrade

A: sudo apt-get autoremove --purge xubuntu-\* xfce\*
sudo apt-get install xfce4

installing xubuntu-desktop may create duplication.


text:
Q: Delete Local site collection term set I had a user try to create a Local Term Set for a site collection, then pin term with children from our actual term store and I need to delete the Local Term Set for the site collection.
When I go to delete I get a message which sounds like it will delete the term from the actual term store and not just the local site collection

It is the 'Client' Term set that needs deleting from the site collection group, my question is, if I delete 'Client' will it delete the top highlighted 'Communities and local government' term set from our actual term store. I have searched for the answer but I cannot find anything that would help.

Hope this makes sense, any questions just ask.
Thanks

A: The message is quite misleading. But that is not the case - Delete will only delete what is under the Term Set.

This action deletes the term and its child terms. If this term is a source term that other locations reuse, it is put in the Orphaned Terms term set in the System group.

https://support.office.com/en-us/article/Create-and-manage-terms-in-a-term-set-549070a7-41c2-4210-9e9c-5fad22bd8748


text:
Q: Building a menu in Android I'm writing an Android application that needs a menu like this:

Please note, this activity has a background and 4 menu items, where each menu item has two parts: Bottom text that should be aligned to left and Right text that should be aligned to right. Would you please tell me how I can implement it? Should I use LinearLayout for each menu item?

A: This is a sample code I made. all of them are buttons in xml
public class MenuActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
}

@Override
// My menu inflater
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.menu, menu);

return (super.onCreateOptionsMenu(menu));
}

// code for the actions that it will do.
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.test2:
    test2();
    return true;
case R.id.test1:
    test1();
    return true;
default:
    return super.onOptionsItemSelected(item);
}
}

 public void test1() {
// TODO Auto-generated method stub
Toast test = Toast.makeText(this, "This is a test", Toast.LENGTH_LONG);
test.show();
 }

 public void test2() {
// TODO Auto-generated method stub
Toast test = Toast.makeText(this, "This is a test", Toast.LENGTH_LONG);
test.show();
  //Add how ever many you want.
 }
}


text:
Q: How to use the paypal payout api return url? I want to use the payout interface of paypal. Using curl in sandbox mode has been called. However, I dont know how to use returnUrl, because I need to know whether the payment of paypal is successful. This should be an asynchronous operation. I filled in the callback address in the location shown in the figure, but I checked the access log and found that no callback was received. Who can help me and how to solve this problem?

A: The URL you speak of in REST App settings really only applies to things like Connect with PayPal or OpenID integrations, and has nothing to do with Payouts.
To be notified of Payouts status, see the API response of your Payouts request, or register for Webhook events that have to do with Payouts.


text:
Q: Remove parent from Maven Shade dependency reduced pom with Flatten The project has the following structure:
FatJarRootPom has dependencies for X and Y.
FatJarA and FatJarB all declare FatJarRootPom as their parent so they get its dependencies X and Y shaded into their JAR along with their own dependencies.
The issue is that, Shade Plugin will leave reference to parent in the dependency-reduced-pom.xml so FatJarA's pom will still explicitly depend on X and Y despite having them inside JAR already.
Flatten Plugin can get rid of parent so it would be optimal to run Shade Plugin on flattened pom. It will process all dependencies and then remove them from dependency-reduced-pom.xml. However, when I configure Flatten Plugin, Shade Plugin will not pick up its output and will still produce incorrect pom.
I have found this answer which suggests changing the invocation order of shade and flatten so that shade comes first, but it won't work since dependencies from FatJarRootPom will still be in the pom, which I am trying to avoid.
Maybe there is some other way of just removing parent section from dependency-reduced-pom.xml without flatten plugin?
Update: I have tried changing my FatJarRootPom to a POM dependency FatJarPom with transitive dependencies listed in it, and amusingly, Maven Shade Plugin will specifically skip POM dependency and will not remove it from dependency reduced POM, even as it would mean that all shaded dependencies will absolutely appear as dependencies of fat-jar artifact.

A: I have overlooked that Flatten Plugin has "fatjar" mode which will strip all dependencies. It is a very coarse grained approach, but it should do in my use case.
So the solution is placing
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>flatten-maven-plugin</artifactId>
                <version>1.2.7</version>
                <executions>
                    <execution>
                        <id>flatten</id>
                        <phase>package</phase>
                        <goals>
                            <goal>flatten</goal>
                        </goals>
                        <configuration>
                            <updatePomFile>true</updatePomFile>
                            <flattenMode>fatjar</flattenMode>
                        </configuration>
                    </execution>
                    ...

after the corresponding Shade Plugin section.


text:
Q: CPU info in kernel module I want to know the cpu info inside the kernel module like number of cpus,cores,etc.
Are there ways to find it?
Besides than opening file in kernel module like /proc/cpuinfo.

A: Try the lscpu command or the lshw program.

A: Check files in /proc. You can find some interesting stuff in there about you CPU and processes currently running on you system.

A: Depending on your kernel version, you may find information under /sys/devices/system/cpu/ as well.


text:
Q: SQL. Выбрать пользователей не отправляющих отчеты последние 2 дня в текущем месяце
Прошу помощи с составлением sql-запроса. Сегодня 3 ноября и мне нужно вывести ID менеджера который не присылал отчеты последние 2 дня подряд в текущем месяце (1 и 2 ноября этот отчет пуст, в предыдущий месяц смотреть не нужно).
Задача максимально упрощена, в реальном проекте 4 таблицы с 2 join'ами
SELECT user_id, user_first_name, user_last_name
FROM USERS
WHERE user_id NOT IN (
    SELECT
        user_id FROM REPORTS
        WHERE user_id IN (
           SELECT
           user_id FROM REPORTS
           WHERE date >= '2020-11-01'
        )
)

Не работает.

A: SELECT users.*
FROM users
WHERE NOT EXISTS ( SELECT NULL
                   FROM reports
                   WHERE users.user_id = reports.user_id
                     AND reports.`date` > CURRENT_DATE - INTERVAL 2 DAY )

PS. Использован синтаксис MySQL. Для другой СУБД - откорректировать выражение вычисления пограничной даты.


text:
Q: The Alternates For 'in respect of' In Two Cases I'd like to ask if the three phrases below can be used instead of in respect of in the two cases and still mean the same thing.

*

*with respect to

*in/with regard to

*as regards

*

*A writ was served on the firm in respect of their unpaid bill.

*money received in respect of overtime worked
Thank you.

A: They all sound unnecessarily fancy and wordy and would not be considered good writing style,  in my opinion.  Better to just use "for" or "regarding" instead.


text:
Q: Spring FeignClient fallback not called but goes to exception I'm having an issue trying out the feignclient fallback based on the documentation.
Assume myFeignClient can't connect to myFeign
@FeignClient(name = "myFeign", fallback = MyFeignClientFallback.class)
public interface MyFeignClient {
    @PostMapping("/test")
    Object test(@RequestParam("param1") String param1);
}

My fallback class is this:
@Component
public class MyFeignClientFallback implements MyFeignClient {
    public Object test(@RequestParam("param1") String param1) {

        return "Error";
    }

}

instead of calling the fallback method it just outright fails:

2018-05-07 15:19:48.052 ERROR 41592 --- [nio-8081-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: myFeign] with root cause
com.netflix.client.ClientException: Load balancer does not have available server for client: myFeign

I already have my feign client working. I was experimenting with the idea of using Hystrix when I encountered this issue.
Did I use this incorrectly or did I miss something?

A: Please enable the hystrix in your configuration file application.yml, the default is false and the function will not work.
build.gradle
buildscript {
    ext {
        springBootVersion = '2.0.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    launchScript ()
}

archivesBaseName = 'framework'
version = '1.0'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
    compile('org.springframework.cloud:spring-cloud-starter-openfeign')

    testCompile('org.springframework.boot:spring-boot-starter-test')
}

ext {
    springCloudVersion = 'Finchley.RC1'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

application.yml
eureka:
  client:
    serviceUrl:
      defaultZone: //...
  instance:
    preferIpAddress: true

feign:
  hystrix:
    enabled: true

Application.java
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

FrameworkHelloService.java
package framework.root.service;

import framework.root.service.FrameworkHelloService.HelloServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "framework", fallback = HelloServiceFallback.class)
public interface FrameworkHelloService {
    @GetMapping("/api/hello")
    public String hello();

    @GetMapping("/api/exception")
    public void exception();

    @GetMapping("/none")
    public String none();

    @Component
    class HelloServiceFallback implements FrameworkHelloService {
        @Override
        public String hello() {
            return null;
        }

        @Override
        public void exception() { }

        @Override
        public String none() {
            return "Fallback!";
        }
    }
}


text:
Q: How to move or Transfer row in database java I want to move row in sqlite java.  I thought about taking the values of the row, then deleting it, then adding id + 1, then adding the row, but this does not work, id unique. Is there an easier way?

ex:
Transfer id to id2

id
name

1
mark

2
john

3
smith

4
tom

Change to:

id
name

2
john

3
smith

4
mark

5
tom

String n=Db.getName(id);
Db.delete(id);
Db.transId(id2);
Db.insert(id2,n);

void transId(int id){
sq.execSQL("update table set id=id+1 where id>="+id);
}

error:

Exception: dispatching input event
UNIQE constraint failed: table.id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY[1555])

A: A-(id1=fromid;id2=toid) //add+1 (id2)
Update table set id=-id where id>id2
Update table set id=-id+1 where id<id2

B detNAME(id1) and delete(id1)
C insertRowId(id2+1,name)


text:
Q: How to retain highchart line graph by onClick() function - php mysql I have two files
1. Analytics.php
2. get_data_journ.php
Analytics.php Code
 function show_journal(jour_id){
   $.post("journal_table/get_data_journ.php", {JOURNID: ""+jour_id+""},  function(data_jour){

        var options = {
            chart: {
                renderTo: 'container_journal',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },

             xAxis: {
                 title: {
                    text: 'Year'
                },
                 categories: []
                },

               yAxis: {
                    title: {
                        text: 'Number of Citations'
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },

            series: [{
                type: 'line',
                name: 'Citations',
                data: []

            }]

        }

        $.getJSON("journal_table/get_data_journ.php", {JOURNID:jour_id}, function(data_jour) {
            options.series[0].data = data_jour;

            chart = new Highcharts.Chart(options);
        });

});
}

  echo ''.$jour_title.'';

get_data_journ.php Code
 <?php
  include '../connect.php';

  $get_journid = $_REQUEST['JOURNID'];

  $result_journ = mysql_query("SELECT year, citations, jour_id FROM journ_graph WHERE  jour_id = '$get_journid'");

  $rows_journ = array();
   while($r_journ = mysql_fetch_array($result_journ)) {
 $row_journ[0] = $r_journ[0];
 $row_journ[1] = $r_journ[1];
 array_push($rows_journ,$row_journ);
 }

 print json_encode($rows_journ, JSON_NUMERIC_CHECK);

 ?>

So the onclick function working with while loop, so if have 10 journals, 10 journals will be listed, the user can chose any journal, so according to the user click the line graph will be shown. Here I am using highcharts. This is working very fine. The graph will change accordingly as the user clicks. But now the problem is when users wants to compare the journals like 2 or more, the olp point values should remain in the graph other than disappearing. This onclick event working in the way as per the click, if user clicks another journal then the first journal graph points getting disappeared. How to do that. Please help.

A: If you have created chart, in the second chosing by user, you can use addSeries which will add serie to the chart, instead of creating new chart.


text:
Q: Force NSScrollView to use NSScrollerStyleOverlay independently from input device How to force NSScrollView to use scrollers like that:

independently from input device, because now if computer has wired mouse connected or app is running on laptop (macbook) it uses scrollers like this:

witch is always visible. It is possible to achieve my desired result if user changes settings in system preferences. But I need to have that result without changing anything. Or maybe there is some easy method to use  custom NSScrollers?
Hiding scrollers would be pretty acceptable result, but when I hide them I have some scrolling issues. I use custom NSClipView witch adjusts documentView to be centered when adjusting its frame size. But when I adjust frame size, and it is scrolled to center, if I scroll anywhere it jumps to bottom left corner and then works as it should.

A: I'm using table view and I just put this code in awakeFormNib:
[[self.tableView enclosingScrollView] setScrollerStyle:NSScrollerStyleOverlay];

I also tried to hide scrollers but then I couldn't scroll the content using trackpad (no problem using mouse). In the other project I have similar table view with the same settings and hiding scrollers doesn't cause any issues.

A: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify:) name:NSPreferredScrollerStyleDidChangeNotification  object:nil];

- (void)notify:(NSNotification*)
{
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakself.scrollView.scrollerStyle = NSScrollerStyleOverlay;
    });
}


text:
Q: event.getHtmlLink() is returning NULL I'm building the application to insert the event in Google Calendar, but it's returning Null in event.getHtmlLink(). Which means it couldn't be able to insert Event. How to do that?
Insert Codes have been taken from:-
https://developers.google.com/google-apps/calendar/v3/reference/events/insert
and
Actual quickstart Codes from:-
https://developers.google.com/google-apps/calendar/quickstart/android
package com.example.joshiyogesh.eventreminderbear;

import android.Manifest;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventAttendee;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.api.services.calendar.model.EventReminder;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
* MainActivity used for Google Api. It demonstrates how to use authorization to
*add event in Google Calender
* */
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{

    static final int REQUEST_ACCOUNT_PICKER = 1000;
    static final int REQUEST_AUTHORIZATION = 1001;
    static final int REQUEST_GOOGLE_PLAY_SERVICE = 1002;
    static final int REQUEST_PERMISSION_GET_ACCOUNT = 1003;

    private static final String PREF_ACCOUNT_NAME = "accountName";
    GoogleAccountCredential googleAccountCredential;
    private static final String[] scopes = {CalendarScopes.CALENDAR};

    ProgressDialog progressDialog;
    /**
    * Create the main Activity.
    * @param savedInstanceState previously saved instance state
    * */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        Initialize credentials and service object
            googleAccountCredential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(scopes)).
                    setBackOff(new ExponentialBackOff());
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Calling Google Calendar API ...");

        sendResultToApi();

    }

    /**
     * Attempt to call the API, after verifying that all the preconditions are
     * satisfied. The preconditions are: Google Play Services installed, an
     * account was selected and the device currently has online access. If any
     * of the preconditions are not satisfied, the app will prompt the user as
     * appropriate.
     */

    private void sendResultToApi(){
        if(! isGooglePlayServiceAvailable()){
            acquireGooglePlayService();
        }
        else if (googleAccountCredential.getSelectedAccountName() == null){
            chooseAccount();
        }
        else if (! isDeviceOnline()){
            Toast.makeText(MainActivity.this,"Check Your Network Connection",Toast.LENGTH_LONG).show();
        }
        else{
            new MakeRequestTask(googleAccountCredential).execute();
        }
    }

    /**
     * Check that Google Play services APK is installed and up to date.
     * @return true if Google Play Services is available and up to
     *     date on this device; false otherwise.
     */
    private boolean isGooglePlayServiceAvailable(){
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        final int connectionStatusCode = googleApiAvailability.isGooglePlayServicesAvailable(this);
        return connectionStatusCode == ConnectionResult.SUCCESS;
    }

    /**
    * Checks whether Device has Active Network Connection or not.
     * @return true if Network (Internet) is available ;
     * false otherwise
     */
    private boolean isDeviceOnline(){
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    /**
     * Attempt to resolve a missing, out-of-date, invalid or disabled Google
     * Play Services installation via a user dialog, if possible.
     */
    private void acquireGooglePlayService(){
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        final int connectionStatusCode = googleApiAvailability.isGooglePlayServicesAvailable(this);
        if (googleApiAvailability.isUserResolvableError(connectionStatusCode)){
            showGooglePlayServiceAvailabilityErrorDialog(connectionStatusCode);
        }
    }
    /**
    *Display an Dialog showing Google Play Service is missing or Out of date
     * @paramConnectionStatusCode code describing the prescence or Lack :: Goggle Play service on Device
     */
    void showGooglePlayServiceAvailabilityErrorDialog(int connectionStatuscode){
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        Dialog dialog = googleApiAvailability.getErrorDialog(MainActivity.this,connectionStatuscode,REQUEST_GOOGLE_PLAY_SERVICE);
        dialog.show();

    }

    /**
    * Display currently LogIn Account on Device for selecting Account ,
    *so that CalendarId can be get For That Account..
     * Attempts to set the account used with the API credentials. If an account
     * name was previously saved it will use that one; otherwise an account
     * picker dialog will be shown to the user. The setting the
     * account to use with the credentials object requires the app to have the
     * GET_ACCOUNTS permission, which is requested here if it is not already
     * present. The AfterPermissionGranted annotation indicates that this
     * function will be rerun automatically whenever the GET_ACCOUNTS permission
     * is granted.
     *  */
    @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNT)
    private void chooseAccount(){
        if (EasyPermissions.hasPermissions(this, android.Manifest.permission.GET_ACCOUNTS)){
            String accountName = getPreferences(Context.MODE_PRIVATE).getString(PREF_ACCOUNT_NAME,null);
            if (accountName != null){
                googleAccountCredential.setSelectedAccountName(accountName);
                sendResultToApi();
            }
            else {
                //start a dialog so that user can select Acount Name
                startActivityForResult(googleAccountCredential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER);
            }
        }else {
            // Request the GET_ACCOUNTS permission via a user dialog
            EasyPermissions.requestPermissions(
                    this,
                    "This app needs to access your Google account (via Contacts).",
                    REQUEST_PERMISSION_GET_ACCOUNT,
                    Manifest.permission.GET_ACCOUNTS);

        }

    }

    /**
     * Called when an activity launched here (specifically, AccountPicker
     * and authorization) exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     * @paramrequestCode code indicating which activity result is incoming.
     * @paramresultCode code indicating the result of the incoming
     *     activity result.
     * @paramdata Intent (containing result data) returned by incoming
     *     activity result.
     */
    @Override
    protected void onActivityResult(int requestCode , int resultCode , Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch (requestCode){
            case REQUEST_GOOGLE_PLAY_SERVICE:
                if (resultCode != RESULT_OK){
                    Toast.makeText(MainActivity.this,"This App Requires Google Play Service ! Please Install it and Try Again Later",Toast.LENGTH_LONG).show();
                }else {
                    sendResultToApi();
                }
                break;
            case REQUEST_ACCOUNT_PICKER:
                if (resultCode == RESULT_OK && data != null &&
                        data.getExtras() != null) {
                    String accountName =
                            data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        SharedPreferences settings =
                                getPreferences(Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(PREF_ACCOUNT_NAME, accountName);
                        editor.apply();
                        googleAccountCredential.setSelectedAccountName(accountName);
                        sendResultToApi();
                    }
                }
                break;
            case REQUEST_AUTHORIZATION:
                if (resultCode == RESULT_OK) {
                    sendResultToApi();
                }
                break;

        }
    }

    /**
     * Respond to requests for permissions at runtime for API 23 and above.
     * @param requestCode The request code passed in
     *     requestPermissions(android.app.Activity, String, int, String[])
     * @param permissions The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions
     *     which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(
                requestCode, permissions, grantResults, this);
   }
    /**---------methods implemented from EasyPermissions.PermissionCallbacks---------*/
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
            //Do nothing
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
            //Do nothing
    }
    /**------------------------------------------------------------------------------*/

    /**
     * An asynchronous task that handles the Google Calendar API call.
     * Placing the API calls in their own task ensures the UI stays responsive.
     */

    private class MakeRequestTask extends AsyncTask<Void,Void,Void>{
        private com.google.api.services.calendar.Calendar mService = null;
        private Exception mLastError = null;
        Event event;

        MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.calendar.Calendar.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("Google Calendar API Android Quickstart")
                    .build();
        }
        @Override
        protected void onPreExecute(){
            progressDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.hide();
            Toast.makeText(MainActivity.this, "Your Event Has been Successfully added  "+event.getHtmlLink(), Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServiceAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            MainActivity.REQUEST_AUTHORIZATION);
                } else {
                    Toast.makeText(MainActivity.this,"The following error occurred:\n"+mLastError.getMessage(),Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(MainActivity.this,"Request Cancelled",Toast.LENGTH_LONG).show();
            }

        }

        @Override
        protected Void doInBackground(Void... params) {
            createEvent();
            return null;
        }
        /**
         * createEvent() method help in adding Event in google play service Calendar
        * */
        private void createEvent(){
             event = new Event()
                    .setSummary("There is Placement Drive")
                    .setLocation("Jalandhar")
                    .setDescription("Elite SmartCare Solutions is going to visit");
            DateTime date = new DateTime("2017-04-11T09:00:00-05:30");
            EventDateTime start = new EventDateTime()
                    .setDateTime(date)
                    .setTimeZone("Asia/Calcutta");
            event.setStart(start);

            DateTime endDateTime = new DateTime("2017-04-12T09:00:00-05:30");
            EventDateTime end = new EventDateTime()
                    .setDateTime(endDateTime)
                    .setTimeZone("Asia/Calcutta");
            event.setEnd(end);

            String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
            event.setRecurrence(Arrays.asList(recurrence));

            EventAttendee[] attendees = new EventAttendee[] {
                    new EventAttendee().setEmail("abc@nitj.ac.in"),
                    new EventAttendee().setEmail("xyz@gmail.com"),
            };
            event.setAttendees(Arrays.asList(attendees));

            EventReminder[] reminderOverrides = new EventReminder[] {
                    new EventReminder().setMethod("email").setMinutes(24 * 60),
                    new EventReminder().setMethod("popup").setMinutes(10),
            };
            Event.Reminders reminders = new Event.Reminders()
                    .setUseDefault(false)
                    .setOverrides(Arrays.asList(reminderOverrides));
            event.setReminders(reminders);

            String calendarId = "primary";
            try {
                event = mService.events().insert(calendarId, event).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

How to fix this code, so that one can insert Events in Google Calendar?
Update : 1
Logcat of Android Moniter
04-09 17:41:54.362 3954-4015/com.example.joshiyogesh.eventreminderbear I/OpenGLRenderer: Initialized EGL, version 1.4
04-09 17:41:54.482 3954-4015/com.example.joshiyogesh.eventreminderbear D/OpenGLRenderer: Enabling debug mode 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: PartialUpdate status: Disabled
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Left Align: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Width Align: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Top Align: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Height Align: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Min ROI Width: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Min ROI Height: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Needs ROI Merge: 0
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Dynamic Fps: Enabled
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Min Panel fps: 45
04-09 17:41:54.542 3954-4015/com.example.joshiyogesh.eventreminderbear I/qdutils: Max Panel fps: 60
04-09 17:41:54.682 3954-3968/com.example.joshiyogesh.eventreminderbear W/art: Suspending all threads took: 7.777ms
04-09 17:41:56.732 3954-3968/com.example.joshiyogesh.eventreminderbear W/art: Suspending all threads took: 51.622ms
04-09 17:41:56.892 3954-4016/com.example.joshiyogesh.eventreminderbear W/Auth: [GoogleAuthUtil] GoogleAuthUtil
04-09 17:41:56.952 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err: com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:299)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.example.joshiyogesh.eventreminderbear.MainActivity$MakeRequestTask.createEvent(MainActivity.java:363)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.example.joshiyogesh.eventreminderbear.MainActivity$MakeRequestTask.doInBackground(MainActivity.java:320)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.example.joshiyogesh.eventreminderbear.MainActivity$MakeRequestTask.doInBackground(MainActivity.java:272)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at java.lang.Thread.run(Thread.java:818)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err: Caused by: com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze$1.zzat(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze$1.zzau(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze.zza(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze.zzc(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze.getToken(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze.getToken(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.zze.getToken(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:269)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:     at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:294)
04-09 17:41:56.972 3954-4016/com.example.joshiyogesh.eventreminderbear W/System.err:    ... 13 more
04-09 17:41:57.282 3954-4015/com.example.joshiyogesh.eventreminderbear V/RenderScript: Application requested CPU execution
04-09 17:41:57.312 3954-4015/com.example.joshiyogesh.eventreminderbear V/RenderScript: 0x55ab5f3610 Launching thread(s), CPUs 8
04-09 17:41:57.352 3954-3954/com.example.joshiyogesh.eventreminderbear I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3d3b858f time:55536505


text:
Q: SQL query for top 100, displayed in reverse I have a database of logos, 18K strong. Each logo has a score. I want to select the top 100 by score and display them from 100 to 1, not from 1 to 100.
My query is:
SELECT * FROM tbllogos WHERE status = 'live' ORDER BY score DESC LIMIT 100

which works fine for selecting the top 100, but the php WHILE loop then displays them from 1 to 100. I can't figure out how to swap the order so it displays 100 to 1. Changing DESC to ASC obviously isn't the answer as that selects the 100 with the lowest scores.

A: Use a subquery:
SELECT t.*
FROM (SELECT *
      FROM tbllogos
      WHERE status = 'live'
      ORDER BY score DESC
      LIMIT 100
     ) t
ORDER BY score ASC;


text:
Q: How to loop each document and get its data I'm new to javascript and new into Firebase cloud functions, I want to know how to iterate each document my query returns and get from each document the deviceToken of my user, this is what I did
    let docRef = db.collection('user').doc(userId);
    let shopUserRef = db.collection('user').where('shop', '==', shopId);

    var orderStatusDetail;
    var notificationTitle;
    switch(orderStatus){
        case 0:
            notificationTitle = "You have a new order ! "
            orderStatusDetail = String("A new order has arrived, check it out")
            docRef = shopUserRef;
            break;
        case 1:
            notificationTitle = "Hey there! "
            orderStatusDetail = "✅ Your order is ready"
            break;
}

 return docRef.get().then(userDoc => {
       const deviceToken = userDoc.data().deviceToken
        const payload = {
        notification: {
            title: notificationTitle,
            body: orderStatusDetail
        }
    }
        console.log("userId:"+userId+"orderstatus:"+orderStatus+"deviceToken"+deviceToken)
        return admin.messaging().sendToDevice(deviceToken,payload)
  });

So, what this code does is simple, if the case is 0  (orderStatus == 0) I need to send a notification only to the owner of the shop, thats why I use another reference to get that user device token , but here it could be more than 1 user that has that shop id so I want to iterate these documents to get each id and send them all the notificaiton of the new order.
The docRef here is just the customer who have bought a product and the notification needs to arrive to them.
But in case 0 I need to send a notification to all shop customers ids
I want to know how to for loop here
return docRef.get().then(userDoc => {
   for(user in userDoc) {
    // I dont know if this is the correct for loop way to get each document data
}
...

A: Check out https://firebase.google.com/docs/firestore/query-data/queries#execute_a_query
It sounds like you are looking for
docRef.get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });


text:
Q: inputfield value not changing <apex:page controller="MyContactDemoController" showHeader="false" >

      <apex:slds />

      <apex:form >

               <apex:outputLabel styleClass="slds-form-element__label">First Name</apex:outputLabel>
               <apex:inputField value="{!con.FirstName}" styleClass="slds-form-element__control slds-input"  style="{!IF(con.FirstName =='', 'background-color:red;color:blue', 'background-color:blue;color:red')}>"  />

               <apex:outputLabel styleClass="slds-form-element__label">Last Name</apex:outputLabel>
               <apex:inputField value="{!con.LastName}" styleClass="slds-form-element__control slds-input" />

               <apex:outputLabel styleClass="slds-form-element__label">Email</apex:outputLabel>
               <apex:inputField value="{!con.Email}" styleClass="slds-form-element__control slds-input"    />

               <apex:outputLabel styleClass="slds-form-element__label">Phone</apex:outputLabel>
               <apex:inputField value="{!con.Phone}" styleClass="slds-form-element__control slds-input"    />

            <apex:commandButton value="Save" action="{!Save}" styleClass="slds-button slds-button--neutral " style="margin-left: 151px;"/>

      </apex:form>

</apex:page>

/////////////
On line 11 the colour of inputfield is not changing on changing FirstName value

A: As @david Said You can use the javascript call with Event functions (onchange) in the input.

As you mentioned in previous edit

You are using <apex:inputfield> So you can't just use getElementById('id1').value and get input Value.
Instead, Access with $component Followed by Form-Id and then InputFied-Id (add the path the Field)

A: Visualforce bindings don't provide that kind of instant feedback, like you might get in a Lightning component. Visualforce expressions, like
{!IF(con.FirstName =='', 'background-color:red;color:blue', 'background-color:blue;color:red')}

are evaluated only during server-side rendering. If you want "live" reactions in your Visualforce code, you need to either

*

*Use client-side JavaScript to update the style on this element.

*Perform a server round-trip and partial page rerender (using the rerender attribute on, for example, an <apex:actionFunction> component), where the rerender includes the element whose Visualforce expression needs to be reevaluated.


text:
Q: ElasticSearch Hosted on AWS by ES to pandas df and back to ES ConnectionError

I just started with ElasticSearch, and took free 14 days trial from here.
Got an username, password and id, now I am passing my elasticsearch host url, username and password. But getting Error. How can I retrieve dataframe from elasticsearch to pandas from AWS hosted ES.
I wan't process this and save it back to ES, i.e. to same index as well in a new Index after processing it.
Also if I look at /_cat/indices?v it exists there.
What I did is used logstash to push MySql (hosted on AWS) to ES (as well hosted on AWS) Now I want to get data, process it and push back to ElasticSearch. Like am forming Apriori (Market Basket Analysis) from transaction. How can I do so?

A: The connection Shall be like:
es = Elasticsearch(host="yourhost.aws.found.io",
port="9243", scheme="https",
http_auth=('elastic', 'password'))

The Elastic Search Add http:// and port as 9200 if not passed as default , which results into wrong host as:

http://https://yourhost:yourport:9200
https://yourhost:youport  --rather than this

And then to ConnectionError. Where as my host was on https:// with s and on different port.
Worked for me!


text:
Q: How to prove that it can be : $ρ=(a+d)\cos θ + (b-c)\sin θ =0$ while $Δ<0$ Note : I avoided writing the whole expression of $Δ$ on the title, sorry for that.
The following must be solved in the way described, since this is what the exercise asks.
I was solving a problem of dynamical systems which came down to the following expressions, after some big calculations via Jacobians for the linearized system. My calculations are double checked and probably correct. I now have to prove a string of cases, so that I can determine the kind and the stability of $O(0,0)$, which I'm being asked to prove that it can be an : Asymptotically stable knot, Asymptotically Stable focus, Stable center, Unstable focus, Unstable knot, while $θ\in [0,π]$ and $a,b,c,d \in \mathbb R$.
From my Jacobian calculations, I've got that :

$$ρ=(a+d)\cos θ + (b-c)\sin θ $$
$$Δ=(a\cosθ-c\sinθ-b\sinθ-d\cosθ)^2 + 4(b\cosθ-d\sinθ)(a\sinθ+c\cosθ)$$

Starting from the case to be made, so that $O(0,0)$ is a stable center, I would need to prove that :
$$ρ=0$$
$$Δ<0$$
My question is : How can I prove the statements above ? The system seems too complicated, with a ton of different cases, regarding constants, regarding $θ$ which can all vary.
My attempt :
Starting from $ρ=0$, we have :
$$(a+d)\cosθ +(b-c)\sinθ=0 \Leftrightarrow (a+d)\cosθ=-(b-c)\sinθ \Leftrightarrow \tanθ=-\bigg(\frac{a+d}{b-c}\bigg)$$
In that case, I'm considering that $b-c \neq 0$, but getting a completely unknown $\tan^-1$ solution will not help me proving that $Δ<0$.
If it was $b-c=0$ then we would have that : $(a+d)\cosθ =0$ which either means that $a+d = 0$ or $\cosθ=0 \Rightarrow θ = nπ + π/2$ but since $θ\in \mathbb [0,π]$ , the only acceptable value is : $θ=π/2$
Now, for $θ=π/2$ $Δ$ becomes :
$$Δ=(-c -b)^2 -4da$$
which would be $<0$ if : $(-c-b)^2 < 4da $. I guess this can hold, since $a,b,c,d$ are unrestricted constants.
But even like this, there is still another case (vice versa, with $a+d=0$) and still I cannot seem to prove what happens when $(a+d),(b-c) \neq 0$
Moreover than that, there are still many different cases that should be checked on the other kinds of $O(0,0)$ which really makes it an incredibly huge exercise which could mean there could be an easier way proving such systems (like the one I got from the Stable center case, $ρ=0,Δ<0$.
I would really appreciate any help since I'm stuck on how to proceed. I don't need help for all the points, I just need a hint or a thorough explanation on how to handle such a system, since all the other points could probably work the same way around.
A final question is, does finding such values for $a,b,c,d$ (at least if there are specific) mean that a conclusion could be made ? In this case, I would not need to proceed with all the different cases. (I'm asking this, because when in other exercises we work with Lyapunov Functions involving constants, finding even specific constants that fullfill our needs, leads us to a general result. So if that's the case here, it could be simplified a lot.)


text:
Q: C# container: Row, Index I need to create container like this: Container.Add(RowIndex, ValueIndex);
I know Dictionary just have Key and Value and this is not good for me.
And i havent no idea how to use 2 containers to create Row, Index how i want.
So example:
Container[Row][Index]:
Container[0][0] = "Apple";
Container[0][1] = "Orange";
Container[1][0] = "Number";

Because im trying use this container for read sql. When i got next result it add to current row value +1. And Index mean field value.
In code:
                int row = 0;

                while (ObjReader.Read())
                {
                    foreach (var result in ObjReader)
                        ReadList.Add(row, result.ToString());

                    row++;
                }

                ObjReader.NextResult();

this is for reading
and now get result to another Class
    public string Field(int row, int index)
    {
        return ReadList[row][index];
    }

A: It seems you're looking for a List of Lists.
List<List<string>> results = new List<List<string>>();

while (haveMoreRows)
{
    List<string> nextRow = new List<string>();
    foreach (var item in currentRow)
        nextRow.Add(item.ToString());

    results.Add(nextRow);
}

Now you can do something like: results[2][1] to get the value at the 3rd row in the 2nd column.

A: Use a simple pair class:
public class Pair<P, T>
{
    public Pair() { }
    public Pair(P first, T second)
    {
        First = first;
        Second = second;
    }
    public P First { get; set; }
    public T Second { get; set; }
}

to use:
List<Pair<int, string>> ReadList = new List<Pair<int, string>>();
while (ObjReader.Read())
{
    foreach (var result in ObjReader)
        ReadList.Add(new Pair<int, string> {
            First = row,
            Second = result.ToString()
        });

    row++;
}

ObjReader.NextResult();

A: try with iterator and type anonymous
iterator use the keyword yield
foreach (var result in ObjReader)
{
        yield return result.ToString();
}

You will have IEnumerable

A: Sounds like what you really want is a DataTable. It's a collection of rows and columns specifically designed to represent a database table.


text:
Q: Set Build to Unstable status if Quality Gates fails I need some help, i am trying to set the build status as "Unstable" if quality gate on sonarqube fail. Find below the configuration i've got so far:
Stage sonarQube Scan
I've found this also, but i am not sure how to integrate on my stage above:
step {
                qualitygate = waitForQualityGate()
                if (qualitygate.status != "OK") {
                    currentBuild.result = "UNSTABLE"
                }
            }

Any suggestion?
Thanks in advance for the support,

A: Try this:
...
timeout(25) {
    def qualitygate = waitForQualityGate()
    if (qualitygate.status != "OK") {
        currentBuild.result = "UNSTABLE"
    }
}

Inspired by Set the build unstable if sonar Quality Gate is failed


text:
Q: How to aggregate values of pandas series Data manipulation using pandas
Anyone having bright ways to manipulate the values of concatenated pandas series to find total counts?

Current data (type: pandas.core.series.Series)
FYI, this data is generated by using 'groupby' function from the raw data.
date          device
2015-07-08    a         0
              b         0
              c         0
              d         1
2015-07-09    a         0
              c         1
              d         1
2015-07-10    a         1
              b         1
              c         1

Expected result (type: pandas.core.series.Series)
Value of each device denotes the total number of counts up to date A.
As an example, total(2015-07-10, c) = 2 because (2015-07-09, c) = 1 and (2015-07-10, c) = 1
date          device
2015-07-08    a         0
              b         0
              c         0
              d         1
2015-07-09    a         0
              c         1
              d         2
2015-07-10    a         1
              b         1
              c         2

A: I think you can use DataFrameGroupBy.cumsum with groupby by second level:
dates = pd.DatetimeIndex(['2015-07-08','2015-07-08','2015-07-08','2015-07-08',
                          '2015-07-09','2015-07-09','2015-07-09',
                          '2015-07-10','2015-07-10','2015-07-10'])
devices = ['a','b','c','d','a','c','d','a','b','c']
idx = pd.MultiIndex.from_tuples(list(zip(dates, devices)), names=['date', 'device'])
s = pd.Series([0,0,0,1,0,1,1,1,1,1], index= idx)
print (s)
date        device
2015-07-08  a         0
            b         0
            c         0
            d         1
2015-07-09  a         0
            c         1
            d         1
2015-07-10  a         1
            b         1
            c         1
dtype: int64

print (s.groupby(level=1).cumsum())
date        device
2015-07-08  a         0
            b         0
            c         0
            d         1
2015-07-09  a         0
            c         1
            d         2
2015-07-10  a         1
            b         1
            c         2
dtype: int64


text:
Q: TypeError in Django Application I am making a Django application. It's a wikipedia page that will allow you to create a new page if you click .
The path is in urlpatterns is:
path("create", views.create, name="create")
The function in views.py is:
def create(request):
if request.method == 'POST':
    form = Post(request.POST)
    if form.is_valid():
        title = form.cleaned_data["title"]
        textarea = form.cleaned_data["textarea"]
        entries = util.list_entries()
        if title in entries:
            return render(request, "encyclopedia/error.html", {"form": Search(), "message": "Page already exist"})
        else:
            util.save_entry(title,textarea)
            page = util.get_entry(title)
            page_converted = markdowner.convert(page)

            context = {
                'form': Search(),
                'page': page_converted,
                'title': title
            }

            return render(request, "encyclopedia/entry.html", context)
else:
    return render(request, "encyclopedia/create.html", {"form": Search(), "post": Post()})

The error message I am getting is:
TypeError: decoding to str: need a bytes-like object, NoneType found
Full Traceback:
Traceback (most recent call last):
File "/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/encyclopedia/views.py", line 60, in webpages
"title":markdowner.convert(page)
File "/Users/franciscogutierrez/Desktop/Software1/CS50W/project1/wiki/env/lib/python3.8/site-packages/markdown2.py", line 316, in convert
text = unicode(text, 'utf-8')
TypeError: decoding to str: need a bytes-like object, NoneType found

A: As the trace shows, you are passing None in the markdowner function while it expects you to send a byte object. You are getting page from your utils.get_entry function. Make sure that do not return None. If that's not possible, check for None values before calling the markdower function. Try it like this -
page = util.get_entry(title)
if page:
    page_converted = markdowner.convert(page)

A: Had a str:title path that ran before the "create" path and so create would go in the path above instead of the other path. Fixed it by putting create on top of str:title


text:
Q: Can't Access the Object's Child's Mesh I wanted to get the mesh from the gameObject's Children for my game's placement system.
The gameObject is an Empty Object and the Child has all of the mesh.
But the error message says

Cannot convert type 'UnityEngine.Mesh' to 'UnityEngine.MeshFilter'

How can I solve this bug? or is there any better way to get a mesh from an gameObject's children by code
MeshFilter viewedModelFilter = (MeshFilter)gameObject.GetComponentInChildren<MeshFilter>().sharedMesh;
buildingPreviewMesh = viewedModelFilter.mesh;

(buildingPreviewMesh is a private Mesh)

A: Im not on unity right now so i cant try this right now but did you try like this ?
Mesh viewedModelFilter =gameObject.GetComponentInChildren<MeshFilter>().sharedMesh;

buildingPreviewMesh = viewedModelFilter;

A: Adding to the other answer,
First, get the Mesh Filter component.
MeshFilter viewedModelFilter = gameObject.GetComponentInChildren<MeshFilter>();

Once you get the MeshFilter, you may access the Mesh using
buildingPreviewMesh = viewedModelFilter.mesh;

OR
 buildingPreviewMesh = viewedModelFilter.sharedMesh;

You just need to do it step by step to understand it well first.. Or you can also go for the direct approach suggested in the other answer. Also note that GetComponentInChildren only returns the first child gameobject's MeshFilter component. if you have multiple children, you'll need to implement arrays to store the multiple mesh filters.


text:
Q: OnTriggerEnter and OnTriggerExit called twice despite checking it I have read a lot of questions about this problem but i couldn't solve it yet. I have one ball with a Sphere Collider and an invisible wall to restart the ball when it passes through it (on the onTriggerExit method). The problem is that i've not been able to solve it, even with a boolean to avoid entering the method.
public class ballRestart : MonoBehaviour
{
    shootController instance;
    bool isColliding;
    // Use this for initialization
    void Start()
    {
        instance = Camera.main.GetComponent<shootController>();
        isColliding = false;
    }

    public void OnTriggerEnter(Collider col)
    {
        Debug.Log("TeEnter: " + isColliding);
        if (!isColliding)
        {
            isColliding = true;
            Debug.Log("TRIGGERED: " + isColliding);
        }

    }

    void OnTriggerExit(Collider hit)
    {
        Debug.Log("TeExit: " + isColliding);
        if (isColliding)
        {
            instance.initializeBall();
            isColliding = false;
            Debug.Log("exit");
        }
    }
}

OUTPUT:
Here is the output of the Logs
As you see, it enters twice each time the ball enters the collider and twice each time the ball exits the same collider. I don't know what happens here.

A: I'm pretty sure you have 2 colliders on your object, each of them causes event triggering. Check your components and child objects.
P.s.: I know it is old question, but my answer can be helpful for others.


text:
Q: Ubuntu reinstallation issue I had dual booted my laptop with the windows 11 and Ubuntu. I ran the "sudo rm -rf /*" command accidentally and after that my laptop is not listing any boot device and showing as please reinstall the OS. But when I tried to install the Ubuntu I am getting the following error.
"The installer encountered an error copying files to the hard disk:
[Errno 5] Input/output error
This is often due to a faulty CD/DVD disk or drive, or a faulty hard
disk. It may help to clean the CD/DVD, to burn the CD/DVD at a lower
speed, to clean the CD/DVD drive lens (cleaning kits are often
available from electronics suppliers), to check whether the hard disk
is old and in need of replacement, or to move the system to a cooler
environment."
Can anyone please help me to resolve this?

A: There's quite a few that will swear by Rufus. I haven't had the best of luck with it myself in the past. If you've got a working Windows machine, might try spinning up diskpart and then select disk <USB Drive> and do a good ol' clean in case there's an issue with the drive. Make sure to select the propper drive. You can check the label and/or size to verify.
Reference the checksum of the ISO if you're worried about initial ISO corruption.
Then try giving Ventoy a shot.
If it is an issue with the installation media like @Thomas Ward and @Nmath have reccomended, the above should take care of it.
If you are still getting the same error after all that, there's a chance that  Intel's Rapid Storage Technology might be getting in the way.
If it's a fairly new laptop, and you're using an older version of Ubuntu, it might be giving you issues.
Here's a guide on how to manage it and help Windows use AHCI if you switch it over.
Granted, that's just a hunch based on the fact it's giving you IO error to your HD.


text:
Q: Home-brew installation of LAPACKe I've been trying to find the right package to install so that I can use
#include <lapacke.h>

but I've not been able to find a home-brew command that once downloaded contains this library. Is it possible to download this using home-brew, if not what our my alternatives?

A: Accelerate ships with OS X and provides LAPACK: https://developer.apple.com/library/prerelease/mac/documentation/Darwin/Reference/ManPages/man7/LAPACK.7.html
Alternatively, the homebrew/science/openblas package provides a LAPACK implementation.


text:
Q: How to save Bitmap Image in Android device through code written in C++ I'm trying to save a bitmap image in the Android but through C++ functionality. Do I use ofstream? And if yes, what path should I give for the ofstream object created?
std::ofstream bmpF;
bmpF.open(<Android Path?>, std::ofstream::binary | std::ofstream::out);

A: fileName can be any path in android project. You can pass it through jni layer and get same in java from : context.getFilesDir() +"/"+
As far as use of ofstream: you may choose to write to file in same way as you would in normal c/c++ project.
Text file example
void writeToFile( const char* fileName) {
    FILE* fid = fopen(fileName, "w");
    if (fid==NULL) {
        printf("WriteVectorArt: couldn't open the file");
    } else {
        fprintf(fid, "SomeText to write");
        fclose(fid);
   }}

A: bmpF.open("//storage//emulated//0//pictures//name.bmp", std::ofstream::binary | std::ofstream::out);


text:
Q: Footer overflowing into container above I'm using bootstrap 4. I have a footer container and a contact-us container directly above.  The site renders perfectly in the Firefox Browser but when I try it in Chrome, the footer and the contact-us containers overlap while on XS screen size.
Any idea why this might be?
Thanks.

                © Copyright Arcane Defense.
All
Rights Reserved.
 Website designed by InnoDesigns.

                Home
                About
                Academy
                Products