text:
Q: Given a system of quadratic equations $x^2-a_ix+b_i=0$, can all of the coefficients $a_i$, $b_j$ be solution to  one of  these above equation? Here are $n$ quadratic equations ($n>1$): $$x^2-a_ix+b_i=0\quad(i=1,\ldots, n)$$ where the $a_i$, $b_i$ are distinct. Can all of the $a_i,b_i$ be roots of one of the above equations?

A: In general the answer is NO: Assume this is possible, then $\{a_i , i=1..n\}=\{a_i+b_i, i=1..n\}$ and $\{b_i, i=1..n\}=\{a_i*b_i, i=1..n\}$, and we obtain as necessarily conditions $\sum {b_i} = 0$ and $\prod{a_i}=1$. Can't say more for the moment.

A: I don't fully understand the question, but I will try:
Recall a polynomial of degree $2$ over $\Bbb C$ has two roots. If we are allowed to construct the system of $n$ of polynomials, then we can force the desired root properties as follows.
Let's start with an arbitrary polynomial call it $p_1 = x^2 - a_1 x + b_1.$ Now to construct $p_2 = x^2 - a_2 x + b_2$ such that $\{a_1, b_1 \}$ are roots of $p_2,$ we need to have $$ a_2 = a_1 + b_1, b_2 = a_1 b_1. \tag{1}$$
And so forth, the polynomial $p_i$ will have roots $\{a_{i-1}, b_{i-1} \}.$
We need to do something to wrap around $p_n$ and $p_1.$ But I will leave that to you. Does this help?

Update: if all you want is sufficient conditions on $a_i$'s and $b_i$'s such that all $a_i, b_i$ are roots of some $p_j.$ Then we can generalize $(1)$ into the following $n$ conditions; for a given system of polynomials $p_i = x^2 - a_i x + b_i, 1 \le i \le n,$ the following have to hold:
$$ a_1 = a_n + b_n, \quad b_1 = a_n b_n \\
   a_2 = a_1 + b_1, \quad  b_2 = a_1 b_1 \\
   a_3 = a_2 + b_2, \quad  b_3 = a_2 b_2 \\
   \ldots \\
   a_{n} = a_{n-1} + b_{n-1}, \quad b_n = a_{n-1} b_{n-1} $$
The explicit construction I gave doesn't satisfy the first condition though.

A: so if we are talking about complex numbers or roots could be complex numbers,then yes,otherwise for real solution discriminant
$D=a^2-4*b$ must be nonnegative and also using vietas theorem,roots could be satisfies
$x_1*x_2=b$
$x_2+x_2=a$


text:
Q: Reading in file and using Strtok, some fields read successfully, some fields do not I'm making a function to read in data from a file. The file input is a name and and ID#.
Example:
"George Washington, 2345678
John Adams, 3456789
Thomas Jefferson, 4567890"
I can read in all the names correctly, but the id numbers do not read correctly. The numbers that are read in are all right around 2682824. None of the ID's are close to that. Sometimes the numbers go up or down by 5 but stay around those numbers. Here is the code I have now. Any help would be greatly appreciated.
void readDataIn(){
struct pres tempFill[30];
char s[2] = ",";
char t[50], j[1900];
char *token, *token2;
int *h;
int i = 0, f;
    FILE* file;

    if((file=fopen("AssignmentOneInput.txt", "r")) != NULL){
    while(fgets(j, sizeof(j), file)){
    token = strtok(j, ",");
    printf("%s\n", token);
    token = strtok(NULL, "\n");
    printf(" %i\n", token);

    }

    pause;

    }
pause;
fclose(file);
return;

}

A: When you call strtok second time in the while loop, pass NULL as the argument instead of j.
token = strtok(NULL, "\n");

When you pass NULL in the first argument, strtok resumes parsing from the last token. When you pass j, it parses starting from j again.
Please check out strtok documentation.
The other problem is that you are using
printf(" %i\n", token);

token is still a string. "%i" is not the right format specifier to use here. You need to use:
printf(" %s\n", token);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Constrained optimization in random variables I was handed this problem:
Let $X_1,\ldots, X_n$ be a sequence on $n$ independent random variables, with $\mathbb{E}\left[X_i\right]=\mu_i$ and $\mathbb{V}\left[X_i\right]=\sigma_i^2$. Find the constants $a_i$ so that $\mathbb{V}\left[\sum_{i=1}^2 a_i X_i\right]$ is minimized given that $\mathbb{E}\left[\sum_{i=1}^2 a_i X_i\right]=\mu$.
and I came up with the following solution:
It's true that $$\mathbb{E}\left[\sum_{i=1}^{n}a_{i}X_{i}\right]=\sum_{i=1}^{n}a_{i}\mathbb{E}\left[X_{i}\right]=\sum_{i=1}^{n}a_{i}\mu_{i}=\mu$$
and
\begin{align}
\mathbb{V}\left[\sum_{i=1}^{n}a_{i}X_{i}\right]&=\mathbb{E}\left[\left(\left(\sum_{i=1}^{n}a_{i}X_{i}\right)-\mathbb{E}\left[\sum_{i=1}^{n}a_{i}X_{i}\right]\right)^{2}\right]=\mathbb{E}\left[\left(\sum_{i=1}^{n}a_{i}X_{i}-\sum_{i=1}^{n}a_{i}\mu_{i}\right)^{2}\right]\\
&=\mathbb{E}\left[\left(\sum_{i=1}^{n}a_{i}\left(X_{i}-\mu_{i}\right)\right)^{2}\right]=\mathbb{E}\left[\left(\sum_{i=1}^{n}a_{i}\left(X_{i}-\mu_{i}\right)\right)\left(\sum_{i=1}^{n}a_{i}\left(X_{i}-\mu_{i}\right)\right)\right]\\
&=\mathbb{E}\left[\sum_{i=1}^{n}\sum_{j=1}^{n}a_{i}a_{j}\left(X_{i}-\mu_{i}\right)\left(X_{j}-\mu_{j}\right)\right]=\sum_{i=1}^{n}\sum_{j=1}^{n}a_{i}a_{j}\mathbb{E}\left[\left(X_{i}-\mu_{i}\right)\left(X_{j}-\mu_{j}\right)\right]\\
&=\sum_{i=1}^{n}\sum_{j=1}^{n}a_{i}a_{j}Cov\left(X_{i},X_{j}\right).
\end{align}
Since the random variables are independent, for $i\neq j\: : \: Cov\left(X_i,X_j\right)=0$ . So using Kronecker's delta we get
$$\sum_{i=1}^{n}\sum_{j=1}^{n}a_{i}a_{j}Cov\left(X_{i},X_{j}\right)=\sum_{i=1}^{n}\sum_{j=1}^{n}a_{i}a_{j}\delta_{i,j}\mathbb{V}\left[X_{i}\right]=\sum_{i=1}^{n}a_{i}^{2}\sigma_{i}^{2}.$$
So we need to find constants $a_{i}$ so that the following minizes $\sum_{i=1}^{n}a_{i}^{2}\sigma_{i}^{2}$ given that $\sum_{i=1}^{n}a_{i}\mu_{i}=\mu$.
We define the function $L:\mathbb{R}^{n}\to\mathbb{R}$ as
$$L\left(a_{1},a_{2},\ldots,a_{n}\right)=\left(\sum_{i=1}^{n}a_{i}^{2}\sigma_{i}^{2}\right)+\lambda\left(\left(\sum_{i=1}^{n}a_{i}\mu_{i}\right)-\mu\right).$$
The critical points of $L$ are given by
$$\frac{\partial L}{\partial a_{i}}=2\sigma_{i}^{2}a_{i}+\lambda\mu_{i}=0\Rightarrow a_{i}=-\frac{\lambda\mu_{i}}{2\sigma_{i}^{2}},\quad i=1,\ldots,n.$$
Replacing the $a_{i}$ we just found in the constraint we get
$$\sum_{j=1}^{n}-\frac{\lambda\mu_{j}}{2\sigma_{j}^{2}}\mu_{j}=\mu\Rightarrow-\frac{\lambda}{2}\sum_{j=1}^{n}\frac{\mu_{j}^{2}}{\sigma_{j}^{2}}=\mu\Rightarrow\lambda=-\frac{2\mu}{\sum_{j=1}^{n}\frac{\mu_{j}^{2}}{\sigma_{j}^{2}}}.$$
We conclude the the critical point of $L$ are
$$a_{i}=-\left(-\frac{2\mu}{\sum_{j=1}^{n}\frac{\mu_{j}^{2}}{\sigma_{j}^{2}}}\right)\frac{\mu_{i}}{2\sigma_{i}^{2}}=\mu\frac{\mu_{i}}{\sigma_{i}^{2}}\frac{1}{\sum_{j=1}^{n}\frac{\mu_{j}^{2}}{\sigma_{j}^{2}}},\quad i=1,\ldots,n.$$
But now I can't prove that that is a minimum. I thought that I could use the Cauchy - Schwarz inequality, but I'm kinda lost.
PS: Sorry for any and all grammatical errors I'm translating Greek.
Edit. Fix the mistakes pointed out by StubbornAtom.

A: This is a slight generalization of this question.
By Cauchy-Schwarz,
$$\sum_{i=1}^n (a_i\sigma_i)^2\sum_{i=1}^n \left(\frac{\mu_i}{\sigma_i}\right)^2\ge \left(\sum_{i=1}^n a_i\mu_i\right)^2$$
Or, $$\sum_{i=1}^n a_i^2\sigma_i^2\ge \mu^2\left(\sum\limits_{i=1}^n \frac{\mu_i^2}{\sigma_i^2}\right)^{-1}$$
Equality holds precisely when $a_i\sigma_i$ is proportional to $\frac{\mu_i}{\sigma_i}$ for every $i$, i.e. when $a_i=\frac{c\mu_i}{\sigma_i^2}$ for some non-zero constant $c$. From the constraint $\sum\limits_{i=1}^n a_i\mu_i=\mu$, we have $$c=\mu\left(\sum\limits_{i=1}^n \frac{\mu_i^2}{\sigma_i^2}\right)^{-1}$$
So the optimal solution is $$\hat a_i=\mu\left(\sum\limits_{i=1}^n \frac{\mu_i^2}{\sigma_i^2}\right)^{-1}\frac{\mu_i}{\sigma_i^2}\quad,\,i=1,\ldots,n$$

