text:
Q: Update data using sequelize I'm working on a Reactjs project. There is login/register forms after login I am able to display the user's data in an Account page.
On the Account page the user will be able to update the data he filled in when he signed up.
The form contains :

*

*First name

*Last name

*Email

*Phone

*Delivery address

I want to update the data using the Reactjs form.
My code
Front
class Account extends Component {
  constructor() {
    super();
    this.state = {
      first_name: "",
      last_name: "",
      email: "",
      phone: "",
      deliveryAddress: "",
      errors: {}
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

  handleSubmit(e) {
    e.preventDefault();

    const { first_name, last_name, email, phone, deliveryAddress } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    const json = JSON.stringify(body);
    console.log(json);

    axios.put("http://localhost:5000/users/:id", json).then(res => {
      console.log(res);
    });
  }

UserController.ts
export const updateUser = (req, res) => {
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: req.body.id
      }
    }
  ).then(user => {
    res.json(user);
  });
};

I think my issue is in my where attribute because when I click on the Save Button I got : Executing (default): UPDATE users SET updatedAt='2020-02-18 14:30:03' WHERE id = NULL and nothing happens, nothing is updated.
EDIT
UserController.ts
export const updateUser = (req, res) => {
  const id = req.params.id;
  User.update(
    {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email: req.body.email,
      phone: req.body.phone,
      deliveryAddress: req.body.deliveryAddress
    },
    {
      where: {
        id: id
      }
    }
  ).then(user => {
    if (user == 1) {
      res.send({
        message: "User was updated successfully"
      });
    } else {
      res.send({
        message: `Cannot update User with id=${id}. Maybe User was not found or req.body is empty!`
      });
    }
  });
};

