text:
Q: Why does my getter,setter not working in Typescript? I want to check my password`s length before assigning value to the password. If value's length is less than 3 it has to throw an error. But it is not returning anything. Why?
I have a Department class and ITDepartment subclass.
class Department {
    static currentYear = 2022
    departmentName:string
    empNum:number
    employees :string[] = []
    constructor(public name:string,nums:number,
        employees:string[]){
        this.departmentName =name
        this.empNum = nums
        this.employees = employees
    }

}

class ITDepartment extends Department {
orginizingDate : number
 private password :number

 public get pass (){
    return this.password
 }

 public set pass (value:number){
    if(value.toString().length < 3){
        throw new Error ('The password is not safe ')
    }
     this.password = value
 }

constructor(empNum:number,employees:string[],orginizingDate :number,password:number){
    super("IT",empNum,employees)
    this.orginizingDate = orginizingDate
    this.password = password
}
printInfo(){
    console.log("The Department " + this.departmentName  +" has " + this.empNum +" employers and orginized in " +this.orginizingDate)
}

addEmployee(employee: string): void {
    if(employee === "Adam"){
        return
    }
    this.employees.push(employee)
}
}

let it = new ITDepartment(52,[],2000,22)

A: this.password = password won't go through the setter named pass. Furthermore, you aren't actually comparing the length, but the value itself.


text:
Q: `Write-Output` in `foreach` collection expression I'm actually working my way through Bruce Payette's Powershell in Action and run to a code snippet I actually don't understand.
$characterData = @{
    'Linus' = @{ age = 8; human = $true}
    'Lucy' = @{ age = 8; human = $true}
    'Snoopy' = @{ age = 2; human = $true}
  }

  function Get-Character ($name = '*')
  {
    foreach ($entry in $characterData.GetEnumerator() | Write-Output)
    {
      if ($entry.Key -like $name)
      {
          $properties = @{ 'Name' = $entry.Key } +
            $entry.Value
          New-Object PSCustomObject -Property $properties
       }
    }
  }

My problem is that I don't understand why Write-Output is used in foreach ($entry in $characterData.GetEnumerator() | Write-Output)? Can this syntax be interpreted as equivalent to $characterData.GetEnumerator() | ForEach-Object { ...  ?
Thx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nodemon Error: listen EADDRINUSE: address already in use :::3000 I'm working node app and my nodemon throws error of:

Error: listen EADDRINUSE: address already in use :::3000

every-time if there is change in files.
I've searched a lot and most of them suggest to kill the process running on port 3000 and restart the server.Which I'm doing by the following command:
kill -9 $( lsof -t -i:3000) && clear &&  npm start
But this is too tiring as my app consists of authentication functionality. I have to re-login into the app every-time I restart the server.
Is there any permanent fix to this since lot of people are having same issue.

const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const csrf = require('csurf');
const flash = require('connect-flash');
const multer = require('multer');

const errorController = require('./controllers/error');
const User = require('./models/user');

const MONGODB_URI =
"mongodb url here";

const app = express();
const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions'
});
const csrfProtection = csrf();

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'images');
  },
  filename: (req, file, cb) => {
    cb(null, new Date().toISOString() + '-' + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === 'image/png' ||
    file.mimetype === 'image/jpg' ||
    file.mimetype === 'image/jpeg'
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const authRoutes = require('./routes/auth');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(
  multer({ storage: fileStorage, fileFilter: fileFilter }).single('image')
);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use(
  session({
    secret: 'my secret',
    resave: false,
    saveUninitialized: false,
    store: store
  })
);
app.use(csrfProtection);
app.use(flash());

app.use((req, res, next) => {
  res.locals.isAuthenticated = req.session.isLoggedIn;
  res.locals.csrfToken = req.csrfToken();
  next();
});

app.use((req, res, next) => {
  // throw new Error('Sync Dummy');
  if (!req.session.user) {
    return next();
  }
  User.findById(req.session.user._id)
    .then(user => {
      if (!user) {
        return next();
      }
      req.user = user;
      next();
    })
    .catch(err => {
      next(new Error(err));
    });
});

app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(authRoutes);

app.get('/500', errorController.get500);

app.use(errorController.get404);

app.use((error, req, res, next) => {
  // res.status(error.httpStatusCode).render(...);
  // res.redirect('/500');
  res.status(500).render('500', {
    pageTitle: 'Error!',
    path: '/500',
    isAuthenticated: req.session.isLoggedIn
  });
});

mongoose
  .connect(MONGODB_URI)
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });


text:
Q: Is this a subspace? $X = \{x \in \mathbb R^2: x \cdot y = 0\}$ I am completely lost in this question and hoping someone could explain this question through for me.
Let $y=[1,2]$
$X = \{x \in \mathbb R^2: x \cdot y = 0\}$
Is $X$ a subspace?
So I get the equation:
$x_1 + 2x_2 = 0 $. For it to be a subspace, it has to include the $0$ vector (which it does right?), has to be closed in addition, and be able to multiply by a constant. Where I get completely lost is understanding what values $x$ can take. For it to be closed under addition, $x + y$ must be in the subspace so am I only looking for x-values where $x_1 + 2x_2 = 0$ is satisfied? So if I take $x_1 = 1$ and $x_2 = 1$ which doesn't satisfy the equation, does this mean $X$ is not a subspace?
Sorry if there are formatting errors; first post! Thanks

A: You don't need to know exactly what values $x$ has to take. First notice that X is subset of $\mathbb{R}^2$. Therefore, we only have to check if it is closed under addition, closed under multiplication  and the zero is contained in order to determine if it is subspace. So to verify those conditions, you basically assume you take two elements/ one element of $X$ and see if the addition of them/multiplication with a scalar also satisfies the property, which qualifies them to be in $X$ ( this property for an $x$ is $x \cdot y = 0$ in order $x$ to be in $X$). You then check if that condition is satisfied also by $0$, to conclude that $0 \in X$.

*

*Closure under addition:

Assume $x_1,x_2 \in X$, then $(x_1+x_2)\cdot y = x_1\cdot y + x_2 \cdot y = 0$, hence $x_1 + x_2 \in X$. done.

*Closure under multiplication:

Assume $x_1 \in X$ and $\lambda \in \mathbb{R}$, then $\lambda x_1 \cdot y = \lambda (x_1 \cdot y) = 0$, hence $\lambda x_1 \in X$. done.

*zero is an element of $X$:
since $0\cdot y = 0$, $0 \in X$. done.

Let me know in case any step is not clear.


text:
Q: How to call a library function from a spreadsheet drop-down menu generated by the same library I created a library that has a specific function that create new spreadsheet menus (using addMenu). My menus options should call other functions within my library to do stuff.
// Bare Minimum Deployment on a blank spreadsheet with
// my library registered (called myLibraryName for this example).

function onOpen() {
  myLibraryName.setMenus(); // creating new drop-down menus
}

function onEdit(event) {
  myLibraryName.doEvent(event); // sending the onEdit event to a function in my library.
}

Now the issue is that when I choose a menu option, google app script give me an error message like

Script function myMenuFunction could not be found

So I tried to add a prefix in my menu entry
menuEntries.push({name: "About", functionName: "myLibraryName.myMenuFunction"});

But It's also not working.
So I am asking for suggestions on how to create a library that can create Menus that are linked to functions within the library.

A: I'm not 100% sure what you're calling, but I think this is a known issue.
Looks like you need to call a function directly from the menu, not call it from the upper level.
There's a good example here.
In looking at your question closer, it seems like you're trying to call the same function across different menus in your spreadsheet. Based on the bug I linked, you probably can't do this since you need to define a local function and use that to interact with the script.

A: Yep, similar problem.
I have about twenty spreadsheets and it's quite boring to update all its scripts with silly code:
 function doSomething(){ myLib.doSomething();}

every time I add new menu entry in main lib.
So I've found more or less dirty workaround - link menu entries to "proxy" functions in lib and create several similar functions in the client spreadsheets in advance (do it once for all client spreadsheets)
//-----------LIB-----------
function libMenu() {
  var mySheet = SpreadsheetApp.getActiveSpreadsheet();

  var menuEntries = [ {name: "Increment current cell", functionName: "processMenuEntry0"},
                      {name: "Do something with row", functionName: "processMenuEntry1"}
                    ];
  mySheet.addMenu("Library Functions", menuEntries);
 }

 function processMenuEntry0()  { incrementCurrentCell();}
 function processMenuEntry1()  { doSomethingWithRow();  }

 //-----------LIB-----------

 //-----------CLIENT-----------
 function onOpen() {
   Library.libMenu();
 }

 function processMenuEntry0()  {gTracking.processMenuEntry0();}
 function processMenuEntry1()  {gTracking.processMenuEntry1();}
 function processMenuEntry2()  {gTracking.processMenuEntry2();}
 function processMenuEntry3()  {gTracking.processMenuEntry3();}
 // etc.
 // I have reserved twenty menu entries in a such way
 //-----------CLIENT-----------

At the moment I do use a little bit enhansed version that allow me to update  menuEntries array only.
Here it is:
 //-----------LIB-----------

 var menuEntries = [ {name: "Increment current cell", functionName: "incrementCurrentCell"},
                  {name: "Do something with row", functionName: "doSomethingWithRow"}
                ];

 //returns menu entries with changed 'functionName' parameter (-> "processMenuEntry" + id)
 function convertMenuEntries() {
   var newMenuEnties=[];
   for (var i=0; i< menuEntries.length ;i++){
     if (menuEntries[i] == null) {// for line separators
       newMenuEnties.push(null);
       continue;
     }
     newMenuEnties.push({name: menuEntries[i]["name"], functionName: "processMenuEntry" + i});
   }
   return newMenuEnties;
 }

 function libMenu() {
   var mySheet = SpreadsheetApp.getActiveSpreadsheet();

   mySheet.addMenu("Library Functions", convertMenuEntries());
 }

 // get function name from menuEntries array and call it
 function processMenuEntry(id){
   this[menuEntries[id]["functionName"]]();
 }

 function processMenuEntry0()  {processMenuEntry(0);}
 function processMenuEntry1()  {processMenuEntry(1);}
 // etc.

 //-----------LIB-----------
 //-----------CLIENT-----------
 function onOpen() {
   Library.libMenu();
 }

 function processMenuEntry0()  {gTracking.processMenuEntry0();}
 function processMenuEntry1()  {gTracking.processMenuEntry1();}
 function processMenuEntry2()  {gTracking.processMenuEntry2();}
 function processMenuEntry3()  {gTracking.processMenuEntry3();}
 // etc.
 //-----------CLIENT-----------


text:
Q: Vscode debugger: Ignore node_modules in all projects I'm using Vscode debugger to debug few inter-related projects, all in the same root folder(using "concurrently" to run multiple npm commands together), like that:
-root
  -project1
    -node_modules
  -project2
    -node_modules

I have a .vscode/launch.json file in the root folder. Problem is, that it does not ignore node_modules in any of the subfolders(the root doesn't have node_modules).
I've tried:
"skipFiles": [
    "<node_internals>/**",
    "${workspaceFolder}/**/node_modules/**/*.js",
],

It doesn't work. The debugger still stops in functions coming from any of the node_modules folders. How can this be done?


text:
Q: Accessing both inputs name and value from controller in Angular I have the following inputs and need both their 'name' and 'value' :

     <input type="text" name="{{userAttribute }}" dynamic-model="(userAttribute | alphanumeric | spaceToUnderscore | lowercase)">

     <input type="text" name="{{userAttribute}}" dynamic-model="'controllerAs.' + (userAttribute | alphanumeric | spaceToUnderscore | lowercase)">

<input type="text" ng-model="your_age" name="Your Age"/>

<input type="text" ng-model="controllerAs.your_age" name="Your Age"/>

nb: dynamic-model directive - allows you to apply filters to a value to generate the model name - eg, remove spaces etc.
With either of the previous Output examples methods how can I access both the name attribute "Your Age" and the user inputted value (eg: 23) from the controller, eg, on button click.
This is just an example and the ng repeat will have a varying number of inputs with variable names etc depending on many factors.
Thanks

A: As I see it, you have two options given your specific scenario:

*

*Create a custom directive and from there you would be able to have access to all attributes through scope declarations on the directive.

*Add the value of the name attribute to your model (i.e. userAttribute.value and userAttribute.name)

Example of 2 above.
Javascript:
var userAttributes = response.userAttributes.split(','); //$scope
$scope.userAttributes = [];
for(var attr in userAttributes){
    if(attr == "your_age"){
        $scope.userAttributes.push({value: attr, name: "Your Age"});
    }
    //...etc
}

HTML:

   <input type="text" name="{{userAttribute.attr}}" ng-model="userAttribute.value" />  //not sure on dynamic-model usage


text:
Q: Christoffel symbols and fundamental forms How can we prove that the christoffel symbol is
\[ \Gamma^k_{ij} = \frac 12 \sum_{l=1}^2 g^{kl} \left(\frac{\partial g_{il}}{\partial u^j} + \frac{\partial g_{jl}}{\partial u^i} - \frac{\partial g_{ij}}{\partial u^l}\right)
\]
I can think of some substitution using the first and second fundamental forms, but can't see how to really fit it in.
Thanks

A: $\def\+#1{\frac{\partial}{\partial u^{#1}}}$We have, as the metric has vanishing covariant derivative
\[
  0 = \nabla_{\+j} g_{ik} = \+j g_{ik} - \sum_m (g_{im}\Gamma^m_{kj} + g_{mk}\Gamma^m_{ij})
\]
or
\[ \+jg_{ik} = \sum_m  (g_{im}\Gamma^m_{kj} + g_{mk}\Gamma^m_{ij})\]
That is
\begin{align*}
  \frac 12 \sum_l g^{kl}\left( \+j g_{il} + \+ig_{jl} - \+l g_{ij}\right)
&= \frac 12 \sum_{m,l} g^{kl} \left(g_{im}\Gamma^m_{lj} + g_{ml}\Gamma^m_{ij}
   + g_{jm}\Gamma^m_{li} + g_{ml}\Gamma^m_{ji} -
   g_{im}\Gamma^m_{jl} - g_{mj}\Gamma^m_{il}\right)\\
&= \frac 12 \sum_{m,l} \left(g^{kl}g_{im}\Gamma^m_{jl} - g^{kl}g_{im}\Gamma^m_{lj}\right) + \frac 12(\Gamma_{ij}^k +  \Gamma^k_{ji})\\
  &= \Gamma^k_{ij} \quad\text{by symmetry}
\end{align*}

A: One approach is to use the fact that the Levi-Civita connection is metric compatible:
$$ 0 =\nabla_ig_{jk}=\frac{\partial g_{jk}}{\partial u^i}-\Gamma^l_{ji}g_{lk}-\Gamma^l_{ki}g_{jl},$$
and then permute indices, add and multiply by the inverse metric to isolate $\Gamma^i_{jk}$. Remember that by definition, the Christoffel symbols are symmetric: $\Gamma^i_{jk}=\Gamma^i_{kj}$. (A slight cheat: knowing the answer gives a guide as to which permutation to consider.)


text:
Q: Trouble using prepared statement with select query Getting the following
mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1 in C:\Users\user\Documents\examplePHP\UAMP\UwAmp\www\php-project\update.php on line 55
Using the following
//getting id from url sent from the select.php
$StaffID = $_GET['StaffID'];

        // Prepare an insert statement
        $sql = mysqli_query($conn, "SELECT Name, Address, Telephone, BusinessID FROM staff WHERE StaffID = ?");

        if($stmt = mysqli_prepare($conn, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "i",$param_staffid);

            // Set parameters

            $param_staffid = $StaffID;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Redirect to login2 page if successful
               while($row = mysqli_fetch_array($result))
{
    $Name = $row['Name'];
    $Address = $row['Address'];
    $Telephone = $row['Telephone'];
    $BusinessID = $row['BusinessID'];
}
            }
            else{
                 die("ERROR: Could not insert. " . mysqli_connect_error());
}

}

A: You should just set $sql to the string, not call mysqli_query() there.
$sql = "SELECT Name, Address, Telephone, BusinessID FROM staff WHERE StaffID = ?";

You perform the query when you call mysqli_stmt_execute().

A: change query to this way :-
$sql = "SELECT Name, Address, Telephone, BusinessID FROM staff WHERE StaffID = ?";
if($stmt = mysqli_prepare($conn, $sql)){

    // the rest of your code

if(mysqli_stmt_execute($stmt))
{
    // the rest of your code
}
else
{
    // the rest of your code
}

Note:- check this


text:
Q: Overlaid raster gets shifted around when printing to pdf or when resizing graphics device with mouse I've spent the past couple of days learning how to use the maps, raster, and rgdal packages to create nice images, but I'm running into trouble when trying to make pdf's for actually presenting.  I'm overlaying two rasters -- one has my data and the other is a mask.  The problem is that the mask moves around depending on the size of the output pdf, AND also with simple resizings of the graphcis device.
I've made a little minimal example here:
library(raster)
library(maps)
library(mapdata)
library(rgdal)
lat = seq(from=36,to=40,by = .01)
lon = seq(from=-121,to=-117,by = .01)
d = expand.grid(lon,lat)
colnames(d) = c('lon','lat')
d$z = sin(d$lat)-cos(d$lon)+rnorm(nrow(d))
head(d)
coordinates(d)=~lon+lat
gridded(d)= TRUE
r = raster(d)
dd = expand.grid(lon[lon<120],lat[lat<37])
colnames(dd) = c('lon','lat')
dd$z = 1
coordinates(dd)=~lon+lat
gridded(dd)= TRUE
rr = raster(dd)
map('usa',xlim=c(-123,-116),ylim=c(35,41))
plot(r,add=TRUE)
plot(rr,add=TRUE,col="black",legend = F)
dev.copy2pdf(file = "example.pdf",height=8,width=8)

Here is the output when first rendered on my screen:

And here is the output when I resize the window!

and the example PDF is different again!  (Unfortunately SE doesn't seem to support pdf images, but if you run the code you can see it on your own machine)
Any idea how to work around this behavior?
Thanks!

A: To overcome the shifting problem you should use image() instead of plot()
map('usa',xlim=c(-123,-116),ylim=c(35,41))
image(r,add=TRUE)
image(rr,add=TRUE,col="black",legend = F)
dev.copy2pdf(file = "example.pdf",height=8,width=8)


text:
Q: Importing an svn branch into git I am new to git, and have a subversion repository that I want to be able to import into a git repository occasionally (for deployment). So I want to perform most of the updates using svn but wanted to see what's the best way to push it to git (just the default/master branch).

A: I know you only want to import the master/trunk branch of your svn repository, but I would like to mention svn2git in order to import your svn into a git repository.
It is better than  git svn clone because if you have this code in svn:
  trunk
    ...
  branches
    1.x
    2.x
  tags
    1.0.0
    1.0.1
    1.0.2
    1.1.0
    2.0.0

git-svn will go through the commit history to build a new git repo.
It will import all branches and tags as remote svn branches, whereas what you really want is git-native local branches and git tag objects.
So after importing this project, you would get:
  $ git branch
  * master
  $ git branch -a
  * master
    1.x
    2.x
    tags/1.0.0
    tags/1.0.1
    tags/1.0.2
    tags/1.1.0
    tags/2.0.0
    trunk
  $ git tag -l
  [ empty ]

After svn2git is done with your project, you'll get this instead:
  $ git branch
  * master
    1.x
    2.x
  $ git tag -l
    1.0.0
    1.0.1
    1.0.2
    1.1.0
    2.0.0

Finally, it makes sure the HEAD of master is the same as the current trunk of the svn repo.

A: Why not just work in git on your workstation too? That would be the most straightforward.

*

*git svn clone will grab your SVN repository and import the revisions into a new git repo.

*If you need to push to a remote git repository for deployment, then git remote add will add it for you.

*If you need to push back to the SVN repository then git svn dcommit

A: in a nutshell:
mkdir my_blog_tmp
cd my_blog_tmp
git-svn init http://code.yoursite.net/my_blog/trunk/ --no-metadata
git config svn.authorsfile ~/Desktop/users.txt
git-svn fetch

and congrats for joining us gits! Here is a great cheat sheet for (ex)svn users.


text:
Q: Importing a table from an HTML file directly to Tableau I recall seeing a direct import of a table in a Wikipedia HTML document directly into tableau. Tableau's website has a method that involves using Google doc HTML import function
=ImportHtml("http://en.wikipedia.org/wiki/List_of_bank_failures_in_the_United_States_(2008%E2%80%93present)","table",2)

to first import the tables into a Google spreadsheet and later download the spreadsheet that can be linked to Tableau.
Is there any way to import a Wikipedia table, or anyt other HTML doc directly into Tableau?
Thanks

A: Tableau lets you paste data from any application that uses csv delimited text on the clipboard (not all apps do). Here's a knowledge based article on it.
http://onlinehelp.tableausoftware.com/current/pro/online/en-us/clipboard_datasource.html
Unfortunately, it didn't seem to work o nthe table you pointed out in your example, perhaps the HTML is too complex. But if you can somehow export the table as CSV, it can be loaded in Tableau.
Tableau Version 8 is due out soon, and has a couple different new APIs available that should help with connecting to data from various sources.


text:
Q: Why does seeing the up- and downvote count as a privilege? Why can't all users see upvote and downvote counts? Is it somehow problematic for new users to have this information? The total score doesn't show all of the relevant information (+5-4 and +1-0 are very different, but both total +1), and it would be nice to have this on sites where I don't have enough reputation yet, but I don't see any reason a user who's new to the entire network shouldn't see it either.
Is this just to give people an incentive to participate more and gain rep (seems pointless considering the other privileges, which do have obvious reasons for needing restrictions), or is there some reason I'm missing?


text:
Q: Boundedness of perturbed nonlinear ode Let an ode
\begin{equation}
\dot{x} = f(x,t), \ \ x_0 = x(0)
\end{equation}
where $f \in\mathbb{R}^n$ is locally Lipschitz in $x$ and uniformly bounded in $t$. Assume that the solution of that ode is bounded as $\|x(t)\| \leq L(x_0)$ for all $t\geq 0$. Assume now the second ode
\begin{equation}
\dot{y} = f(y,t) - g(y,t)y, \ \ y_0 = y(0)
\end{equation}
where $g \in \mathbb{R}^{n\times n}$ is locally Lipschitz in $x$, uniformly bounded in $t$, and positive definite for all $x \in \mathbb{R}^n$, $t \geq 0$. Is there a way to show that the solution $y(t)$ of that second ode is bounded as $\|y(t)\| \leq M(L(x_0),y_0)$? Here  $M(L(y_0),y_0)$ is a constant dependent on $L(y_0)$ and $y_0$.
Intuitively, since $f()$ produces a bounded solution and the term $-g(y,t)y$ produces an exponentially stable solution, I expect the overall solution $y(t)$ to remain bounded, but have not found a rigorous way to show it (or a counter-example).


text:
Q: Private video streaming for Amazon CloudFront in ruby How does signed URLs work for streamed videos in Amazon CloudFront?
I'm using aws_cf_signer gem, but can't get signed urls work for rtmp streamed mp4-file. For static files, like text.txt it works fine, but not when I have streaming distribution.
Example:
I have file named test.mp4 so how do I get signed url out of signer.sign()?
E.g. signed_url = signer.sign('rtmp://xyz.cloudfront.net/test', :ending => Time.now + 3600) does not produce working url. I have tested URLs with VLC player and rtmpdump
The distribution itself is created with boto like this:

stream_dist = cf.create_streaming_distribution(origin=origin,
  enabled=True,
              trusted_signers=["Self"],
              comment="test distribution")

A: According to the AWS: Restricting End User Access doc, the format for signed RTMP urls is different from HTTP:

With HTTP, a full URL uniquely describes an object. You can include the URL
  in the signature. The content of a streaming distribution, however, cannot always
  be described by a valid URL. In a streaming distribution, you only use the stream
  name to create a signature. For example, if your stream including the signature is:
example/mp3_name.mp3?Expires=1258237200&Signature=TBD&Key-Pair-Id=PK12345EXAMPLE
The value for RESOURCE is:
example/mp3_name
For streaming distributions, you do not include a prefix, such as mp3: or mp4:,
  for the resource name in the policy.
Also, when referencing an MPEG file, you might have to omit the file extension for
  the URL enclosed in the signature. For example, you use mp3_name instead of mp3_name.mp3.

I'm not sure whether aws_cf_signer gem supports signing RTMP urls, unfortunately.  If you find out, please let me know!


text:
Q: ExtJS disable panel in FF + IE I have Ext.getCmp("id").disable(); and it works in FF but not IE, if my panel id is test, or panel name is test, how would I disable it without doing disabled: true from the beginning?

A: try this :
Ext.getCmp('id').setDisabled(true);

setDisabled( Boolean disabled ) : Convenience function for setting disabled/enabled by boolean.
check docs


text:
Q: How to access an Angular controller from the main page when using ngRoute I want to access an Angular controller from outside of the controller component.
This is answered well in this question: AngularJS. How to call controller function from outside of controller component
However, what if I am using ngRoute with code like this:
myApp.config(function ($routeProvider) {

    $routeProvider

    .when('/', {
        templateUrl: 'pages/main.html',
        controller: 'mainController'
    })

    .when('/second', {
        templateUrl: 'pages/second.html',
        controller: 'secondController'
    })

});

So the index page only has this tag: <div ng-view></div>.
Is there a way I can access the controller that is currently in the ng-view?
(I tried to locate mainController on the index page, but for:
var scope = angular.element(document.getElementById("mainController")).scope();

scope is undefined.)


text:
Q: Intellij issues with multiple source folders In our project, we are having two source folders, one source folder is for our application code(src/main) and another one is to generate JSON API schema(src/schema).

The functionalities are working fine because we are using Gradle to build and run the application, the only issue we are facing is: Intellij keeps showing compilation issues when we refer(import) a java class from the src/main folder in the src/schema folder like below:

where UnsolicitedResponseProcessor.java is a java class in the src/schema folder which is importing Response.java from the src/main folder.
So far, I have tried to mark the src/schema folder as Source Directory but this is not helping me.
Is there any way I can solve this IntelliJ's compilation issue?
Thanks in advance.


text:
Q: My button component disables after it triggers a css animation. How can I avoid it? I was programming a React application. And I wanted to start very simple. I drew a cube in 3d perspective using css. With it I created a button. Whenever this button is clicked, the transition to the next side of the cube is being shown. I achieved this with the following code.
import React, {useState} from 'react';
import './App.css';

function App() {
  const [panel, setPanel] = useState(1);
  const handlePanelIncrement = () => {
    setPanel(panel + 1);
  };
  let boxArea;
  const rotateRight = () => {
    boxArea = document.getElementById('main-box-area');
    boxArea.style.transition = "transform 1s linear 0s";
    boxArea.style.transform = `rotate3d(0,1,0, -${panel*90}deg)`;
    handlePanelIncrement();
    boxArea=null;
  };

  return (

            <button onClick={rotateRight}>Right</button>

  );
}

.App {
  text-align: center;
  height: 100%;
  width: 100%;
  margin:0px;
  display: flex;
  flex-direction: column;
}

.app-body{
  display: flex;
  width: 100%;
  height: 100%
}

.cube-panel{
  display: flex;
  flex-direction: column;
}
.cube-actions{
  width: 896px;
  display: flex;
  justify-content: space-around;
}

.wrapper{
  display:flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
  height: 482.3px;
  width: 896px;
  perspective: 1500px;
}

.box-area{
  display: flex;
  justify-content: center;
  align-items: center;
  width:100%;
  height:100%;
  position: relative;
  transform-style: preserve-3d;
}

.box{
  transform-style: preserve-3d;
  position: absolute;
  width:100px;
  height:100px;
  border: 2px solid black;
}

.front {
  transform: translateZ(50px);
  background-color: rgba(244, 50,50, 0.5);
}

.back {
 transform: translateZ(-50px);
  background-color: rgba(244, 50,50, 0.5);
}

.left {
  transform-origin: left;
  transform: translateZ(50px) rotateY(90deg);
  background-color: rgba(244, 50,50, 0.5);
}

.right {
  transform-origin: right;
  transform: translateZ(50px) rotateY(-90deg);
  background-color: rgba(244, 50,50, 0.5);
}

Everything works fine. But after the transition, the trigger-button can't be clicked anymore. It is disabled. What is curious is that if I click the button fast multiple times, the rotation works fine those many times. It is disabled when I wait like a second after it was triggered.
Does anybody know why does this happen? Or where am I making the mistake? maybe I have to declare the style attributes in a different way but I don't know how.. I searched everywhere but I had no success.
Thank you for your time!


text:
Q: Barplots and other graphics not displaying in terminal (Debian and R) I am using debian, and installed R using the following command:
apt-get install r-recommended

I then tested out whether it worked by using R to run
barplot(1:100)

This gave no errors, but provided no output.
Non graphical R commands work, but anything that should display a graphic seems to be ignored. No errors, no warnings, no output at all.
Am I missing a critical library?

A: Type in x11() and hit enter.  This should open up a graphics window.  Then if you do plot(1:100) you should see a graph.

A: You can write any plot to the server using the following:
png('path/for_my_image/my_image.png', width=6, height=6, units='in', res=300)
dev.off()

Choose your height and width as needed.
Then just go find your image through either FTP or by downloading to your local directory via scp.


text:
Q: which frameworks(MVVM light, Prism, MEF,..) should i use for my Financial Silverlight application? first of all, I am new to silverlight(play around with it for one month) and this is my first job. However, i am willing to learn anything which can let me advance my silverlight knowledge.
Currently, I need to implement a big Silverlight project about Financial(kind of similar to Microsoft Accounting). It will have a lot of tables from database.
Because it is too big, scalability and maintain are pretty important.
Can anyone here tell me which silverlight framework i should learn and use (MEF, Prism, .....)?
Time is also a constraint so i don't think i can learn all. Plz advise me the best one.
thank you

A: 4 months ago I embarked on a very large Silverlight project which is still underway. In the end, I chose no MVVM framework. It seems their utility decreases as Silverlight gains new features. For examples, Silverlight now has commands built in, taking away a nice chunk of why Prism and the like were created.
I do use MVVM light's messaging, but I don't use its MVVM capabilities at all. My app ended up being:

*

*Ninject for IOC

*built in Silverlight 4 ICommand implementation for commands

*MVVM Light messaging for messages

*A very simple, to the point MVVM framework I wrote from scratch. There's really nothing to this, just a simple base ViewModel class that handles common tasks and that's about it.

A: if I can give you one big tip, which I wish I had before starting a rather big application; do not use ria services if you have more then 2-3 level relations between your database tables if you want to really be in control of your data manipulation.
mvvm can be quite chaotic at first sight but once you get the hang of it it's really transparent and very maintainable.
good luck :)

A: For a large scale project I would implement MVVM especially if you are just learning simply because it will keep your code at a more manageable level. I would also check this link:
http://www.silverlight.net/learn/handsonlabs/
There are some really great labs for learning silverlight as well as a couple of MVVM labs.

A: If you expect to produce a product that is maintained for years to come, and probably worked on by multiple developers, you will need to go beyond simple MVVM and think about modularity on a broader scale. That means learning about IOC, MVVM, commanding and events, as well as all the basics of Silverlight.
Prism 4 is on the verge of release (currently at Alpha as of August 18). The new version includes MEF so gives you several choices for dynamically loading project modules. It is well worth investigating. Both Prism and MEF were originated by Microsoft.
MEF is used to produce plug-in based framework apps like Visual Studio. We are using Prism 2 at the moment for a very large long-term project (hundreds of modules) and expect to migrate to version 4 on release (I am currently trying out version 4 Alpha on another personal project).

A: Mvvm Light is a great framework.
CinchV2 is another that uses MEF as well.
But as others have said.  Framework is kind of irrelevant, design is what matters.  The frameworks just make some of the design easier.  Read about the MVVM pattern, but in my experience non of the tutorials really address large projects and how they components will talk to each other.  This is where the frameworks come in.  They address some of the issues, but MVVM is only one of many patterns that you will use in a large app.


text:
Q: Trigger an event (tableview reload) whenever a text is in a certain position of a textView in iOS I just started with iOS programming and I could not find anywhere an answer about this.
I have a Textview, containing a large text divided in paragraphs.
I would like to trigger the reload of a Tableview whenever each paragraph reaches the middle of the TextView.
How could I do it?
Here is the code I wrote so far:
@IBOutlet weak var testo: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    if databaseDB.open() {

        // Here I definethe string attributes
        var style = NSMutableParagraphStyle()
        style.lineSpacing = 15
        let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
        let textFont = [NSFontAttributeName:font, NSParagraphStyleAttributeName : style]
        let fontSuper = UIFont(name: "Georgia-Italic", size: 13.0) ?? UIFont.systemFontOfSize(13.0)
        let superFont = [NSFontAttributeName:fontSuper, NSBaselineOffsetAttributeName:6]

        // and here the variables
        let mainText = NSMutableAttributedString()
        var paragraphId : String = ""

        // I load the text from a table in the database
        let querySQL = "SELECT id, versetext FROM table1"
        let results:FMResultSet? = databaseDB.executeQuery(querySQL, withArgumentsInArray: nil)

        while results!.next(){

            paragraphId = results!.stringForColumn("id")

            // I add some other information from another table (here goes also other code, but I have skipped it for simplicity)
            let queryDescrSQL = "SELECT paragraph FROM table2 WHERE id = \(paragraphId)"
             let paragraphResults:FMResultSet? = databaseDB.executeQuery(queryDescrSQL, withArgumentsInArray: nil)

            if paragraphResults?.next() == true {
            // here I add the attributes to the text to be shown
                let numberParagraph = paragraphResults!.stringForColumn("paragraph")

                let paragraphNumber = NSAttributedString(string: numberParagraph, attributes:superFont)
                mainText.appendAttributedString(paragraphNumber)

                let textParagraph = results!.stringForColumn("versetext")+" "
                let paragraphText = NSAttributedString(string: textParagraph, attributes:textFont)
                mainText.appendAttributedString(paragraphText)
            }
        }
        databaseDB.close()
        // and finally everything is loaded on the TextView
        testo.attributedText = mainText
    }

}
// I'm letting out the code for the TableView, as it is probably not relevant for the matter

I was thinking of adding some other attribute to paragraphNumber, something like here, but I haven't been able to find how to do it.
Thanks in advance,
Silvo

A: It's not clear how your paragraphs are divided up (is each in its own UITextView, or do they all form one large text view), but the basics of this are that you need to reload a table view when the scroll view reaches a certain scrolled position.
UITableView has a method reloadData, so call this when your scroll view is at the position.
Scrolling a scroll view just means you are modifying its contentOffset, and the scroll view sends its delegate a message every time the content offset changes. Make your controller the delegate of the scroll view, and implement the scrollViewDidScroll(_:) delegate method. In here, check the current content offset, and if it's at the value you're looking for, reload the table view:
class MyViewController: UIViewController, UIScrollViewDelegate {

    // var scrollView = ...
    // var tableView = ...

    override viewDidLoad() {
        super.viewDidLoad()
        scrollView.delegate = self
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        // var scrollThreshold = (calculate some scroll threshold based on your paragraph text)
        if scrollView.contentOffset.y > scrollThreshold {
            tableView.reloadData()
        }
    }
}


text:
Q: Repetition and 'think for yourself what...' 'After 20 seconds, when the first printed words appeared, I found out what the message of the video was. In my opinion, this is a good timing, because you must first think for yourself what message SIRE wants spread with this video.'
The fragment, which I have written myself, is about a commercial from SIRE (company) called "Hands off our social workers".
I have two questions about this fragment. First, how do I avoid the repitition of' video'? And second, is it correct to use 'what' with 'think for yourself'?


text:
Q: Conflict with get_posts and the_content I have this snippet in my header.php to display a slider:
    <?php
    $args = array(
        'post_type'             => 'post',
        'posts_per_page'        => 6,
        'meta_query'            => array(
            array(
                'key'           => '_thumbnail_id',
                'compare'       => 'EXISTS'
            ),
        )
    );
    $posts = get_posts( $args );

    global $post;
    foreach ( $posts as $post ) {
        setup_postdata( $post );
    ?>

            <a href="<?php echo esc_url( home_url() ); ?>/category/<?php $category = get_the_category(); echo $category[0]->category_nicename; ?>"><?php $category = get_the_category(); echo $category[0]->cat_name; ?>
             -
             <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

        <img style="width:1000px;height:288px" src="<?php $src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID) , array(1000, 288) , false, ''); echo $src[0]; ?>" />

    <?php
    }
        wp_reset_postdata();
    ?>

But it conflicts with my content.php as the_content() no longer displays the actual post content but the latest recent post!
I can't figure out why!
No conflict instead with query_posts (but I know it shouldn't be used).
    <?php
    $args = array(
        'post_type'             => 'post',
        'posts_per_page'        => 6,
        'meta_query'            => array(
            array(
                'key'           => '_thumbnail_id',
                'compare'       => 'EXISTS'
            ),
        )
    );
    query_posts( $args );
    while ( have_posts() ) : the_post();
    ?>

            <a href="<?php echo esc_url( home_url() ); ?>/category/<?php $category = get_the_category(); echo $category[0]->category_nicename; ?>"><?php $category = get_the_category(); echo $category[0]->cat_name; ?>
             -
             <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

        <img style="width:1000px;height:288px" src="<?php $src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID) , array(1000, 288) , false, ''); echo $src[0]; ?>" />

    <?php
    endwhile;

    wp_reset_query();
    ?>

Why is this happening with get_posts?


text:
Q: How to hide object pooling? For context, I am creating a networking library and have internally implemented object pooling - instances of byte[] get reused in order to avoid creating constant garbage.
For users of my library, I have exposed a public ref struct Packet which allows the user to perform write operations to the pooled byte[]. Here is the code:
public ref struct Packet
{
    private readonly byte[] _buffer;

    public Packet()
    {
        // Here we take a byte-array from the pool.
        _buffer = Pool.Get();
    }

    // Some write methods here...

    public void Return()
    {
        // Here byte-array returns to the pool so it can be reused later.
        Pool.Return(_buffer);
    }
}

While all of this is great and it works, there are some problems that I have with this approach:

*

*I am leaking implementation details: user shouldn't really know or care how packets get their byte[], they only want to get the packet, write some data to it and send it.

*I am forcing my users to call Return method when they are done using the packet.

*If user forgets to call Return, byte[] will not get returned and leak occurs.

To somewhat remedy said problems, here is what I tried. Whenever user sends the packet, that send method will call Return method for the user.
public class Client
{
    public void Send(Packet packet)
    {
        // Performs socket operations here...

        // Returns byte-array to the pool so users don't have to.
        packet.Return();
    }
}

While this works most of the time, what if user creates a packet, but does not send it? Again, leak will occur. There seems to be no way to actually hide that library is internally using object pooling and there must exist public Return method so user can manually return byte[] in case they don't actually send the packet.
So, what I want to achieve is:

*

*User doesn't even have access to Return method, it is completely hidden from the user.

*byte[] instances get reused (pooled) and are always returned to the pool, even if user does not send the packet or does anything with it.

Any suggestions?

A: I would consider implementing IDisposable. Nevertheless, it could be beneficial to only get from the Pool in case a Send request is invoked:
public void Send(Action<Packet> modifyPacket)
{
    // Performs socket operations here...
    var packet = new Packet();
    try
    {
        modifyPacket(packet);
        // send...
    }
    finally
    {
        packet.Return();
    }
}

Thus the payload would be out of the Pool for the shortest amount of time. As I do not know the methods on Packet I do not know in how far you want to hide it.  But I hope you get the idea.


text:
Q: Searching for synonyms on the Tags page seems very inconsistent There are a few similar questions on MSO that deal with tag search results when using the site-wide search, but my concern is not with that functionality; it is rather with the search box on the Tags page (i.e. the one labeled "Type to find tags:") for which I did not find a relevant dupe.
There seems to be a bit of inconsistency in the Tags page with regards to how synonyms are treated, and it leads to what I would consider unexpected results, with the side effect being that it may be harder to find some tags then it perhaps should be.
An illustrative example: on Android.SE we have a boot-loop tag, intended for cases where a phone is rebooting itself repeatedly due to a system crash/error. A secondary tag cropped up that was named "repeating-reboot", so it was turned into a synonym of "boot-loop". Now if I type "reboot", "repeating", or just "boot" into the tags area of a question, I get the master in the autocomplete list. Great.
However, if I type "reboot" into the search on the Tags page, I get this, and no other results:

...relevant, I suppose, but we have a better tag for boot loops which someone unfamiliar with the parlance might miss now. I would have expected the "repeating-reboot" tag to appear, even if it simply links me to the "boot-loop" tag. In fact, this does happen if I search for "repeating" or similar:

So why does it not show in the first search? It's also a partial match to the synonym, just the second half instead of the first. I would expect it to appear in both of these searches, and arguably (in this case) having it as a result for "reboot" is more important.
Also of note, if you search for an actual tag (one that is not a synonym of another), the partial matching works how I would expect - in this example, a search for "loop" will correctly return the "boot-loop" tag in the results. The issue only appears to affect synonyms.
Is this intended behavior, or a bug? If it's intended, would it be possible to improve the search on the Tags page when dealing with partial matches of synonyms?


text:
Q: update multiple array values with multiple ids in laravel 5.1 My query as follows
        $dueid = array('1','2');

        for($n = 0; $n< count($post['percentage']); $n++) {

            $due=invoiceduedates::whereIn('id',$dueid)
            ->update(array(
            'percentage' => $post['percentage'][$n],
            'amount'=>$post['pamount'][$n],
            'date' => $post['date'][$n]

            )
            );

        }

But in table,at 1st and 2nd ids the 2nd array data is getting updated.Please help me to sort it out.

A: I don't know what you what to get... but in this way it's normal that you get what you get. I can only sugest you to try like this:
$dueid = array('1','2');
$dues = invoiceduedates::whereIn('id',$dueid)->get();

for($n = 0; $n< count($post['percentage']); $n++) {
        $due = $dues->find($dueid[$n+1]);

        $due->update(array(
                'percentage' => $post['percentage'][$n],
                'amount'=>$post['pamount'][$n],
                'date' => $post['date'][$n]
            )
    );

}


text:
Q: arrayformula sum in Google spreadsheet How do you arrayformula() a sum() such as:
=sum(A1:H1)
I need to go down 1000 rows.

A: with new functions in google sheets (since 20 Sep, 2022) all you need is:
=BYROW(A:H; LAMBDA(x; SUM(x)))

A: Another option:
=ArrayFormula(SUMIF(IF(COLUMN(A1:H1),ROW(A1:A1000)),ROW(A1:A1000),A1:H1000))

A: Of the two answers that work, Jacob Jan Tuinstra and AdamL, Jacob gives a better answer. Jacob's runs faster and is easier to remember.
However, why use crazy formulas when it is much easier to use Google Sheets to the fullest?
=ARRAYFORMULA(A2:A+B2:B+C2:C+D2:D+E2:E+F2:F+G2:G+H2:H)

In the foregoing formula, you can use named ranges instead of the ranges by reference.
=ARRAYFORMULA(range1+range2+range3+range4+range5+range6+range7+range8)

As well, you can sum across rows that span sheets rather than being stuck working with columns within the same sheet.
To fix the formula to block returning zeros for blank rows, use this:
=arrayFormula(if(isNumber(A2:A),A2:A+B2:B+C2:C+D2:D+E2:E+F2:F,G2:G,H2:H))

See: See Ahab's answer on Google Forums
For a cool sum accumulation formula, see Otávio Alves Ribeiro's answer on Google Forums

A: This is what you are looking for:
=MMULT(A1:H1000,TRANSPOSE(ARRAYFORMULA(COLUMN(A1:H1000)^0)))

See this answer on Web Application I gave: https://webapps.stackexchange.com/a/53419/29140
Note: tried it on the new Google Spreadsheet, without succes.

A: Summing A-H horizontal and running down for 523 lines:
=ARRAYFORMULA(iferror(mmult(A1:H523;TRANSPOSE(column(A1:H1))^0)))

A: if I look at this formula I really think the following might be simpler. Add this to Tools > Script Editor:
function row_sum(range_to_sum_per_row) {
  var result_column = [];
  for (var r = 0; r < range_to_sum_per_row.length; r++) {
    var row_sum = parseFloat(0);
    for (var c = 0; c < range_to_sum_per_row[r].length; c++) {
        row_sum += range_to_sum_per_row[r][c] || 0;
    }
    result_column.push([row_sum]);
  }
  return result_column;
}

use this like so for performance reasons, where C:H is the range you want to sum up and A:A is a column that does not contain an empty string:
=row_sum(filter(C2:H, len(A2:A)>0))

A: If you want to be able to add rows and sum to the last row for all values in A1:H, you can use:
 =ArrayFormula(SUMIF(IF(COLUMN(A1:H1),ROW(A1:A)),ROW(A1:A),A1:H))

Alternatively, if you want be be able to add rows and columns to the spreadsheet and sum to the last of both this can also be done. Paste the following code into any cell and it will create a column of summed values for all cells in each row below and to the right of pasted cell:
=arrayformula(SUMIF(IF(COLUMN(indirect(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":",VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", ""))))),ROW(indirect(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":",REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""))))),ROW(indirect(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":",REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", "")))),indirect(concatenate(concatenate(REGEXREPLACE(address(row(),column()+1),"[^[:alpha:]]", ""),VALUE(REGEXREPLACE(address(row(),column()),"[^[:digit:]]", "")),":"),address(rows($A:$A),columns($1:$1))))))

A: Using DSUM:
=ARRAYFORMULA(DSUM(
  TRANSPOSE(FILTER({A2:A,A2:H},A2:A<>"")),
  SEQUENCE(COUNTA(A2:A)),{IFERROR(1/0);IFERROR(1/0)}))

notes:

*

*{IFERROR(1/0);IFERROR(1/0)} is to make zero creteria for DSUM.

*{A2:A,A2:H} -- added fake column for DSUM to mimic header column.

*may be able to cahnge the formula into DMAX or DAVERAGE

A: Using Query
=INDEX(TRANSPOSE(
  QUERY(TRANSPOSE(FILTER(A2:H,A2:A<>"")),
  "select sum(Col"&JOIN("), sum(Col",SEQUENCE(COUNTA(A2:A)))&")",0)
),,2)

notes:

*

*generating query string on the fly

A: Answer similar to @adamL suggestion, but removing the internal if.
=ArrayFormula(
     sumif(ROW(A1:A10)*COLUMN(A1:H1)^0,ROW(A1:A10),A1:A10)
 )

In this case I use ROW(A1:A10) * COLUMN(A1:H1)^0 to generate the row number matriz. To understand how it works, you can test just this part in your Google sheets:
= ArrayFormula(ROW(A1:A10) * COLUMN(A1:H1)^0)

So, with your row matrix, sumif can operate for each line, is the line has the matched row number, it will be summed up.

A: Let us not complicate this.
Simply put parenthesis in each of the array in the range.
=arrayformula( Sum( (A1:A):(H1:H) )

This spans not only upto 1000 rows but upto infiinity.
If you really want to limit then go
=arrayformula( Sum( (A1:A1000):(H1:H1000) )


text:
Q: Yesod: how to send Redis results as JSON Apologies in advance for my Haskell inexperience.  I am writing a little wrapper for a Redis instance for a learning project.  So far Yesod has been an absolute wonder.  With very little Haskell experience I got browserId Auth working, and I'm inserting records into Redis successfully and quickly.
I'm stuck figuring out how to get the Redis responses converted into JSON and sent back.  Here is a working, un-scaffold, app that shows getting a static RepJson or a RepPlain with Redis info (App is called LRedis):
{-# LANGUAGE OverloadedStrings, TemplateHaskell, TypeFamilies,
             MultiParamTypeClasses, QuasiQuotes #-}

import Yesod
import Data.Text
import Data.Text.Encoding
import Data.ByteString.UTF8
import Database.Redis
import qualified Data.ByteString.Lazy as L

data LRedis = LRedis

instance Yesod LRedis where

mkYesod "LRedis" [parseRoutes|
    / HomeR GET
    /learnJson LearnJsonR GET
    /redisWorks RedisWorksR GET
    |]

getHomeR :: Handler RepHtml
getHomeR = do
    defaultLayout[whamlet|
    <p>Hi this is a headless API thing.
    |]

getLearnJsonR :: Handler RepJson
getLearnJsonR = do
    jsonToRepJson $ object [("json", ("ftw"::Text))]

getRedisWorksR :: Handler RepPlain
getRedisWorksR = do
    conn <- liftIO $ connect defaultConnectInfo
    liftIO $ runRedis conn $ do
        result <- Database.Redis.get (fromString "hello")
        case result of
            Left e -> return $ RepPlain "Error"
            Right mAnswer -> do
                case mAnswer of
                    Nothing -> return $ RepPlain "Not found."
                    Just x -> return $ RepPlain (toContent x)

main :: IO()
main = do
    warpDebug 3000 $ LRedis

Again, that is all working.  It will return the string stored in "hello" in redis if you curl /redisWorks, or it will return JSON if you curl /learnJson, but I want to give the redis answer as JSON, not a plain string.  I thought I could just naively combine the two, like:
getRedisJsonR :: Handler RepJson
getRedisJsonR = do
    conn <- liftIO $ connect defaultConnectInfo
    liftIO $ runRedis conn $ do
        result <- Database.Redis.get (fromString "hello")
        case result of
            Left e -> jsonToRepJson $ object [("response", ("error"::Text))]
            Right mAnswer -> do
                case mAnswer of
                    Nothing -> jsonToRepJson $ object [("response", ("Nothing"::Text))]
                    Just x -> jsonToRepJson $ object [("response", ((decodeUtf8 x)::Text))]

But after adding the route /redisJson RedisJsonR GET it fails with this compilation error:
Couldn't match expected type `Redis a0'
            with actual type `GHandler sub0 master0 RepJson'
In the expression:
  jsonToRepJson $ object [("response", ("error" :: Text))]
In a case alternative:
    Left e -> jsonToRepJson $ object [("response", ("error" :: Text))]
In a stmt of a 'do' block:
  case result of {
    Left e -> jsonToRepJson $ object [("response", ("error" :: Text))]
    Right mAnswer
      -> do { case mAnswer of {
                Nothing -> ...
                Just x -> ... } } }

It seems like its telling me I need to do something different with the result in case of an error, but I don't know what that would be, or why it's necessary given the RepPlain version is working.
Is there an example of getting the results from Redis into JSON within Yesod?
Is there just something simple I'm doing wrong with IO or something?
Convenient link to Hedis docs: http://hackage.haskell.org/package/hedis   Thank you for helping me with this.  Sorry again if it turns out to be super simple.

A: getRedisJsonR :: Handler RepJson
getRedisJsonR = do
    conn <- liftIO $ connect defaultConnectInfo
    res <- liftIO $ runRedis conn $ do
        result <- Database.Redis.get (fromString "hello")
        case result of
            Left e -> return $ jsonToRepJson $ object [("response", ("error"::Text))]
            Right mAnswer -> do
                case mAnswer of
                    Nothing -> return $ jsonToRepJson $ object [("response", ("Nothing"::Text))]
                    Just x -> return $ jsonToRepJson $ object [("response", ((decodeUtf8 x)::Text))]
    res

I actually don't trust myself to explain why this works and your original code doesn't -- I've been programming in Haskell on a daily basis for just under three months, so I have a developing gut sense for what will work but I'm really not there yet on the theory side, especially when it comes to stacked monads, which I think is what we're dealing with here (either Redis is on top of Handler or vice versa, and liftIO is facilitating the stacking).
Hopefully someone else can weigh in -- seems like a great concrete example to illustrate some monad concepts.


text:
Q: Trying to replace a Cross Apply with a JOIN We have a table, ProductHierarchy, which is set. The # of rows will not change. It has simple parent/child Product Hierarchy data in it.
We also have a Table-valued function which takes a ProductHierarchyId and then returns all rows where IsDescendantOf is true for that Id. Or in other words, it returns that row, plus all of its ancestors.
The problem is that with this Table-valued function, we have to use it with CROSS APPLY, and this is seriously slowing down the query.
My thought is to create either a second permanent table (or a temp table/table variable in the query in question) that has all possible results from the Table-valued function already in it. And then JOIN to that table instead of using the CROSS APPLY. In this table, we would add a column called something like QueryID. So instead of
CROSS APPLY dbo.GetProductLevels(P.ProductHierarchyId)

We could use
LEFT JOIN FutureTable ft ON ft.QueryId = P.ProductHierarchyId

I'm struggling with the query to create that table. Here's what I have so far...
SELECT
    *
    , 1 AS QueryId
FROM
    dbo.ProductHierarchy
WHERE
    (SELECT ProductHierarchyNode FROM dbo.ProductHierarchy WHERE ProductHierarchyId = 1).IsDescendantOf(ProductHierarchyNode) = 1

Ok, so that works great for the record where ProductHierarchyId = 1.  But then I'd need to repeat that for ProductHierarchyId = 2:
SELECT
    *
    , 2 AS QueryId
FROM
    dbo.ProductHierarchy
WHERE
    (SELECT ProductHierarchyNode FROM dbo.ProductHierarchy WHERE ProductHierarchyId = 2).IsDescendantOf(ProductHierarchyNode) = 1

And then for 3, and then for 4, all the way to the last Id, doing a UNION each time, inside a loop -- which is hideous.
I KNOW there is a way to do this all in one query. Something like a recursive CTE. But my brain isn't getting there.

A: Wouldn't you just do this?
SELECT . . .    -- the columns you want
INTO . . .      -- where you want them
FROM dbo.ProductHierarchy ph CROSS APPLY
     dbo.GetProductLevels(P.ProductHierarchyId);


text:
Q: Stacked Area Line Chart with Overlapping Values I'm trying to create an attendance chart. Previously, there was only 1 time slot, so I used a line chart. However, now there are 2 time slots. So, I'd like to do a stacked area line chart to summarize both individual and total attendance between both time slots. The problem is that some attend both time slots. I don't want the total attendance for the day to be skewed (i.e. total number of people in attendance), nor do I want the attendance for each time slot to be skewed.
How can I track the attendance accurately and represent it on the chart? Is there some way I can specify an "overlap" in attendance (i.e. 100 at time 1, 100 at time 2, 25 at both, for a total of 175 for the day)? Here is an example of one day of data:

A: Apparently you want to plot attendance vs date, which wasn't clear.
Set up data as shown, with dates in the first column, then attendance in the first time slot only, attendance in the second time slot only, then attendance in both time slots.
Make a chart of this data. I show a stacked area chart, but I prefer the stacked column chart.

EDIT:
Here's how to do an overlap with Area Charts. Arrange the data as shown, with total for each time slot, and in between the negative of the number of people common to both. Make your area chart. Format 9:00 AM as blue, but with 50% transparency. Format 9 & 11 as no fill. Format 11:00 AM as orange with 50% transparency.
Since the 9 & 11 series is negative, it moves down from the previous (9:00 blue) series, and the next series (11:00 orange) starts from the lower position. Where there is no overlap, the orange just seems to start at the top of the blue. And you can use your own colors that might show the overlap more clearly.


text:
Q: Filter javascript objects array based on a multivalue object Need to filter array based on a filter object having multiple values consisting arrays
    var vendors = [
      {
        vendor_name: "John",
        region: ["APAC", "UKDE"],
        scanned_status: "Yes",
        channel: ["FILE", "API"],
        pii_attributes: ["A", "B"]
      },
      {
        vendor_name: "Onir",
        region: ["APAC", "LATAM"],
        scanned_status: "No",
        channel: ["FILE"],
        pii_attributes: ["A", "C"]
      },
      {
        vendor_name: "Suresh",
        region: ["UKDE", "NA"],
        scanned_status: "Yes",
        channel: ["API"],
        pii_attributes: ["C", "B"]
      }
    ];

    var filterCriteria = {
      region: ["APAC", "LATAM"], // 'APAC', 'LATAM', 'NA', 'UKDE'
      channel: ["API"], // 'API', 'FILE'
      attributes: ["A", "B"],
      scan_status: "Yes" // 'Yes', 'No', 'All'
    };
    let filtered_vendors = [];
    var result = vendors.filter((el, index, arr) => {
      if (
        filterCriteria["region"].includes(el["region"]) &&
        filterCriteria["channel"].includes(el["channel"]) &&
        filterCriteria["attributes"].includes(el["pii_attributes"])
      ) {
        filtered_vendors.push(el);
        return true;
      }
      return false;
    });

    console.log(result);
    console.log(filtered_vendors);

But I am not able to apply multiple iteration at the filter level for including the elements. WOuld like to know efficient way to filter the array.

A: You could take a dynamic approach by using same keys for filterCriteria as well.
This approach checks if the filter value is an array and iterates the values and checks with includes.
If no array then it compares the value directly.

var vendors = [{ vendor_name: "John", region: ["APAC", "UKDE"], scanned_status: "Yes", channel: ["FILE", "API"], pii_attributes: ["A", "B"] }, { vendor_name: "Onir", region: ["APAC", "LATAM"], scanned_status: "No", channel: ["FILE"], pii_attributes: ["A", "C"] }, { vendor_name: "Suresh", region: ["UKDE", "NA"],
scanned_status: "Yes", channel: ["API"], pii_attributes: ["C", "B"] }],
    filterCriteria = { region: ["APAC", "LATAM"], channel: ["API"], pii_attributes: ["A", "B"], scanned_status: "Yes" },
    filters = Object.entries(filterCriteria),
    result = vendors.filter(o => filters.every(([k, value]) => Array.isArray(value)
        ? value.some(v => o[k].includes(v)) // change to every if all have to match
        : o[k] === value
    ));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: var data = [{
    "id": 1,
    "term_id": 5,
    "type": "car"
  },
  {
    "id": 2,
    "term_id": 3,
    "type": "bike"
  },
  {
    "id": 3,
    "term_id": 6,
    "type": "car"
  }
];

var result = data.filter(function(v, i) {
  return ((v["term_id"] == 5 || v["term_id"] == 6) && v.type == "car");
})

console.log(result)

A: I had to interpret your question a little. So, in the following code, we check if for every filter if all elements of the filter property value are also in the given vendor object property (basically a subset operation). In case you meant any element for every filter you need to use an intersection operation.
To implement this, we can use reduce for the iteration and sum up individual checks with && (function isSupersetOf). To apply this for every filter property, we can apply the same technique on the entries set (function isMatch).
Note that I also had to adjust the property names for this to work.
Code:

var vendors = [
      {
        vendor_name: "John",
        region: ["APAC", "UKDE"],
        scanned_status: "Yes",
        channel: ["FILE", "API"],
        pii_attributes: ["A", "B"]
      },
      {
        vendor_name: "Onir",
        region: ["APAC", "LATAM"],
        scanned_status: "No",
        channel: ["FILE"],
        pii_attributes: ["A", "C"]
      },
      {
        vendor_name: "Suresh",
        region: ["UKDE", "NA"],
        scanned_status: "Yes",
        channel: ["API"],
        pii_attributes: ["C", "B"]
      },
      // Add a match for illustration
      {
        vendor_name: "Denep",
        region: ["APAC", "LATAM", "NA"],
        scanned_status: ["Yes"],
        channel: ["API"],
        pii_attributes: ["A", "B", "C"]
      }
    ];

    const filterCriteria = {
      region: ["APAC", "LATAM"], // 'APAC', 'LATAM', 'NA', 'UKDE'
      channel: ["API"], // 'API', 'FILE'
      pii_attributes: ["A", "B"],
      scanned_status: ["Yes"] // 'Yes', 'No', 'All'
    };
    const isSupersetOf = (subset, superset) =>
      subset.reduce((result, next) => result && superset.includes(next), true);
    const isMatch = (filter, element) =>
      Object.entries(filter)
        .reduce((result, [property, values]) => result && isSupersetOf(values, element[property] || []), true)

    const filteredVendors = vendors.filter((el, index, arr) =>
      isMatch(filterCriteria, el))

    console.log(filteredVendors);


text:
Q: Computed data in Vue component I was doing a course at Vue Mastery and found such code:
    export default {
      data() {
        const times = []
        for (let i = 1; i <= 24; i++) {
          times.push(i + ':00')
        }
        return {
          event: this.createFreshEvent(),
          times,
          categories: this.$store.state.categories,
        }
      },
      methods: {
        createFreshEvent() {
          const user = this.$store.state.user
          return {
            organizer: user,
            attendees: []
          }
        }
      }
    }

*

*Why sometimes author uses inline code to generate data (times)?

*Why for next data property he uses method? Is there a difference?

*Why data() doesn't have only declarations and we don't generate all of above in created() life cycle hook?

A: For question 1 and 3 it's better to ask the one who created to course. There is no real reason to do it like this. I wouldn't do it the way he does, but indeed use created or mounted method.
For question 2:

In component's data option must be a function, so that each instance
can maintain an independent copy of the returned data object::

https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

A: By Vue's definition of created lifecycle hook: https://v2.vuejs.org/v2/api/#created

Called synchronously after the instance is created. At this stage, the
instance has finished processing the options which means the following
have been set up: data observation, computed properties, methods,
watch/event callbacks. However, the mounting phase has not been
started, and the $el property will not be available yet.

So generating data in data() will not trigger any related computed properties, watch/event callbacks. If you generate those data in created and your component has, for example, a watcher on times, there will be unneeded watch callbacks.
Btw, I am confused of the initialization of categories from this.$store.state.categories. Storing shared data from vuex in local data is unnecessary.


text:
Q: Rxjs - Calculate time spent inside/outside a div I am learning Rxjs and wanted to try out a few examples on my own
but I can't seem to get my head around to think reactively.
I am trying to calculate the time a user's mouse pointer spends inside and outside a div.
see fiddle - https://jsfiddle.net/ishansoni22/44af3n3k/

let $space = $(".space")

let in$ = Rx.Observable.fromEvent($space, "mouseenter")
                       .map((event) => "in")
let out$ = Rx.Observable.fromEvent($space, "mouseleave")
                       .map((event) => "out")

let inOut$ = Rx.Observable.merge(in$, out$)

let time$ = Rx.Observable.interval(1000)
                     .buffer(inOut$)
                     .map((list) => list.length)

time$.subscribe((value) => console.log(value));

I am able to calculate the time but how do I relate it to the respective in/ out streams? I want the output to look something like :

*

*inside, in - 20, out - 30

*outside, in - 20, out - 35

*inside, in - 100, out - 35

Also, can someone point me to some examples I could do so that I can start thinking in the reactive paradigm?

A: There are some examples in the official documentation (http://reactivex.io/rxjs) but they are a little bit scarce indeed.
I think I would some your sample something like this:

let $space = $(".space")
let in$ = Rx.Observable.fromEvent($space, "mouseenter")
let out$ = Rx.Observable.fromEvent($space, "mouseleave")

let durations$ = in$
  .map(_ => Date.now())
  .switchMap(inTime => out$
    .take(1)
    .map(_ => Date.now())
    .map(outTime => outTime - inTime)
  )

durations$
  .scan((sum, next) => sum + next, 0)
  .subscribe(total => console.log(total))

This would start listening to in$, then upon a mouseenter-event it starts to listen to mouseleaves, takes 1 of those events and calculate the duration.
I have written multiple maps below each other for clarity, but of course you can compose that into a single function.

A: One of the things I found most challenging when starting out with Rx was using streams of streams, and becoming comfortable with flatMap and switchMap. The problem you describe is most easily solved using exactly this approach. With your streams defined as follows (I prefer const over let to make it clear no mutation is occuring):
const in$ = Rx.Observable.fromEvent($space, 'mouseenter');
const out$ = Rx.Observable.fromEvent($space, 'mouseleave');

you can describe entering and then leaving as follows:
const inThenOut$ = in$.switchMap(() => out$);

To understand exactly what this is doing I urge you to learn about flatMap, become comfortable with streams of streams, and then learn how switchMap works by only maintaining a subscription to the most recent inner stream. For this I found the official rxjs documentation the best source. The included marble diagrams often tell complex stories with just a few dots and lines.
From here it's a relatively small step to get the time spent inside. First, we map our original streams into timestamp values:
const timestamp = () => + new Date();
const in$ = Rx.Observable.fromEvent($space, 'mouseenter').map(() => timestamp());
const out$ = Rx.Observable.fromEvent($space, 'mouseleave').map(() => timestamp());

(note: there is a timestamp method in rxjs you could use instead of doing this manually, but I feel this better illustrates how you can map your stream elements into anything you please).
From there, we can adjust our switchMap usage to access both the in and out values, and return the difference between them:
const inThenOut$ = in$.switchMap(() => out$, (x, y) => y - x);

Here's the whole thing working:
https://jsbin.com/qoruyoluho/edit?js,console,output

A: You could use RXJS - Timestamp operator to attach timestamp to each item emitted by an Observable indicating when it was emitted.
const { fromEvent } = Rx;
const { map, switchMap, timestamp, take, tap } = RxOperators;

const in$ = fromEvent($space, 'mouseenter').pipe(
  timestamp(),
  tap(x => console.log(`In: ${x.timestamp}`))
)

const out$ = fromEvent($space, 'mouseleave').pipe(
  timestamp(),
  tap(x => console.log(`Out: ${x.timestamp}`))
)

const duration$ = in$.pipe(
  switchMap(start => out$.pipe(
      take(1),
      map(finish => finish.timestamp - start.timestamp),
      tap(value => console.log(`Duration ms: ${value}`))
    )
  )
)

/* output example
In: 1552295324302
Out: 1552295325158
Duration ms: 856
*/

Try it here: https://rxviz.com/v/rOW5g9x8


text:
Q: MediaElement.NaturalDuration is less than the actual duration of the audio On some audio files the value of MediaElement.NaturalDuration is less than the actual duration of the audio. When I open the file in Windows Media Player the duration is correct (also when I look at the properties of the file). Although the value of the NaturalDuration property is incorrect, the audio is played fully, but at some point the value of the Position property becomes greater than the value of the NaturalDuration property, which, as I understand, should never happen.
I have created a simple application to reproduce the problem: https://skydrive.live.com/redir?resid=ACF8BFD4384116CE!2908&authkey=!AG-wF6Ae-7EAYk8
The duration of the audio file used in the application is 00:02:54, but the value of the NaturalDuration property is 00:01:59.
Does anyone know why and if there is a workaround for this?
Thanks in advance for any help.

A: Ok, this is not an answer but some results of a short investigation that give some clues why it behaves like that and where those numbers come from (2:58 and 1:59). First look at this thread: Calculating the length of MP3 Frames in milliseconds
Two things that we will use from there:
1) Frame length (in ms) = (samples per frame / sample rate (in hz)) * 1000, and
Duration in sec = Frame length (in ms) * number of frames / 1000
2) There are some standards regarding number of samples for different MPEG versions:
Samples per frame:
MPEG Version 1
        384,    // Layer1
        1152,   // Layer2
        1152    // Layer3

MPEG Version 2 & 2.5
        384,    // Layer1
        1152,   // Layer2
        576     // Layer3

Now lets check in winamp what it says about files format info:
MPEG-2.5 layer 3
16 kbps, 2482 frames
Now if you take frames = 2482 and samples per frame = 576 (MPEG-2.5 layer 3) you'll get duration 2:58. But it looks like for some reason silverlight and iTunes uses samples per frame = 384 which gives us 1:59. Next step could be to check the real values of file's headers and if they are correct and it is possible to calculate correct duration - well than you could cook up some hack to get durations separately (from the server for example). But I'm pretty sure - that file has some defects (inconsistent headers and content) and some players can handle it, others - not.


text:
Q: How can a 2 level multidimensional array be changed to n levels? I have an array like the following:
Array
(
    [1g27] => Array
        (
            [42] => AAAAA
            [52] => BBBBB
            [4] => 2g4
        )
    [2g4] => Array
        (
            [9] => CCCCC
            [14] => 3g14
            [15] => 3g15
            [20] => DDDDD
            [34] => EEEEE
        )
    [3g14] => Array
        (
            [49] => FFFFF
        )
    [3g15] => Array
        (
            [50] => GGGGG
        )
)

I would like it to become an array like the following:
Array
(
    [1g27] => Array
        (
            [42] => AAAAA
            [52] => BBBBB
            [2g4] => Array
            (
                [9] => CCCCC
                [3g14] => Array
                (
                    [49] => FFFFF
                )
                [3g15] => Array
                (
                    [50] => GGGGG
                )
                [20] => DDDDD
                [34] => EEEEE
        )
)

Notice that the values of the original array are also keys found in the original array. When there is a match between a value and an array, I want the array to replace the value (and rename that value's key).
I have tried foreach and array_walk_recursive, but I can't figure it out. (See following attempt which only goes 1 level deep.)

function inflate($flatree, $array)
    {
    global $inflatedtree;
    foreach ($array as $arraykey => $arrayvalue)
        {
        $inflatedtree[$arraykey] = $arrayvalue;
        if (array_key_exists($arrayvalue, $flatree))
            {
            $inflatedtree[$arrayvalue] = $flatree[$arrayvalue];
            inflate($flatree, $inflatedtree[$arrayvalue]);
            }
        }
    }
inflate($flatree, $flatree['1g27']);

using this function, however, gives me this:
Array
(
    [42] => AAAAA
    [52] => BBBBB
    [2g4] => Array
        (
            [9] => CCCCC
            [14] => 3g14
            [15] => 3g15
            [20] => DDDDD
            [34] => EEEEE
        )

    [3g14] => Array
        (
            [49] => FFFFF
        )
    [3g15] => Array
        (
            [50] => GGGGG
        )
)

A: I replaced the global variable $inflatedtree by a local one, which is the return value of the function inflate(). This return value is the new build branch.
function inflate($flatree, $array)
{
    $inflatedtree = array();
    foreach ($array as $arraykey => $arrayvalue) {
        if (array_key_exists($arrayvalue, $flatree)) {
            $inflatedtree[$arrayvalue] = inflate($flatree, $flatree[$arrayvalue]);
        } else {
            $inflatedtree[$arraykey] = $arrayvalue;
        }
    }
    return $inflatedtree;
}

I use a function start() for the initial call to get back the array as wished. Calling inflate() directly will return the inner array.
function start($flatree, $key)
{
    return array($key => inflate($flatree, $flatree[$key]));
}

$result_tree = start($flatree, '1g27');

A: I don't see a reason why your code should only go one level deep. It seems that you are calling the recursive function properly. The only error is that the key is not renamed but copied to a new name. You need to delete the old value like this
function inflate($flatree, $array)
{
global $inflatedtree;
foreach ($array as $arraykey => $arrayvalue)
    {
    $inflatedtree[$arraykey] = $arrayvalue;
    if (array_key_exists($arrayvalue, $flatree))
        {
        unset($inflatedtree[$arraykey]);
        //now the new stuff is only at $arrayvalue, not $arraykey
        $inflatedtree[$arrayvalue] = $flatree[$arrayvalue];
        inflate($flatree, $inflatedtree[$arrayvalue]);
        }
    }
}
inflate($flatree, $flatree['1g27']);

If your code ran on the example data does not give example results, then please post what array it makes otherwise.


text:
Q: How to set collation for MS SQL Server using Testcontainers Using Testcontainers, how can I set the database collation when starting a docker image for a MS SQL Server database?

A: On the container, you should just add an environment variable.
String dockerImageName = // here the specific imahe + tag
String collation = // a valid collation, e.g. "Latin1_General_CS_AS"
MSSQLServerContainer mssqlServerContainer = new MSSQLServerContainer(dockerImageName);
mssqlServerContainer.addEnv("MSSQL_COLLATION", collation);


text:
Q: JavaScript. Return random number from 1 to 10 not working correctly So I have code where is spawning 15 items, I need to make, that after user click on any item, It will return unique number. But for now after click all items returning the same number.
for (var t = 0; t < 16; t++) {
    ....//PART OF CODE
    var min = 1;
    var max = 10;
    var random = Math.floor(Math.random() * (max - min + 1)) + min;
    _chestArr[t].addEventListener('click',function(){
    var tezt = document.createTextNode(random);
    document.body.appendChild(tezt);
    },false);
}

A: It's not the random part that's the problem, it's the fact that the event handler functions you're creating close over the variable random, not the value it had when the individual functions were created. So they all see the last value you assign to it.
The typical way to fix this is with a builder function or Function#bind:
Builder function:
for (var t = 0; t < 16; t++) {
    ....//PART OF CODE
    var min = 1;
    var max = 10;
    var random = Math.floor(Math.random() * (max - min + 1)) + min;
    _chestArr[t].addEventListener('click',buildHandler(random),false);
}
function buildHandler(r) {
    return function(){
        var tezt = document.createTextNode(r);
        document.body.appendChild(tezt);
    };
}

Function#bind:
for (var t = 0; t < 16; t++) {
    ....//PART OF CODE
    var min = 1;
    var max = 10;
    var random = Math.floor(Math.random() * (max - min + 1)) + min;
    _chestArr[t].addEventListener('click',function(r){
    var tezt = document.createTextNode(r);
    document.body.appendChild(tezt);
    }.bind(null, random),false);
}

Note that the Function#bind option will affect the value of this within your handler, whereas the builder function version won't. You're not using this in your handler, but if you were, the builder function would probably be the way to go.


text:
Q: bootstrap3 text area too small I have a textarea in the following HTML code with Bootstrap3, which is too small. I gave its parent div class="col-xs-6", and expect it to take about half of the page width. But on a 1300x768 screen in a maximized browser window, the text area is only about 1/8 of the screen width.
Can some help explain what's the cause of the small size and how to fix it?
Thanks
Code is below (and js fiddle):

            <textarea id="dataquery" name="data"></textarea>

            <button id="datasubmit" class="btn btn-primary btn-xs"></button>

            Status:

        Results:

A: You can use bootstrap class form-control to textarea like
<textarea id="dataquery" name="data" class="form-control"></textarea>
This class takes 100% width of the parent


text:
Q: Combining Google Maps (Basic Javascript Issue) Hoping someone can point out something really obvious here (I don't really know Javascript at all). Basically I have two maps, one which does Geocoding based on a an address passed over through PHP, and another which pulls a list of locations from a MySQL DB into an XML file.
Both maps work perfectly in isolation. I need to combine them however, so the one map marks the locations in the XML file, and also shows the Geocoded marker. The code of the two of these combined is below:

Any guidance appreciated!

A: Thanks @John Smith, got this resolved. Posting the working code below. This will allow for lookup and pin of a Geocoded address, as well as pulling and pinning the lat/lng coords from an XML file through PHP, on the one map.


text:
Q: .Net WebApi concurrent constructor initialization from different controller methods Let's say I have this .NET WebApi controller "SampleController"
public class SampleController : ApiController
{
    public string SampleAPIMethod1()
    {
        TestClass tc = new TestClass("sampleParam1", "sampleParam2");

        bool success = tc.TestFunction();

        //some logic
    }

    public string SampleAPIMethod2()
    {
        TestClass tc = new TestClass("sampleParam1", "sampleParam2");

        bool success = tc.TestFunction();

        //some different logic
    }
}

And this utility class "TestClass"
public class TestClass
{
    //other out of scope properties

    Stream myFile;
    TextWriterTraceListener myTextListener;

    public TestClass(string inParam1, string inParam2) {
        string newGuidStr = Guid.NewGuid.ToString();
        StackTrace st = new StackTrace();

        myFile = File.Create("c:\logs\" + newGuidStr + ".txt");
        myTextListener = new TextWriterTraceListener(myFile);
        Trace.Listener.Add(myTextListener);

        Trace.WriteLine("Current UTC Time: " & DateTime.UtcNow.ToString() & " - Called from: " & st.GetFrame(1).GetMethod().Name);
    }

    public bool TestFunction()
    {
        try
        {
            Trace.WriteLine("1");
            //some logic
            Trace.WriteLine("2");
            //some further logic
            Trace.WriteLine("3");
        }
        catch(Exception ex)
        {
            //some error handling
        }
        finally
        {
            Trace.Flush();
            myFile.Close();
        }
    }
}

How can a file with the same name (as defined by the newGuidStr variable which is always re-instantiated within the TestClass() constructor) contain trace logs that indicate instantiation from both SampleAPIMethod1 and SampleAPIMethod2? The issue happens when concurrent multiple requests are sent from a client app to the .NET WebApi. In my opinion, this should never be the case, as the 'tc' object within SampleAPIMethod1 and SampleAPIMethod2 is re-initialized and re-instantiated upon every new request and the 2 different API methods should be totally independent. This even happened by multiple requests on the same API method. That 2 different instances created the same GUID file name is highly unlikely, and that it happened to me multiple times makes it more so.
Text file output in the same file: 5a483a4f-4d5f-4135-8f5a-8eb840a433ed.txt

*

*Current UTC Time: 29/03/2020 16:15:44 - Called from: SampleAPIMethod1

*Current UTC Time: 29/03/2020 16:15:44 - 1

*Current UTC Time: 29/03/2020 16:15:44 - 2

*Current UTC Time: 29/03/2020 16:15:46 - Called from: SampleAPIMethod2

*Current UTC Time: 29/03/2020 16:15:46 - 1

*Current UTC Time: 29/03/2020 16:15:46 - 2

*Current UTC Time: 29/03/2020 16:15:46 - 3

*Current UTC Time: 29/03/2020 16:15:46 - 3

A: What's happening here is that even though you create a new trace listener for each request, you then put them in a global collection of listeners in the form of Trace.Listeners, which is shared between all requests. Calling Trace.WriteLine will write the given message to all listeners in this collection, and thus if a new request comes in before the old listener is deactivated (i.e. the file it writes to is closed), both listeners will get calls to log the same message.
To fix this, the TestClass object should call WriteLine on its own myTextListener object directly, instead of using the global Trace object. This ensures the message will only ever be written to the listener specific to that TestClass instance. This also means you no longer have to add the trace listeners to the Trace.Listeners collection.
I have modified your TestClass example to implement this, using comments to annotate changes:
public class TestClass
{
    //other out of scope properties

    Stream myFile;
    TextWriterTraceListener myTextListener;

    public TestClass(string inParam1, string inParam2) {
        string newGuidStr = Guid.NewGuid.ToString();
        StackTrace st = new StackTrace();

        myFile = File.Create("c:\\logs\\" + newGuidStr + ".txt");
        myTextListener = new TextWriterTraceListener(myFile);
        // Removed `Trace.Listeners.Add(myTextListener)`

        myTextListener.WriteLine("Current UTC Time: " + DateTime.UtcNow.ToString() + " - Called from: " + st.GetFrame(1).GetMethod().Name);
    }

    public bool TestFunction()
    {
        try
        {
            // Changed `Trace` to `myTextListener` here
            myTextListener.WriteLine("1");
            myTextListener.WriteLine("2");
            myTextListener.WriteLine("3");
        }
        catch(Exception ex)
        {
        }
        finally
        {
            // Changed `Trace` to `myTextListener` here
            myTextListener.Flush();
            myFile.Close();
        }
    }
}


text:
Q: My Xamarin app crashed in only-ipv6 environment The version of Xamarin.form is 2.3.3.168.
I used FubarCoder.RestSharp.Portable framework.
My app was rejected because:

We discovered one or more bugs in your app when reviewed on iPhone
  running iOS 10.3 on Wi-Fi connected to an IPv6 network.

My app crashed in only-ipv6 environment when I just want to login to the MainPage, VisualStudio(My Os is win7) tells the errors below:
An error occurred while sending the request
  at System.Net.Http.HttpClientHandler+<SendAsync>c__async0.MoveNext () [0x0047a] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.6.0.10/src/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs:383
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.6.0.10/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.6.0.10/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/10.6.0.10/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156

I read many answers about app crashed in only-ipv6, but no one worked.
Maybe I don't understand their methods.
I tried to set

but the result was still failure.
So I am so puzzled now.
Could you tell me how to solve this problem?
Thank you.

A: I instead of ipv4 string in my code to a domain string, so the app doesn't crash no more.


text:
Q: Application Loader (Apple) stuck on "Sending API usage to iTunes Connect" I am submitting an iOS app to the App Store using Application Loader, however, it never gets past the "Sending API usage to iTunes Connect" stage. There is no error - this stage just doesn't complete.
I have verified that the Mac is connecting to the internet (I can visit websites). Also, the app is tiny (6MB) so this can't conceivably just be a long upload. I've tried leaving this for 20 minutes.
The background to this is that I developed in Flash CS5 on a Windows PC, built it for distribution there, and now on the Mac I am loading the final file into Application Loader to submit it. It verifies/validates the file just fine, but won't go beyond this point.
Any ideas anyone? Perhaps it's a network issue?

A: You can solve this with a different approach using your iPhone. Disconnect ethernet internet cable connection (if you have one) and/or switch off wifi connection on your mac. Switch off your iPhone's wifi connection so G3 or G4 is active and turn on personal hotspot. Connect your iPhone with a usb cable with your computer and check in System Preferences -> Network if you're connected to internet via usb with iPhone. Start delivering your app with Application Loader program on your computer via your iPhone's internet connection. And yes you will cross the "Sending API usage to iTunes Connect" barrier and you will be able to upload the package to the iPhone store. At least I was!

A: If your Mac is has both a WiFi and an Ethernet connection, try turning off WiFi. That solved the problem for me (this time anyway).

A: I had this problem when behind a firewall.
I got around it by going to Xcode > Contents > Applications > Application Loader > Contents > MacOS > itms > java > lib  - Open net.properties with TextEdit and change the line
# https.proxyPort=443
 to https.proxyPort=80.  This enables the application to use the HTTP port for HTTPS. Worked straight away after this. Hope this helps.

A: I solved only rebooting mac.
I'm still searching for a less drastic solution!

A: I had my DNS set up to Google DNS. I removed the DNS settings and it worked for me.

A: Turning off iphone's wifi worked for me

A: Are you using Xcode Organiser > Upload to App Store or  Application Loader?
I found I had the same issue when going though Xcode Organiser so tried it from the Application Loader (found within Xcodes application files) and it worked just fine. If that doesn't work there is a detailed activity log you can check to get a more detailed error.
Other things to try
- check your firewall settings, maybe temporary disable them.
- use an alternative connection, another wifi hotspot if you are on a MacBook, if not do what Oliver said and use your iPhone's cellular data.

A: I was connected to a VPN, disconnected and problem was solved.


text:
Q: In an Oracle database query, is there any way to acquire a shared row lock inside of a transaction? Is there any way to acquire a shared row lock inside of a transaction?
I realize that SELECT ... FOR UPDATE can be used to get a exclusive row lock (that would cause UPDATEs and SELECTs to block till the transaction ends), but is there any equivalent that can be used to get a shared row lock (that would cause SELECT ... FOR UPDATE queries to block, but other attempts to acquire the same shared row lock would not block)?


text:
Q: XML Schema Collection breaks xquery The script below can be used to show an example of the problem I have. The script will return an error "There is no element named 'this'".
If I change the declaration of the @XML variable so it is untyped XML (replace the line DECLARE @XML XML(Test) with DECLARE @XML XML), I do not get the error, but get the expected result instead.
Why do I get the error when using the Schema collection and how can I avoid it - I want to fill a table column with properly typed xml, but I'm having trouble getting my data back out of the column.
IF EXISTS (SELECT name FROM sys.xml_schema_collections WHERE name = 'test') DROP XML SCHEMA COLLECTION Test
CREATE XML SCHEMA COLLECTION Test AS
'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:t="http://tempuri.org/this.xsd"
      targetNamespace="http://tempuri.org/this.xsd"
      elementFormDefault="qualified">
  <xsd:element name ="this">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="What" minOccurs="1" maxOccurs="1" >
          <xsd:simpleType>
            <xsd:restriction base ="xsd:string">
              <xsd:enumeration value ="01."/>
              <xsd:enumeration value ="02."/>
              <xsd:enumeration value ="03."/>
              <xsd:enumeration value ="04."/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
        <xsd:element name="When" minOccurs="1" maxOccurs="1" >
          <xsd:simpleType>
            <xsd:restriction base ="xsd:string">
              <xsd:enumeration value ="01."/>
              <xsd:enumeration value ="02."/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
        <xsd:element name="Outcome" minOccurs="1" maxOccurs="1" >
          <xsd:simpleType>
            <xsd:restriction base ="xsd:string">
              <xsd:enumeration value ="one"/>
              <xsd:enumeration value ="two"/>
              <xsd:enumeration value ="whatever"/>
              <xsd:enumeration value =""/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>'
GO

    DECLARE @XML XML(Test)

    SET @XML =
    '<this xmlns="http://tempuri.org/this.xsd">
      <What>02.</What>
      <When>01.</When>
      <Outcome></Outcome>
    </this>'

    SELECT @XML

    SELECT
        Field.value('What[1]','VARCHAR(100)')
    FROM @Xml.nodes('/this') AS this(Field)

A: The problem is your namespace declaration: <this xmlns="http://tempuri.org/this.xsd">. Everything in that XML snippet belongs to the namespace http://tempuri.org/this.xsd. Your query used the unqualified name for this and What. Use this instead:
;WITH XMLNAMESPACES (
    'http://tempuri.org/this.xsd' as t
)
SELECT
    Field.value('t:What[1]','VARCHAR(100)')
FROM @Xml.nodes('/t:this') AS this(Field)


text:
Q: Java program throws exception if i add more participants in CC list I have developed a below program to send the mail using java ail api , now it through error if i add more than one recipient in cc can you please advise how can i customise my below program so that i can add more people in cc , shall i go for an array for cc feild .
public class abctest{

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String mailSmtpHost = "66.66.66.66;
        String mailSmtpPort = "1789" ;

        String mailTo = "ert@abc.com";
        String mailCc = "ewq@abc.com "; // ******throws exception if i add more than one email in cc list
        String mailFrom = "rrr@abc.com";
        String mailSubject = "Test Email from Java";
        String mailText = "This is an email for Brokerage  from Java";

        sendEmail(mailTo, mailCc, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
    }

    public static void sendEmail(String to, String cc, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
        try {
            Properties properties = new Properties();
            properties.put("mail.smtp.host", smtpHost);
            properties.put("mailSmtpPort", mailSmtpPort);
            Session emailSession = Session.getDefaultInstance(properties);

            Message emailMessage = new MimeMessage(emailSession);
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            emailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            emailMessage.setFrom(new InternetAddress(from));
            emailMessage.setSubject(subject);

            emailMessage.setText(text);

            emailSession.setDebug(true);

            Transport.send(emailMessage);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}

A: You can use
emailMessage.addRecipients(Message.RecipientType.CC,
                    InternetAddress.parse("eranda@mahesh.com, mahesh@eranda.com"));

or
Address[] cc = new Address[] {new InternetAddress("eranda@mahesh.com"),
            new InternetAddress("mahesh@eranda.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);


text:
Q: getNamedDispatcher on Appengine Java Due to some unavoidable issues, I am attempting to forward request on Appengine Java from one servlet to another.  However, the "standard" config doesn't seem to work.  I have:
web.xml
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>class.of.MyServlet</servlet-class>
    </servlet>

otherServlet.java
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("MyServlet");
dispatcher.forward(req, resp);

However, dispatcher is null (presumably because it can't find "MyServlet"), so I get an NPE.
This feels like a bug / non-standard implementation on the AppEngine side, but maybe I am missing something.