A: Another possible ad simpler solution is:
We observe that the second partial derivatives of $L$ are
$$\frac{\partial^{2}L}{\partial a_{i}\partial a_{j}}=\begin{cases}
2\sigma_{i}^{2} & i=j\\
0 & i\neq j
\end{cases}.$$
So the Hessian matrix of $L$ will be
$$D^{2}L=\begin{bmatrix}\frac{\partial^{2}L}{\partial a_{1}^{2}} & \frac{\partial^{2}L}{\partial a_{1}\partial a_{2}} & \cdots & \frac{\partial^{2}L}{\partial a_{1}\partial a_{n}}\\
\frac{\partial^{2}L}{\partial a_{2}\partial a_{1}} & \frac{\partial^{2}L}{\partial a_{2}^{2}} & \cdots & \frac{\partial^{2}L}{\partial a_{2}\partial a_{n}}\\
\vdots & \vdots & \ddots & \vdots\\
\frac{\partial^{2}L}{\partial a_{n}\partial a_{1}} & \frac{\partial^{2}L}{\partial a_{n}\partial a_{2}} & \cdots & \frac{\partial^{2}L}{\partial a_{n}^{2}}
\end{bmatrix}=\begin{bmatrix}2\sigma_{1}^{2} & 0 & \cdots & 0\\
0 & 2\sigma_{2}^{2} & \cdots & 0\\
\vdots & \vdots & \ddots & \vdots\\
0 & 0 & \cdots & 2\sigma_{n}^{2}
\end{bmatrix}$$
We see that the eigenvalues of $D^2L$ are $\lambda_{i}=2\sigma_{i}^{2}\geq0,\,i=1,\ldots,n$. That means that $D^2L$ is semi-positive defined matrix, and as a result for $a_{i}=\mu\frac{\mu_{i}}{\sigma_{i}^{2}}\frac{1}{\sum_{j=1}^{n}\frac{\mu_{j}^{2}}{\sigma_{j}^{2}}},\,i=1,\ldots,n$ the value of $\mathbb{V}\left[\sum_{i=1}^{n}a_{i}X_{i}\right]$ is minimized.


text:
Q: SafeModeResult is null after update Using MongoDB and the latest 10gen C# driver (CSharpDriver-1.3.1.4349), I am trying to do an "in place" update and get back the # of documents effected in the result.
public static long SaveListings(string state, bool isActive, DateTime updateDate)
{
    var result = Collection().Update(
    Query.And(
        Query.EQ("State", state),
        Query.And(
            Query.EQ("IsActive", isActive),
            Query.LT("UpdateDate", updateDate))),
    Update.Set("IsActive", false), UpdateFlags.Multi);
    return result != null ? result.DocumentsAffected : -1;
}

The result is null for some reason. If I were doing this from the console, I could get the number of rows effected by doing this:
db.Listing.update( { State: state.Abbreviation, IsActive: true, UpdateDate: { $lt: expiredDate } }, { $set: { IsActive: false } }, false, true);
var numRows = db.getLastErrorObj().n;

Any idea what I'm doing wrong or is this a bug in the C# driver?

A: Update contains overloaded method that take SafeMode. Just add it to your code as fourth parameter to your update and should be not null:
...
UpdateFlags.Multi,
SafeMode.True);

That's not driver bug, it work as expected. Mongodb does not wait for document if get inserted without safe mode (therefore driver return null), but if you saying SafeMode = true -- you force mongodb wait until document get inserted.

A: Doing inserts and updates without specifying safe mode yields null because they're asynchronous operations - there's simply no way to know how the insert or update went.
Therefore, add e.g. SafeMode.True as the last argument in inserts and updates in cases where you care about the result. This will make the driver issue a getLastError command, which blocks until the insert/updated has completed:
var result = collection.Update(query, update, SafeMode.True);

You can read some more about getLastError and different safe modes here (general) and here (SafeMode with the C# driver).

A: Try getLastError here: http://www.webtropy.com/articles/art9-1.asp?f=GetLastError


text:
Q: Rewrite subdomain to subdirectory in Apache .htaccess file Suppose I have a domain called example.com and I want to use rewrite rules in the .htaccess file of Apache to rewrite:
https://office.example.com/index.html
to
https://example.com/office/index.html.
How would I do that? I checked lots of answers here, and the solution seems to be something like this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^office.example.com$
RewriteRule ^(.*)$ https://example.com/office/$1 [L,NC,QSA]

This works when I test it here:
https://htaccess.madewithlove.be?share=b40ca72f-86d3-5452-a04b-ac9f24812c57
Regrettably, it does generate an error 500 on my server. I enabled logging and found that this seems to be a recursion problem:
AH00124: Request exceeded the limit of 10 internal redirects.

In the logs it seems to add office to office endlessly: /office/office/office/.... I have no idea why this is happening. The rewritten URL doesn't meet the rewrite condition, so why would it do this?
I have found a way to make it "work". If I add R=301 to the RewriteRule attributes it does a redirect, and works, but I would prefer if the original URL remained in the address bar.
Here's the log for the first 2 redirects:
init rewrite engine with requested uri /
applying pattern '^(.*)$' to uri '/'
applying pattern '^(.*)$' to uri '/'
applying pattern '^(.*)$' to uri '/'
pass through /
[perdir /var/www/vhosts/example.com/httpdocs/] strip per-dir prefix: /var/www/vhosts/example.com/httpdocs/ ->
[perdir /var/www/vhosts/example.com/httpdocs/] applying pattern '^(.*)$' to uri ''
[perdir /var/www/vhosts/example.com/httpdocs/] rewrite '' -> 'https://example.com/office/'
reduce https://example.com/office/ -> /office/
[perdir /var/www/vhosts/example.com/httpdocs/] internal redirect with /office/ [INTERNAL REDIRECT]
#1 init rewrite engine with requested uri /office/
#1 applying pattern '^(.*)$' to uri '/office/'
#1 applying pattern '^(.*)$' to uri '/office/'
#1 applying pattern '^(.*)$' to uri '/office/'
#1 pass through /office/
#1 [perdir /var/www/vhosts/example.com/httpdocs/] strip per-dir prefix: /var/www/vhosts/example.com/httpdocs/office/
#1 [perdir /var/www/vhosts/example.com/httpdocs/] applying pattern '^(.*)$' to uri 'office/'
#1 [perdir /var/www/vhosts/example.com/httpdocs/] rewrite 'office/' -> 'https://example.com/office/office/'
#1 reduce https://example.com/office/office/ -> /office/office/
#1 [perdir /var/www/vhosts/example.com/httpdocs/] internal redirect with /office/office/ [INTERNAL REDIRECT]
#2 init rewrite engine with requested uri /office/office/
#2 applying pattern '^(.*)$' to uri '/office/office/'
#2 applying pattern '^(.*)$' to uri '/office/office/'
#2 applying pattern '^(.*)$' to uri '/office/office/'
#2 pass through /office/office/
#2 [perdir /var/www/vhosts/example.com/httpdocs/] add path info postfix: /var/www/vhosts/example.com/httpdocs/office
#2 [perdir /var/www/vhosts/example.com/httpdocs/] strip per-dir prefix: /var/www/vhosts/example.com/httpdocs/office/
#2 [perdir /var/www/vhosts/example.com/httpdocs/] applying pattern '^(.*)$' to uri 'office/office/'
#2 [perdir /var/www/vhosts/example.com/httpdocs/] rewrite 'office/office/' -> 'https://example.com/office/office/off
#2 reduce https://example.com/office/office/office/ -> /office/office/office/
#2 [perdir /var/www/vhosts/example.com/httpdocs/] internal redirect with /office/office/office/ [INTERNAL REDIRECT]

A:
RewriteCond %{HTTP_HOST} ^office.example.com$
RewriteRule ^(.*)$ https://example.com/office/$1 [L,NC,QSA]

Rather confusing, this should implicitly trigger an external 302 (temporary) redirect, not an internal rewrite - when specifying a different host in the substitution string to the one being requested. (Although in my experience, any absolute URL in the substitution string triggers an external redirect.)
If it does trigger an internal rewrite (as indicated by the logs) then the requested hostname does not change (since this is not a separate request) and you will indeed get a rewrite loop.
However, if "the subdomain is an alias of the main domain" and a rewrite is what's required, then there is no need to specify a hostname in the substitution string and you will indeed need to make additional checks to prevent an internal rewrite loop (500 error).
Try the following instead:
RewriteEngine on

RewriteCond %{HTTP_HOST} ^office\.example\.com [NC]
RewriteRule !^office office%{REQUEST_URI} [L]

...to exclude any requests (including rewritten requests) that already start /office.
No need for the NC and QSA flags.
Alternatively, to only target direct requests (not rewritten requests) you could check the REDIRECT_STATUS environment variable instead (which is empty on the initial request and set to "200", as in 200 OK, after the first successful rewrite).
For example:
RewriteCond %{HTTP_HOST} ^office\.example\.com [NC]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule (.*) office/$1 [L]

This has the added "benefit" that you can potentially have a sub-subdirectory called /office as well. ie. /office/office.
UPDATE: A third version is to check against the REQUEST_URI server variable. However, I would not expect this to be any different from the first version above.
RewriteCond %{HTTP_HOST} ^office\.example\.com [NC]
RewriteCond %{REQUEST_URI} !^/office
RewriteRule ^ office%{REQUEST_URI} [L]

Sadly enough, both your suggestions gave the same error as before.

Two things to try...

*

*Add a slash prefix on the substitution string. ie. /office%{REQUEST_URI} and /office/$1 respectively. This changes the substitution string into a URL-path, rather than a relative filesystem path. However, I wouldn't necessarily expect this to make any difference in this respect. (It would be required for an external redirect.)

*Use the END flag instead of L on the RewriteRule directives - this is an Apache 2.4 addition that should halt all processing. The L flag "only" ends the current pass before restarting the rewriting process (hence the need for additional checks to prevent rewrite loops).

But now any other file (IMG, CSS) gives an 404.

The above rewrites everything, so it will naturally rewrite all static resources if they don't already start /office. (If they already start /office then they should already be excluded by the above rules.)
To exclude common resources, you could make an exception (an additional RewriteCond directive) to exclude specific file extensions. For example:
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|gif)$

And/or add an additional RewriteCond directive to exclude requests that already map to physical files (although this is "marginally" more expensive). For example:
RewriteCond %{REQUEST_FILENAME} !-f

Summary:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^office\.example\.com [NC]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|gif)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) office/$1 [END]


text:
Q: Sequelize: Error: Error: Table1 is not associated to Table2 I am trying to create the following associations using sequelize but I keep getting     the following error "Error: Error: customer is not associated to order!". I have bi-directional associations according to what I found in the documentation. I am confused about what the problem could be because when I look into the database tables I can see the foreign keys.  For this example, I am trying to pull the order and customer associated with the particular order.  Technically, I could do three seaprate db pull but that seems inefficient as opposed to joins.
'use strict';

module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    username: DataTypes.STRING(30), //remove
    password: DataTypes.STRING(255),
    emailaddress: DataTypes.STRING(255),
    firstname: DataTypes.STRING(30),
    middlename: DataTypes.STRING(30), //remove
    lastname: DataTypes.STRING(30),
    approve: DataTypes.BOOLEAN,
    roles: DataTypes.STRING(50),
    isactive: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        this.hasMany(models.order);
      }
    }
  });

  user.hook('afterCreate', function(usr, options) {
      //hash the password

      return user.update({ password: passwd }, {
        where: {
          id: usr.id
        }
      });
  });

  return user;
};

'use strict';
module.exports = function(sequelize, DataTypes) {
  var order = sequelize.define('order', {
    ponumber: DataTypes.STRING(30), //remove
    orderdate: DataTypes.DATE,
    shippingmethod: DataTypes.STRING(30),
    shippingterms: DataTypes.STRING(30),
    deliverydate: DataTypes.DATE,
    paymentterms: DataTypes.STRING(30),
    overridediscount: DataTypes.BOOLEAN,
    shippingaddress: DataTypes.STRING(30),
    shippingcity: DataTypes.STRING(30),
    shippingstate: DataTypes.STRING(20),
    shippingzipcode: DataTypes.STRING(10),
    isactive: DataTypes.BOOLEAN
  }, {
      associate: function(models) {
        // associations can be defined here
        this.belongsTo(models.user);
        this.belongsTo(models.customer);
      }
  });

  order.hook('afterCreate', function(ord, options) {
      //generate po number

      return order.update({ ponumber: ponumbr }, {
        where: {
          id: ord.id
        }//,
        //transaction: options.transaction
      });
  });

  return order;
};