When I use Postman and the request PUT on http://localhost:5000/users/10 I correctly update the user. My issue is that I can't get the id if I use my Reactjs code.
EDIT 2
I added the id in the state and in the componentDidMount() function as follows :
  componentDidMount() {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);
    this.setState({
      id: decoded.id,
      first_name: decoded.first_name,
      last_name: decoded.last_name,
      email: decoded.email,
      phone: decoded.phone,
      deliveryAddress: decoded.deliveryAddress
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const {
      id,
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    } = this.state;
    const body = {
      first_name,
      last_name,
      email,
      phone,
      deliveryAddress
    };
    const json = JSON.stringify(body);
    console.log(json);

    axios.put(`http://localhost:5000/users/${id}`, json).then(res => {
      console.log(res);
    });
  }

I'm now able to get the current id : Executing (default): UPDATE users SET updatedAt='2020-02-19 08:48:57' WHERE id = '15' but nothing happens because the first_name field is not modified like I do with Postman : Executing (default): UPDATE users SET first_name='Quentin',updatedAt='2020-02-19 08:50:57' WHERE id = '15'

A: You're not sending an id field from the app, so you cannot do
where: {
  id: req.body.id
}

You can either make sure you save the id locally too and send it so your API endpoint can use it or you can do an upsert instead.
Another option is to find the user by email instead of ID:
where: {
  email: req.body.email
}

You would have to make sure to not allow your user to change their email from this page. Or, you can even add another field called oldEmail if you really need that.
EDIT: After seeing your new edit and more code, I believe I see the issue, you're not sending the ID correctly from React. You're doing:
axios.put("http://localhost:5000/users/:id", json).then(res => {

When you should really be doing the following:
axios.put(`http://localhost:5000/users/${this.state.id}`, json).then(res => {

Assuming you have the id field in your state and that it's an existing user.


text:
Q: Object reference not set to an instance of an object while reading file properties from SP2010 I have sharepoint document library which has custom field called "DocumentType" this is not mandatory field. When I am trying to read this property using the below code, when value is there in this field its working fine but where its value empty giving the error "Object reference not set to an instance of an object." If value is not there I need to pass empty string for further logic, how can I handle this?
SPFile spFile=Web.GetFile(Context.Request.Url.ToString());
string spDocumentType=string.Empty;
if (spFile.Properties["DocumentType"].ToString() == "INV") *In this line exception throwing where value is empty in this field in the doc library.
{
spDocumentType = spFile.Properties["DocumentType"].ToString();
}

A: do like this:
if(spFile.Properties["DocumentType"] !=null)
 {
   spDocumentType = spFile.Properties["DocumentType"].ToString() == "INV" ? spFile.Properties["DocumentType"].ToString() : "";

 }
else
{
spDocumentType ="";

}

A: Change this piece of code:
spFile.Properties["DocumentType"].ToString()

To this:
Convert.ToString(spFile.Properties["DocumentType"])

While ToString() throws the exception you're getting when the value is null, the Convert.ToString() method tests for null and returns an empty string.

redpajama_set_name: RedPajamaStackExchange


text:
Q: turn the cursor into a hand when you move the cursor in a clickable direction width phaser 3 Can you show me how to turn the cursor into a hand when I point the cursor in a clickable direction, but the hand does not appear when I point:
balls.getChildren().forEach(
s => s.setInteractive({  cursor: 'url(./src/games/gewgly/assets/images/pointer.png). pointer'
  })
);

A: To change the cursor image when the user is hovering over a specific area, you can use input events like this example.
this.input.on('gameobjectover', function (pointer, gameObject) {
    document.body.style.cursor = 'url("http://lorempixel.com/23/23/"), default';
});

this.input.on('gameobjectout', function (pointer, gameObject) {
    document.body.style.cursor = 'default';
});


text:
Q: Is this summation solvable? $S_n = \sum_{i = 2}^{n}\log_i{(n)}$ Is it possible to solve a summation with a variable base of log?
$$
S_n = \sum_{i = 2}^{n}\log_i{(n)}
$$
Should I use the derivative of $\log_i{(n)}$?

A: While I don't believe there is a nice closed form for $S_n$, you can write the sum in terms of known functions and constants up to a very small error.  Specifically, $$\sum_{i=2}^{N}\log_{i}(N)=\text{li(N)}\log N+C\log N+O(1),$$ where $\text{li}(N)$ is the logarithmic integral and $C$ is a constant equal to $$C=\frac{1}{\log2}+\int_{2}^{\infty}\frac{\{x\}}{x\log^{2}x}dx.$$

Proof:  Writing $$\sum_{i=2}^{N}\log_{i}(N)=\log N\sum_{i=2}^{N}\frac{1}{\log i},$$ our goal is then to find an asymptotic for the sum of $1/\log i$.  Writing this as a Riemann Stieltjies integral we have $$\sum_{i=2}^{N}\frac{1}{\log i}=\int_{2^{-}}^{N^{+}}\frac{1}{\log x}d\left[x\right]=\int_{2}^{N}\frac{1}{\log x}dx-\int_{2^{-}}^{N^{+}}\frac{1}{\log x}d\left\{ x\right\}.$$ By integration by parts, $$\int_{2^{-}}^{N^{+}}\frac{1}{\log x}d\left\{ x\right\} =\frac{\left\{ x\right\} }{\log x}\biggr|_{x=2^{-}}^{x=N^{+}}+\int_{2}^{N}\frac{\left\{ x\right\} }{x\log^{2}x}dx$$ $$=\frac{1}{\log2}+\int_{2}^{\infty}\frac{\{x\}}{x\log^{2}x}dx-\int_{N}^{\infty}\frac{\left\{ x\right\} }{x\log^{2}x}dx,$$ and since $$\int_{N}^{\infty}\frac{\{x\}}{x\log^{2}x}dx=O\left(\frac{1}{\log N}\right),$$ we have that $$\sum_{i=2}^{N}\frac{1}{\log i}=\text{li}(N)+C+O\left(\frac{1}{\log N}\right)$$ where $\text{li}(N)$ is the logarithmic integral and $$C=\frac{1}{\log2}+\int_{2}^{\infty}\frac{\{x\}}{x\log^{2}x}dx.$$ Thus it follows that $$\sum_{i=2}^{N}\log_{i}(N)=\text{li(N)}\log N+C\log N+O(1).$$ (Note that the asymptotic is then $\sum_{i=2}^{N}\log_{i}(N)\sim N.$)
Remark: In fact, we could apply integration by parts again to work out the $O(1)$ term exactly and evaluate the sum up to an error of $O\left(\frac{1}{N}\right)$. This general process of writing the sum $\sum_{k\leq N} f(k)$ as a series whose main term is $\int_{1}^N f(x)dx$ is known as Euler-Maclaurin summation.

A: A simple (perhaps useful, perhaps not) bound via Jensen inequality. Because $1/\log(x)$ is convex:
$$S_n = \sum_{i = 2}^{n}\log_i{(n)}= (n-1) \log(n) \frac{\sum_{i = 2}^{n} \frac{1}{\log(i)}}{n-1}  \ge (n-1) \log(n)  \frac{1}{\log \frac{\sum i}{n-1}}= \frac{(n-1) \log(n)}{\log(\frac{n}{2}+1)}  $$
This bound seems quite decent. For large $n$ it tends to $n$ (the same asymptotic found by Eric Naslund - notice however that the convergence is slow)

A: Since $\log_{i} n = \frac {\log n} {\log i}$, we have $$S_n = \sum_{i = 2}^{n} \frac {\log n} {\log i} = \log n \sum_{i = 2}^{n} \frac {1} {\log i}$$ and we have by Euler-McLaurin summation formula $$\sum_{i = 2}^{n} \frac {1} {\log i} = \int_{2}^{n} \frac {\text {d} x} {\log x} + \log \sqrt {2n} + O \left(\frac {1} {\log n}\right),$$ which leads us to $$S_n = \text {Li} (n) \log n + \frac {1} {2} \log^2 n + \log \sqrt {2} \log n + O (1).$$ Hope this helps.


text:
Q: dict value in struct is ignored for Bool now with a happy, short Minimum Viable Example  at the bottom
I am seeing this weird behavior .. I am trying to set  a time series entry with location to true:
struct TimeSeriesEntry: Codable, Equatable {
    let id: String
    let uid: String
    let date: Date
    let apps: [String:Double]
    let locations: [String:Bool]

    func changeApp(app: String, value: Double) -> TimeSeriesEntry {
        var apps = self.apps
        apps[app] = value

        return TimeSeriesEntry(id: self.id, uid: self.uid, date: self.date, apps: apps, locations: self.locations)
    }
}

There are no extensions to this code. That is TimeSeriesEntry in its entirety.
I am evaluating this in the debugger because for some reason it always is set false, but I do the assignment hard coded to true in my code. It works the same in the debugger:
debugger Evaluation
TimeSeriesEntry(id: String(describing: UUID()), uid: DBIFirebase.uid,
    date: data.date.round(to: TimeSeries.defaults.interval,
    TimeSeries.defaults.intervalComponent), apps:[:], locations:
    [data.id:true])
.locations["c72b2cc2-897e-4621-8fba-452cf43afa0a"]

result
... = (Bool?) false

Elsewhere, when I am assigning apps, the Doubles are working just fine. I'm a bit stuck as to why this is happening.
addendums
the actual assignment is happening in this function, and in this branch of the code it is the section in the function for locations, not apps:
func timeSeriesData (appData: AppData? = nil, locationData: LocationData? = nil) -> TimeSeriesEntry? {
    if let data = appData {
        return TimeSeriesEntry(id: String(describing: UUID()), uid: DBIFirebase.uid, date: data.date.round(to: TimeSeries.defaults.interval, TimeSeries.defaults.intervalComponent), apps: [data.id:data.metric], locations:[:])
    } else {
        guard let data = locationData else {
            return nil
        }
        return TimeSeriesEntry(id: String(describing: UUID()), uid: DBIFirebase.uid, date: data.date.round(to: TimeSeries.defaults.interval, TimeSeries.defaults.intervalComponent), apps:[:], locations: [data.id:true])
    }
}

to make it a complete standalone mve:
import Foundation

struct TimeSeriesEntry: Codable, Equatable {
    let id: String
    let uid: String
    let date: Date
    let apps: [String:Double]
    let locations: [String:Bool]

    func changeApp(app: String, value: Double) -> TimeSeriesEntry {
        var apps = self.apps
        apps[app] = value

        return TimeSeriesEntry(id: self.id, uid: self.uid, date: self.date, apps: apps, locations: self.locations)
    }
}

struct LocationData: Codable, Equatable {
    //    let name: String
    let id: String
    let date: Date
    let latitude: Double
    let longitude: Double
}

func timeSeriesData (locationData: LocationData) -> TimeSeriesEntry? {
    return TimeSeriesEntry(id: String(describing: UUID()), uid: "DBIFirebase.uid", date: locationData.date, apps:[:], locations: [locationData.id:true])
}

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ssZ"

let locationData = LocationData(
    id: "c72b2cc2-897e-4621-8fba-452cf43afa0a",
    date: df.date(from: "2017-08-28 00:00:01Z")!,
    latitude: 67.1404,
    longitude: -151.4804)

let timeSeriesEntry = timeSeriesData(locationData: locationData)

in repl, locations will contain 1 entry with the correct id but the bool set false:
 39. let timeSeriesEntry = timeSeriesData(locationData: locationData)

df: DateFormatter = {
  Foundation.Formatter = {
    baseNSObject@0 = {
      isa = NSDateFormatter
    }
  }
}
locationData: LocationData = {
  id = "c72b2cc2-897e-4621-8fba-452cf43afa0a"
  date = 2017-08-28 00:00:01 UTC
  latitude = 67.1404
  longitude = -151.4804
}
timeSeriesEntry: TimeSeriesEntry? = some {
  id = "C836C671-B266-4CA1-9A80-841E3329C6C8"
  uid = "DBIFirebase.uid"
  date = 2017-08-28 00:00:01 UTC
  apps = 0 key/value pairs
  locations = 1 key/value pair {
    [0] = {
      key = "c72b2cc2-897e-4621-8fba-452cf43afa0a"
      value = false
    }
  }
}

edit: okay, now Im confused.. playing with it a bit more in the repl, I see:
 42> timeSeriesEntry!.locations["c72b2cc2-897e-4621-8fba-452cf43afa0a"]
$R1: Bool? = true
 43> timeSeriesEntry!
$R2: TimeSeriesEntry = {
  id = "C836C671-B266-4CA1-9A80-841E3329C6C8"
  uid = "DBIFirebase.uid"
  date = 2017-08-28 00:00:01 UTC
  apps = 0 key/value pairs
  locations = 1 key/value pair {
    [0] = {
      key = "c72b2cc2-897e-4621-8fba-452cf43afa0a"
      value = false
    }
  }
}
 44> timeSeriesEntry!.locations
$R3: [String : Bool] = 1 key/value pair {
  [0] = {
    key = "c72b2cc2-897e-4621-8fba-452cf43afa0a"
    value = false
  }
}


text:
Q: Intuition about : $a = b \iff | a − b| < \epsilon$, for every $\epsilon > 0$ This is Theorem 1.2.6 in Abbott. Understanding Analysis (2016 2 edn). pp 9 - 10. I'm NOT asking about proof that the author proves. Please don't prove. I'm longing just for intuition.

*

*I can't intuit how, God willing, an equality (on LHS)  can be equivalent to a conjunction of strict inequalities (on RHS).

*Is there any picture that can assist?

A: For $x$ non-negative, $\forall \epsilon>0:x<\epsilon$ is a contrived way to say $x=0$ without saying it.
Because if $x$ is positive, you will find some $\epsilon$ that contradicts the inequality $x<\epsilon$ (for example $\epsilon=\frac x2$).

Note that $\forall \epsilon>0:x\le\epsilon$ also works. But not $\forall \epsilon\ge0:x<\epsilon$.

A: Identity of Indiscernibles :

If we cannot find the slightest difference between two objects $a$ and $b$, then necessarily the two must be identical.

And vice versa.

A: Short answer:
Smaller than anything can only be zero.

A: Suppose $|a-b|  < \epsilon$ for all $\epsilon > 0$. Thus the distance between $a$ and $b$ is smaller than every strictly positive number.
Suppose to the contrary that this distance is non-zero, then $|a-b| > 0$ and then your claim says that $|a-b| < |a-b|$, which is a contradiction.
Thus we must have that the distance $|a-b| = 0$, which only happens when $a=b$.
Drawing a picture to see what's going on will definitely help. Take two distinct points $a\neq b$. On the picture, argue why $|a-b| < \epsilon$ for all $\epsilon > 0$ can never happen (my proof above contains the answer). So I would argue that the proof is actually the intuition.


text:
Q: syncError not flagged on Field instance with dot syntax name I have a Field poll.id that is part of a form that contains multiple parts. Each part is contained in a component with a @reduxForm annotation and each component may have it's own unique validation method.
My problem is that in this case, when the validatePoll returns a validation exception, it doesn't show up at Field level. I wonder if this has to do with the dot syntax of the field.
@reduxForm({
    form: 'posteditor',
    destroyOnUnmount:false,
})
@autobind
class MyForm extends React.Component {

    [...]

    pollButton(field){
        console.log('poll.id', field);//meta.error = undefined
        [...]
    }

    poll(){
        const { poll, visible, syncErrors } = this.props;
        return (
          <Field
            name="poll.id"
            value={poll && poll.id}
            type="number"
            component={this.pollButton}
            props={{
              visible: visible,
              questions: (poll && poll.questions) || []
            }}
            />
        );
    }
}

@reduxForm({
    form: 'posteditor',
    validate: validatePoll,
    destroyOnUnmount:false,
})
@autobind
class PostPoll extends React.Component {

A: You left out your validation function, but my guess is that you are returning this:
validate(values) {
  const errors = {}
  if(!values.poll.id) {
    errors['poll.id'] = 'Required' // ❌
  }
  return errors
}

...and you should be returning this:
validate(values) {
  const errors = {}
  if(!values.poll.id) {
    errors.poll = { id: 'Required' } // ✅
  }
  return errors
}


text:
Q: R - retrieve correct objects from google maps API and save to data frame for a work project I'm trying to weight bulk twitter data by geographic distribution of the tweets. Currently, I'm planning to achieve this by running the location information provided in most tweets I've collected through the Google Maps API and retrieving detailed information on this location as far as it's available, i.e. town, county, state, country, longditude, latitude.
I've adapted some R code I found on github, https://gist.github.com/josecarlosgonz/6417633, and it works pretty well, returning the desired data points into an R character vector. However, as I'll be doing this for several millions of locations, I want the data saved in a data frame which I can then match up with the tweet dataframe so as to facilitate weighting. Hence, I went ahead and modified Jose's code slightly:
library(RJSONIO)
library(plyr)
library(RCurl)

# This is the function that transforms an "address" string into a URL readable by the G maps API

url <- function(address, return.call = "json", sensor = "false"){
  root <- "http://maps.google.com/maps/api/geocode/"
  u <- paste(root, return.call, "?address=", address, "&sensor=", sensor, sep = "")
  return(URLencode(u))
}

# This function returns the data provided by the API
# When the request is ambiguous, e.g. "Portland", "Manchester" or "Frankfurt", it seems that the API returns the "best" match
# first, i.e. Portland, Oregon, Manchester, UK and Frankfurt am Main, Germany.
# The below set-up currently only works with U.S. localities, as the 'county' and 'state' elements are sorted at different points
# in the list for other countries.

geoCode <- function(address,verbose=FALSE){
  if(verbose) cat(address,"\n")
  u <- url(address)
  doc <- getURL(u)
  x <- fromJSON(doc,simplify = FALSE)
  if(x$status=="OK") {
    if(exists(x$results[[1]]$address_components[[1]]$long_name)){
      town <- x$results[[1]]$address_components[[1]]$long_name
    } else {
    town <- NA
    }
    if(exists(x$results[[1]]$address_components[[2]]$long_name)){
      county <- x$results[[1]]$address_components[[2]]$long_name
    } else {
      county <- NA
    }
    if(exists(x$results[[1]]$address_components[[3]]$long_name)){
      state <- x$results[[1]]$address_components[[3]]$long_name
    } else {
      state <- NA
    }
    if(exists(x$results[[1]]$address_components[[3]]$short_name)){
      state_code <- x$results[[1]]$address_components[[3]]$short_name
    } else {
      state_code <- NA
    }
    if(exists(x$results[[1]]$geometry$location$lat)){
      lat <- x$results[[1]]$geometry$location$lat
    } else {
      lat <- NA
    }
    if(exists(x$results[[1]]$geometry$location$lng)){
      lng <- x$results[[1]]$geometry$location$lng
    } else {
      lng <- NA
    }
    if(exists(x$results[[1]]$geometry$location_type)){
      location_type <- x$results[[1]]$geometry$location_type
    } else {
      location_type <- NA
    }
    if(exists(x$results[[1]]$formatted_address)){
      formatted_address <- x$results[[1]]$formatted_address
    } else {
      formatted_address <- NA
    }
    return(c(town, county, state, state_code, lat, lng, location_type, formatted_address))
    Sys.sleep(0.5)
  } else {
    return(c(NA,NA,NA,NA,NA,NA,NA,NA))
  }
}

However, when trialling this with a trivial example, I encounter several errors that I can't account for. It seems to me that, based on the level of detail provided in the string that's being fed into the G maps API, it returns different types of data at different points in the list, which is obviously bad if I want a dataset where all the counties, or long/lat data are listed in the correct columns. So, anyway, I created an arbitrary character vector with 'address' data comparable to what would be found in my tweet dataset:
pacific_northwest <- c('Vancouver', 'Seattle', 'Olympia', 'Redmond', 'Eugene', 'Portland', 'Tacoma', 'Whistler')

and then an empty data frame that google maps' output could be fed into
location_data.df <- data.frame(town=character(),
                           county=character(),
                           state=character(),
                           state_code=character(),
                           lat=character(),
                           lng=character(),
                           location_type=character(),
                           formatted_address=character(),
                           stringsAsFactors = FALSE)

And finally, I wrote a simple loop that was supposed to add the output to this data.frame:
for (i in pacific_northwest){
  readout <- geoCode(pacific_northwest[i])
  location_data.df[nrow(location_data.df) + 1, ] <- readout
  rm(readout)
}

Anyway - this doesn't work, I encounter loads of errors, even with the more or less unambiguous addresses provided in pacific_northwest, such as: Error in x$results[[1]]$address_components[[2]] : subscript out of bounds
What to do? Any help would be greatly appreciated! Thanks in advance.


text:
Q: Tests fail to run after upgrading .net core from 2.1 to 3.1 Tests fail to run after upgrading .net core from 2.1 to 3.1. Main error:
vstest.console process failed to connect to testhost process after 90 seconds. This may occur due to machine slowness, please set environment variable VSTEST_CONNECTION_TIMEOUT to increase timeout.

A: There are numerous fixes out there that didn't work for me. The fix that worked was adding the package: Microsoft.NET.Test.Sdk


text:
Q: ASP dynamically created image, unable to display in web browser control I'm currently under the belief it may be to do with the header information but I'm really not too sure. The image on this page is the best example of it that I can give. It will display sometimes in a web browser control, and other times it just plain refuses to. Does anyone have any idea as to why?
The code I'm using to try and grab the image is simply:
WebBrowser.Navigate("http://www.lse.co.uk/tools/user/imgChatUsagePie.asp?nick=mulledwine", null, null, "image/gif");

It's really hard to ascertain as to what is causing the image to display sometimes and others not as it works completely fine within Chrome. Is this a problem related specifically to the web browser control?
Thank you in advance.

A: Apparently, the server side script checks the ASP Session ID cookie and displays the image depending on some session variable stored on the server.
Try navigating the to the HTML page first, then request that image.

A: Sometimes the data is a valid image, and sometimes it is not.
But seriously You need to give more information I assume you mean
http://www.lse.co.uk/tools/user/imgChatUsagePie.asp?nick=mulledwine
Maybe post the code you use to generate the image. Is this browser specific. Under what conditions does the pie chart fail to generate. Does the url give an error message when it refuses to display the image etc. I would assume some variable you use to generate the image is null and throws an unhandled exception causing the page to return 500 and some kind of error rather than image data.
If it is really just sometimes it works and sometimes it doesn't id recommend using some kind of test suit to keep requesting the image at random images until it fails and then isolate the error message. Selenium or Fiddler may be of some use to isolate the problem.


text:
Q: help with performing operations on matrix parts inside a loop I would like to translate the following code into Mathematica language but am having some trouble doing so:
h1=1;
L1=Array[f,9];
for(i=1,i<4,i++)
 {
   for(j=1,j<4,j++)
    {
     q1=Part[SomeMatrix,i,j]
     q2=Apart[q1]
     f[h1]=q2
     h1++
    }
 }

the aim is to perform 2 operations on each cell of a matrix and then create a new 3X3 matrix out of the predefined array L1.
help will be much appreciated.
Thank you in advance

A: Is this what you're trying to accomplish?
Map[Apart, SomeMatrix, {2}]

A: (* create an example matrix *)
mA = Array[(Subscript[c, #] + Subscript[d, #])/(Subscript[a, #] +
      Subscript[b, #]) &, {3, 3}]

(* direct translation *)
h1 = 1;
L1 = Array[f, 9]
For[i = 1, i < 4, i++,
 For[j = 1, j < 4, j++, q1 = Part[mA, i, j]; q2 = Apart[q1];
  f[h1] = q2; h1++]]
L1

(* better approach *)
Apart /@ Catenate@mA


text:
Q: JavaScript: O resultado é exibido mesmo sem ter dados inseridos pelo usuário! Bem, a ideia era a seguinte: fazer uma simples função que calculasse o valor inserido em um input e retornar-se o resultado para o usuário, porém se o valor inserido for zero, a mensagem que retorna é: "Valor em branco!"; (Porque o " " ao ser convertido para número passa a ser igual a zero). Resumindo, existe uma forma disso aí funcionar ou eu vou ter que rescrever de uma outra forma.
function inp() {

    var num = Number(input.value);
    var myNum = (num == " ");

    if (Number.isNaN(num) == true) {
        alert("Formato Inválido!");
    } else if (myNum === true) {
        alert("Valor em branco!")
    } else {
        alert((50 + 50 + 50) * num);
    }
}

A: Pode usar um ternário para definir num:

function inp() {

    var input = document.querySelector("#ip");
    var num = input.value == '0' ? '0' : Number(input.value);
    var myNum = (num == " ");

    if (Number.isNaN(num) == true) {
        alert("Formato Inválido!");
    } else if (myNum === true) {
        alert("Valor em branco!")
    } else {
        alert((50 + 50 + 50) * num);
    }
}
<input type="text" id="ip" />
<input type="button" value="ok" onclick="inp()" />


text:
Q: json to nested ul li jquery / javascript I am creating dynamic json using javascript from a drag and drop builder, Now I am unable to convert the json to Nested Ul li. The json is below.
[
  {
    "id": "11",
    "name": "BALANCE"
  },
  {
    "id": "p1",
    "name": "Conditions",
    "nodes": [
      {
        "id": "p1-13",
        "name": "SPINAL CORD INJURY",
        "nodes": [
          {
            "id": "p1-13-12",
            "name": "STROKE",
            "nodes": [
              {
                "id": "p1-13-12-17",
                "name": "REACHING"
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": "p1-16",
    "name": "STRETCHES"
  },
  {
    "id": "p1-11",
    "name": "BALANCE"
  }
]

A: You can create a function and call recursively if there is nodes in item.

var json = [{"id":"11","name":"BALANCE"},{"id":"p1","name":"Conditions","nodes":[{"id":"p1-13","name":"SPINAL CORD INJURY","nodes":[{"id":"p1-13-12","name":"STROKE","nodes":[{"id":"p1-13-12-17","name":"REACHING"}]}]}]},{"id":"p1-16","name":"STRETCHES"},{"id":"p1-11","name":"BALANCE"}];

function createUl(data, $elm) {
  data.forEach(function(item) {
    var $li = $('
' + item.name + '
');
    $elm.append($li);

    if (item.nodes) {
      var $ul = $('

');
      $li.append($ul);
      createUl(item.nodes, $ul);
    }
  });
};

createUl(json, $('ul'));


text:
Q: Python SQLite You can only execute one statement at a time I get error when running this code
import sqlite3
conn = sqlite3.connect("Sqlite3 file path")
cursor = conn.cursor()

Name = "Test"
LastName = "Test"
Id = 2
Grade = 12

cursor.execute("""
    BEGIN TRANSACTION;

    INSERT INTO Students (FirstName,LastName) VALUES(?,?);

    INSERT INTO StudentsYears (StudentId,YearId,Grade) VALUES((SELECT LAST_INSERT_ROWID() from Students),?,?);

    END TRANSACTION;""" , (Name , LastName , Id , Grade))

conn.commit()

What is the problem?
.......................................

A: Your issue is that you are using the wrong command to execute multiple SQL statements at once.
According to the docs execute() " will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a ProgrammingError. Use executescript() if you want to execute multiple SQL statements with one call. "
To fix your issue change your code to
cursor.executescript("""
    STATEMENTS
    ...
    """


text:
Q: WebClient GET unit test with mockito I am facing issue with Webclient and mockito
Below is my service code:
public Flux<Config> getConfigs(String param1, String param2) {
        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();

        if(!StringUtils.isEmpty(param2)) {
            queryParams.add("name", param2);
        }
        String path = "api/v1/config";
        return webClient.get().uri(uriBuilder -> uriBuilder.path(path)
                .queryParams(queryParams)
                .build())
                .retrieve().bodyToFlux(Config.class)
                .doOnError(MyRuntimeException::throwError);
    }

Test Case i am trying is failing with below error:
Strict stubbing argument mismatch. Please check:
 - this invocation of 'uri' method:
    requestHeadersUriSpec.uri(
    com.rs.para.conf.service.ConfigServiceImpl$$Lambda$309/1334433160@3925299f
);

Test case code:
@Test
    public void testConfig() {
        List<Config> configs = new ArrayList<>();
        doReturn(requestHeadersUriMock).when(webClientMock).get();
        doReturn(requestHeadersMock).when(requestHeadersUriMock)
                .uri(anyString());
        doReturn(responseMock).when(requestHeadersMock).retrieve();
        doReturn(Flux.fromIterable(configs)).when(responseMock).bodyToFlux(Config.class);
        Flux<Config> configFlux = configService.getConfigs("100005", "test");
    }

I can run normal GET without query param but when I am trying to run this test which has query param it's giving me error
PS: I don't want to use mockwebserver

A: The problem here is you are using a lambda inside the uri method. Whereas in the test cases you are using anyString(). Also since URI has multiple ways of implementation, just using anyString() will not work. Providing a specific class is what is required.
Changing
doReturn(requestHeadersMock).when(requestHeadersUriMock)
                .uri(anyString());

to
 doReturn(requestHeadersMock).when(requestHeadersUriMock).uri(Mockito.any(Function.class));

does the job here.


text:
Q: HTML p line breaks (repost of a repost) I know this question has been asked many times before, but never an answer that helps me in my situation.
I have a
 with a
 underneath it. There is whitespace between the paragraph and the list. I don't want this but can't get rid of it.
I've applied the most straight-forward solution but it doesn't work in my page.
This is what it should be: http://codepen.io/anon/pen/EsFqd
And this is what I get with the same css as shown in codepen:

Who can help me out?
As requested, HTML:
<article id="overzicht"
         style="<% if (browser.contains("Chrome") || browser.contains("MSIE")) {%>margin-right: 45px;<%}%>">

Overzicht

Groepen

            <% try {
                while (bands.next()) { %>

<%= bands.getString("band_naam") %>

<%= bands.getString("pod_omschr") %>

            <%  }
               } catch (Exception e) { %>

Nog geen groepen

            <% }%>

Campings

            <% try {
                while (campings.next()) { %>

<%= campings.getString("camp_adres") %>

<%= campings.getString("camp_cap") %>

            <%  }
               } catch (Exception e) { %>

Nog geen campings

            <% }%>

Tickets

            <% try {
                while (tickets.next()) { %>

<%= tickets.getString("typ_omschr") %>

<%= tickets.getString("typ_prijs") %>

            <%  }
               } catch (Exception e) { %>

Nog geen tickets

            <% }%>

and full CSS:
article[id="details"] {
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  -webkit-flex: 1;
  -ms-flex: 1;
  text-align: center;
  margin-left: 10px;
  margin-right: 10px;
  padding: 10px;
}
p {
    font-size: 1.2em;
    text-align: center;
    border: 1px solid #cbcbcb;
    border-bottom: none;
    padding: 0;
    margin: 0;
    color: white;
    background-color: green;
}

ul {
    background-color: rgba(255, 255, 200, 0.2);
    height: 150px;
    margin: 0;
    padding: 0;
    overflow-y: scroll;
    list-style: none;
    text-align: left;
    border: 1px solid #cbcbcb;
    border-top: none;
}
li {
    margin-bottom: 5px;
    padding-left: -30px;
    margin-left: -30px;
}
li:nth-child(even) {
    text-align: right;
    padding-right: 5px;
    margin-left: -40px;
    padding-left: -40px;
    border-bottom: 1px solid white;
}
li:last-child {
    border-bottom: none;
}
li:first-child {
    padding-top: 3px;
}

A: If the CSS on your actual site is the same as in CodePen, it sounds like you need a reset, or have conflicting CSS.
Maybe try adding margin: 0 !important; to see if that sorts the problem for you. If so there's probably some other styles being applied that are more specific than your ul selector.
Like others have said though, seeing your actual CSS would make troubleshooting a LOT easier.

A: You most likely need to use a css reset. This will reset all the default browser (user agent) html styling to a consistent baseline. Codepen is most likely using such a reset and thus the difference in your code from theirs.
Add the css for Eric Meyers reset style sheet at the top of your css. You can find it here http://www.cssreset.com/. Reload your page and see if it removes the spacing.
Edit: Avoid using !important because it will potentially override your other margin styles in your application. This can cause lots of headaches in the long run. Go with a css reset or figure out why the margin is being applied and override that style with less forceful css specificity.

A: I know !important seemed to fix your problem. But for now remove it and try adding:
body, * {
  margin: 0;
  padding: 0;
}

to the top of your CSS file to see if that fixes it. If not, maybe try the CSS reset mentioned in @mikecan's answer.


text:
Q: How to resolve a 'Cannot set property "pages" of the undefined' error in TypeScript? I want to define the visibility of certain items based on the userType in TypeScript that has logged in. However when I am trying to define the pages, I get a run time error that cannot set property pages of the undefined.
Kindly help me please.
My code:

    export class MenuPage implements OnInit {
      pages : [];
      value="";

      definepages(){
        var pages=[];
        var usersRef = firebase.database().ref().child('Users');
        var userEmail = "";
        var userType = "";
        firebase.auth().onAuthStateChanged(function (user) {
          if (user) {
            console.log(user.email);
            userEmail = user.email;
            //userType = user.userType;
          } else {
            // No user is signed in.
          }
        });

        var counter = 0;
        var currentUserData = {};
        usersRef.once("value", function (snapshot) {
          pages=[];
          snapshot.forEach(function (c) {
            if (userEmail == c.val().email) {
              currentUserData["email"] = userEmail;
              currentUserData["entity"] = c.val().userType;
              if( currentUserData["entity"]== 'Admin')
              {

               this.pages = [
              {
                title:'Home',
                url:'/menu/home',
                display:'false',
                icon:'home'
              },
              {
                title:'Register',
                url:'/menu/register',
                display:'true',
                icon:'create'
              },
              {
                title:'Login',
                url:'/menu/login',
                display:'true',
                icon:'log-in'
              },
              {
                title:'Shop by Brand',
                url:'/menu/brand',
                display:'true',
                icon:'log-in'
              },
              {
                title:'Shop by Category',
                url:'/menu/category',
                display:'true',
                icon:'log-in'
              },
            ];
            }
            else if(currentUserData["entity"]== 'Sakhi')
            {
              this.pages=[
                {
                  title:'My Inventory',
                  url:'/menu/my-inventory',
                  display:'true',
                  icon:'log-in'
                },
                {
                  title:'Contact-Us',
                  url:'/menu/contact',
                  display:'true',
                  icon:'contacts'
                },
              ];
              console.log("hello");
            }
            }//check user email details

          });

        }
        );
      }
      constructor() { this.pages=[]}

      ngOnInit() {
        this.definepages();
      }

    }

I am getting the following error:

ERROR TypeError: Cannot set property 'pages' of undefined
      at menu.page.ts:40.

A: You have these lines under the function scope pages=[]; which is mostly giving you error, you probably wanted to replace with this.pages. And I see you are also creating var pages local variable, not sure if you need that, can be replaced with this.pages = [].


text:
Q: Add package routes into main app routes with Express im writing my own MEAN stack. I want to structure it in a horizontal architecture similar to how mean.io does theirs. Each package has its own server and public folder with its own routes.
I have a server.js which is my main express file at the root level. When I start things with npm start I would like to have each package register its own routes / mount its own routes on my main app instance. For some reason though im getting express errors when I try to do this.
Can anyone advise me? Thanks so much.   https://github.com/peb7268/LMFM.git

A: In the submodule / package ( in this case users ) I needed to mount things differently:
var express         = require('express');
var router          = express.Router();

var Users = function(){
    var self        = this;
    self._name      = 'users';
    console.log('initializing ' + self._name);

    router.route('/')
    .get(function(req, res){
        res.send('finding '+ self._name);
    });
}

module.exports = {'router': router, 'instance': new Users()};

Instead of router.route('/users');
Because when you do app.use('/users', router); the '/', default path will collide with '/users' in the sub module.


text:
Q: How to pass more than 10 parameters from one method to another I need to pass more than 10 parameters from one method to another all are of a different type.
If I pass them as parameters it's not looking nice.

A: Create a class like the below:
public class ParamObject
{
    public string Blah1 { get; set; }
    public DateTime Blah2 { get; set; }
}

And instantiate it and use it in your methods.
public void DoStuff (ParamObject uglyRecord)
{
    //do stuff...
}

public void CallStuff()
{
    ParamObject uglyRecord = new ParamObject();
    uglyRecord.Blah1 = "things";
    uglyRecord.Blah2 = DateTime.Now();

    DoStuff(uglyRecord);
}

However, a method that accepts lots of parameters or complex objects is probably a sign that the method is doing too much and should be refactored into several smaller and simpler methods.


text:
Q: Is there a way through which i can access,use and manipulate files from one server using shell scripting on another server > I tried accessing files from remote server "10.101.28.83" and manipulating files to create folders on host server where script has been run. But * is the output of echo "$(basename "$file")" command which implies that files are not read from remote server.
#!/bin/bash
#for file in /root/final_migrated_data/*; do
for file in root@10.101.28.83:/root/final_migrated_data/* ; do
echo "$(basename "$file")"
IN="$(basename "$file")"
IFS='_'
read -a addr <<< "$(basename "$file")"
# addr[0] is case_type, addr[1] is case_no, addr[2] is case_year
dir_path="/newdir1";
backup_date="${addr[0]}_${addr[1]}_${addr[2]}";
backup_dir="${dir_path}/${backup_date}";
mkdir -p "${backup_dir}";
cp /root/final_migrated_data/"${backup_date}"_* "${backup_dir}"

done

I expect the output of echo "$(basename "$file")" to be the list of files present at the location /root/final_migrated_data/ of remote server but the actual output is * .

A: You can use sshfs. As the name suggests, sshfs allows to mount locally (both for reading and writing) a distant filesystem to which you have SSH access. As long as you already know SSH, its usage is very straightforward:
# mount the distant directory on your local machine:
sshfs user@server.com:/my/directory /local/mountpoint
# manipulate the filesystem just like any other (cd, ls, mv, rm…)
# unmount:
umount /local/mountpoint

If you need to mount the same distant filesystem often, you can even add it to your /etc/fstab, refer to the documentation for how to do it.
Note however that using an SSH filesystem is slow, because each operation on the filesystem implies fetching or sending data through the network, and sshfs is not particularly optimized against that (it does not cache file contents, for instance). Other solutions exist, which may be more complex to set up but offer better performance.
See by yourself whether speed is a problem. In your case, if you are simply copying files from one place in your server to another place in your server, it seems rather absurd to make it transit through your home computer and back again. It may be more advantageous to simply run your script on your server directly.


text:
Q: MySQL database is saying the password does not meet the required policy yet it should So this is my sql im trying to run (if i can get it to work ill change the password)
CREATE USER 'foxxything'@'192.168.100.%';
SET PASSWORD FOR 'foxxything'@'192.168.100.%' = '32$jV8klN2nGp2BmLuUb';
GRANT SELECT, INSERT, UPDATE, DELETE ON `foxxything`.* TO 'foxxything'@'192.168.100.%';
REVOKE REFERENCES, CREATE, DROP, ALTER, INDEX, TRIGGER ON `foxxything`.* FROM 'foxxything'@'192.168.100.%';
FLUSH PRIVILEGES;

here are the password policy's
validate_password.dictionary_file
validate_password.length    8
validate_password.mixed_case_count  1
validate_password.number_count  1
validate_password.policy    MEDIUM
validate_password.special_char_count    1

and yet it errors like this.

Your password does not satisfy the current policy requirementsYour password does not satisfy the current policy requirements

so i dont understand, any help would be a huge help!

A: It's throwing that error on the first sql statement when you create the user. Creating the user that way sets the password to nothing which is a violation of the validate_password settings.
Instead specify the password when creating the user with the IDENTIFIED BY clause:
CREATE USER 'foxxything'@'192.168.100.%' IDENTIFIED BY '32$jV8klN2nGp2BmLuUb';


text:
Q: How are positrons produced? What are the methods of positron production? Please don't use mathematical formulas in the explanation.

A: You can easily find the answer in Wikipedia, http://en.wikipedia.org/wiki/Positron_emission.
One source of positrons are nuclear reactions.
I just quote from there: "In 1934 Frédéric and Irène Joliot-Curie bombarded Aluminium with alpha particles to effect the nuclear reaction
$$\ _2^4He + _{13}^{27}Al \to _{15}^{30}P + _0^1n,$$
and observed that the product isotope $ _{15}^{30}P$ emits a positron identical to those found in cosmic rays by Carl David Anderson in 1932. This was the first example of β+ decay (positron emission). . . "
In general the positron is produced if we force a proton to decay as
$$ _1^1p → -0^1n + e^+ + \nu _e$$
This decay doesn't occur spontaneously, because the proton is a stable particle. The procedure is to produce, by a nuclear reaction, a nuclide rich in protons which for reaching a more stable configuration emits a positron for passing to more neutrons.
You can see in Wikipedia a list of unstable nuclides that, if produced, would emit positrons:
$ _6^{11}C, \ _7^{13}N, \ _8^{15}O, \ _9^{18}F, \ _{11}^{22}Na,$ etc.
See for comparison the stable isotopes of these isotopes
$ _6^{12}C, \ _7^{14}N, \ _8^{16}O, \ _9^{19}F, \ _{11}^{23}Na. $
All the nuclides in the preceding list need one more neutron for acquiring stability, but since they don't have that neutron, they produce it by positron decay passing to nuclides that have fewer protons.

A: There are basically three methods:
Bombardment, decay, decay following bombardment.
But really all positron emitters that exist on earth in practical quantities are man made: it always starts with bombardment of nuclei with protons, deuterons or alpha particles. Usually the "thing" that is made is the unstable nucleus - the actual production of the positron is the product of the decay of that nucleus.


text:
Q: Publishing a worker role to Azure Our developers need to publish a worker role to Azure and be able to get the diagnostics information if there's problem. The network admin suggests this requires the developers to log into Azure portal and upload packages and he doesn't want to do it because developers would need full admin rights.
Is this correct? This doesn't sound right. All we need to do is publish a newly created worker role to Azure -- preferrably directly from Visual Studio.
We also need to see any errors our new worker role may generate.
How should we go about it? Do we have to keep generating packages and giving them to the network admin and wait to hear from him?

A: Ideally you shouldn't ever be publishing into a prod environment directly from Visual Studio - it's certainly possible though.  The better bet is deploy via a build server which is configured to deploy into a Worker Role.  This way you remove the need for a co-admin level of access for your developers.
If you want to capture errors from a Web or Worker Role (aka a Cloud Service) then you can use Azure Diagnostics to write the logs to an Azure Blob Storage account.


text:
Q: Max Number of Overlapping datetimes, with many start and end times After some experimenting and some search I found out that this query give me exactly the result I need:
SET @start := '2015-12-12 00:00:00', @end := '2015-12-12 23:59:59';

SELECT Max(simultaneous_people),
       Max(simultaneous_event),
       boundary
FROM   (SELECT Count(id)                AS simultaneous_people,
               Count(DISTINCT uniqueId) AS simultaneous_event,
               boundary
        FROM   mytable
               RIGHT JOIN (SELECT row_begin AS boundary
                           FROM   mytable
                           WHERE  row_begin BETWEEN @start AND @end
                           UNION
                           SELECT row_end
                           FROM   mytable
                           WHERE  row_end BETWEEN @start AND @end
                           UNION
                           SELECT @start
                           UNION
                           SELECT @end
                           UNION
                           SELECT Max(boundary)
                           FROM   (SELECT Max(row_begin) AS boundary
                                   FROM   mytable
                                   WHERE  row_begin <= @start
                                   UNION ALL
                                   SELECT Max(row_end)
                                   FROM   mytable
                                   WHERE  row_end <= @end) t) t
                       ON row_begin <= boundary
                          AND boundary < row_end
        WHERE  row_status = 1
        GROUP  BY boundary) t;

Which are the maximum number of overlapping time periods in the same time.
But I need this information to be extracted between many time intervals, for example 10.
I can't find out how to extract this information inside a calendar built in run time with a query like:
SELECT DATE_SUB(@date, INTERVAL @num MINUTE) AS endSample,
       DATE_SUB(@date, INTERVAL @num:=@num+@lenght MINUTE) AS startSample
FROM
  mytable,
  (SELECT @num:=0) num
LIMIT 10;

I'm using MySQL and unfortunately I cannot store any data/table/procedure/view on this Database.
If someone have an idea of how can I merge those two queries in an efficient way will be great.
Thanks!

Update:
My schema:
CREATE TABLE mytable (
  id         INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  uniqueId   INT,
  row_status INT,
  row_begin DATETIME,
  row_end   DATETIME
);

And some data just for one day, to test only the hour granularity:
INSERT INTO mytable (uniqueId, row_status, row_begin, row_end)
VALUES
  (1, 1, '2015-12-12 08:00:00', '2015-12-12 12:00:00'),
  (1, 1, '2015-12-12 08:00:00', '2015-12-12 14:00:00'),
  (1, 1, '2015-12-12 08:00:00', '2015-12-12 14:00:00'),
  (2, 1, '2015-12-12 13:00:00', '2015-12-12 14:00:00'),
  (2, 1, '2015-12-12 13:00:00', '2015-12-12 16:00:00'),
  (3, 1, '2015-12-12 09:00:00', '2015-12-12 12:00:00'),
  (3, 0, '2015-12-12 08:00:00', '2015-12-12 16:00:00');

I just added the SQL Fiddle.
Here I have to set manually each date range with variables, but I need to be able to set a 'calendar', and be able to specify if the calendar is day by day, hour by hour or minute by minute, by tuning the @length variable.
The first part of my solution is taken from this answer.
My desired output, with hour as time granularity, will be something like:
start_sample        | end_sample          | MAX(simultaneous_people) | MAX(simultaneout_event)
2015-12-12 08:00:00 | 2015-12-12 08:59:59 | 3                        | 1
2015-12-12 09:00:00 | 2015-12-12 09:59:59 | 4                        | 2
2015-12-12 10:00:00 | 2015-12-12 10:59:59 | 4                        | 2
2015-12-12 11:00:00 | 2015-12-12 11:59:59 | 4                        | 2
2015-12-12 12:00:00 | 2015-12-12 12:59:59 | 2                        | 1
2015-12-12 13:00:00 | 2015-12-12 13:59:59 | 4                        | 2
2015-12-12 14:00:00 | 2015-12-12 14:59:59 | 1                        | 1
...

But if I need to change granularity to days, with this data, I will obtain
start_sample        | end_sample          | MAX(simultaneous_people) | MAX(simultaneout_event)
2015-12-12 00:00:00 | 2015-12-12 23:59:59 | 4                        | 2
2015-12-13 00:00:00 | 2015-12-12 23:59:59 | 0                        | 0
...

A: The solution was easier than I thought (hopefully is right as it seems until now).
I'll add some extra boundaries using my calendar generator, in order to avoid empty holes for my final data (a day with no entries will not be shown otherwise):
                       ...
                       UNION
                       SELECT @start
                       UNION
                       SELECT @end
                       UNION
                           SELECT DATE_SUB(@date, INTERVAL @num:=@num+@lenght MINUTE)
                           FROM
                             mytable,
                             (SELECT @num:=0) num
                           LIMIT 10
                       ...

Then I have to group by the date_part (in postgres) ora DATE_FORMAT (in MySQL), more interesting to me (I must add a variable to be paired with @length), not the whole boundaries as I was doing before, and the external query will become:
SELECT Max(simultaneous_people),
       Max(simultaneous_event),
       DATE_FORMAT(boundary,'%Y%m%d')
FROM (...) as t
GROUP BY DATE_FORMAT(boundary,'%Y%m%d');

I hope this may help someone else, it took a while to reach this point.
This query is really heavy with a lot of data, so the more you cut/segment (vertically and horizontally) the data, the better it will perform, the 'WHERE  row_status = 1' should be added everywhere a bound is obtained throud the Unions.


text:
Q: PageViewController current index I want to set the value of a slider with the current index of a pageViewController.
My idea is to use this method but i dont know how I get the index...
-(void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{

    if(completed)
    {

        //self.slider.value = THE INDEX;
    }
}

A: I think you will have to implement custom method on your datasource,
that will return you index of view controller. You very likely have array with ViewControllers in  your datasource. so simple call like one below should do :
[pageViewController.datasource indexOfViewControler:[pageViewController.viewControllers]objectAtIndex:0]]; // index of viewcontroller is methond you need to implement on your datascource

A: you have to implement the method for getting index. you can do this simply by adding your viewController in NSArray .
NSArray * viewControllers = [NSArray arrayWithObjects:firstViewController,secondViewController, nil];

& then get iindex like this:
self.slider.value=[viewControllers indexOfObject:[pageViewControlle.viewController]];


text:
Q: How to write log before instalation My computer crashes while trying to load the kernel from a LiveCD with the message "unable to handle kernel paging request". I'd like to reproduce the error output on a forum to get some ideas on where to dig, but I can't figure out how to save that trace except by taking a picture with a camera. Is there some option to save the output on a hard drive, or at least allow scrolling to the beginning of the error? I currently have Windows and Ubuntu 9.10 installed, and I'm trying to install Ubuntu 12.04. The same error happens with other Linux distributions (openSUSE 13.1, Linux Mint 16).

A: Possibly kexec is your friend in this case.
Though I'm not sure as I have not tried


text:
Q: UIButton custom button wont change font colour on select I'm using this code to create a UIButton, however when pressing the button the font doesn't change colour.
_gameSlider = [UIButton buttonWithType:UIButtonTypeCustom];
    [_gameSlider setBackgroundImage:[[UIImage imageNamed:@"sliderBackgroundSticker"] resizableImageWithCapInsets:UIEdgeInsetsMake(22, 16, 22, 16)] forState:UIControlStateNormal];
    _gameSlider.frame = CGRectMake(0, 0, self.view.frame.size.width - 20, 70);
    newCnt = self.view.center;
    newCnt.y = newCnt.y + 120;
    _gameSlider.center = newCnt;
    [_gameSlider setTitle:@"PLAY" forState:UIControlStateNormal];
    [_gameSlider.titleLabel setFont:[UIFont fontWithName:@"Chalkduster" size:22]];
    [_gameSlider setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_gameSlider setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected | UIControlStateHighlighted];
    [_gameSlider addTarget:self action:@selector(playButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_gameSlider];

A: Put your background color you want under forState:Highlighted.
While its being pressed it isn't in UIControlStateNormal it's UIControlStateHighlighted.


text:
Q: Chrome JetBrains plugin wont be recognized by WebStorm 6.0 I've tried to solve this for so long now. I've installed the plugin from the Chrome store but the plugin button in the browser is grayed out and says "Not connected" on hover. When I debug in WS I get this popup:

I've seen the help section on JB site but the help there is utterly poor, and doesn't even mention the problem with the plugin and the IDE not recognizing eachother.
I've looked over other posts here with similar problems, though usually it revolved around LiveEditing, and I haven't found any help there for my problem.
Can someone please give me a sequence of steps to perform to check where the problem is with the syncing between the IDE and the Chrome plugin?
EDIT :
The JB console is empty when I open it:

A: *

*Right click to JetBrains chrome extension

*Select "Options"

*Set Host: 127.0.0.1

*Set Port: 63343

*Click "Apply"
You're ready to go

A: please, check what is written in extension console (http://confluence.jetbrains.com/display/WI/LiveEdit, How do I know what's wrong?)
The console contents along with your idea.log (Help/Reveal log) would be helpful


text:
Q: changing a text field value dynamically in java I'm making a postal service application. I'm getting the weight of the box in one text field and I want to show it's price at the moment in another text field which is not editable.
for example if he typed 100, then that text field text sets to 1000 and if he typed 200, the the text field sets to 2000 with no need of pushing any button etc.
Thanks in advance

A: Add a KeyListener to the text field that would update the price whenever a new value was entered.  You might want to add a delay that would only update the price after a second or two to make sure the user finished entering the value instead of updating with each key stroke.
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

A: Add a DocumentListener to the Document of the JTextField. It will be invoked when text is added/removed from the text field.
Read the section from the Swing tutorial on How to Write a Document Listener for more information.

A: set up an a keylistener to listen for inputs in your weight textField,
set up a switch statement to convert the weightTextField's input to the pricePerWeight textfield and pricePerWeight.setText()

A: you need add an event listener for the onchange event to your text input and when the event is received, perform the calculation and update the second text input
The following topic shows how to add the event listener
Value Change Listener to JTextField


text:
Q: How to build a controll panel with cakePHP/MVC frameworks I'm building a simple Virtual Learning Environment(VLE) system for a test project with CakePHP. The project contains the following:

*

*Courses

*Lessons

*Questions

*Answers

I've made the Controller, Models and Views for the courses and Lessons and I'm able to add lessons to a course and delete them. I've generally been following cakePHPs blog tutorial and changing as I go along.
This however leaves me with a very rigid structure of content and pages and URL's (I understand how to change the URL's to be more user and SEO friendly with Routes). My pages are all /{controler}/{method}
Part of the project is to create a management panel for the courses. On the page you can see lessons, and the students assigned to the course with links to add/edit these.
I can not however work out how to do this combination of several models into an admin style page. I can think of a few ways of dong this involving perhaps cakePHP pages, or routes and bringing one models data into another's controller to get it into the view. However I am trying to find out the correct way of doing this with cakePHP or failing that in MVC frameworks in general.
I apologise if this is laid out anywhere obvious but I've looked and have yet of find any answer that coveres my issue is a laid out fashion. Unfortunately I really need this spelling out for me as I'm just overwhelmed with a lot of MVC without anyone to ask and haivng only worked in CMS systems.

A: Just create a Controller called "DashboardsController" or something like that.
Within it's actions, you can load any model(s) you want, then use it just as you would in the respective Controller:
$this->loadModel('Course');
$courses = $this->Course->find('all');
$this->set(compact('courses'));

This is a very common problem/solution, and I believe I even asked this same question a few years ago on here myself (though I couldn't find it).  You still retain the MVC structure, as it still acts as the Controller - it just accesses methods from varying models.
It's incredibly common to call more than just the model of the controller you're in, so in a case like this, you just load whichever models you want/need.
You can make a Dashboard.php model as well and just set
$useTable = false;

to tell it you don't need a "dashboards" table.
I have one of these "generic" controllers in almost every project I do, and am not really sure of any other/better way to handle it.  This seems the cleanest, easiest, and most logical approach IMO.


text:
Q: how can I add css and js files with jsps with spring Mvc I'm currently developing a JavaEE spring based application using spring MVC but when I added css and js files,the jsps doesn't read them,after some researches  I added this line on my dispatcher servlet file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="controllers"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsps/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

</beans>

and this is the project hierarchy

A: try this,
on your jsp page, if you are using jstl  then do this
First include the jstl tag library,
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

then
    <link href="<c:url value="/resources/css/myCSSFile.css" />"  rel="stylesheet">
   <script src="<c:url value="/resources/js/jquery.1.10.2.min.js"  />"></script>
    <script src="<c:url value="/resources/js/main.js" />"></script>

Say, if you are already using Spring tag library then can you do like this,
First include the tag library, as bellow
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>

and then do this,
<s:url value="/resources/css/main.css" var="mainCss" />
<s:url value="/resources/js/jquery.1.10.2.min.js" var="jqueryJs" />
<s:url value="/resources/js/main.js" var="mainJs" />

<link href="${mainCss}" rel="stylesheet" />
<script src="${jqueryJs}"></script>
<script src="${mainJs}"></script>

Do let me know If i missed something to explain here

A: You need to add the css/js files to <script> and <link> tags in the .jsp's themselves like you would an HTML file.
CSS and JS are both client side and need to be sent / loaded on the client rather than the server.
Edit to be a bit more clear: JSPs are "formatted" on the backend (Spring) and then sent to the client as if it were static HTML, so loading the JS/CSS on the server would be like running all the client code on the server, stop running the client code, then send the static page to the client.


text:
Q: How to create/delete files in secondary storage SDCARD version after KitKat? Knows that the permission of creating and deleting changes to SAF(storage access framework) in secondary storage SDCARD OS version after KitKat.
Under manifests, permission has been set,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Version after KitKat
By using new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
Secondary storage SDCARD route will be chosen, converting DocumentUri
set as takePersistableUriPermission()
For example, Version before KitKat.
File file = new File(path);
file.delete()

can be successfully deleted.
version after KitKat,
delete() getting write permission error,
DocumentsContract.deleteDocument(getContentResolver(), Uri.fromFile(file)));

using deleteDocument() not found indicated with documented and unable to delete.
Is there any solutions for this issue?
Is there any ways to find/change General mediated or filed to documented?


text:
Q: How to concatenate every four lines for the first four lines of a file I'm not sure the best wording to ask this question, but I'm trying to concatenate the first four lines to the next four lines and so on until the end of the file.
My data looks like:
aggaacgtgagttgaaaattgaagcgacaaacttggtttcatgtcctgtttgtggaaaga
catctattgttagagacaatatattgtctgatctgacttatctgcatgttc---------
 .     **    ..* * *. * .* * .*..**..**  .  * ****.

gcataaaaggaatggacacaatcataaatgaacatcttgatatctgccttacaagaaggt
----------tgtggattcctttctttttccttttggagatatctgccttacaagaaggt
           .****. *  *. *   *   . *   **********************

ccaaacgaaaacttacccaacgcacactacttcagtttggtgttggatcaagtaccaaaa
ccaaacgaaaacttacccaacgcacactacttcagtttggtgttggatcaagtaccaaaa
************************************************************

And I'm trying to merge/concatenate every four lines to the four lines before to create a horizontal file format that looks like:
aggaacgtgagttgaaaattgaagcgacaaacttggtttcatgtcctgtttgtggaaagagcataaaaggaatggacacaatcataaatgaacatcttgatatctgccttacaagaaggtccaaacgaaaacttacccaacgcacactacttcagtttggtgttggatcaagtaccaaaa
catctattgttagagacaatatattgtctgatctgacttatctgcatgttc-------------------tgtggattcctttctttttccttttggagatatctgccttacaagaaggtccaaacgaaaacttacccaacgcacactacttcagtttggtgttggatcaagtaccaaaa
 .     **    ..* * *. * .* * .*..**..**  .  * ****.                    .****. *  *. *   *   . *   **********************************************************************************

I know I can use paste - - to delete a newline character every other line, but what would be the simplest route to paste together the different lines of my file for the first four lines every other four lines?

A: You could use perl:
#!/bin/perl

use strict;
use warnings;

my %lines;                   # hash container to store the lines

while(<>) {                  # read lines from stdin
    chomp;                   # remove newline
    my $idx = ($. - 1) % 4;  # calculate index of line [0,4)
    $lines{$idx} .= $_;      # concatename the current line to what's at $idx
}

# Done, print the result:
for(my $i = 0; $i < 4; ++$i) {
    print $lines{$i} ."\n";
}

A: One way is to store each line in an array to be printed at the end:
awk -v n=4 '
{ a[NR]=$0 }
END {
  for (i=1; i<=n; i++) {
    for (j=i; j<=NR; j+=n) {
      printf "%s", a[j]
    }
    print ""
  }
}' file

Another way is to read the file 4 times (this avoids storing the entire file in memory):
awk -v n=4 '
  FNR==1 {
    if (c++) print ""
  }
  ! ((NR-c)%n) { printf "%s", $0 }
  END {
    if (c) print ""
  }
' file file file file

This could be done using a shell loop:
for c in 1 2 3 4
do
  awk '! ((NR-c)%n)' n=4 c="$c" ORS= file
  echo
done

Output from any of the above will be:
aggaacgtgagttgaaaattgaagcgacaaacttggtttcatgtcctgtttgtggaaagagcataaaaggaatggacacaatcataaatgaacatcttgatatctgccttacaagaaggtccaaacgaaaacttacccaacgcacactacttcagtttggtgttggatcaagtaccaaaa
catctattgttagagacaatatattgtctgatctgacttatctgcatgttc-------------------tgtggattcctttctttttccttttggagatatctgccttacaagaaggtccaaacgaaaacttacccaacgcacactacttcagtttggtgttggatcaagtaccaaaa
 .     **    ..* * *. * .* * .*..**..**  .  * ****.                    .****. *  *. *   *   . *   **********************************************************************************

A: It seems every three lines are separated by a blank line. If this is the case, this awk program might be what you're looking for:
awk 'BEGIN { RS = ""; FS = "\n" }
           { for (i = 1; i <= 3; ++i) line[i] = line[i] $i }
     END   { for (i = 1; i <= 3; ++i) print line[i] }
' file

A: If your file is huge storing its whole content in variables or processing it several times could lead to memory or performance issues. Generating 4 different files on the fly and concatenating them together could then help. Example with GNU awk in a bash script:
#!/usr/bin/env bash

# file myScript.sh

unset tmpdir
trap 'rm -rf -- "$tmpdir"' EXIT TERM

declare input="${1:--}"
declare tmpdir

tmpdir=$(mktemp -d) || exit 1
awk -v t="$tmpdir" '
{
  printf("%s", $0) > t "/file." (NR-1)%4 ".part"
}
END {
  for(i=0; i<4; i++) print "" > t "/file." i ".part"
}' "$input"
cat "$tmpdir"/file.{0..3}.part

The script uses a temporary directory to store the 4 intermediate files. A trap deletes the temporary directory upon normal termination or if the script is terminated before its normal end. Usage: ./myScript.sh [FILE]. With no FILE, or when FILE is -, the script reads the standard input.

A: This awk script will do the change
awk '
{
    line = (line == "" ? $0 : line$0);
    if (++i == 4) {
        print line;
        i = 0; line="";
    }
}
END {
    if (line != "")
        print line;
}'

you can add filenames to the awk command to process several files or read from the standard input as the command is shown.  You can add a separator char between line and $0 if you want the lines separated by some string, or change the 4 for the number of lines you want together.  For example to group the lines in groups of three, and separate them by @ characters:
awk '
{
    line = (line == "" ? $0 : line"@"$0);
    if (++i == 3) {
        print line;
        i = 0; line="";
    }
}
END {
    if (line != "")
        print line;
}'


text:
Q: How to update the configuration files in WAS Liberty once after deployment Can it not be like Tomcat web server? After deploying WAR file in WAS Liberty container, I try to edit one of the configuration file under "WEB-INF" folder by stopping and again restarting the WAS liberty server. However, I  cannot use updated information and it uses the old configuration which was used during initial deployment.

A: If you put .war it is automatically expanded each time the server starts. However you can also use 'expanded deployment' and put unpacked .war to the apps folder. In that case you will be able to modify files on the fly without rewrites during restarts. Check this link for more details.

A: Continue with this issue ... and thank you for your replies for this question.
I am looking for solution where it will unpack WAR file automatically like tomcat,WAS,etc… and we can update and use the information after this WAR extraction.
I checked autoexpand option and made it false. Now after making this changes, WAR file is not getting extracted in the apps folder.
Actually, we can use this solution as workaround i.e. need to enable the auto expand option in the server.xml. This will expand/extract the WAR file. Then need to stop the Liberty server. Now, update server.xml and disable the auto expand option. After that we need to update the required configuration file. Then need to start the server. This actually work, but this cannot be solution.
I am looking for solution like tomcat web server, where after deploying war file, we can make changes inside webapps/xx/WEB-INF/ path for further configuration settings.

A: Thank you for your reply!!
Please find the requirement details.
WAR file is deployed @ /opt/Liberty/wlp/usr/servers/TCLiberty/apps/
-rw-r--r-- 1 clsqa cls 43358874 Apr  5 17:21 TC-DEV-4.3.war
This file will get extracted @ /opt/Liberty/wlp/usr/servers/TCLiberty/apps/expanded/
/opt/Liberty/wlp/usr/servers/TCLiberty/apps/expanded>ls
drwxr-x--- 10 clsqa cls 4096 Apr 11 14:53 TC-DEV-4.3.war
/opt/Liberty/wlp/usr/servers/TCLiberty/apps/expanded>ls -ltr TC-DEV-4.3.war
total 60
-rw-r-----  1 clsqa cls  1555 Feb 28 01:53 index.html
drwxr-x---  3 clsqa cls  4096 Apr 11 14:53 ..
drwxr-x---  2 clsqa cls  4096 Apr 11 14:53 META-INF
drwxr-x---  9 clsqa cls  4096 Apr 11 14:53 images
drwxr-x---  2 clsqa cls  4096 Apr 11 14:53 logs
drwxr-x---  8 clsqa cls  4096 Apr 11 14:53 WEB-INF
drwxr-x---  3 clsqa cls  4096 Apr 11 14:53 css
drwxr-x---  2 clsqa cls 12288 Apr 11 14:53 html
drwxr-x--- 10 clsqa cls  4096 Apr 11 14:53 .
drwxr-x---  2 clsqa cls 12288 Apr 11 14:53 js
drwxr-x---  2 clsqa cls  4096 Apr 11 14:53 pdf
The WAR file extraction was done automatically since we have made auto expand = true

<!-- Enable features -->
<featureManager>
    <feature>webProfile-8.0</feature>
</featureManager>

<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint id="defaultHttpEndpoint"
              httpPort="9080"
              httpsPort="9443"
              host="*" />

<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>
<webApplication contextRoot="TC-DEV-4.3" location="TC-DEV-4.3.war" />
<mimeTypes>
<type>.htc=text/x-component</type>
</mimeTypes>

Now my requirement is to make changes in file which is available in "/opt/Liberty/wlp/usr/servers/TCLiberty/apps/expanded/TC-DEV-4.3.war/WEB-INF/"
/opt/Liberty/wlp/usr/servers/TCLiberty/apps/expanded/TC-DEV-4.3.war/WEB-INF>ls TMS.properties
-rw-r----- 1 clsqa cls 2789 Apr  2  2010 TMS.properties
Content of this file are some predefined variables (constants)and ip address(variable) of the application and corresponding port. This IP address is always different which need to modified depending upon the application server and ports of the environment
appaddrlist=//:
In order to make this files changes, I need to stop the Liberty server. But when I restart the server again, the existing WAR file will be extracted in the "expanded" path. And I lose my changes.
Now, as per our discussion and solution provided, I can make server.xml file and make changes of autoexpand option to false. In this case TMS.property file will not be overwritten and my issue is resolved.
However, I believe this solution as workaround because every time I need to modify the server.xml file.
Is there any other solution? Earlier I had given reference of the tomcat web server where we can make changes in the WEB-INF folder after auto extraction by tomcat server.
Request to guide in this regards.
Thanks


text:
Q: How to compute the determinant of some 3x3 matrix more quickly than by Sarrus method? I know that the determinant of this matrix: $ \begin{bmatrix} 2-\lambda & -1 & 1\\1& 5-\lambda & -2 \\ 0 & 1 & 2-\lambda \end{bmatrix} $ is $(3-\lambda)^3$ by simply computing the determinant (using Sarrus method), but I want to know if I can compute this determinant faster, by doing some operations with the rows and columns.
Thank you for your help!

A: For $3 \times 3$ Matrices, Sarrus is the fastest way to go. You might find matrices that have certain features (a coloumn or a row with no or only one nonzero element), which can give you a boost, but in general (as in this case), you should use Sarrus.

Example where you can go faster using Laplace's formula:
$$M=\begin{bmatrix} 2-\lambda & -1 & 1\\0& 5-\lambda & -2 \\ 0 & 1 & 2-\lambda \end{bmatrix}$$
As you can see, this is very similar to your matrix, but the first row has only one element different from zero ($2-\lambda$). If this is not the case, Laplace's won't save you work on $3\times 3$ or smaller.
So we go down the first row with Laplace:
\begin{align}
\det(M) &= \det\begin{pmatrix} 2-\lambda & -1 & 1\\0& 5-\lambda & -2 \\ 0 & 1 & 2-\lambda \end{pmatrix}\\
 &= (2-\lambda) \cdot \det\begin{pmatrix} 5-\lambda & -2 \\ 1 & 2-\lambda \end{pmatrix}
-0  \cdot \det\begin{pmatrix} -1 & 1\\1 & 2-\lambda \end{pmatrix}
+0  \cdot \det\begin{pmatrix} -1 & 1\\5-\lambda & -2 \end{pmatrix}\\
&=(2-\lambda) \cdot \det\begin{pmatrix} 5-\lambda & -2 \\ 1 & 2-\lambda \end{pmatrix}
\end{align}
... and this is much easier to calculate.
For more detail, look here.


text:
Q: VirtualBox crashes Ubuntu 16.04 vm's Host: xubuntu 16.04 amd64
Guests: xubuntu 16.04 and lubuntu 16.04
The vm crash right away when booting for the very first time from the desktop iso's. The screen gets garbled. And that's it. The picture shows the xubuntu 16.04 screen. Lubuntu's 16.04 looks evenly strange.

Lubuntu lets me select a language. Xubuntu crashes after the dot animation. xubuntu 15.10 seems to install properly.
Is this a known problem?
Forgot to mention this is VirtualBox 5.0.18_Ubuntu r106667.

A: Not really a solution, but to work around the problem, you have to issue the guest OS Ctrl+Alt+F2 followed by Ctrl+Alt+F7. This will cycle through the TTY and back to X11, therefore restoring resolution to the correct value.
In order to issue the Ctrl+Alt+FX combo you should press Host_key+FX. (Host_key is by default mapped to the Right Ctrl key in VirtualBox).
Oracle seems to consider this a bug in Ubuntu, and therefore will not try to solve it.
Alternativey, you may also reinstall and run Ubuntu on "EFI mode". Makes the issue disappear, and seems to work well enough for me.

A: I was facing the same problem and to my surprise the virtualization feature was disabled by default in BIOS. The issue was gone after enabling (both VT-x and VT-d).
Also, I have disabled Hyper-V via powershell using this guide.
Version 5.1.6 r110634


text:
Q: Make universal function for entire App React Consider this function (this is just an example):
function highlight(el) {
  el.style.transition = "background-color 0.5s";
  el.classList.add("highlight");
  setTimeout(() => {
    el.classList.remove("highlight");
    setTimeout(() => {
      el.style.transition = "";
    }, 500);
  }, 500);
}

document.getElementsByTagName("a").addEventListener("click", function () { highlight(this) });

This is "universal function" that automatically binds to every <a> on page onload, it is short (only several lines long) and I can add or remove it in seconds (the code on pages are intact).
What is the best approach to implement it in React App?
Course I knew the obvious way, with the manual add of onClick to every <a> in every component on page with setState logic, but ... it kinda sucks
I'm new to React, maybe someone can point me to the right direction
How I can implement this logic on every page(every component that has <a>) efficiently, with the ability to easy remove it if it is no longer needed?

A: Well, the way I see it, if you want the react way, then you would want to create a presentation component with the defined behavior and use that component instead of .
In fact, that would actually be a perfect fit for a presentational react component.
Then, if you need to implement any changes, you would do them inside that component.
You could alternatively add vanilla js to the index page but that kinda misses the whole point of react.

A: If you are currently developing this application then the best approach is to create a small tiny component for it. For example you can create a component HighligtedAnchor and can implement the stylistic features in it directly.
Secondly, if you directly want to handle a lot of anchors then the most appropriate place would be the root of your application that is usually App.js or you can write it down in the index.html as well if you really want to move forward with the plane js approach.

A: If you are looking at for something like good old jquery live you can't do that in reactjs.
The best thing you can do is to create a custom component that wraps the <a> tag. And use your custom component everywhere you would use regular <a> tag.


text:
Q: unable to access internet from windows in VMware guest OS I'm using windows 7. I have installed vmware. In vmware i have installed guest OS(windows). Now i want to access internet in my guest OS. How can i access? Please suggest me. Thanks in advance.

A: *

*Go to VM > Settings > Hardware and add a network adapter if one is not already present.

*Configure the VM's network adapter to use NAT to reuse your host's IP address. (You may wish to use bridged networking instead, which will make your VM appear as a physical machine on your local network and which will be a bit faster, but this can be a little trickier for wireless networks or if your host has multiple network adapters.) You can click the Help button in the VM Settings dialog for more information.


text:
Q: Ionic Firebase. Get current user I want to get current user and display at the page. I follow Firebase docs and use {{}} and not working. Do I miss another code or need to use another way? Someone can give an example. Thank youuuuuuuuuuuuuuuuuuu
.controller('dashCtrl', function($scope, $state, $ionicPopup, $ionicLoading, $firebaseAuth) { //library injection

var user = firebase.auth().currentUser; // code from firebase docs
var name, email, photoUrl, uid; //declare the variable

//checking the user
if (user != null) {
  name = user.displayName; //fetch the name
  email = user.email; // fetch the email
  photoUrl = user.photoURL; // fetch
  uid = user.uid;  // fetch uid
  //password = user.password;
  // The user's ID, unique to the Firebase project. Do NOT use
  // this value to authenticate with your backend server, if
  // you have one. Use User.getToken() instead.

  console.log(email); //log the email. success display at console
  console.log(uid);
}
  //logout function
  $scope.logout=function(){
     firebase.auth().signOut().then(function() {
     console.log("Sign-out successful.");

     $state.go('login');
   }, function(error) {
      // An error happened.
  });
 }

})

<ion-view hide-back-button="true" cache-view="false" ng-controller="dashCtrl">
  <ion-nav-title>Dashboard</ion-nav-title>
    <ion-nav-buttons side="right">
      <button class="button icon ion-log-out" ng-click="logout()"></button>
    </ion-nav-buttons>
 <ion-content class="padding has-header" scroll="true">

// need to display at this title

Welcome to your dashboard, {{user.email}}

<button class="button button-block button-calm">
  <h7>Update Email</h7>
</button>

</ion-content>
</ion-view>

A:

var user = firebase.auth().currentUser;
if (user != null {
  $scope.user = {
    name: user.displayName,
    email: user.email,
    photoURL: user.PhotoURL
  }
}

Good luck...


text:
Q: Doing things with images I have the following input
<input class="text-right" type="file" id="cameraupload" name="upload" accept="image/*"/></input>

How can I use jQuery (or javascript if necessary) to get what was uploaded and put it on the page in a div

A: Try this:
<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

<script>
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });
</script>


text:
Q: Pushing Files to a particular directory of a Github Repository using Git Bash/Terminal I have an existing repository in Github. But how do I commit changes and push the files to a particular directory in that repository?
Note - I've done all the steps from git remote add origin to 'git commit' to 'git push` but, how do I select that particular directory I want to push changes into the repository from the terminal.
PS - I want to push changes from my local [which is not in my project directory] to a particular existing Directory of the Repository.

A:
Suppose I've created some files in a temp local directory [which is not in my project directory for some reasons] and I wanna push the files inside the temp folder to a pre-existing directory of my repository using git remote add. I

First, git remote add is just to declare a remote URL: it does not add or push any file.
Second, simply copy those file in the local repository, with the right folder.
Then:
git add theRightFolder
git commit -m "Add theRightFolder content"
git push -u origin master

If that folder includes other files you do not want to push, you will need to git add only the files you have copied
git add theRightFolder/file1
...
git add theRightFolder/filen

git commit -m "Add some files in theRightFolder"
git push -u origin master


text:
Q: What edge connector for prototype board? For personal hobby projects I'm using prototype boards like this (2.54 mm pitch):

I connect them using wires, which is a mess. I want to use a backplane with female edge connectors, for a solution like this:

Making a PCB is out of question, mostly because I keep adding components to my projects to add further functionalities.
After searching, the only female edge connector I found was 3.96mm pitch ones, that seems to be incompatible with prototype boards.
I'm looking for a solution, better if it accepts the prototype board as is (without a male connector). Cost is not a big factor.
Any sugestion is welcome.
Edit
Durability is not an issue; I keep producing new versions every 12 to 18 months. Cheap components, hardware is totally disposable (I don't even bother recycling them).

A: Why not do it like in the picture you posted?
Your prototype board already has the holes to fit 0.1" right angle male headers on the edges, and you can use strip board as the "backplane" with female 0.1" connectors.
You can get all of this on aliexpress for ridiculously low prices (like $1 = 500 pins worth of headers).
Using a card edge connector is just going to be more cumbersome and more expensive. Also the fingers on your protoboard are too short, they don't reach the edge, once you solder something into the holes they'll be full of solder, and you'll need to cut the board... or you can use a $0.05 pin header!

A: If you are not averse to cutting down the PCB and chamfering the raw edges slightly* then something like an ordinary PCB edge connector could work with ordinary Veroboard as the backplane PCB for single-sided daughter boards.
* Remember it's fibreglass so don't get the little shards on your skin or in your lungs if you can avoid it.

A: JST connectors
This could be a little bit too advanced or too much but it is a good practice to start using them in your hobbies because most companies in the tech industry use them. Plus you will learn how to crimp, and for the size of the connector you are looking for the tool is really affordable; Amazon has it for around $22. I know the link I gave you is for 2.50 mm pitch but it should be able to work.


text:
Q: Is there a solid algebraic motivation behind the derivative? I work in my university's math help center and am often presented with questions rooted in poor conceptual or intuitive understanding understanding of various mathematical questions; esp. with the beginning calculus students I work with. From day one of my calculus studies, and from theirs as well, the idea behind the derivative has always been presented with the geometric motivation of finding "the slope of the line tangent to the graph of a certain function at a particular point." But as we all know, the derivative has helped us solve many problems outside of geometry; indeed, its properties and abilities are easily adapted to many problems outside of the classic tangent line problem.
So my question is this: is there a way to construct the derivative in the context of purely algebraic problem, especially the kind of problem that can be digested by younger students? So I suppose the answer to my question is another question, one whose natural, intuitive solution involves developing a difference quotient and using it to solve the problem, in the process building the derivative.
Hopefully this might be a nice thought experiment.

A: A good motivation is that the derivative of a function at some point is the best linear approximation to the function at that point.
Students are familiar with the idea that linear functions are easier to deal with than the other, more elaborate functions they've already come across.  So it's easy to explain that differentiation lets you analyze even complicated functions by reducing them (in the neighborhood of any particular point) to the easier-to-understand linear case.


text:
Q: c++17: inner class default member initializer ignored in static inline varilables Compiling it using clang -std=c++17, and the error msg is default member initializer for '_x' needed within definition of enclosing class 'A' outside of member functions.
I tried it with gcc, and got the same error msg.
It's not obvious to me why it's disallowed, and it seems that once I move the inner struct outside the enclosing class (move B out of A), it compiles fine.
#include <iostream>

class A {
struct B {
  size_t _x = 0;
};
  private:
    static inline B b = {};
};

int main(void) {
  return 0;
}


text:
Q: g++ errno_t and fopen_s error in Debian 8.1 Jessie I have written some code in Windows 8.1, Visual Studio 2013 Express. Now, I am trying to transfer and run this code on my Beagle Bone Black which is running Debian 8.1 Jessie. This is my first time using Linux so I am having some problems.
#include <iostream>
#include <errno.h>
#include <stdio.h>

using namespace std;

int main()
{
    FILE *cfPtr;
    errno_t err;

    if ((err = fopen_s(&cfPtr, "objects.txt", "a +")) != 0) // Check if we can reach the file
        cout << "The file 'objects.txt' was not opened.\n";
    else
        fclose(cfPtr);

    return 0;
}

I compile this code with:

g++ source.cpp -o source

But it gives me some ... was not declared in this scope kind of errors.
source.cpp: In function 'int main()':
source.cpp:10:4: error: 'errno_t' was not declared in this scope
source.cpp:10:12: error: expected ';' before 'err'
source.cpp:12:8: error: 'err' was not declared in this scope
source.cpp:12:50: error: 'fopen_s' was not declared in this scope

I see, *_s functions for Windows, so how can I fix this and errno_t problems?
Thank you.

A: Like you say, fopen_s is a Microsoft Windows specific extension to the C standard library and you need to use fopen instead.
Now, errno_t is basically just an int, so you could use an int instead.
I'd recommend doing it this way:
#include <iostream>
#include <stdio.h>

using namespace std; // bad

int main(){
     FILE *cfPtr = fopen("objects.txt", "r");

     if (cfPtr == NULL){
         cout << "The file 'objects.txt' was not opened.\n";
     } else {
         cout << "Success!";
         fclose(cfPtr);
     }
     return 0;
}

Do note that "a+" will create a new file if it doesn't exist, as such it will work in most cases, regardless. I have decided to use "r" instead as this will fail if the file does not exist -- as an example.


text:
Q: MediaCodec::CreateByType "video/avc" fails on nexus 7 I am trying to encode h264 using MediaCodec in nexus 7 device and after re running ( after closing ) my encoder process several times I get a failure when trying to create MediaCodec
( MediaCodec::CreateByType(looper, "video/avc", true) ). the log shows:
E/OMX-VENC-720p(  181):  Is component secure 0
E/OMX-VENC-720p(  181): ERROR: Omx_venc::Comp Init Returning failure
E/OMX-VENC-720p(  181):
E/OMX-VENC-720p(  181): ERROR: venc_open failed
E/OMX-VENC-720p(  181):
E/OMX-VENC-720p(  181):  Destroy C2D instance

after rebooting the device I can once again create the encoder.
Is this a bug in the nexus hardware encoder or could this be a result of not releasing the encoder properly ?

A: This is not expected.
If you grab the latest version of Grafika, you can find a "Codec open test" activity near the bottom.  When you run this and click "START", it will try to open as many codecs as it can.  If you click "Halt", it will halt the VM, and the app will be restarted.
With a Nexus 7 (2013) running 4.4.2, the first time I hit "start" I see four codecs created.  If I hit it again, I get zero.  If I cause a GC with DDMS or halt the process, it goes back to four.  The only way it should get "stuck" is if the app is holding several open and is still running.
Whatever the case, make sure you release codecs when your app pauses.  This is, of course, impossible if your app crashes, but in normal operation you don't want to hold on to hardware resources when your app isn't in the foreground actively using them.  If there's a bug somewhere that prevents the system from cleaning up, it's even more important to release them promptly.


text:
Q: Animating CSS by transitions when a class is added to an element I'm using the Foundation framework on a project & it's Top Bar feature for navigation allows for drop-down navigation to appear on hover.
During the hover event it adds a .hover class to the relevant element, therefore the changes in CSS pop into sight rather than animating by way of a smooth transition.
This got me thinking. Is it possible to animate (via transitions or similar) the changes in CSS definitions?
Take this example. Here is our default element:

Some content

And it's default CSS:
.a-box {
    width: 200px;
    height: 200px;
    background: red;
}

On hover the framework (which I do not wish to edit the core file to keep it clean for updates) adds the hover class. Making our element now look like this:

Some content

Here could be some CSS for the hovered element:
.a-box.hover {
    width: 400px;

    // I thought perhaps adding the following would work but it doesn't appear to

    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    transition: all 200ms ease;
}

I'd be keen to hear others POV on this! I'm not sure if this is a duplicate, but all the posts I've read relate to some form of jQuery animation.

A: You aren't far off the mark, here is a working example.
The main error in your example is that you have

Some content

But your CSS is looking for a-box not my-box.
As a habit, I normally define the animation on the simplest (most general) selector for the element and then any additional selectors will benefit from it.
.my-box {
    width: 200px;
    height: 200px;
    background: red;
    -webkit-transition: all 200ms ease;
    -moz-transition: all 200ms ease;
    -ms-transition: all 200ms ease;
    transition: all 200ms ease;
}

.my-box.hover {
    width: 400px;
}


text:
Q: Android and using dependencies. Is it ok? Like using someone else's build implementation of something in your code. So like the title says, is it ok to use someone elses implementation of something? Like for instance i used this well known PagerSlidingTabStrip in my code.
https://github.com/astuetz/PagerSlidingTabStrip
So let's say i used this in my gradle in my dependencies and the app i was making was to go to the google play store. Is this legal? Or do i need the permission from the creator. If you could please also give me some guidelines to follow for these type of things.
Sorry for the dumb question but I'd rather ask then not.
Thank you.

A: Whenever you're using a library from github, check the license at the bottom of the page.
PagerSlidingTabStrip is licensed under the Apache 2.0 license, which you can read about here. In short you're fine to 'redistribute' the library along with your own work.

A: almost most of libraries over github and maven central are open source. so you can use it in your code.
but you should check license type.


text:
Q: Make a service which execute 4 PM EST every day in Android In my project need to updated web service only ones a day ,4 pm est every day.
But I don't Have any Idea how can create a back ground service , which execute 4 PM EST every DAy
Please Help me how i can fix this issue
Thanks In Advance

A: Just Create one service like below example and change Time 9 to 16 for pm and do perform your task
import java.util.Calendar;
import java.util.Date;

import android.R.integer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

public class MantraAlarmService extends Service {

private Handler handler;
private Runnable runnable;
integer message;

@Override
public void onCreate() {
    super.onCreate();

    handler = new Handler();
    runnable = new Runnable() {

        public void run() {
            // TODO Auto-generated method stub

            Calendar cal = Calendar.getInstance();

            Date time = cal.getTime();

            Calendar cal1 = Calendar.getInstance();

            cal1.set(cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH),
                    cal1.get(Calendar.DAY_OF_MONTH), 9, 0, 0);

            Date time1 = cal1.getTime();

            if (time1.equals(time)) {

                int day = cal.get(Calendar.DAY_OF_WEEK);

                // do your task here
            }

            handler.postDelayed(runnable, 1000);

        }
    };

    handler.post(runnable);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
@Deprecated
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();

}

private void generateNotification(Context context, String message) {
    System.out.println(message + "++++++++++2");
    int icon = R.drawable.manta_icon;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    String subTitle = message;
    Intent notificationIntent = new Intent(context, PlayView.class);
    notificationIntent.putExtra("content", message);
    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    notification.setLatestEventInfo(context, title, subTitle, intent);
    // To play the default sound with your notification:
    notification.defaults = Notification.DEFAULT_SOUND;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);

}
}