'use strict';
module.exports = function(sequelize, DataTypes) {
  var customer = sequelize.define('customer', {
    customernumber: DataTypes.STRING(30), //remove
    customerspecificationid: DataTypes.INTEGER,
    customertypeid: DataTypes.INTEGER,
    sportid: DataTypes.INTEGER,
    customername: DataTypes.STRING(20), //remove
    address: DataTypes.STRING(30),
    city: DataTypes.STRING(30),
    state: DataTypes.STRING(30),
    zipcode: DataTypes.STRING(30),
    ordercomplete: DataTypes.BOOLEAN,
    isactive: DataTypes.BOOLEAN
  }, {
      associate: function(models) {
          // associations can be defined here
        this.hasMany(models.order);
      }
  });

  customer.hook('afterCreate', function(cust, options) {
      //generate the customer number

        return customer.update({ customernumber: custnumber }, {
        where: {
          id: cust.id
        }
      });
  });

  return customer;
};

Here is the constructor and method inside of a repository class I want to join

constructor(model){
    super(model.order);
    this.currentmodel = model;
}

findById(id){
    let that = this;
    return new Promise(
        function(resolve, reject) {
            that.model.find({
                where: { id: id },
                include: [ that.currentmodel.customer, that.currentmodel.user ]
            })
            .then(function(order){
                resolve(order);
            })
            .catch(function(err){
                reject(err);
            })
    });
}

I have reviewed the documentation and searched the internet looking for a fix to this issue but I am not finding any answers.  Could someone please shed some light on what I could be missing?
For the example above, I am trying to retrieve the user and the customer tied to the order record via the primary key.  All of the findBy scenarios I have found so far would be getting a list of orders tied to the customer and user.  What do I need to change in order to retrieve the order and customer whose foreign keys are tied to this order?

A: The problem is probably with how you are setting you association, kindly mention your strategy.
Following is working fine if you use the express index.js file setup and then query http://docs.sequelizejs.com/en/1.7.0/articles/express/
'use strict';
module.exports = function(sequelize, DataTypes) {
  var customer = sequelize.define('customer', {
    customernumber: DataTypes.STRING(30), //remove
    customerspecificationid: DataTypes.INTEGER,
    customertypeid: DataTypes.INTEGER,
    sportid: DataTypes.INTEGER,
    customername: DataTypes.STRING(20), //remove
    address: DataTypes.STRING(30),
    city: DataTypes.STRING(30),
    state: DataTypes.STRING(30),
    zipcode: DataTypes.STRING(30),
    ordercomplete: DataTypes.BOOLEAN,
    isactive: DataTypes.BOOLEAN
  }, {
      associate: function(models) {
          // associations can be defined here
        models.customer.hasMany(models.order);
      }
  });

  customer.hook('afterCreate', function(cust, options) {
      //generate the customer number

        return customer.update({ customernumber: custnumber }, {
        where: {
          id: cust.id
        }
      });
  });

  return customer;
};

'use strict';
module.exports = function(sequelize, DataTypes) {
  var order = sequelize.define('order', {
    ponumber: DataTypes.STRING(30), //remove
    orderdate: DataTypes.DATE,
    shippingmethod: DataTypes.STRING(30),
    shippingterms: DataTypes.STRING(30),
    deliverydate: DataTypes.DATE,
    paymentterms: DataTypes.STRING(30),
    overridediscount: DataTypes.BOOLEAN,
    shippingaddress: DataTypes.STRING(30),
    shippingcity: DataTypes.STRING(30),
    shippingstate: DataTypes.STRING(20),
    shippingzipcode: DataTypes.STRING(10),
    isactive: DataTypes.BOOLEAN
  }, {
      associate: function(models) {
        // associations can be defined here
        models.order.belongsTo(models.user);
        models.order.belongsTo(models.customer);
      }
  });

  order.hook('afterCreate', function(ord, options) {
      //generate po number

      return order.update({ ponumber: ponumbr }, {
        where: {
          id: ord.id
        }//,
        //transaction: options.transaction
      });
  });

  return order;
};

'use strict';

module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    username: DataTypes.STRING(30), //remove
    password: DataTypes.STRING(255),
    emailaddress: DataTypes.STRING(255),
    firstname: DataTypes.STRING(30),
    middlename: DataTypes.STRING(30), //remove
    lastname: DataTypes.STRING(30),
    approve: DataTypes.BOOLEAN,
    roles: DataTypes.STRING(50),
    isactive: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        models.user.hasMany(models.order);
      }
    }
  });

  user.hook('afterCreate', function(usr, options) {
      //hash the password

      return user.update({ password: passwd }, {
        where: {
          id: usr.id
        }
      });
  });

  return user;
};

// index.js file where you shall associate the routes
var fs        = require('fs')
    , path      = require('path')
    , Sequelize = require('sequelize')
    , lodash    = require('lodash')
    , sequelize = new Sequelize('sequelize_test', 'root', 'root')
    , db        = {}

  fs.readdirSync(__dirname)
    .filter(function(file) {
      return (file.indexOf('.') !== 0) && (file !== 'index.js')
    })
    .forEach(function(file) {
      var model = sequelize.import(path.join(__dirname, file))
      db[model.name] = model
    })

  Object.keys(db).forEach(function(modelName) {
    if (db[modelName].options.hasOwnProperty('associate')) {
      db[modelName].options.associate(db)
    }
  })
  // sequelize.sync({force: true})
  module.exports = lodash.extend({
    sequelize: sequelize,
    Sequelize: Sequelize
  }, db)

Put the above db code in respective files in db folder or whatever you like to name it and then you can use your query
var db = require('./db');
db.order.find({
            where: { id: 0 },
            include: [ db.customer, db.user ]
        })
        .then(function(order){
            console.log(order)
        })


text:
Q: Modifying angular.json Angular 6+ to load scripts in index.html correctly I am running an angular project on my computer:
Angular CLI: 7.1.4
Node: 11.6.0
OS: darwin x64
Angular: 7.1.4
I have updated angular from 4.5.5 to 7.1.4.
Now I get the following error in my console in my chrome browser:

9 GET http://localhost:3000/runtime.js net::ERR_ABORTED 404 (Not Found)

So it can't find the script in my index.html (See below)
But when I have a look at my folder in my dev environment I can find the files and the path seems correct too:

![two muppets][1]
My backend is in Node.js and app.js file looks like this:
const express = require('express');

const router = require('./router'),
    templates = require('./views/templates');

// Setup
const app = express();
const port = process.env.PORT || 3000;
router(app);

templates.initSync();

// Start server
app.listen(port, function () {
    console.log('Kommis back-end is running on port', port);
});

// Catch unhandled promise rejections, see
// https://nodejs.org/dist/latest-    v8.x/docs/api/process.html#process_event_unhandledrejection
process.on('unhandledRejection', (err) => {
        console.log(err.stack);
    });

module.exports = app;

This is my index.html file:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Digitaler Tischplan</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.png">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
  <app-root></app-root>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>
</html>

I realized I had to add to the base ref gen/ then it works!

But how can I change the output of the generated angular code so that it works, without modifying it afterward?
I had a look before I did the Angular update the scripts in the index.html file are stated like this:
gen/scriptname.js
Why is it not doing it anymore?
These are my first lines of the angular.json:
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-src": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
         "build": {
           "builder": "@angular-devkit/build-angular:browser",
           "options": {
             "outputPath": "../public/gen/",
             "index": "src/index.html",
             "main": "src/main.ts",
             "tsConfig": "src/tsconfig.app.json",
             "polyfills": "src/polyfills.ts",
              "assets": [
                "src/assets",
                "src/favicon.ico"
             ],
              "styles": [
               "src/css/main.scss"
              ],
              "scripts": []
            },

In order to build the angular application correctly I had to gen/ in the index.html in the angular-src.


text:
Q: Lag function to calculate a value in back day I update the questions with data. I hope it's a proper question.
Please help me.
enter image description herei.stack.imgur.com/NAlpL.png

A: 1) diff  Base diff can do that:
x <- 1:10
c(rep(NA, 4), diff(x, 4))
##  [1] NA NA NA NA  4  4  4  4  4  4

2) collapse::flag
library(collapse)

x - flag(x, 4)
##  [1] NA NA NA NA  4  4  4  4  4  4

3) dplyr::lag  This has the disadvantage that it overwrites base lag in an incompatible way so we exclude it and then specifically access it.
library(dplyr, exclude = c("filter", "lag"))

x <- 1:10
x - dplyr::lag(x, 4)
##  [1] NA NA NA NA  4  4  4  4  4  4


text:
Q: Is it possible to get a direct link to the TAR package file of the latest release of an extension? Everytime I need to download a Magento package, I need to do so via the Connect Marketplace and I then have to copy the URL (key) from there. For example, to download the "Log Viewer" extension, I have to go here:
http://www.magentocommerce.com/magento-connect/log-viewer-1.html
after which I have to copy-paste the key http://connect20.magentocommerce.com/community/Rockwells_LogViewer into my Magento Connect Manager.
Is it possible to get a direct HTTP link to the TAR package of an extension.

A: Freegento provides a service which provides a downloadable archive for Magento Connect extensions: http://freegento.com/ddl-magento-extension.php
Copy and paste the the key Magento Connect Key into the text area and submit the form. It will then provide a link above the text area with which you can download the archive.
Personally, I never use the Magento Downloader (I do not even upload it to the web server). If possible I use Composer, otherwise I use the archive.

A: You should use special URL to download any module from Magento Connect using your favorite browser.
Format of the URL:
http://connect20.magentocommerce.com/community/{PACKAGE NAME}/{VERSION}/{PACKAGE NAME}-{VERSION}.tgz

Example:
For example you want to download the "Facebook Products Tab" module as TGZ (.tar.gz) archive from Magento Connect.

*

*Open Magento Connect page of the module: http://www.magentocommerce.com/magento-connect/facebook-products-tab.html

*Remember last release version number. You can find this information in the  the 'Release Notes' tab.
In our sample last version of the module is "1.1.0".

*Check an Extension key for "Magento Connect 2.0".

For our module the Extension key is:
http://connect20.magentocommerce.com/community/Facebook_Products_Tab

*Configure URL for downloading and open it in your browser: http://connect20.magentocommerce.com/community/Facebook_Products_Tab/1.1.0/Facebook_Products_Tab-1.1.0.tgz
You will see standard download window in your browser.


text: Q: Execute program after receiving webhook I have to update two ticketing systems and make sure that when one its updated the other one is as well (Zendesk and Cherwell) , I plan on using ngrok running locally on the company server to recieve the webhooks. Then execute a script in to add a ticket with the recieved information in the other platform. What would I use as trigger to execute this script?


text:
Q: Quero colocar dentro de um ARRAY já existente as informações de um arquivo de texto .TXT com PHP A ideia e fazer a tradução de um sistema em PHP, onde cada chave do ARRAY é uma tradução.
De forma manual eu já consegui retirar todas as chaves e traduzir elas, separar cada chave traduzida em uma linha, colocando todas em um arquivo de texto.txt, agora quero colocar essas linhas já traduzidas dentro do ARRAY como VALOR, puxando automaticamente do arquivo de texto.txt
Ex:
<?php
$lang["CHAVE"] ="VALOR";
?>

Parte do código é esse:
<?php
$lang["Signup"]              ="";
$lang["Sign In"]             ="";
$lang['Login Successful']    ='';
?>

Tem que ficar assim:
<?php
$lang["Signup"]              ="Inscrição";
$lang["Sign In"]             ="Entrar";
$lang['Login Successful']    ="Login com êxito";
?:>

Esse arquivo tem mais de 2600 linhas, todas nesse padrão, por isso quero automatizar esse trabalho, tem mais arquivos como esse para fazer.
Reparei que ainda tem muitos scripts em PHP que utilizam essa forma de tradução, seria interessante montar um script para fazer esse trabalho automatizado.
Arquivo texto.txt
Inscrição
Entrar
Login com êxito

A: Embora eu entenda ser uma péssima lógica a proposta pela pergunta, acho que isto soluciona a questão:
$lang = ['Signup', 'Sign in', 'Login successfull'];

foreach ($lang as $key => $value) {
    $txt = trim(fgets($file_handle))
    $lang[$key] = $txt;
}

Note que omiti o código de abertura/fechamento do arquivo de texto (que poderá ser feito por fopen() e fclose().
Também assumi que o arquivo texto não possui linhas em branco no ínicio e no meio das traduções.


text:
Q: "System program problem detected" with apport-gpu-error-intel.py My Ubuntu 12.10 was working fine, until a week ago when a software update was installed.
Now, every two minutes, the computer hangs for a couple of seconds, and then an error message pops up saying "System program problem detected." Upon click "Show details", it shows that this is a problem with a file named apport-gpu-error-intel.py in /usr/share/apport/. How can I stop this from happening?

A: I've recently had the same problem on Ubuntu 12.04LTS. It appears this confirmed regression bug:
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1140716 affecting Sandy Bridge Intel Processors (e.g. my i5-2410M with onboard-graphics).
I used the synaptic packager manager to remove the package
 xserver-xorg-core-lts-quantal and install the package xserver-xorg-core 2:1.11.4-0ubuntu10.12.
Also removed xserver-xorg-video-intel-lts-quantal and installed xserver-xorg-video-intel 2:2.17.0-1ubuntu4.3.
So far, this workaround seems to have solved the problem.

A: I also have this issue and I know I need to replace my thermal paste on my i7 and ATI/AMD GPU. I think I have my ATI turned off and so I think I'm just using my intel one.  I recently cleaned out the fluff in my laptops heatsink.  I had been meaning to clean it out for a while and my system froze and the GPU dialogue came up the next time I restarted.  My laptop had also just been a bit wet from rain.
I opened it and cleaned the heatsink etc looking for any water, I didn't find any but I cleared all sorts of dust out.
My test will be after I've replaced the thermal paste as there should be no hardware/heat issues.
I've never had heat issues with my Sony Vaio, previously, I had an AMD HP which would get quite hot but was ok, there are many HPs with heat issues, especially the GPU.  The chip does not directly touch the heatsink as there is a thermal pad.  The GPU temp is not monitored and so it gets too hot and eventually stresses the solder joints underneath and they fracture causing screen flickering etc at moderate temperatures.  This is fixed by heating up the chip enough to melt the solder properly and then adding aluminium foil or extra copper to the heatsink etc to get proper heat conduction.
So my point is that while it may be a software bug, it could be an indication of a hardware issue, I have killed my flash plugin and not experienced the hang warning for a few days now as I either suspend or hibernate my system for the last few days so the plugin generally stays killed and my fan is not going full on like it was before.

A: I face a similar issue intermittently. What happens is that there is a single error message in the log, which is read again and again and causes the error message to pop up. I solve it by typing this into the terminal:
sudo rm /var/crash/*

To remove old crashes and the problem seems to be solved.


text:
Q: MAC: Remote Desktop Connection - take over session of active user on client I am new to RDP, hence not entirely sure if this is the desired behaviour or not.
I am using RDP on my MAC to connect to clients throughout the office and do minor maintenance on them. Today I noticed that the moment I login via RDP, the currently active user on this machine gets logged off and directed to the Windows 10 Login screen, while RDP starts a new "login" for me where I can control the computer and do what is needed without the user sitting in front of the PC actually seeing what's happening.
Is it possible that instead of logging out the user and keeping him/her at the login screen, I could simply take over the current session running on the PC? I am thinking along the lines of Teamviewer, where the user can see me moving the mouse, clicking on folders, etc. Basically a real "remote control" session if you so want.
Is this achievable via RDP or should I just stick to Teamviewer?
Thanks


text:
Q: SQL function to change the column format I have a staging table with a column LastAnalysisAmount (varchar data type) which contains values like this:
LastAnalysisAmount
-------------------
    0000000.00
    0000114.77-
    0000367.78
    0290367.45
    0090367.26-

This column holds both positive and negative numbers. I need to convert this LastAnalysisAmount column values into decimal with correct format and load this into destination table.
For example, in the destination table, the values should be
     0.00
  -114.77
   367.78
290367.45
-90367.26

Can you please help me to write a SQL function to do this conversion?
Thank you for your help and time.

A: You can do like this to load on Destination Table
INSERT INTO dest_table (LastAnalysisAmount)
SELECT CAST(CASE WHEN RIGHT(LastAnalysisAmount,1) = '-'
                 THEN '-' + REPLACE(LTRIM(LastAnalysisAmount),'-','')
                 ELSE LTRIM(LastAnalysisAmount)
             END AS decimal(10,2))
FROM from_table

A: Try this : This will handle negative value case and convert it into DECIMAL(8,2)
SELECT CAST(
        CASE WHEN CHARINDEX('-',LastAnalysisAmount) > 0
             THEN STUFF(LEFT(LastAnalysisAmount,LEN(LastAnalysisAmount)-1),1,0,'-')
             ELSE LastAnalysisAmount
             END AS DECIMAL(8,2)
         ) AS LastAnalysisAmount

A: You can do this using varchar() with a case sttaement:
select (case when LastAnalysisAmount like '%-'
             then '-' + replace(LastAnalysisAmount, '-', '')
             else LastAnalysisAmount
        end) as LastAnalysisAmount

If you want to send the data as a decimal, you can cast this to the appropriate type.

A: You can use REPLACE() and TRIM() with CASE EXPRESSION :
SELECT CASE WHEN LastAnalysisAmount LIKE '%-'
            THEN '-' + REPLACE(LTRIM(LastAnalysisAmount),'-','')
            ELSE LTRIM(LastAnalysisAmount)
        END as LastAnalysisAmount
FROM YourTable

To load it as decimal to destination table:
INSERT INTO Destination_Table (LastAnalysisAmount)
SELECT CAST(CASE WHEN LastAnalysisAmount LIKE '%-'
                 THEN '-' + REPLACE(LTRIM(LastAnalysisAmount),'-','')
                 ELSE LTRIM(LastAnalysisAmount)
             END AS decimal(10,2))
FROM YourTable


text:
Q: Microsoft XPS Document writer v4 Printing a PrintDocument to file using Microsoft XPS Document Writer in Windows 10 always throw exception 'The handle is invalid'. But in Windows 7 it is working perfectly.
The error throws when the PrinterSettings changed to custom page size. No error when printed without changing the PrinterSettings.
Could anyone explain how to overcome this issue in C# Windows Forms application executed in Windows 10?

A: SORRY FOR THE TROUBLE I MADE.
The error was related to a minor error in calculating the page height and width. I passed value slightly lower than the actual page height and width.
Conclusion
In windows 7 minor variations in page settings will not affect the actual print, but in Windows 10 and Windows Server 2012, the page settings must be accurate.


text:
Q: How to pass value of selectoption to the standardsetcontroller I have a selectoption and I am trying to pass the value of the itemValue attribute to the standardsetcontroller in order to return query results based on the itemValue. I have the default selection set to 'e' which returns the expected result. But when a different selectOption value is selected, the page doesn't reRender to produce the new resultset based on the change. Below is my apex and visualforce markup :
public with sharing class cases {

// Variables required for Sorting.
    public String temp {get; set;}
    public list<case> temp1 {get; set;}
    public id uid;
    public id creator;
    public id actid;
    public String soql {get;set;}
    public List <case> caseList1 = New List <case>();

public List <case> caseList2 = New List <case>();

// Constructor
public cases(){
    this.uid = UserInfo.getUserid();
    this.actid = [select accountid from user where id = :uid][0].accountid;

     if (temp != null){
         this.temp = temp;
         System.debug('selected temp is :' + this.temp);
     }else{
        this.temp = 'e';
    }

    getCaseList2();

}

            public pageReference getCaseList2(){
                  this.temp = temp;
                  getCaseList();
                  return null;
            }

            // Method for list display
            public List<case> getCaseList() {

                return con.getRecords();
            }

            // instantiate the StandardSetController from a query locator
            public ApexPages.StandardSetController con {
                get {

                                            if(con == null && this.temp == 'a') {
                                                            // String Query to have a list of cases for a respective End-user.
                                                            soql = ''+ 'SELECT'+ ' CreatedById,' + ' AccountId,' + ' OwnerId,' + ' Id,' + ' CaseNumber,' + ' CreatedDate,' + ' Requested_By__c,' + ' Subject,' + ' Release_Type__c,' + ' Status,' + ' Priority,' + ' Major_Release_Version__c,' + ' type' + ' From Case';
                                                            System.debug('temp a is: ' + temp);
                                                            // Passing the String array to a list with Selected field sorting.
                                                            caseList1 = Database.query(soql + ' AccountId = :actid and status = \'Closed\' ' );

                                                            // setting values of List in StandardSetController.
                                                            con = new ApexPages.StandardSetController(caseList1);
                                                            system.debug(con);
                                                            // sets the number of records in each page set
                                                            con.setPageSize(20);
                                            }
                                            else if(con == null && temp == 'b') {
                                                            // String Query to have a list of cases for a respective End-user.
                                                            soql = ''+ 'SELECT'+ ' CreatedById,' + ' AccountId,' + ' OwnerId,' + ' Id,' + ' CaseNumber,' + ' CreatedDate,' + ' Requested_By__c,' + ' Subject,' + ' Release_Type__c,' + ' Status,' + ' Priority,' + ' Major_Release_Version__c,' + ' type' + ' From Case';
                                                            System.debug('temp b is: ' + temp);
                                                            // Passing the String array to a list with Selected field sorting.
                                                            caseList1 = Database.query(soql + ' AccountId = :actid and status != \'Closed\' ');

                                                            // setting values of List in StandardSetController.
                                                            con = new ApexPages.StandardSetController(caseList1);

                                                            // sets the number of records in each page set
                                                            con.setPageSize(20);

                                                            }else if(con == null && temp == 'e') {
                                                            // String Query to have a list of cases for a respective End-user.
                                                            soql = ''+ 'SELECT'+ ' CreatedById,' + ' AccountId,' + ' OwnerId,' + ' Id,' + ' CaseNumber,' + ' CreatedDate,' + ' Requested_By__c,' + ' Subject,' + ' Release_Type__c,' + ' Status,' + ' Priority,' + ' Major_Release_Version__c,' + ' type' + ' From Case';
                                                            System.debug('temp e is: ' + temp);
                                                            // Passing the String array to a list with Selected field sorting.
                                                            caseList1 = Database.query(soql + ' order by ' + sortField + ' ' + sortDir );

                                                            // setting values of List in StandardSetController.
                                                            con = new ApexPages.StandardSetController(caseList1);

                                                            // sets the number of records in each page set
                                                            con.setPageSize(20);
                                            }
                                            return con;
        }
        set;
    }
}

Visualforce markup
 <apex:page controller="cases">

    <apex:form id="form">
    <apex:selectList id="selected_list" value="{!temp}" required="false" size="1">
        <apex:selectOption itemvalue="a" itemLabel="All Closed Cases"/>
        <apex:selectOption itemvalue="b" itemLabel="All Open Case"/>
        <apex:selectOption itemvalue="e" itemLabel="Recently Viewed Cases" />
        <apex:actionSupport event="onchange" reRender="pgblock" action="{!getCaseList2}" oncomplete="getCaseList2();">

        </apex:actionSupport>
    </apex:selectList>

<apex:pageBlock id="pgblock" >
    <apex:pageBlockSection title="Case Details
        <apex:pageBlockTable value="{!CaseList}" var="CaseList" >

                <apex:column >
                    <apex:facet name="header">
                       <apex:commandLink value="Case Number" action="{!toggleSort}" rerender="pgblock">

                            <apex:param name="sortField" value="CaseNumber" assignTo="{!sortField}"/>
                       </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!CaseList.CaseNumber}"/>
                </apex:column>

                <apex:column >
                    <apex:facet name="header">
                       <apex:commandLink value="Created Date" action="{!toggleSort}" rerender="pgblock">

                            <apex:param name="sortField" value="CreatedDate" assignTo="{!sortField}"/>
                       </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!CaseList.CreatedDate}"/>
                </apex:column>
    </apex:pageBlockTable>
</apex:pageBlockSection>
</apex:form>

Thanks for any suggestions.

A: Change you page to :
<apex:page controller="cases">

    <apex:form id="form">
    <apex:selectList id="selected_list" value="{!temp}" required="false" size="1">
        <apex:selectOptions value="{!items}"/>
    </apex:selectList>

<apex:pageBlock id="pgblock" >
    <apex:pageBlockSection title="Case Details
        <apex:pageBlockTable value="{!CaseList}" var="CaseList" >

                <apex:column >
                    <apex:facet name="header">
                       <apex:commandLink value="Case Number" action="{!toggleSort}" rerender="pgblock">

                            <apex:param name="sortField" value="CaseNumber" assignTo="{!sortField}"/>
                       </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!CaseList.CaseNumber}"/>
                </apex:column>

                <apex:column >
                    <apex:facet name="header">
                       <apex:commandLink value="Created Date" action="{!toggleSort}" rerender="pgblock">

                            <apex:param name="sortField" value="CreatedDate" assignTo="{!sortField}"/>
                       </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!CaseList.CreatedDate}"/>
                </apex:column>
    </apex:pageBlockTable>
</apex:pageBlockSection>
</apex:form>

Controller: When you see the system.debug statements you should the temp value to be the value you choose. Adjust your SOQL accordingly in the code.
public with sharing class cases {

// Variables required for Sorting.
    public String temp {get; set;}
    public list<case> temp1 {get; set;}
    public id uid;
    public id creator;
    public id actid;
    public String soql {get;set;}
    public List <case> caseList1 = New List <case>();
public List <case> caseList2 = New List <case>();

// Constructor
public cases(){
    this.uid = UserInfo.getUserid();
    this.actid = [select accountid from user where id = :uid][0].accountid;
    getCaseList2();
}
            public List<SelectOption> getItems() {
                List<SelectOption> options = new List<SelectOption>();
                options.add(new SelectOption('a','a'));
                options.add(new SelectOption('b','b'));
                options.add(new SelectOption('c','c'));
            return options;
            }
            public pageReference getCaseList2(){
                  this.temp = temp;
                  getCaseList();
                  return null;
            }

            // Method for list display
            public List<case> getCaseList() {

                return con.getRecords();
            }

            // instantiate the StandardSetController from a query locator
            public ApexPages.StandardSetController con {
                get {

                                            if(con == null && this.temp == 'a') {
                                                            // String Query to have a list of cases for a respective End-user.
                                                            soql = ''+ 'SELECT'+ ' CreatedById,' + ' AccountId,' + ' OwnerId,' + ' Id,' + ' CaseNumber,' + ' CreatedDate,' + ' Requested_By__c,' + ' Subject,' + ' Release_Type__c,' + ' Status,' + ' Priority,' + ' Major_Release_Version__c,' + ' type' + ' From Case';
                                                            System.debug('temp a is: ' + temp);
                                                            // Passing the String array to a list with Selected field sorting.
                                                            caseList1 = Database.query(soql + ' AccountId = :actid and status = \'Closed\' ' );

                                                            // setting values of List in StandardSetController.
                                                            con = new ApexPages.StandardSetController(caseList1);
                                                            system.debug(con);
                                                            // sets the number of records in each page set
                                                            con.setPageSize(20);
                                            }
                                            else if(con == null && temp == 'b') {
                                                            // String Query to have a list of cases for a respective End-user.
                                                            soql = ''+ 'SELECT'+ ' CreatedById,' + ' AccountId,' + ' OwnerId,' + ' Id,' + ' CaseNumber,' + ' CreatedDate,' + ' Requested_By__c,' + ' Subject,' + ' Release_Type__c,' + ' Status,' + ' Priority,' + ' Major_Release_Version__c,' + ' type' + ' From Case';
                                                            System.debug('temp b is: ' + temp);
                                                            // Passing the String array to a list with Selected field sorting.
                                                            caseList1 = Database.query(soql + ' AccountId = :actid and status != \'Closed\' ');

                                                            // setting values of List in StandardSetController.
                                                            con = new ApexPages.StandardSetController(caseList1);

                                                            // sets the number of records in each page set
                                                            con.setPageSize(20);

                                                            }else if(con == null && temp == 'e') {
                                                            // String Query to have a list of cases for a respective End-user.
                                                            soql = ''+ 'SELECT'+ ' CreatedById,' + ' AccountId,' + ' OwnerId,' + ' Id,' + ' CaseNumber,' + ' CreatedDate,' + ' Requested_By__c,' + ' Subject,' + ' Release_Type__c,' + ' Status,' + ' Priority,' + ' Major_Release_Version__c,' + ' type' + ' From Case';
                                                            System.debug('temp e is: ' + temp);
                                                            // Passing the String array to a list with Selected field sorting.
                                                            caseList1 = Database.query(soql + ' order by ' + sortField + ' ' + sortDir );

                                                            // setting values of List in StandardSetController.
                                                            con = new ApexPages.StandardSetController(caseList1);

                                                            // sets the number of records in each page set
                                                            con.setPageSize(20);
                                            }
                                            return con;
        }
        set;
    }
}

A: I finally discovered what the issue was with my code. There was no reason for me to check for "if (con == null) as when the page loads it already displays the values based on the default selectoption. Hence I only needed to check for the value of "temp".


text:
Q: Taking variance of some rows above in panel structrure (R data table ) # Example of a panel data
library(data.table)
panel<-data.table(expand.grid(Year=c(2017:2020),Individual=c("A","B","C")))
panel$value<-rnorm(nrow(panel),10) # The value I am interested in

I want to take the variance of prior two years value by Individual.
For example, if I were to sum the value of prior two years I would do something like:
panel[,sum_of_past_2_years:=shift(value)+shift(value, 2),Individual]

I thought this would work.
panel[,var(c(shift(value),shift(value, 2))),Individual]
# This doesn't work of course

Ideally the answer should look like
a<-c(NA,NA,var(panel$value[1:2]),var(panel$value[2:3]))
b<-c(NA,NA,var(panel$value[5:6]),var(panel$value[6:7]))
c<-c(NA,NA,var(panel$value[9:10]),var(panel$value[10:11]))
panel[,variance_past_2_years:=c(a,b,c)]
# NAs when there is no value for 2 prior years

A: You can use frollapply to perform rolling operation of every 2 values.
library(data.table)
panel[, var := frollapply(shift(value), 2, var), Individual]

#    Year Individual     value        var
# 1: 2017          A  9.416218         NA
# 2: 2018          A  8.424868         NA
# 3: 2019          A  8.743061 0.49138739
# 4: 2020          A  9.489386 0.05062333
# 5: 2017          B 10.102086         NA
# 6: 2018          B  8.674827         NA
# 7: 2019          B 10.708943 1.01853361
# 8: 2020          B 11.828768 2.06881272
# 9: 2017          C 10.124349         NA
#10: 2018          C  9.024261         NA
#11: 2019          C 10.677998 0.60509700
#12: 2020          C 10.397105 1.36742220


text:
Q: Enhance WSDL presentation with XSLT for wsdl which generates on the fly I developed a small web service using JAX-WS. Now I need to add XSL to enhance WSDL presentation. I've found a great solution for this - http://tomi.vanek.sk/index.php?page=wsdl-viewer , but the problem is that my wsdl file is generating on the fly so I cannot add stylesheet directly to my wsdl. Is there some solution for this?

A: You can store your WSDL file in WEB-INF/wsdl  and  specify its path in your "sun-jaxws.xml" file
<?xml version="1.0" encoding="UTF-8"?>
    <endpoints
     xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
     version="2.0">
       <endpoint
     name="fromwsdl"
     interface="fromwsdl.server.AddNumbersPortType"
     implementation="fromwsdl.server.AddNumbersImpl"
     wsdl="WEB-INF/wsdl/AddNumbers.wsdl"
     service="{http://duke.example.org}AddNumbersService"
     port="{http://duke.example.org}AddNumbersPort"
     url-pattern="/addnumbers" />
    </endpoints>

Plz check below URL for WAR structure
https://jax-ws.java.net/nonav/2.2.1/docs/UsersGuide.html#1.0_Introduction


text:
Q: Regex for removing Commas within brackets I am stuck at writing the regex which needs me to remove comma inside brackets. The commas outside should stay as is
Here's what I need
Input :(37.400809377128354, -122.05618455969392) , (37.3931723332768, -121.89276292883454)
Output :(37.400809377128354 -122.05618455969392) , (37.3931723332768 -121.89276292883454)
Thanks in Advance!

A: You can use this regex which uses positive look ahead to discard matching a comma that is outside the parenthesis,
,(?=[^()]*\))

Demo

var s = "(37.400809377128354, -122.05618455969392),(37.3931723332768, -121.89276292883454)";
console.log(s.replace(/,(?=[^()]*\))/g, ''));

A: ES '18 Solution using Look-behind Assertions

const s = "(37.400809377128354, -122.05618455969392),(37.3931723332768, -121.89276292883454)";

console.log(
    s.replace(/(?<=\d),/g, '')
);

ECMAScript® 2018 Language Specification


text:
Q: I want Staffuser in Django not to see any superusers Right now i have applied this code
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class MyUserAdmin(UserAdmin):
    def get_fieldsets(self,request,obj=None):
        if not obj:
            return self.add_fieldsets

        if request.user.is_superuser:
            perm_fields = ('is_active','is_staff','is_superuser','groups','user_permissions')

            return [(None, {'fields': ('email', 'password')}),
                    ('Personal info', {'fields': ('first_name', 'last_name')}),
                    ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
                    ('Important dates', {'fields': ('last_login', 'date_joined')}),
                    ('Contact info', {'fields': ('contact_no',)})]
        else:
            perm_fields = ('is_active','is_staff')

            return [(('Creds'),{'fields':('username','password')}),
                    (('Personal info'),{'fields':('first_name','last_name','email')})]

admin.site.unregister(User)
admin.site.register(User,MyUserAdmin)

Here all the staff user are able to see superuser when i am logged in as staffuser

But I want that the staffuser wont be able to see any superuser.
so in this case staffuser can only view 1 user which is "new"
and "admin" user which is superuser, should be hidden
How can i do that ?

A: You need to override get_queryset method:
 def get_queryset(self, request):
        qs = super(MyUserAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs

        return qs.filter(is_superuser=False)


text:
Q: gunicorn returns same pid for different worker process I'm trying to get a better understanding of how gunicorn manages its processes so I wrote the following code:
from fastapi import FastAPI
import os
from time import sleep

app = FastAPI()
sleep_time = [5, 0]
global_var = 100
order_called = 0

@app.get('/test')
def test_handler():
    global global_var, order_called
    order_called += 1
    local_order_called = order_called
    sleep(sleep_time[order_called - 1]) # doing some time consuming stuff here
    global_var += 1
    return {"test": os.getpid(), "global_var": global_var, "order called": local_order_called}

And I started gunicorn with:
gunicorn -w 2 -k uvicorn.workers.UvicornWorker server:app --preload

The server is supposed to output: pid, 102, 1 and pid, 101, 2 for two consecutive requests - because it takes more time for worker #1 to finish.
I'm getting the correct output, but somehow the two pids returned are the same, which is very strange - this happens with or without the --preload.
Anyone can shed some lights on this? Thanks!

A: What makes you think the server should produce multiple PIDs? I don't see anything here that would fork another process. os.getpid() will return the same value each time if called by the server. Hope that helps!


text:
Q: Scala: For Comprehension compile error (newbie question) I am getting a type mismatch compile error for the following code:
  case class MyClass(name: String)
  def getMyClass(id : String) = {
      //For now ignore the id field
      Some(Seq(MyClass("test1"), MyClass("test2"), MyClass("test3"), MyClass("test4"), MyClass("test5")))
  }

  def getHeader() = {
    Map(
      "n" -> List(Map("s"->"t"), Map("s"->"t"), Map("s"->"t")),
      "o" -> List(Map("s"->"t"), Map("s"->"t"), Map("s"->"t")),
      "id" -> "12345"
    )
  }
  def castToString(any: Option[Any]): Option[String] = {
    any match {
      case Some(value: String) => Some(value)
      case _ => None
    }
  }

  val h = getHeader()

  for{
    id <- castToString(h.get("id")) //I hate I have to do this but the map is a Map[String,Any]
    m <- getMyClass(id)  //This strips the Some from the Some(Seq[MyClass])
    item <- m     //XXXXXXXX Compile errors
    oList <- h.get("o")
    nList <- h.get("n")

  } yield {
    (oList, nList, item)
  }

The error is:
C:\temp\s.scala:28: error: type mismatch;
 found   : Seq[(java.lang.Object, java.lang.Object, this.MyClass)]
 required: Option[?]
        item <- m
             ^

But m is of type Seq[MyClass].   I am trying to iterate through the list and set item

A: You can't mix container types in this way, specifically given the signature of Option.flatMap (to which this expression is desugared - see the comment by pst). However, there's a pretty easy solution:
for{
  id <- castToString(h.get("id")).toSeq
  m <- getMyClass(id).toSeq
  oList <- h.get("o")
  nList <- h.get("n")
} yield {
  (oList, nList, item)
}

A: A better explanation of why the code you mentioned doesnt work can be found here:
What is Scala's yield?
You could change your code to the one Kris posted.


text:
Q: How to store 100000 rows and 100000 columns values (as a result of computation) in a cell array Matlab I am currently working on a sparse matrix 'A' of 100000 rows and 100000 columns.
I am trying to use this to calculate the shortest path between all the nodes using the graphshortestpath function.
I need to store the path for each and every node in an variable for later computation.
Currently for smaller set of data, I am able to achieve this using these set of commands
pathoutput=cell(70,70);
for i=1:70
    for j=1:70
        [dist1,path1,pred1]=graphshortestpath(A,i,j,'Method','Bellman-Ford');
        pathoutput{i,j}=path1;
        save('test.mat','pathoutput');
        disp(pathoutput);
    end
end

Suppose if in my results for path, for node 1 it is only the value 7 and in other it is [723 6 1 2025], how can I save this result of 100000 rows and 100000 columns?
However,Cell array does not seem to support such a huge data.
If I set pathoutput=cell(100000,100000)I am getting an error message.
Error using cell Maximum variable size allowed by the program is exceeded.
Could you suggest an alternative way to achieve this.
Thank you.

A: You may use matfile function to read/write your data directly in a file. The 100 GB is therefore managed by your hard drive and not your RAM.
Here is some code that shows how to read, write and append cells.
A = {1:3, 2, 0
     0  , 5, 8};
save('A.mat', 'A','-v7.3');
clear A

matObj = matfile('A.mat','Writable',true);
matObj.A(1,2) = {[2 2]};       %modify one cell
matObj.A(3,3) = {[10 10 10]};  %append one isolated cell  => creates empty cells
matObj.A(4,:) = {1, 1, 2};     %append a full row

disp(matObj.A)

This gives
A =

    [1x3 double]    [2]    [0]
    [         0]    [5]    [8]

matObj.A =

    [1x3 double]    [1x2 double]    [         0]
    [         0]    [         5]    [         8]
              []              []    [1x3 double]
    [         1]    [         1]    [         2]

Reading is performed this way
%read
matObj = matfile('A.mat');
loadedData = matObj.A(1,1);

It gives

loadedData =
[1x3 double]


text:
Q: how to add application/wasm mime type on debian localhost I need to attach application/wasm mime type on my debian localhost.For now firefox 59 doesn't allow me use webassembly examples giving me error in dev console

TypeError: Response has unsupported MIME type

I remember that mime types are placed under /usr/share/mime*..
I tried to add alias application/wasm wasm but it doesn't help.
Advice will be appreciated.

A: Found a workaround :

*

*Flatten  previously downloaded webassembly studio project

*Launch localserver with python3 -m http.server   (it has application/wasm support)


text:
Q: create a connector to a smarthost that requires authentication on exchange online Can you create a connector to a smarthost that requires authentication on Exchange Online? I looked at the documentation for New-OutboundConnector, and I don't see a place to set the authentication credentials.

A: Yes, I don't know this setting, but we can use TLS :
https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/use-connectors-to-configure-mail-flow/set-up-connectors-for-secure-mail-flow-with-a-partner
May I know the function of this smart host? for filtering spam and malware or archiving or auditing?
You could refer to the following article:
Manage mail flow using a third-party cloud service with Exchange Online
https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/manage-mail-flow-using-third-party-cloud


text:
Q: NULL values returned by pivot I have a dataset like the one below (first column created using ROW_NUMNBER OVER PARTITION):
RNEEAN  NEEAN    GFCUS  SCSAC
NEAN1   9432806  94328  GE
NEAN2   9432807  94328  GE
NEAN3   94328472 94328  ES
NEAN4   9432848  94328  ES
NEAN5   9432875  94328  HK
NEAN6   9432876  94328  HK
NEAN7   9432877  94328  HK
NEAN8   9432878  94328  HK
NEAN9   9432879  94328  HK

I can get this dataset with the below query:
select RNEEAN, NEEAN, GFCUS, SCSAC from #tmp where GFCUS=094328

Now I want to pivot the column NEEAN by RNEEAN so I tried the below:
SELECT MAX([NEEAN1]) [NEEAN1],MAX([NEEAN2]) [NEEAN2],MAX([NEEAN3]) [NEEAN3],
MAX([NEEAN4]) [NEEAN4], MAX([NEEAN5]) [NEEAN5],MAX([NEEAN6]) [NEEAN6],MAX([NEEAN7]    [NEEAN7], MAX([NEEAN8])  [NEEAN8], MAX([NEEAN9]) [NEEAN9], GFCUS
from #tmp
PIVOT(
    min(NEEAN) for RNEEAN in ([NEEAN1],[NEEAN2],[NEEAN3],[NEEAN4],[NEEAN5],[NEEAN6],  [NEEAN7],[NEEAN8],[NEEAN9])
) p1
where GFCUS=094328
GROUP BY GFCUS

But all I get is 9 NULL columns and the GFCUS value.
Where am I going wrong or missing something please?

A: The problem is with your RNEEAN names and then the column names you are using in the PIVOT.
The RNEEAN column contains data that starts with NEAN but then you are attempting to pivot values with a name of NEEAN - if the column names don't match then you will return null.
Using your data above, you'd have to use:
select GFCUS, SCSAC,
  NEAN1, NEAN2, NEAN3, NEAN4, NEAN5, NEAN6, NEAN7, NEAN8, NEAN9
from
(
  select RNEEAN, NEEAN, GFCUS, SCSAC
  from yourtable
) d
pivot
(
  min(NEEAN)
  for RNEEAN IN (NEAN1, NEAN2, NEAN3, NEAN4, NEAN5, NEAN6, NEAN7, NEAN8, NEAN9)
) piv;

See Demo


text:
Q: Creating simple document with JDOM I am trying to create a simple Document with Jdom.
I strictly followed the instructions given on
https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm
I cannot understand why, no matter what I do, I end up with a [document:null].
This is my code :
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.*;
import org.jdom2.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Network {

    public Document SetToXml() throws Exception {
        Document doc = null;
        try {
            DocumentBuilderFactory DBF =
            DocumentBuilderFactory.newInstance();
            DocumentBuilder DB = DBF.newDocumentBuilder();
            doc = DB.newDocument();

            Element root = doc.createElement("network");
            root.setAttribute("name", Name);
            doc.appendChild(root);
        }
    }
}

When I inspect the doc variable, it always contains [document:null].
Is there any way out or should I give up ?
Thanks

A: I would say, no need to worry :)
The "[document:null]" string which your debugger is showing you is only the toString() - representation of the document object. I do not yet understand, why it actually looks like this, but I verified that regardless of this, the document actually has the "netwrok" element you specified and also the name attribute you are assigning to it.


text:
Q: How to replace tags with a javascript function from beginning to end? Here is my problem, while using the replace javascript function in order to replace html tags with BBcode tags, I encountered this issue:
What I wanted:
[b]Some text[/b], with some [b]other text[/b].

What I've got:
[b]Some text, with some other text[/b].

This is basically the way I wrote this:
mystring.replace(new RegExp('(.*)','gi'),'[b]$1[/b]');

I know that with that example I could simply replace it this way:
mystring.replace('','[b]').replace('','[/b]');

But the thing is that I want to use it with some divs with a specific ID... If I were to do this by replacing opening and ending tags separately, then I wouldn't be able to replace the '
' properly.
Is there a way to have this function run through the string "linearly", from beginning to end, rather than from the extremities towards the center ? (My biggest problem is really that I am not able to formulate this question properly, hence the lack of results while searching the web.)
Thank you for any input you may provide.


text:
Q: "must be str, not bytes" I wrote a server on python:
import  socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))

server_socket.listen(1)

(client_socket, client_address) = server_socket.accept()

client_name = client_socket.recv(1024)
client_socket.send('Hello ' + client_name)

client_socket.close()
server_socket.close()

And, I wrote a client:
import socket

my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))

my_socket.send('Sami')
data = my_socket.recv(1024)
print('The server sent: ' + data)

my_socket.close()

But when I run the codes, in the server I get the error: "must be str, not bytes" and in the client I get the error: "a bytes-like object is required, not 'str'".

A: Use encode/decode to convert between str and bytes before sending and after receiving:
my_socket.send('Sami'.encode('utf-8'))  # encode string before sending
data = my_socket.recv(1024).decode('utf-8')  # decode string after receiving

You can replace 'utf-8' with other character encodings depending on your use case (you might see 'cp1252' used in Windows applications, for instance).
For the server, rather than decoding the string and encoding it again after putting 'Hello ' on the front, you can skip a step and do this:
client_name = client_socket.recv(1024)
client_socket.send(b'Hello ' + client_name)

b'Hello' is a literal bytes object, rather than a str object like 'Hello'. So b'Hello' + client_name will do bytes + bytes = bytes directly, rather than converting client_name to str with .decode, adding 'Hello' to get another str and then converting back to bytes with .encode.

A: You need to encode before sending a string. Example:
mySocket.send("Hello".encode() + Client_name.encode())

Or:
mySocket.send(b"Hello" + Client_name.encode())


text:
Q: How to write a python script that does the same thing as this postman request Need to make a request call to upload an image, this is a form-data with not just image
I have tried several ways to mimic the request in the postman image, mostly are different ways to create a data dictionary and put that in the post request
def uploadimage():

    datain = {
        "file": open('test.png','rb').read(),
        "use": "logoGroup-staging",
        "logoGroup": {"_id": "5d42145db3ef8c0031128763", "name":"sstimagetest2", "longName": "sss",
                           "createdAt": "2019-07-31T22:21:17.680Z", "updatedAt": "2019-07-31T22:21:17.680Z", "__v": 0},
        "imageType": {"_id":"5cfeb4703509f72b616bf7b6","name":"colorhybridnw","__v":0,"createdAt":"2019-06-10T19:50:08.928Z","height":"0","type":"Manual","updatedAt":"2019-06-10T19:50:08.928Z","width":"0"}
    }

    response = requests.post(
        'https://xxxxxxxxxx/api/upload',
        data = datain
    )

in all my tries, it can conclude to 3 error categories, wrong python data format(not able to run) , 400 bad request call, 502 bad gateway call

A: import requests

files = {'file': open('test.png','rb').read()}
datain = {'all': 'other', 'data': 'not', 'file': 'upload'}

r = requests.post(url, files=files, data=datain)

And requests with take care of the multi-part form POST.


text:
Q: pivot running total in reverse order I have a pivot table where I want to preserve the order of the columns, but show a running total in reverse order (i.e. the values decrease over time).
I know I can reverse the order of the columns and set up a running total, or create a separate report that references the pivot table, but I'm interested to know if it can be done within the pivot table itself keeping Months Since in ascending order (maybe using a calculated field).  Below is the pivot table I have and the one that I want

A: You could add a calculated field in the pivot:

The field YTD is calculated as such:
In D2 cell insert (change are probably needed to fit to your table):
=SUMIFS($C$2:$C$16,$A$2:$A$16,A2,$B$2:$B$16,">="&B2)
Then drag down from D2 to the bottom of the table.
Widen and refresh your pivot.
If data are aggregated inside the pivot (i.e. there are more rows that compose what in the image is a row), you could take MAX() o MIN() in the pivot (as you discovered yourself ;) )


text:
Q: How to develop a solid CSS strategy? I have taken the time to carefully learn the syntax of HTML5, CSS3, and JQuery.
I would now like to find a good resource that will help me develop a solid "design process."  In what little design I've done up to this point, I've usually ended up with a pretty nasty looking .css style sheet with a lot of one-off-isms.
I'm open to any suggestions of a good resource or just some pointers that will help toward a good HTML/CSS design strategy.
Thanks

A: Break up your stylesheet into modules: Navigation, content types, header, footer, etc.
Don't use ids for assigning styles. This gives some more information on why that is, and more helpful tips http://oli.jp/2011/ids/
Read http://css-tricks.com/, Chris Coyier always has helpful tips on his site

A: Group your CSS styles, like @DevonRW said above.
Comment your CSS, just like you'd comment longer bits of code. It will help you and other team members in later maintenance.
Be careful, though, of doing something like creating a style definition that just defines the color of something. When using jQuery, you often end up needing to add classes, so that an element can have three or four classes at a given time...but you don't want to start out with three or four. Troubleshooting and making instant sweeping changes to your site styles can get really sticky that way.
One thing I've tried is coming up with a nomenclature for class names: sClassName for regular classes, jqClassName for classes that will be added (or removed) by jQuery. That may or may not be helpful to you, though.


text:
Q: My searchable Dropdown list view is not working asp.net mvc Him I downloaded from Nugget package "bootstrap.Chosen". also I was using "@Html.DropDownListFor". also I setup id for jQuery. Everything looks correct but it cannot get Search bar in my dropdown list. My code is below.

        @Html.LabelFor(m => m.MessageTo, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(m => m.MessageTo,(SelectList)ViewBag.Employeelist, new { id =
               "Dropdown" }) //I setup Id for using jQuery.

        @section Scripts{

          }

I also setup Layout page
      @Styles.Render("~/Content/css")
      @RenderSection("scripts", required: false)

      <link href="~/Content/bootstrap-chosen.css" rel="stylesheet" />

I don't know why I cannot use Search bar in my dropdown list.


text:
Q: Find Last and Second Last value in a column from a range in Excel I need to calculate the difference of second last value from the last/latest value in a column from a range in Excel.
For Example
1305
1309
1405
1506

I need to calculate the difference between 1506 and 1405
Again in next month the values may be
1305
1309
1405
1506
1603

Then I need to auto calculate 1603-1505

A: If your data was in column A, you could use
=INDEX(A:A,COUNTA(A:A),0)-INDEX(A:A,COUNTA(A:A)-1,0)

Adjust the A:A from the above to suit your range of data


text:
Q: What's <\/script> for? <\/script>

This is how it is used:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>

I got this from initializr.

A: The backslash prevents the browser from seeing a </SCRIPT> tag which would end the Javascript. Javascript will eat it, so the output will be </SCRIPT> as desired.

A: escape character to insure slash outside of the quoted text is not encoded.

A: It's simply </script> with the forward slash escaped so it doesn't get automatically encoded by the document.write() function.


text:
Q: Centering jQuery UI dialog of unknown height - is it possible? Is there a way of making a jQuery dialog opening in the center of the visible window if it's of an unknown height?
I have a dialog that opens a dynamically loaded form of unknown height. When opening it the first time, it's slightly offset towards the bottom of the screen. When I close it and open it again, it seems that the top offset is calculated properly.
I can't know the content height in advance so this is kind of an issue for me.
edit: here's an example code
I have two pages - one is the dialog container which instantiates the dialog, and another is the dialog content. When a link is clicked, it's href is used as a target page for the dialog.
$(document).ready(function(){
    $(a).click(function(){
        $("#dialog").load($(this).attr('href'))
        .dialog({
            modal: true,
            width: 400
        });
        $("#dialog").dialog('open');
    });
});

A: You need to specify height: 'auto' to make the dialog adjust based on its content.
.dialog({
    height: 'auto',
});

@jon3laze The default value for "position" is 'center', so no need to set it in open callback function.
@eagerMoose There is no need to call the
$("#dialog").dialog('open');

because dialogs have an autoOpen option, which defaults to true and dialog is being opened immediately after instantiation. The second call to .dialog('open') is ignored.
EDIT: because load is asynchronous the dialog is probably initialized before the content is loaded. Try to initialize the dialog in the load complete.
$(document).ready(function(){
    $(a).click(function(){
        $("#dialog").load($(this).attr('href'), function(){
            $(this).dialog({
                modal: true,
                width: 400
            });
        });
    });
});

A: You can grab the height before setting the dialog using the height property

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

$(document).ready(function(){

    var h = $(document).height();

    $(a).click(function(){
        $("#dialog").load($(this).attr('href'))
        .dialog({
            modal: true,
            width: 400,
            height: h
        }).dialog('open');
    });
});

Also, you can chain the .dialog('open') on to the end of the call.
Example here http://jsfiddle.net/BZpPH/1/
UPDATE
The issue sounds like the position of the content. You can use the open event option to have it reset the size upon open. I can't get this to work on jsfiddle because I can't figure out how to get the .load() method to work. However I tried this on my own server, defaulted the position to top and it would open center of the screen.
$(a).click(function() {
    $('#dialog').load($(this).attr('href'))
        .dialog({
            modal: true,
            width: 400,
            height: 'auto',
            open: function() {
                $(this).dialog('option', 'position', 'center');
            }
        });
    });
});

A: The culprit was the .load() function. This is an ajax call meaning the .dialog() function gets called before the content was actually loaded, so the content height was practically guesswork.
I managed to solve the problem by defining dialog and its actions inside the .load() function, like this
$(document).ready(function(){
    $(a).click(function(){
        $("#dialog").load($(this).attr('href'), function(){
            $(this).dialog({
                modal: true,
                width: 400
             });
        });
    });
 });


text:
Q: Gardena battery rain water tank pump 2000/2 – SWD Interface I have a garden and would like to water it automatically with rain. For this I bought a «Gardena Battery Rain Water Tank Pump 2000/2» and would like to control via an ESP8266.
After opening the control panel, I found that the circuit board is molded in black plastic. I was able to remove the plastic from the circuit board.
There is an imprint on the board with the following pinout:

*

*TX

*GND

*VSS

*DAT

*REST

*CLK

I spent two days trying to identify the microcontroller.

I found the Nuvoton NuMicro ML51TC0AE.
Datasheet: https://www.nuvoton.com/export/resource-files/DS_ML51_ML54_ML56_Series_EN_Rev2.02.pdf
I ordered a NU-Link from Taiwan and will now try to communicate with it via SWD.
I tried to talk to the microcontroller with the NuTool - PinView, however it does not go beyond "Detecting target device...". Unfortunately, when I use NuConsole, I get a timeout.
Actually, I would like to read the firmware.
Does anyone have experience in reverse engineering with Nuvoton 8051 chips and can give me a tip?
I still have an old post, but I don't think this one is seen anymore.
Gardena battery rain water tank pump 2000/2 - UART interface


text:
Q: Homebrew/Python: Convince distutils to link against a specific library on OS X? I'm building a Python project with multiple C extensions which require libhdf5.  I have an existing installation of libhdf5 at /usr/local/lib.  For testing and development, I want to develop against a private build of HDF5 located at /Users/name/some/path.
In setup.py, I handle this by setting the "library_dirs" (and "runtime_library_dirs", although on OS X that doesn't do anything) to /Users/name/some/path.  On Linux this works fine.
The trouble is, when my extension modules are compiled, they link against the copy of HDF5 in /usr/local/lib and no amount of tweaking in setup.py can convince them otherwise.
By setting DYLD_LIBRARY_PATH=/Users/name/some/path when running Python, I have successfully loaded the private build of HDF5, so I know the library is built correctly and works.
Running otool -L on one of my extensions produces this:
h5py/_errors.so:
/usr/local/lib/libhdf5.8.dylib (compatibility version 9.0.0, current version 9.1.0)
/usr/local/lib/libhdf5_hl.8.dylib (compatibility version 9.0.0, current version 9.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1)

which confirms that we're linking against the wrong copy of the library.
I noticed that the linking phase looks like this:
clang -bundle -undefined dynamic_lookup -L/usr/local/lib -L/usr/local/opt/sqlite/lib -L/Users/name/some/path <more stuff>
and conjecture that clang is linking against the first version of HDF5 it can find.
Is there any way to force distutils to link against my private build of the library?  I don't need a relocatable version so I don't care about @rpath, etc.
I have also confirmed that this doesn't happen with the system Python, just the one installed via homebrew.

A: My short answer is: Don't use the HomeBrew Python to manage builds outside of homebrew.  You can see here: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/python.rb#L213 that they've hard-coded their library flags into the Python Makefile itself.
Of course, an answer that fixes your problems is much more interesting :)
You could, if you really wanted to, monkey-patch sysconfig.get_config_vars() to inject your flags ahead of system libraries.  You could also monkey-patch distutils.  Neither of these is particularly robust.
Within HashDist we've prioritized building our own Python, which is frustrating, but we've found to be the most robust.  (We support h5py on OS X)


text:
Q: Standard input inconsistency between command line and subprocess.call I would like to create a file that will be used as standard input for a python script, and invoke said script with subprocess.call.
When I do it directly in the command line it works fine:
The input file:
# test_input
1/2/3

The python script
# script.py
thisDate = input('Please enter date: ').rstrip()

The following command works just fine:
python script.py < test_input

But when I try to do the following from within another python script, it doesn't work. (from this)
outfile1 = open('test_input', 'w')
outfile1.write('1/2/3')
outfile1.close()

input1 = open('test_input')
subprocess.call(['python', 'script.py'], stdin=input1)

But then I get the following error:
>>>thisDate = input('Please enter date: ').rstrip()
>>>AttributeError: 'int' object has no attribute 'rstrip'

When I did some debugging, it seems that it is getting the integer 0 as the input.
What is causing the inconsistency here? Are the two methods not equivalent (evidently they are not, but why)? My ultimate goal is to perform the exact same task as the above command line version that worked.
Thank you

A: You are using input when it should be raw_input, input in python2 will eval the string. If you run the script with python3 it will work as is, for python2 change to raw_input.
Using check_call is usually a better approach and using with to open your files.
import subprocess
with open('test_input') as input1:
    subprocess.check_call(['python3', 'script.py'], stdin=input1)

A: So chepner was correct. When I amended the following line:
subprocess.call(['python', 'script.py'], stdin=input1)

to:
subprocess.call(['python3', 'script.py'], stdin=input1)

it worked just fine.
(I am trying to do this in python3)

A: In the first instance, the file has two lines, and input() reads and parses the first line, which is a comment.
In the second case, the comment line is missing, so Python reads and parses a number.
You probably meant to use raw_input(), or run the script with Python 3.
(You probably also meant for the input file to end with a newline, and it doesn't really make sense to use subprocess.call() to run Python when you are already running Python.)

A: python script.py < test_input command should fail. You might mean: python3 script.py < test_input instead due to the difference between input() vs raw_input() on Python 2 as mentioned in other answers. python as a rule refers to Python 2 version.
if the parent script is run only using python3 then you could use sys.executable to run the child script using the same python version (the same executable):
#!/usr/bin/env python3
import subprocess
import sys

with open('test_input', 'rb', 0) as input_file:
    subprocess.check_call([sys.executable or 'python3', 'script.py'],
                          stdin=input_file)

If the parent and the child may use different python versions then set the correct shebang in script.py e.g., #!/usr/bin/env python3 and run the script directly:
#!/usr/bin/env python
import subprocess

with open('test_input', 'rb', 0) as input_file:
    subprocess.check_call(['./script.py'], stdin=input_file)

Here, the child script may choose its own python version. Make sure the script has executable permissions: chmod +x script.py. Note: Python Launcher for Windows understands the shebang syntax too.
Unrelated: use .communicate() instead of outfile1.write('1/2/3'):
#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen(['./script.py'], stdin=PIPE, universal_newlines=True) as p:
    p.communicate('1/2/3')


text:
Q: How do I grep a date pattern from a list of csv files in powershell? I have a list of files in a directory with different dates as such:
1. test_2017-01-01.csv
2. test_2017-02-01.csv
3. test_2017-03-01.csv
4. test_2017-04-01.csv

Let's say I want to pull all the files into a new list labeled $files that holds only files between the dates of 2017-01-01 and 2017-03-01. How would I go about this? I Can pull from the directory at the moment as such:
$files = Get-ChildItem "my_directory" | Sort-Object

A: not sure this can be easily transformed to date format query. Do you think regex would work for you in this case?
$files = Get-ChildItem | Where-Object {$_.Name -match "^test_2017-0[123]{1}-01.csv$"}

There is quite some long one-liner, but it does what you are after - converts the numeric string in the name of file (has to have format of yyyy-MM-dd) to date and then evaluates whether it's in range specified.
$files = Get-ChildItem | Where-Object {($_.Name -match "[\d]{4}-[\d]{2}-[\d]{2}") -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -le (Get-Date 2017/03/01))}


text:
Q: Insert and update simultaneously To insert an identical row to a table I use
Insert into table (select * from table where columnA = 'a' and columnB = 'b')

Am I able to insert and change columnB = 'c' in one sql?

A: Yes, just specify the value in the select:
insert into table (ColumnA, ColumnB)
select ColumnA, 'c'
from table
where columnA = 'a' and columnB = 'b'

(If you have more columns, just add them in the column list and the select just like ColumnA.)


text:
Q: Django Nested Serializers won't work independently- Key Error /dashboard/api/institution/editor/ 'id' I'm trying to create an app using JQuery Datatables Editor and a Django REST framework API. Whenever I try to create an entry, I am returned the above key error. I believe the problem is traced back to the to_internal_value function within the InstitutionDatatableSerializer. However, I cannot delete this function as it is necessary for me to create a new entry for the InvestigatorDatatableSerializer. How can I fix the serializer?
serializers.py
class InstitutionDatatableSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    def to_internal_value(self, data):
        return get_object_or_404(Institution, pk=data['id'])

    class Meta:
        model = Institution
        fields = ('__all__')
        datatables_always_serialize = ('id',)

class InvestigatorDatatableSerializer(serializers.ModelSerializer):
    institution_name = serializers.ReadOnlyField(source='institution.name')
    institution = InstitutionSerializer()

    class Meta:
        model = Investigator
        fields = ('id',
                  'last_name',
                  'first_name',
                  'email',
                  'institution_name',
                  'institution',
                  )
        datatables_always_serialize = ('id',)

models.py
class Institution(models.Model):
    id = models.AutoField(unique=True, primary_key=True)
    name = models.CharField(max_length=50)
    dept = models.CharField(max_length=50)

    class Meta:
        managed = True
        db_table = 'institution'
    def __str__(self):
        return str(self.name)

class Investigator(models.Model):
    id = models.AutoField(unique=True, primary_key=True)
    last_name = models.CharField(max_length=50)
    first_name = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)
    institution = models.ForeignKey(Institution, models.DO_NOTHING, related_name='institution_id', )

    class Meta:
        managed = True
        db_table = 'investigator'
    def __str__(self):
        return str(self.last_name)


text:
Q: How to display image in html page of angular I am using Angular CLI 8.1.0 and i am new into Angular.
I am not able to display the image in my html page. My path is correct but still not getting the image.
I am getting error:
> unsafe:C:/nginx/www/repos/Sportaz-repo/VaamozWeb/VaamozBusiness/Pictures/UserApp/Home/Brands/burgerking.png:1
> GET
> unsafe:C:/nginx/www/repos/Sportaz-repo/VaamozWeb/VaamozBusiness/Pictures/UserApp/Home/Brands/burgerking.png
> net::ERR_UNKNOWN_URL_SCHEME

approval.component.ts

ngOnInit()
  {
    this.col=this.activatedRoute.snapshot.paramMap.get('col');
    this.id=this.activatedRoute.snapshot.paramMap.get('id');
    this.rid=this.activatedRoute.snapshot.paramMap.get('rid');

    this.activatedRoute.queryParamMap.subscribe((queryParams:Params)=>{
      let col=this.col;
      let id=this.id;
      let rid=this.rid;

      this.apiService.getVendorById(col,id,rid)
      .subscribe(data=>{
        this.result = data[0];
        this.getpath=this.result.strOutletUri;
        this.finalpath="C:/nginx/www"+this.getpath;

      });
    });
  }

approval.component.html

my REST API:

[
    {
        "strBusinessName": "Happy Junctions",
        "strBusinessDescription": "Restaurant ",
        "strOutletUri": "/repos/Sportaz-repo/VaamozWeb/VaamozBusiness/Pictures/UserApp/Home/Brands/burgerking.png"
    }
]

A: src property of img tag requires a valid non-empty URL. If you need to show local images from the server, try embedding them using background-image. Although I am not sure if an absolute path will work in Angular.
Component
this.finalpath = "url(C:/nginx/www" + this.getpath + ")";

Template

Update
Angular does not have access to local file system. The images should either come from src/assets/ folder or it should be sent as an encoded base64 of the image from the server. It can then be decoded in the Angular.


text:
Q: hr tag in javascript I am working on phonegap and I am new to it. I want to draw a line using hr under the menu items which are displayed. but unfortunately I am unable to do so.
if somebody can help in this regard. Thanks in advance.
here is the code snippet
{
 success:function(res,code) {
                entries = [];
                var xml = $(res);
                var items = xml.find("item");
                $.each(items, function(i, v) {

                    category1.push($(v).find("category").text());
                    /*  $("#status").append("menu_type "+menu_type+"
");  */
                    console.log( "PRICE" + ": " +  $(v).find("menu_type").text() );

                });
                var category = category1.unique();
                var select = document.getElementById("selectNumber");

                for(var i = 0; i < category.length; i++) {
                     var el1 = document.createElement("li");
                    var opt = category[i];
                    var el = document.createElement("a");
                    el.textContent = opt;
                    el.value = opt;
                    el1.appendChild(el);
                    select.appendChild(el1);
                }

}

A: Try adding something like this
document.getElementById("ElementBelowWhichHRShouldCome").appendChild(document.createElement('hr'));

A: Try innerHTML. Here is an example:
http://jsfiddle.net/Wxv6n/
var doc = document;
var get = function(id){return doc.getElementById(id);};

get("foo").innerHTML = '
';

..and don't forget to cache your references to document

A: After Every Menu Item,you can use this.Its pretty simple.
$("#menu_item").after('
');

after() in jquery
DEMO FIDDLE