To update or to not update?

Question: Since starting working where I am working now, I've been in an endless struggle with my boss and coworkers in regard to updating systems.
I of course totally agree that any update (be it firmware, O.S. or application) should not be applied carelessly as soon as it comes out, but I also firmly believe that there should be at least some reason if the vendor released it; and the most common reason is usually fixing some bug... which maybe you're not experiencing now, but you could be experiencing soon if you don't keep up with .
This is especially true for security fixes; as an examle, had anyone simply applied a patch that had already been available for months, the infamous SQL Slammer worm would have been harmless.
I'm all for testing and evaluating updates before deployng them; but I strongly disagree with the "if it's not broken then don't touch it" approach to systems management, and it genuinely hurts me when I find production Windows 2003 SP1 or ESX 3.5 Update 2 systems, and the only answer I can get is "it's working, we don't want to break it".
What do you think about this?
What is your policy?
And what is your company policy, if it doesn't match your own?
What about firmware updates (BIOS, storage, etc.)?
What about main O.S. updates (service packs)?
What about minor O.S. updates?
What about application updates?
My main interest is of course in updating servers, as client patch management is usually more straightforward and there are well known tools and best practices to handle it.
Comment: Welcome to my world.  I have more Windows 2003 SP1 machines than I care to know about and a patch/update policy that doesn't include servers.  I have argh moments on a regular basis trying to convince my management and the client that this is important to address.
Comment: Almost 5 years after this question was posted, where I work we still have our servers on Windows Server 2003 with updates turned off. Management cannot make a decision about what to do after months of talk.
Answer: Security and agility should be balanced against stability and uptime when determining your patching strategy. Your push-back approach for this should be along the lines of 'Okay, but you need to know that we're now at risk of these servers becoming compromised and having our data stolen, or having the servers be rendered non-functional' and 'Okay, but you need to know that this impacts our vendor support for this system, and future ability to have this system interact with new systems'.
Against the longer-term 'not broke, don't update' mentality, you should make it clear that:

Migrating an unpatched legacy system that's fallen way behind over to a modern system is a much more expensive and painful process than gradually updating that system over time.
Experienced and skilled IT personnel actively seek out new technology and companies that are constantly evolving their IT systems. There's a very real dollar cost in turnover, lost opportunity, and loss of knowledge when a companies loses their highly engaged, creative IT staff due to their systems stagnating and becoming unappealing to work with. Then all you're left with are the 'lifers'.

Hope this gives you some leverage and best of luck in convincing the aboves to take things seriously. As always, establish a paper trail that proves you've apprised management of the risks they're taking.
Comment: +1, We recently had a problem with a system, called the vendor, we hadn't updated in about 18 months, first thing they said "update, then call us if it still doesn't work".
Answer: This is an endless debate and reasonable people will disagree. If you're talking about user PCs, I agree they need to be updated. If you're talking about servers, consider a separate policy for servers that face the internet and those that don't. I don't know about your servers but in my environment, maybe 10% of our servers have ports open to the internet. These internet-facing servers get highest priority when it comes to security patches. Servers that don't face the internet are lower priority.
Security gurus will argue that this approach is problematic because if a hacker ever does get into your network, the unpatched servers will allow exploits to fritter through the network like wildfire and that's a reasonable argument. Still, if you keep those internet-facing servers locked down tight and properly configure your firewall to only open those ports that are absolutely needed, I think this approach works and can often be used to appease managers that are afraid of patches.
If you're only relying on Windows Update for patches (you didn't mention which OS you're running but I'm mostly a Windows guy so this is my reference), take a look at the actual hotfixes that get released every month. I have some servers that if I run Windows Update on them I'll be told I need 50+ patches but if I scroll through those patches and research each of them, I'll find that 90% of the items being patches are not security related but fix bugs that affect services I don't run on that box. In larger environments where you use a patch management system, it's common to review everything that gets released and only bother with what is absolutely necessary and that usually amounts to about 10% of what Microsoft releases.
My argument is that this debate about "to patch or not to patch" suggests you have to be one one side or the other when, really, this is a huge grey area.
Comment: I'm actually concerned with bug-fixing patches, too; too many times I've encountered bugs which had already been fixed by the vendor, but nobody bothered applying patches. This is *especially* dangerous with firmwares.
Answer: I can only talk about servers but we have a 'Quarterly update' regime, on four predetermined and announced dates per year we bunch up update requests, apply them to our reference environment, run them for a month to test stability and if good roll out during the following n days/weeks. On top of this we apply an emergency update policy where we have the ability to deploy into reference, test and roll out urgent updates within a day or two if the severity is such - although this has only been used 2/3 times in the last 4 years or so.
This twin-approach ensures that our servers are reasonably, but not stupidly, up to date, that updates are driven by subject-matter-experts (i.e. firmware, drivers, OS, app staff) not vendors but that it also allows rapid fixes if required. Oh course we're lucky to have very few different hardware models across the whole business (<10 server varients) and sizable, and up to date, reference platforms to test against.
Comment: +1. We have an almost identical update policy.
Answer: My view is that the best course is pretty much smack in the middle of your two extremes. e.g. Why do you so desperately want to upgrade ESX if there's no demonstrable reason for doing so, possibly breaking working systems in the process? Sure it might be vulnerable if it was public facing but there should be no way it can be directly accessed from outside your network, so where's the risk? Are there any bugs or lack of features that are actually presenting you with a reason to upgrade?
Upgrading for the sake of it, which is really what you're proposing ("but you could be experiencing soon"), even while claiming you're not, is an absurd and dangerous road to travel. Unless you can present an actual reason, as opposed to some theoretically possible reason, you're never going to convince others if they're opposed to the upgrade.
If you believe there is a real reason to perform an upgrade you should document both the pros and cons, and there are always cons, and present that to those higher up the tree. Properly documented there should be little resistance. If you can't provide a convincing argument then sit back and give that fact some serious thought.
Edit
I thought I should make it clear that I see a vast difference between applying required security and stability patches as compared to performing software or OS upgrades. The first I implement after proper testing. The latter I do only if there is a real benefit.
Answer: I've worked at different firms that had policies all over the continuum from "apply patches ASAP, we don't care if they break something we have working -- we'll back them out then" to "nothing gets applied without two weeks of testing."  Both extremes (and points in between) are fine as long as the Company understands the tradeoffs.
That's the important point: there is no right or wrong particular answer to this question; it's a matter of balancing stability vs. safety or features in your particular environment.  If your management chain understands that delaying patches for testing may make them more vulnerable to malware, thats fine.  Likewise, if they understand that applying patches as soon as they are available may not work or even break your particular system configuration, that is also fine.  Problems exist when these tradeoffs are not understood.
Answer: Security updates get sent to a staging server, then production after they've shown that they don't blow things up. Unless there's a real bleeping emergency (which I have hit a few times :( ), in which case PRODUCTION NOW. Other updates only as required, after spending time in staging.
Answer: I think the first thing to do is to "classify" updates by severity, and have patch schedule based on the classification.
There is no doubt zero-day security fixes must be applied right away; whereas Service Pack can wait after careful evaluations.

To update or to not update?


Diferença no tamanho da string com FontMetrics.charWidth e FontMetrics.stringWidth

Question: Não estou conseguindo entender o seguinte código:
String text = "C JEA NAV/NAP GRV NAV/ELT NAV SOLA PVC EXP PRETO ";
int posString = FONT_METRICS.stringWidth(text);
int posChar = 0;
for (int i = 0; i < text.length(); i++) {
     Character character = text.charAt(i);
     posChar += FONT_METRICS.charWidth(character);
}
System.out.println("String: " + posString + " Char: " + posChar);

Por que o posString é 198 e o posChar é 207?
Answer: charWidth(char ch)
Returns the advance width of the specified character in this Font.

stringWidth(String str)
Returns the total advance width for showing the specified String in this Font.

O avanço de um String é a distância ao longo da linha de base do String. Essa distância é a largura que deve ser usada para a centralização ou alinhamento à direita da String.
Note-se que o avanço de uma String não é necessariamente a soma dos avanços de seus caracteres medidos isoladamente porque a largura de um caracter pode variar de acordo com seu contexto.
Por exemplo, em texto árabe, a forma de um caracter pode mudar para se "conectar" a outros caracteres. Além disso, em alguns scripts, certas sequências de caracteres podem ser representadas por uma única forma, chamada de ligadura. A medição de caracteres individualmente não é responsável por essas transformações.

Fonte:
Class FontMetrics - Docs Oracle


Creating a substring with a varying number of chars

Question: void findNthRoot(string x) {
  if(x.find("rt:") != string::npos) {
    unsigned position = x.find("rt:");
    double n = position - 1;
    double z = position + 3;
    string str1 = x.substr(n, 1);
    string str2 = x.substr(z, 1);
  }
}

int main() {
  findNthRoot("2 - 1 + 32rt:43 - 89");
}

As part of a calculator program, users can enter nrt:x to represent the nth root of a number x. The code I have written above works perfectly fine, but only if the user inputs a root with a single digit n and a single digit x. So my substrings str1 and str2 in this case would be 2 and 4 respectively. I need the substrings to take the entire number followng rt: and the entire number before rt:. I cannot figure out how to do this. I know this is because I have 1 in x.substr(n, 1) but since the user can enter any number they want, I need to somehow be able to account for that.
Answer: In <cctype> header you have the function std::isdigit() that tells you if a character is a digit.
That way you can find the length of your substring with a simple loop :
void findNthRoot(string x)
{
    size_t position = x.find("rt:");
    if (position != string::npos)
    {
        size_t length = 1;
        size_t n = position - 1;
        while (n > 0 && std::isdigit(x[n - 1]))
        {
            --n;
            ++length;
        }
        string str1 = x.substr(n, length);

        length = 1;
        size_t z = position + 3;
        while (z < x.size() - 1 && std::isdigit(x[z + length]))
            ++length;
        string str2 = x.substr(z, length);
    }
}

int main()
{
    findNthRoot("2 - 1 + 32rt:43 - 89");
}

Comment: Wow that is awesome thank you. I'm looking over the code you gave me to tweak it now, but in testing str2 was correct - no matter what I wrote after rt: I got that number. However, before rt:, all i'm getting is 3.
Comment: Yeah it's because I forgot to update `length` value inside the loop. Check out my edit in a few seconds.
Comment: Okay great, thanks for the help. Now that you have helped me get here,  I need to pass the values to a different method. From here I need to convert them to int from string. This can be done with sstream correct?
Comment: It is correct. Something like `istringstream iss (str); int i; iss >> i; return i;` Or if you're using C++11, you can use [`std::stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol).
Comment: Yes I am using C++11. So stoi is a std function that converts strings to ints? or does it have other purposes as well
Comment: Yes, stoi takes a string as parameter and returns an int if no problem arises during the conversion (this case an exception is thrown). You can follow the link in my previous comment for more informations.
Comment: Okay, I took a break and now I'm back and i was trying to fully understand the code you gave me. I get that, using isDigit, you are simply executing the while loop and moving one index to the left and counting the length of the number. But why does isDigit have array of x[n-1]?


Perform two iterations of Newton's Method on this system. $4{x_1}^2={x_2}^2$ and $4x_1{x_2}^2-x_1=1$.

Question: Perform two iterations of Newton's Method on this system.
Starting with $(0,1)$,  $4{x_1}^2={x_2}^2$ and $4x_1{x_2}^2-x_1=1$.
I'm not sure I understand "starting with $(0,1)$". I know how to use Newton's Method and that the following system can be solved for either variable. Any solutions/hints are greatly appreciated.
Answer: Write $f(x) = \begin{bmatrix} 4x_1^2-x_2^2 \\ 4 x_1 x_2^2 -x_1 -1\end{bmatrix}$. You want to solve $f(x) = 0$.
Start with $x^0 = (0,1)^T$. Then
$x^{n+1} = x^n - f'(x^n)^{-1} f(x^n)$. Repeat twice.
(You can solve the equation any way you want, for example, solve $f'(x^n) \delta = -f(x^n)$, then $x^{n+1} = x^n +\delta$).
Answer: Not using matrices in order to stay close to the one-dimensional problem.
You want to solve two equations $$F=4x_1^2-x_2^2=0$$ $$G=4x_1{x_2}^2-x_1-1=0$$ So $$F'_{x_1}=8x_1$$ $$F'_{x_2}=-2x_2$$ $$G'_{x_1}=4x_2^2-1$$ $$G'_{x_2}=8x_1x_2$$ So, just as for first order Taylor expansion around a given point, we can write at a point $(a,b)$ $$0=(4a^2-b^2)+8a (x_1-a)-2b (x_2-b)$$ $$0=(4ab^2-a-1)+(4b^2-1)(x_1-a)+8ab(x_2-b)$$
Solve for $x_1,x_2$ and now replace $a$ by $x_1$, $b$ by $x_2$ and repeat until convergence (or just for two iterations as you are required).


failed to fetch volume file

Question: When my client try to connect gluster server it gives below error:
[glusterfsd-mgmt.c:1627:mgmt_getspec_cbk] 0-mgmt: failed to fetch volume file (key:gluster_vol_0)
My client is an  Amazon Linux instance located on Anazon EC2.
I installed glusterfs-fuse like below:
<code>sudo su -

#install glusterfs repo
wget -P /etc/yum.repos.d http://download.gluster.org/pub/gluster/glusterfs/LATEST/EPEL.repo   /glusterfs-epel.repo
#fix it for amazon linux
sed -i 's/$releasever/6/g' /etc/yum.repos.d/glusterfs-epel.repo

#install glusterfs
yum install -y glusterfs-fuse

#setup fstab
echo "hostname.example.com:/media-volume /mnt/glusterfs glusterfs defaults 0 0" >> /etc/fstab

#mount
mkdir -p /mnt/glusterfs
mount -a
</code>
Could you help me please.
Kind regards...
Comment: I'm currently having the same issue on Ubuntu 12.04 LTS. If I find a solution, I'll post it here.
Comment: http://serverfault.com/questions/482757/failed-to-fetch-volume-file

might help the one who still has this issue these days
Answer: I experienced the same error (missing key) when installing Glusterfs-server 3.3.1 today. My resolution was to manually install the same version on the client side, as the repo offered me an older version than 3.3.1.
Atleast it fixed it in my case using Debian 6 as server and Ubuntu 12.04 as client.

failed to fetch volume file


Python script to convert from UTF-8 to ASCII

Question: I'm trying to write a script in python to convert utf-8 files into ASCII files:
#!/usr/bin/env python
# *-* coding: iso-8859-1 *-*

import sys
import os

filePath = "test.lrc"
fichier = open(filePath, "rb")
contentOfFile = fichier.read()
fichier.close()

fichierTemp = open("tempASCII", "w")
fichierTemp.write(contentOfFile.encode("ASCII", 'ignore'))
fichierTemp.close()

When I run this script I have the following error :

UnicodeDecodeError: 'ascii' codec
  can't decode byte 0xef in position 13:
  ordinal not in range(128)

I thought that can ignore error with the ignore parameter in the encode method. But it seems not.
I'm open to other ways to convert.
Comment: The problem is that you never decode in the first place.
Comment: You got the error because the character doesn't exist in the ASCII character set, so it can't be converted. Sometimes you can map the UTF8 character to a closest visual-fit character in ASCII, such as `é` to `e`, but that can change the meaning of words. You have to decide if that path will work for your application.
Comment: This seems like a really bad idea!!
Answer: data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

Comment: You should expect data loss if you wish to convert from a 8bit encoding to 7bit.
Comment: Sounds like a bad recipe for data loss.
Comment: I ignored that I have to decode first. It works now thanks. To answer to the questions, I want to do this because my MP3 player can only display lyrics files encoded in ASCII.
Comment: I get `AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?` for the second line with python 3.10.4
Comment: You can have a look at this solution: http://stackoverflow.com/a/517974/1463812
Answer: import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

Answer: UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.
Comment: I think he's aware of that, otherwise he wouldn't be trying to use `'ignore'`.
Comment: @Ignacio True. But this one left me wondering what the asker is trying to achieve. They could be cargo-culting, or maybe their need is best met by something like urlencode, or being lossy is just acceptable.
Comment: I am afraid of the cargo-culting. Culling all characters that you don't have an appreciation for is really insensitive.
Comment: @Ignacio: Imagine being addressed as *Vzquez-Abrams*. :(
Comment: @tchrist: That's why I never use it.
Comment: Sometimes you can convert UTF8 to ASCII without losses, for instance, single quotes or apostrophes, in few other cases - arithmetic operations - both available as UTF8 long encoding and ASCII single symbol.


Elegant way of retrieving query string parameter

Question: I am retrieving one query string parameter, and for that my code is
 Click me

Now I want to retrieve "status=pending" and for that I am doing
 var qString = window.location.search.substring(1);
                  var Keys = qString .split('&');
                 alert(Keys[1]);

This works fine, but I am hard-coding [1] here. is there any elegent way of doing this without hard-coding?
Answer: I'd use a regular expression such as:
status=([a-zA-Z])+

This will retrieve only what the status is. If you already know the variable is always called status, but don't know what the value is, this is the right way to go.
To use it, you'd have to do something like this:
var qString = window.location.search.substring(1);
qString.match(/status=([a-zA-Z])+/);

Hope it helps
Comment: will try the regular expression.
Answer: you can also consider a dedicated url/querystring parser, like this one
Comment: Or try Adam Vandenberg's implementation (http://adamv.com/dev/javascript/querystring) that doesn't depend on jQuery.
Answer: Try this out the easiest and best way without hard coding the index
params = location.search;
getParam = function(arg) {
if (params.indexOf(arg) >= 0) {
var pntr = params.indexOf(arg) + arg.length + 1;
if (params.indexOf("&", pntr) >= 0) {
return params.substring(pntr, params.indexOf("&", pntr));
} else {
return params.substring(pntr, params.length);
}
} else {
return null;
}
}
So you'd end up with something like:
?status=someValue
var val = getParam("status");
val would be "somevalue"
Comment: thnx for d sln.will take a look at this approach


Problem reading XML with SimpleXML in PHP

Question: i've got an xml-string in $response that looks like this:
<?xml version="1.0"?>
<RESPONSE>
  <ERROR>
    <ERROR_CODE>6</ERROR_CODE>
    <ERROR_TEXT>Authentication failed</ERROR_TEXT>
  </ERROR>
</RESPONSE>

In order to read it, I run
$xml_response = simplexml_load_string($response);

The problem is:
$xml_response->getName();

returns - as expected - "RESPONSE", but
isset($xml_response->RESPONSE->ERROR->ERROR_TEXT);

returns FALSE - but why? Any ideas?
Thanks in advance!
Comment: `$xml_response` *is* the root node. That's why you should call it `$RESPONSE` instead, to avoid the confusion.
Answer: Try without the root node when accessing the path that you want:
isset($xml_response->ERROR->ERROR_TEXT);

Comment: Yep, that was the problem! Thanks a lot! :)


What might delete keys from Redis?

Question: We have 3 apps on our server. They talk to each other via Redis. Redis is the bus for all communication.
Something on our server is incorrectly deleting keys from Redis. I am trying to track down the problem. For each app, I downloaded the code to my machine, and then tried:
grep -iR "flush" *
grep -iR "del" *

Two of the apps are free of "flush" and "del". Only one app has "del". So I found its PID and:
kill -9 2312

I also did "ps aux" to make sure that app was off.
The other 2 apps only have:
hset
hget
hmgetall

The disappearance of the keys in Redis is erratic. Some keys last several minutes, or even hours. Others disappear quickly.
As near as I can see, none of the developers have set timeouts on the keys in Redis. But maybe something sets a default timeout?
How do I debug this? Where do I look?
Comment: Open a redis-cli connection to your server and run `MONITOR` to see which commands are sent. Look at the output of `INFO KEYSPACE` to understand if there are any expired keys. Perhaps you're running out of memory and your eviction policy kicks out your keys?
Answer: Do take a look at Redis configuration:
config get maxmemory*

Be sure that maxmemory is large enough for your dataset otherwise keys will be automatically dropped with the specified maxmemory-policy.

What might delete keys from Redis?


how to access multiple users' database via JDBC

Question: I have an account in oracle database. I can connect it via jdbc in my java code.
When I access database from Oracle SQL Developer, under "Connections"->"Other Users", I can access to their tables (I have been assigned privilege for reading others tables).
My question is, how to access / retrieve data from others tables via jdbc?
Answer: You need to prefix the table name with the schema name, which in Oracle is the same as the user name.
<code>select * from some_other_user.their_table;
</code>
If having the user name hardcoded in the SQL statement is a problem, you could make that configurable on the Java side somehow or install a table alias (synonym) into your own schema on the Oracle side.


Add filestream to an existing table column

Question: I have the following table column:
[Content] [varbinary](max) NULL

And I want to make it a filestream column so I tried:
alter table dbo.Files
  alter column Content add filestream

But I get the error:
Incorrect syntax near 'filestream'.

I also tried
alter table dbo.Files
  alter column Content varbinary(max) filestream not null

But I got the error:
Cannot alter column 'Content' in table 'Files' to add or remove the FILESTREAM column attribute.

How can I add filestream to an existing column?
Comment: I have suspicion you may have to create another column "alter table dbo.Files
  add Content_new varbinary(max) filestream not null" then copy what you have in the original column over.
Answer: you'll need to do the following (sourced from here):
/* rename the varbinary(max) column
eg. FileData to xxFileData */
sp_RENAME '<TableName>.<ColumnName>', 'xx<ColumnName>' , 'COLUMN'
GO

/* create a new varbinary(max) FILESTREAM column */
ALTER TABLE <TableName>
ADD <ColumnName> varbinary(max) FILESTREAM NULL
GO

/* move the contents of varbinary(max) column to varbinary(max) FILESTREAM column */
UPDATE <TableName>
SET <ColumnName> = xx<ColumnName>
GO

/* drop the xx<ColumnName> column */
ALTER TABLE <TableName>
DROP COLUMN xx<ColumnName>
GO

Comment: If you encounter an error message "A table that has FILESTREAM columns must have a nonnull unique column with the ROWGUIDCOL property." you can add this property to a column with the following T-SQL statement: `ALTER TABLE  ALTER COLUMN  ADD ROWGUIDCOL`. Note that the column  must be of type uniqueidentifier.


Can i place slip in a wave like pattern?

Question: Can i place slip in a wave like pattern?
Can i place first slip ahead of keeper towards batsman instead of behind the keeper?
I have not seen these types of fieldings.
Comment: As answered in your other question, you can place fielders wherever you like. You probably haven't seen them because they're not a good idea, not because they're forbidden by the laws.
Answer: You can, but if I was 1st slip I'd refuse to stand where you suggested. The ball comes fastest to first slip, and the extra distance is to allow the player to react.
To answer your question, there are no restrictions preventing you from doing it, just logical reasons why it doesn't happen.


"Non-naive" bayesian classification algorithms

Question: Based on the problem description in this post:
Relating parameters to a measured variable

Based on a suggestion, I thought of studying the relationship between the parameters and a measured metric using Naive-Bayes classification. As, I was reading about it, I got to know that it assumes conditional independence i.e. P(x1 | A,x2) = P(x1 | A), where x1  and x2 are parameters.
This may not be true in my case. Are there similar classification algorithms that do not assume independence? I understand that I may require higher number of samples but I can get them because this data is obtained from simulations.
It would be nice if I do not have to code one for myself; so please let me know if R-packages may be available?
Comment: In addition to Dougal's answer: for equal-variance multivariate-normally distributed data in each class, the Bayes classifier is linear discriminant analysis, and for unequal variance it is quadratic discriminant analysis. As a first step I'd recommend to try LDA.
Answer: For a classification problem with data $X$ and labels $Y \in \mathcal{Y}$, if you know the exact distributions, the classifier least likely to make a mistake (the Bayes classifier) is given by
\begin{align}
\hat{y}(x)
&= \arg\max_{y \in \mathcal{Y}} P(Y = y \mid X = x)
\\&= \arg\max_{y \in \mathcal{Y}} \frac{P(X = x \mid Y = y) P(Y = y)}{P(X = x)}
\\&= \arg\max_{y \in \mathcal{Y}} P(X = x \mid Y = y) P(Y = y)
.\end{align}
Since of course in practice we don't know those distributions, we can replace them by an estimate.
The Naive Bayes classifier follows from assuming the components of $X$ are independent, and using some density estimator or another on each dimension of $X$.
The $k$-nearest neighbor classifier is basically equivalent to using a $k$-NN density estimator for $P(X = x \mid Y = y)$ (the built-in knn function). Using kernel density estimation gives you a kernel-based classifier (the np package does this well, though I don't think it has a built-in classifier). These make no independence assumptions.
As @Jacques notes, you can do similar thing with so-called Bayesian networks, which assumes an independence structure according to a particular graph; you can attempt to learn that graph from the data.
Many other classifiers can also be cast in this framework.
Comment: How well does random forest fare against these methods? Someone told me that it performs better than naive-bayes, and so, I was reading about it.
Comment: Very dataset dependent, but if you just throw random forests at your raw data you're probably more likely to get a good result. They don't really fit into this model very nicely.
Answer: The package bnlearn have different forms of "learning the Bayesian network" from the data.


Bind the ngFor index to Formcontrol Id

Question: I'm trying to bind the ngFor index to a input FormControlName when the component start or add new row.

        <mat-form-field floatLabel='never'>
            <input matInput type="number" style="text-align: right" formControlName="Id"  value="{{i+1}}" >
        </mat-form-field>

I made the entire example, please take a look the id don't get the value automatic from the input.
https://stackblitz.com/edit/invoice-id
After a lot of research I found a simple solution with the trackBy: trackByFn.

and
trackByFn(index, item) {

     item.value.Id = index+1
    return index;
  }

Answer: Your initial value setting is not considered a change/input and therefore will not update the value on your FormControl. If you determine the id based on the length of your array, you can pass it to your add function and remove value="{{i+1}}" from your html:
constructor(private formBuilder: FormBuilder) {
    this.invForm = this.formBuilder.group({
        tool: this.formBuilder.array([this.addEqp(1) ])
    });
}

addEqp(id: number) {
    const group =  this.formBuilder.group({
        Id: [id],
        qnt: [''],
        description: [''],
        price: [''],
        total: ['']
    });
    return group;
}

addEquip() {

    const control: FormArray = this.invForm.get(`tool`) as FormArray;
    control.push(this.addEqp(control.length + 1));
}

`
Comment: Thank so much for you answer. It's work, but I need a id more dynamic, if I add 3 rows and delete the second row, the next id of a new row will be 3 like the last.

Bind the ngFor index to Formcontrol Id


Standard deviation of sample proportions (standard error) in R

Question: This resource states that the standard deviation of the sampling distribution (the standard error) is equal to:

They provide an example where a population has p=0.6 and samples of n=25 are drawn from this population. Hence the standard error equals:

Using R, I'm now trying to validate this calculation of the standard error.
set.seed(123)
pop <- c(rep(x = 1, times = 60), rep(x = 0, times = 40))
df <- data.frame()

for(i in 1:1000){

    sample <- sample(x = pop, size = 25)
    df <- rbind(
        df,
        data.frame(mean.prop=mean(sample)))
}

df %>% summarise(se=sd(mean.prop), mean=mean(mean.prop))

se          mean
0.08612411  0.59888

Why does my standard error of 0.086 differ so much from the theoretical standard error of 0.098?
Comment: I believe you want to use: `sample(x = pop, size = 25, replace=TRUE)` if not due to the sampling the small population size skews the results.
Comment: Yes, setting replace=TRUE seems to work. Thank you.
Answer: Dave2e's comment will fix your issue. Alternatively, you can skip the definition of pop and use rbinom to generate a sample from the population directly.
set.seed(123)
df <- data.frame()

for(i in 1:1000){

  sample <- rbinom(n=25, size=1, prob = 0.6)
  df <- rbind(
    df,
    data.frame(mean.prop=mean(sample)))
}

df %>% summarise(se=sd(mean.prop), mean=mean(mean.prop))

          se    mean
1 0.09849019 0.60232


What is the correct way to rename a signed, zip-aligned .apk file?

Question: I use an app when developing for android that takes care of all the signing and zip aligning for me, however when it is finished all the apks end up with the same name. Now I know that it doesn't really matter as google play renames the apk anyway, but I want to be able to tell the apks apart when storing them locally and still have them as valid signed/aligned apks. So I guess my question is can I just rename them using windows explorer or do I need a special tool to rename them correctly?
Answer: I've just been using standard file managers (Mac OS Finder/unix mv) to rename my APKs. Haven't run into any issues so far. I think that the Google Play developer console just ignores the filename for all practical purposes, which is how it should be.
The signing and zip-aligning are thinks that happen to the file data. The filename is part of the file's metadata which is stored seperately by the filesystem of your OS. If you edit a file's metadata it shouldn't result in a change to the data - and if it does, there's a bug in your file manager!
What the Google Play developer console does care about is the manifest in the apk, though!


Python: how to read variables from another process?

Question: So i'm building a custom machine learning simulation and wanting to read certain values from a training process, in another one to visualize real time training data.
So for example, the training simulation has an array of values under a data structure. Let's say the data structure is an instantiated class called data. Inside this class, there is a list of values, let's call it values.
This simulation has a training loop, so while that training loop is going, I would like to run another script that can query data.values and do something with it.
Is this possible? - Ideally I would like to keep my simulation code as is so as to not add necessary bulk.
Comment: The solution suggested by @SBylemans (RabbitMQ) could also be really useful. You should have a look at it ;)
Comment: Maybe you can setup communication between your processes using a socket. Did you read this : https://docs.python.org/3/library/ipc.html ?
Comment: The first thing that comes to my mind "have you tried a fork?", I might be wrong though
Comment: @Eggplant what do you mean by a fork?
Comment: @Antwane I think a socket would be the way to go, but I would also like a route where I can effectively read the memory from one process to another soas to be a more general solution. But for my problem, this may be the way to go.
Comment: @DyllanM I thought forking your process would help, but now I remember that fork only initially copy variables from the parent process. So you wouldn't be able to read changes anyway.
Answer: You can use a message queue for that. Add the value to the queue in your loop process and read and visualize with the other application. Take a look at RabbitMQ
Comment: Hmm, this seems promising. I'll have to try it out when I'm able. Thanks for the recommendation.


Create empty block

Question: I want to create an empty block that could be edited by the administrator, but by default the block should contain a body.
The module block block_custom_block_form() contains the following code.
$form['body_field']['body'] = array(
'#type' => 'text_format',
'#title' => t('Block body'),
'#default_value' => $edit['body'],
'#format' => isset($edit['format']) ? $edit['format'] : NULL,
'#rows' => 15,
'#description' => t('The content of the block as shown to the user.'),
'#required' => TRUE,
'#weight' => -17,

);
How can I override this function to set #required to FALSE?
Answer: block_custom_block_form() is called from block_block_configure(), which an implementation of hook_block_configure(). Those hooks are called from block_admin_configure(), which is the form builder for admin/structure/block/manage/%/%.
The code used from the function to invoke the modules is the following one.
  $block = block_load($module, $delta);
  $form['module'] = array(
    '#type' => 'value',
    '#value' => $block->module,
  );
  $form['delta'] = array(
    '#type' => 'value',
    '#value' => $block->delta,
  );

  // Get the block subject for the page title.
  $info = module_invoke($block->module, 'block_info');
  if (isset($info[$block->delta])) {
    drupal_set_title(t("'%name' block", array('%name' => $info[$block->delta]['info'])), PASS_THROUGH);
  }

  $form['settings']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Block title'),
    '#maxlength' => 64,
    '#description' => $block->module == 'block' ? t('The title of the block as shown to the user.') : t('Override the default title for the block. Use !placeholder to display no title, or leave blank to use the default block title.', array('!placeholder' => '<none>')),
    '#default_value' => isset($block->title) ? $block->title : '',
    '#weight' => -19,
  );

  // Module-specific block configuration.
  if ($settings = module_invoke($block->module, 'block_configure', $block->delta)) {
    foreach ($settings as $k => $v) {
      $form['settings'][$k] = $v;
    }
  }

Code similar to the following one should work.
function mymodule_form_block_admin_configure_form(&$form, &$form_state) {
    // Check the module implementing the block is the Block module, and not another one.
    if ($form['module']['#value'] == 'block' && isset($form['settings']['body_field']['body']))
    $form['settings']['body_field']['body']['#required'] = FALSE;
  }
}

The function is an implementation of hook_form_FORM_ID_alter(), where FORM_ID is block_admin_configure, in your case.
If you are editing an enabled module, you need to first disable, and then re-enable it. Drupal saves in a cache the list of hooks implemented from modules; disabling, and re-enabling a module forces Drupal to clear that cache. Differently, Drupal will not notice you added a new hook to the already enabled module.
Comment: It doesn't work, this function is implemented on the block module not in the block custom module.
Answer: For adding a block with an empty body, the hook should be "mymodule_form_block_add_block_form_alter". You can use the hook code from espero's answer, something like this:
function sf_random_form_block_add_block_form_alter(&$form, &$form_state) {
    // Check the module implementing the block is the Block module, and not another one.
    if ($form['module']['#value'] == 'block' && isset($form['settings']['body_field']['body']))
    $form['settings']['body_field']['body']['#required'] = FALSE;
}

Create empty block


Compactness Interpretation?

Question: We define a set $X$ as compact if: "for every open cover of $X$, there exists a finite subcover."
An Open Cover $C$ of $X$ is defined as the union of a collection of Open Sets:
$$C = \bigcup_{i \in I} A_i$$
and a finite subcover as the union over a finite subcollection:
$$F=\bigcup_{i \in F} F_i$$
If we define the collection of of open sets to contain only one element e.g. the reals $A=\{\Bbb R\}$. Then there exists a finite subcover of $\Bbb R$, since we have a finite subcover consisting of only one element i.e. $\Bbb R$. Thus, $\Bbb R$ is Compact (which is obviously incorrect.)
Take another example: consider any bounded set $E \subset \Bbb R$. Hence one could construct a superset of E given by: $F \supset E $. Let the collection of open sets consist of only element e.g. $A = \{F\}$. Hence there exists a finite subcover of $E$ consisting of only one element i.e. $F$. Hence $E$ is Compact (regardless of whether or not $E$ is closed or open, which is again incorrect.)
I am struggling to understand the concept of a finite subcover. We could always construct the Open Cover to be the union of a collection of a single set, hence a finite subcover will always exist. Is there a constraint on what a finite subcover should be, other than it should be a finite collection of sets? Do the sets in the collection have to be bounded for example, or is there something else? From what I've read, there is no imposed constraint on the finite subcover other than for it to consist of finitely many sets.
Comment: If $X$ is compact, then there is a finite subcover of *any* open cover, not just of those examples where it's easy to find a finite subcover
Comment: But how do we construct such an open cover? There are infinitely many ways to construct an Open Cover?
Comment: Your subcover has to take sets from your cover $\{A_i\colon i\in I\}$, not some new sets.  In other words, there exists a finite subset $F$ of $I$ such that $X=\bigcup_{i\in F}A_i$.  You are not allowed to change  the $A_i$ once they are given to you.
Comment: There may be infinitely many open covers, but to show it's compact, you must show that *any* one of them has a finite subcover
Comment: You have emboldened a lot of words, but you didn't embolden "for every" in the first line. That's a universal quantifier, "for every" means "for every". It doesn't mean, "for some",  "for one", "for whichever one I first think of" etc. It does mean "for every". Did I mention that "for every" means "for every"?
Answer: It seems to me that you understood perfectly the meaning of "finite subcover". The problem lies at "for every open cover". Yes, $\{\Bbb R\}$ is an open cover of $\Bbb R$ which has a finite subcover. However, $\Bbb R$ is not compact since, for instance, the cover$$\bigl\{(n,n+2)\mid n\in\Bbb Z\bigr\}$$is another open cover of $\Bbb R$, and this cover has no finite subcover.
Comment: When a space is not compact, there is no general method to prove that it is not compact by constructing an open cover without a finite subcover. That is done case by case. For instance, the set $\{(x,y)\in\Bbb R^2\mid x^2+y^2<1\}$ is not a compact subset of $\Bbb R^2$ because the set$$\left\{\{(x,y)\in\Bbb R^2\mid(x-1)^2+y^2>r\}\,\middle|\,r>0\right\}$$is an open cover without a finite subcover.
Comment: I completely agree with you, but as far as I understand, the construction of an Open Cover is arbitrary, so how does one go about proving Compactness? In the lectures I see, the lecturer seems to sort of pull out an Open Cover from a hat, without generalizing over what the collection constituting the the Open Cover could be. The case you mention is easy to see, but let's say generally, how does one prove the "for any Open Cover" part?
Comment: But you could consider the set $0r_2\}.$$
Comment: That's not what I meant. There are infinitely many numbers yes, but we could put them in a single set: $\{\{(x,y)∈R^2∣(x−1)^2+y^2>r\}∣∣0r\}∣∣0<r<2\}$ is a single set, correct?
Comment: Oh sorry, misread the parentheses $\{\}$...never mind. You stated the collection composing the Open Cover, and not the Open Cover itself... sorry for the trouble.
Comment: I'm glad I could help.

Compactness Interpretation?


using sort with dup2

Question: I'm experimenting with this dup2 command in linux. I've written a code as follows:
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int pipe1_ends[2];
    int pipe2_ends[2];
    char string[]  = "this \n is \n not \n sorted";
    char buffer[100];
    pid_t pid;

    pipe(pipe1_ends);
    pipe(pipe2_ends);

    pid = fork();

    if(pid > 0) { /* parent */

        close(pipe1_ends[0]);
        close(pipe2_ends[1]);

        write(pipe1_ends[1],string,strlen(string));
        read(pipe2_ends[0], buffer, 100);
        printf("%s",buffer);
        return 0;
   }

   if(pid == 0) { /* child */
       close(pipe1_ends[1]);
       close(pipe2_ends[0]);
       dup2(pipe1_ends[0], 0);
       dup2(pipe2_ends[1],1);
       char *args[2];
       args[0] = "/usr/bin/sort";
       args[1] = NULL;
       execv("/usr/bin/sort",args);
   }
  return 0;
}

I expect this program to behave as follows:
It should fork a child and replace its image with sort process. And since the stdin and stdout are replaced with dup2 command, I expect sort to read input from the pipe and write the output into the other pipe which is printed by the parent. But the sort program doesn't seem to be reading any input. If no commandline argument is given, sort reads it from the stdin right? Can someone help me with this problem, please.
Many thanks!
Answer: Hm. What's happening is that you aren't finishing your write: after sending data to the child process, you have to tell it you're done writing, either by closing pipe1_ends[1] or calling shutdown(2) on it. You should also call write/read in a loop, since it's quite likely in the general case that read at least won't give you all the results in one go. Obviously the full code checks all return values, doesn't it?
One final thing: Your printf is badly broken. It can only accept null-terminated strings, and the result returned by read will not be null-terminated (it's a buffer-with-length, the other common way of knowing where the end is). You want:
int n = read(pipe2_ends[0], buffer, 99);
if (n < 0) { perror("read"); exit(1); }
buffer[n] = 0;
printf("%s",buffer);

using sort with dup2


View that filters content based on current page

Question: I'm in the middle of a Drupal 6 to 8 migration and am attempting to recreate a view.  This view would appear on pages of the content type "People" and would show the "Publications" that this person is associated with.  The "Publications" has a field of type "Entity reference" that references each of the "People" titles.
How do I configure the view block to only show Publications that have the entity reference of the current "People" page?  I figure this has something to deal with contextual filters, but I'm a bit lost on how to filter this correctly.
Thank you in advance.
Answer: Recreating Drupal 6 Views in Drupal 8 should be quite straightforward. What got you confused?
You need to create a list of all "Child" nodes (Publications) and add the Contextual filter for the Entity reference field that references the "parent". Configure that filter to use the "Provide default value", "Content ID from URL". Adjust all the other options in the filter to your specific needs.
When you add the Block to a region in your theme you also have to set the option again (in the Block settings) for the Contextual filter to use the Content ID from URL.
Comment: Thank you for your answer, this was what I needed.


C++ header file

Question:
Possible Duplicate:
In C++ why have header files and cpp files?

Why in C++ is there a .h and .cpp and not only one file like c# and Java ?
Answer: For historical reasons. Specifically, for compatibility with C. That language was originally designed to run on (for 70s standards) low-end machines; header files were (and often still are) substituted inline by a separate program, to keep the memory use of the compiler down. It still helps to keep libraries small.
Answer: Because c# and java do not require forward declarations. C++ requires the forward declarations.
Answer: C++ has a pre-processor that it inherited from C. The pre-processor has many interesting features, but one of the things that it is used for is to structure the code into headers and source files.
Structuring the code into headers and source files allows you to determine which parts of the code are visible to other source files (i.e. the parts you put in the header) and which ones aren't.
It also means that you don't need any special tools to know which classes are available to you, as you would if you had import in stead of #include: you have part of the source code to work with in stead (which you can read with any text editor).
The advantages notwithstanding, the pre-processor is really a legacy from C++'s parent, C, and has survived the evolution of C++ almost entirely in-tact.

C++ header file


JFreeChart - Gráficos em Java Swing não aparecem na tela

Question: Olá, estou desenvolvendo uma aplicação em Java swing para um projeto da universidade. Basicamente é um programa que lê arquivos XML's provenientes de outra aplicação (jogo mobile) e gera relatórios gráficos a partir dos dados (coisa fácil...). Minha dúvida é a seguinte, estou utilizando a biblioteca JFreeChart que é responsável por criar os gráficos, peguei um exemplo básico para entender como funciona e é bem simples, exceto por não ter funcionado.
Criei um JFrame com um JPanel e um botão, no botão coloquei o seguinte código:
DefaultPieDataset dpd = new DefaultPieDataset();
dpd.setValue("Valor 1", 10);
dpd.setValue("Valor 2", 20);
dpd.setValue("Valor 3", 30);
dpd.setValue("Valor 4", 40);

JFreeChart grafico = ChartFactory.createPieChart("Nome do Grafico", dpd, true, true, true);

ChartPanel chartPanel = new ChartPanel(grafico);
primeiroGrafico.add(chartPanel);
primeiroGrafico.validate();

Porém o gráfico não aparece dentro do painel!?
Esses são os namespaces:
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

Desde já, agradeço!
Answer: Testei aqui com este código e deu certo:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

public class Grafico {
    public static void main(String[] args) {
        EventQueue.invokeLater(Grafico::run);
    }

    private static void run() {
        // Cria uma tela com uma panel vazia dentro. Usa esta panel para definir
        // o tamanho mínimo e preferencial da janela.
        JFrame frame = new JFrame("Olá, JFreeChart!");
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel raiz = new JPanel();
        raiz.setLayout(new BorderLayout());
        Dimension tamanho = new Dimension(600, 480);
        raiz.setPreferredSize(tamanho);
        raiz.setMinimumSize(tamanho);
        frame.add(raiz);
        frame.pack();
        Dimension sd = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation((sd.width - frame.getWidth()) / 2, (sd.height - frame.getHeight()) / 2);

        // Cria o painel aonde o gráfico será mostrado.
        JPanel primeiroGrafico = new JPanel();
        Dimension tamanhoArea = new Dimension(600, 450);
        primeiroGrafico.setPreferredSize(tamanhoArea);
        primeiroGrafico.setMinimumSize(tamanhoArea);
        raiz.add(primeiroGrafico, BorderLayout.CENTER);

        // Cria o botão.
        JPanel areaBotoes = new JPanel();
        JButton botao = new JButton("Criar gráfico");
        areaBotoes.add(botao);
        raiz.add(areaBotoes, BorderLayout.SOUTH);

        // Define o que acontece ao clicar no botão.
        botao.addActionListener(e -> {
            DefaultPieDataset dpd = new DefaultPieDataset();
            dpd.setValue("Valor 1", 10);
            dpd.setValue("Valor 2", 20);
            dpd.setValue("Valor 3", 30);
            dpd.setValue("Valor 4", 40);

            JFreeChart grafico = ChartFactory.createPieChart("Nome do Gráfico", dpd, true, true, true);

            ChartPanel chartPanel = new ChartPanel(grafico);
            primeiroGrafico.add(chartPanel);
            primeiroGrafico.validate();
        });

        // Mostra a tela.
        frame.setVisible(true);
    }
}

Eis aqui o resultado após clicar no botão:
Comment: Obrigado! criei um novo projeto e funcionou, agora preciso ver porque não funciona no projeto anterior! mais muito obrigado!


StateError (Bad state: Future already completed) flutter

Question: class MapsView extends GetView<MapsController> {
  MapsView({Key? key}) : super(key: key);

  Completer<GoogleMapController> _controller = Completer();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder<QuerySnapshot<Object?>>(
          stream: controller.getCampus(),
          builder: (context, snap) {
            if (snap.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
                // heightFactor: 13,
              );
            }
            if (snap.hasData) {
              var listCampus = snap.data?.docs;
              for (var i = 0; i < listCampus!.length; i++) {
                var detailCampus = listCampus?[i].data()! as Map<String, dynamic>;

                String title = detailCampus["nama"];
                String snipet = detailCampus["categori"];
                double lat = double.parse(detailCampus["latitude"]);
                double long = double.parse(detailCampus["longitude"]);

                LatLng latlong = LatLng(lat, long);
                MarkerId markerId = MarkerId(detailCampus["latitude"] + detailCampus["longitude"]);

                controller.addMarker(markerId, title, snipet, latlong);
              }
              return Stack(
                children: [
                  // _googleMap(context),
                  // _buildContainer(context),
                  Container(
                    height: Get.height,
                    width: Get.width,
                    child: GoogleMap(
                      mapType: MapType.normal,
                      initialCameraPosition: CameraPosition(target: LatLng(-7.6893549, 110.2408421), zoom: 8),
                      onMapCreated: (GoogleMapController controller) {
                        _controller.complete(controller);
                      },
                      markers: Set<Marker>.of(controller.allMarkers),
                    ),
                  ),
                  Align(
                    alignment: Alignment.bottomLeft,
                    child: Container(
                      margin: EdgeInsets.symmetric(vertical: 25),
                      height: 150,
                      child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: listCampus?.length,
                        itemBuilder: ((context, index) {
                          var detailCampus = listCampus?[index].data()! as Map<String, dynamic>;
                          return InkWell(
                            onTap: () async {
                              final GoogleMapController controller = await _controller.future;
                              var lat = double.tryParse(detailCampus['latitude']) ?? 0;
                              var long = double.tryParse(detailCampus['longitude']) ?? 0;
                              controller.animateCamera(
                                CameraUpdate.newCameraPosition(
                                  CameraPosition(target: LatLng(lat, long), zoom: 18, tilt: 50, bearing: 45),
                                ),
                              );
                            },
                            child: Container(
                              width: 350,
                              height: 150,
                              margin: EdgeInsets.only(right: 12),
                              decoration: BoxDecoration(
                                color: Color(0xffF5f5f5),
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: Row(
                                children: [
                                  Container(
                                    padding: EdgeInsets.all(16),
                                    child: Icon(
                                      Icons.school,
                                      size: 50,
                                    ),
                                  ),
                                  SizedBox(width: 12),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      SizedBox(height: 90),
                                      //title
                                      Text(
                                        "${detailCampus["nama"]}",
                                        overflow: TextOverflow.ellipsis,
                                        softWrap: false,
                                        style: GoogleFonts.signika(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 16,
                                        ),
                                      ),
                                      SizedBox(height: 5),
                                      // subtitle
                                      Text(
                                        "${detailCampus["categori"]}",
                                        style: GoogleFonts.signika(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 14,
                                          color: Colors.grey,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          );
                        }),
                      ),
                    ),
                  ),
                ],
              );
            } else {
              return Center(
                child: Text("Error"),
              );
            }
          }),
    );
  }
}

every time i made a changed in my project this error always appear. i dont know where is the problem. but it does not give any impact in the application. app still running correctly. but this annoying every time i made a change in my program it will appear. please help me to fix this. i also hade some warning with "?" like this [{"The receiver can't be null, so the null-aware operator '?[' is unnecessary.\nTry replacing the operator '?[' with '['.",
"source": "dart",
"startLineNumber": 32,
"startColumn": 46,
"endLineNumber": 32,
"endColumn": 48
}]
Comment: if you are using getx, can you include that tag as well
Answer: It's nothing, just a warning. Check out the code that this warning is pointing. That variable can't be null so there's no need to have operator "?". Just carefully investigate that variable, find out why it could be/couldn't be null.
Edit:
Oh I find out. The line above you code listCampus!.length with operator "!" make the compiler surely think listCampus cannot be null. So the line bellow you use listCampus?[i] is not necessary, that's why it gives a warning.
Edit 2:
Check out this related question. Did you complete _controller in anywhere else? Flutter: Google Maps StateError (Bad state: Future already completed)
Comment: on **edit 2** i was see it and try it. it fix my problem but it made my ink well didnt work


Array to string conversion

Question: <code>$replacements = array(
    '{order_id}' => $order_id,
    '{site_url}' => $settings["site_url"],
    '{email}' => $user_email,
    '{last_name}' => $last_name,
    '{phone}' => $phone,
    '{order_total}' => currency_format($order_total),
);

    foreach($replacements as $param => $value){
    $sms = str_replace($param, $value, $db2->f('sms'));
    $user_to = str_replace($param, $value, $db2->f('user_to'));
    $user_from = str_replace($param, $value, $db2->f('user_from'));
    $user_subject = str_replace($param, $value, $db2->f('user_subject'));
    $user_body = str_replace($param, $value, $user_body);
    $admin_to = str_replace($param, $value, $db2->f('admin_to'));
    $admin_from = str_replace($param, $value, $db2->f('admin_from'));
    $admin_subject = str_replace($param, $value, $db2->f('admin_subject'));
    $admin_body = str_replace($param, $value, $db2->f('admin_body'));
}
</code>
What is the problem? Why can't work? Array to string conversion....
Can anyone suggest how to reduce the number of lines of code in such a case?
Comment: What are you getting ? What is $db2 ? What are $order_id, $settings, etc...
Comment: When you ask a question on stack overfow. You should tell people what the problem is, not ask them :)
Comment: http://stackoverflow.com/questions/3819423/convert-this-associative-array-to-a-string-or-single-indexed-array
Comment: Read docs of [`str_replace`](http://docs.php.net/str_replace). You don't need this `foreach` loop. There is an example of exactly what you need.
Comment: @SilentGhost You think I don't read this? I've used before two arrays, templates and replace, but variables too much (much more than I described), and I thought somehow reduce the code...
Comment: @Luntegg: _variables too much_? What are you trying to say? There are too many variables? So make an array of the variables names and iterate over it.
Comment: @SilentGhost I'm trying to make it
Answer: <code>$replacements = array(
    '{order_id}' => $order_id,
    '{site_url}' => $settings["site_url"],
    '{email}' => $user_email,
    '{last_name}' => $last_name,
    '{phone}' => $phone,
    '{order_total}' => currency_format($order_total),
);

$templates = array(
    'sms' => $db2->f('sms'),
    'user_to' => $db2->f('user_to'),
    'user_from' => $db2->f('user_from'),
    'user_subject' => $db2->f('user_subject'),
    'user_body' => $db2->f('user_body'),
    'admin_to' => $db2->f('admin_to'),
    'admin_from' => $db2->f('admin_from'),
    'admin_subject' => $db2->f('admin_subject'),
    'admin_body' => $db2->f('admin_body')
);

foreach($templates as $way => $tmp){
    $templates[$way] = strtr($tmp, $replacements);
}
</code>
Answer: You're overwritting $user_body each time you loop.
Try that:
<code>$replacements = array(
    '{order_id}' => $order_id,
    '{site_url}' => $settings["site_url"],
    '{email}' => $user_email,
    '{last_name}' => $last_name,
    '{phone}' => $phone,
    '{order_total}' => currency_format($order_total),
);

$user_body = $db2->f('user_body');
foreach($replacements as $param => $value){
    $user_body = str_replace($param, $value, $user_body);
}

echo $user_body;
</code>
Comment: What notice are you talking about ?
Comment: Maybe $db2->f() is returning an array. We can't just guess.
Comment: Use var_dump() on every suspicious variable. That will show you if one of them is an array

Array to string conversion


Force User to enable location before log in - ASP.NET MVC 5

Question: I am working on ASP.NET MVC 5 Razor based web application. I want to implement GPS Tracking. I want to force user to allow access to its location when he hits login button after entering username and password.
So when user enters username and password and hits submit button, I want to show pop up saying 'Do you want to give access to your location?'. If he says yes, then he should be signed in other wise the request does not move forward.
I tried to search but could not find anything upto my needs.
Any Help?
Answer: You can read about getting user consent and having a fallback if geolocation is required right here
Comment: It's nice to post most important link content on SO in case link'a content will be removed.


How to pass a date format from view in python to a

Question: I set a field where the user can choose date range (Start, End):
if request.method == 'POST':
            fecha = (request.POST.get('datefilter')).split(' - ')
            start = datetime.strptime(
                fecha[0].strip(), "%Y-%m-%d").date()
            end = datetime.strptime(
                fecha[1].strip(), "%Y-%m-%d").date()

when I print the variable start after selecting the date range I get the correct date which was chose by the user. Now I have to take both of them (start and end) and send them to HTML page where I am going to use them but when I try to send them like this:
return render(request, "path/page.html", {"start": start, "end": end})

and get them like this inside the script in the HTML page

I am getting an integer instead of the date which I am trying to send from the view.
for example. If I want to call data from 25-01-17 to 25-01-18
25-01-17 would be the start date and 25-01-18 the end date so when I print those variables in the view to be shown in the console I get the correct date chose by the user.
print(start)
print(end)

output:

25-01-17
25-01-18

but when I try to print those same variables in the script inside html page, I get something different
console.log(start);
console.log(end);

output:

7
6

I realized that what is happening is a math operation. 25 - 01 = 24 - 17 = 7.
How can I solve this problem ?
Answer: Try just wrapping them in quotes, if they should be strings, like this:


Having trouble with getJSONObject method

Question: I am trying to populate an adapter with information from my jsonArray. I have seen this done in many examples but I am getting an error that "The method getJSONObject(String) in the type JSONObject is not applicable for the arguments (int)"
Here's the code...
// jsonArray declared and filled with information
int length = jsonArray.length();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
    for (int i = 0; i < length; i++)
    {
        String obj = jsonArray.getJSONObject(i).getString("NAME");
        adapter.add(obj);
    }

Comment: WHat is the type of the jsonArray variable?
Comment: JSONObject, that could very well be the problem
Comment: Guess you answered your own question then.
Answer: As you can see in the documentation, the prototype of the function is not getJSONObject(int) but getJSONObject(java.lang.String), so you can't use this function with your i
I think you can use the keys() function to get an Iterator with string name.


How to handle both the KeyDown and KeyUp events in a Silverlight 3 TextBox

Question: I am attaching handlers to the KeyDown and KeyUp events of a Silverlight 3 TextBox as so:
_masterTextBox.KeyDown += (s, args) =>
{
     CheckForUserEnteredText(MasterTextBox.Text);
     args.Handled = false;
};

_masterTextBox.KeyUp += (s, args) => { UpdateText(MasterTextBox.Text); };

When I comment out the KeyDown handler, then the KeyUp will trap the event, otherwise, only the KeyDown handler is triggered.
Can someone explain why the KeyUp event handler is not firing after the KeyDown handler does?
Thanks.
Answer: I think you need to look inside your CheckForUserEnteredText function.  Certainly there is no reason from the posted code alone for KeyUp not to fire and it does in my testing.
Perhaps CheckForUserEnteredText does something to prevent it? You seem to have both a public field/property called MasterTextBox and one called _masterTextBox, do you need both? Could it be the KeyUp is firing but UpdateText isn't doing what you expect?  The list could go on, the bottom line is there isn't a problem with the code you've posted.
Answer: It turns out that the problem was that I was setting a break point in the keydown method.  Apparently, when you set a break point, it misses the keyup event.


How to "configure host" in MegaRaid Storage manager 13.01.04.00

Question: Context
I have created a virtual machine on ESxi host and installed Megaraid Storage manager on the virtual machine. I can see localhost discovered on MSM but when I configure Esxi host IP and try discovering the host I get error " Servers could not be found because server may be down or server not installed in the host system"
Question
Am I missing something from installing or have followed the wrong process? can someone please help on this.
Comment: You installed the Megaraid Storage manager on a VM so that you could manage the storage of the host? If so, that's probably not going to work. Does the host have any embedded management tool, like ILO or iDRAC?
Comment: this is a UCS server it has ucs manger configured for the host system (esxi host).
Answer: In order to use MegaRAID Storage Manager (MSM) remotely the following steps should be completed before attempting discovery:

LSI SMIS Provider VIB (lsiprovider) should be downloaded and installed on the ESXi Host where RAID adapter is located and the host restarted.
CIM Server on ESXi host under Configuration->Security Profile should be set to Start and Stop with host and be in a Running state.
Firewall rules for CIM Server on the same page should allow inbound connections for CIM Server, CIM Secure Server and CIM SLP
Status of RAID Adapter should be visible in Health Settings under Storage.

Within MSM, discovery options should be set to Display all the ESXi-CIMOM servers in the network of local server, saved and only then discovery attempted.
Answer: Having done this exact scenario on 2 different servers I can vouch that installing the MSM on a VM to manage the health of the RAID card on the host is very much doable.
Peter Zhabin is absolutely correct with his instructions on needing to install the VIB and setting up the CIM service and firewall rules.  However there are a couple gotchas in those seemingly easy instructions.  Before installing the VIB make sure to change your host acceptance level to "community supported" and enter maintenance mode. Also be sure to install the vib using the the "no-sig-check" parameter.  Lastly there is a tricky step needed on the VM guest so that it can communicate with the host.
On your Windows virtual machine, you need to edit the hosts file so it can communicate with the esx host. Right click on Notepad and select "Run as Administrator." Open your system hosts file, which can be found at c:\windows\system32\drivers\etc. You will need to select "all file types" to be able to see it. Add the IP address for both the hostname and the FQDN of your ESXi host.
The 2 resources I used to get this working are below, take a look through them you should have no issue getting your MSM up and running.
https://serenity-networks.com/how-to-install-lsi-megaraid-storage-manager-msm-on-vmware-esxi-5-5/
https://tinkertry.com/esxi-5-1-can-run-lsi-megaraid-in-a-vm
Answer: I don't know if it's still of any value for you, or if your problem was connected to the VM, but anyhow; maybe someone else finds it useful.
I had the same error message, and the following resolved the issue for me (on a HP workstation without a VM installed):
The "MSMFramework" service ("MegaRAID Storage Manager Framework Service") was not started, instead, startup type was set to "Automatic". So I simply started the service (I don't know why it was not running, though), and then it worked.


codeigniter multiple ckeckbox

Question: I'm trying to get multiple checkbox values I get the last value always not all of it I tried to check if it array but it's single value
<?php echo form_open('user/favorit_cats');?>

please select the food cateogry you want to see it the most

 <?php
    for($i=0;$i<sizeof($cats_names);$i++){
        echo'<input type="checkbox" name="meal_cat" value='.$cats_id[$i].'>';
        echo ''.$cats_names[$i].'
';

    }
    ?>
    <?php echo form_submit('submit','set as favorit'); ?>
    </form>

and my controller
 if($this->input->post('subm it')){
               if(is_array($this->input->post['meal_cat'])){
                   echo'array';
               }
            }

I want to get all the values that checked
Answer: On html form if you want pass input as array, you should name it as an array. For example:
<input type="checkbox" name="var[]"/>

Answer: Try changing name :
Instead of meal_cat in :
<input type="checkbox" name="meal_cat" value='.$cats_id[$i].'>';

Change by meal_cat[] :
<input type="checkbox" name="meal_cat[]" value='.$cats_id[$i].'>';

And in your php use this variable as array.
Answer: You pass the input name as an array and then you can access all checked boxes using the var itself which would then be an array.
Set the name in the form to meal_cat[] and you will be able to access all the checkboxes as an array.
$this->input->post('meal_cat');

It will be an array, the same thing as $_POST['meal_cat'].
To Print the array:
<?php
if (isset($_POST['meal_cat']))
{
    print_r($_POST['meal_cat']);
}
?>
// OR

<?php
if (isset($this->input->post('meal_cat')))
{
    print_r($this->input->post('meal_cat'));
}
?>

And if you want that data in the comma separated list then it try implode
echo implode(',', $this->input->post('meal_cat'));

codeigniter multiple ckeckbox


Sigma fields and intervals on R

Question: I've been looking at the following question and am having some trouble with parts,
basically you have to assume that a sigma field is generated by each of the following collections of subsets below and show why they are all equal.
A = {$(a,b)|a<b \in R$};
B = {$(a,\infty)|a\in R$};
C = {$(-\infty,a)|a\in R$};
D = {$[a,b)|a<b \in R$};
I've found that showing $\sigma (A) = \sigma(D)$ is quite easy as you just use the fact that you can write open internals i.t.o closed and vice versa. But what i cannot seem to get is why $\sigma (A) = \sigma(B)$ then $\sigma (B) = \sigma(C)$ and $\sigma (c) = \sigma(D)$
My initial though after seeing the problem was that you could simply use the fact that b>a and therefore if b could potentially be infinity and therefore showing $\sigma (A) = \sigma(B)$ is pretty trivial, only given that $b \in R$ am i correct in assuming that b could not actually ever be infinity and I have to find some other way of doing it? Should i rather use the fact that I am working with sigma fields and try to work it out that way? I am sorry if this is a completely idiotic question but it's quite late at night and I might be missing something very simple.
Answer: $\sigma$-fields are closed under countable union and complements, so consequently also under countable intersection.

If $a,b\in\mathbb R$ with $a<b$ then $(a,b)\in\sigma(B)$ because: $$(a,b)=(a,\infty)\cap[b,\infty)^{\complement}=(a,\infty)\cap\left(\bigcap_{n=1}^{\infty}\left(b-\frac1n,\infty\right)\right)^{\complement}$$
This proves $A\subseteq\sigma(B)$ and consequently $\sigma(A)\subseteq\sigma(B)$.
If $a\in\mathbb R$ then $(a,\infty)\in\sigma(C)$ because:$$(a,\infty)=(-\infty,a]^{\complement}=\left(\bigcap_{n=1}^{\infty}\left(-\infty,a+\frac1n\right)\right)^{\complement}$$
This proves $B\subseteq\sigma(C)$ and consequently $\sigma(B)\subseteq\sigma(C)$.
If $a\in\mathbb R$ then $(-\infty,a)\in\sigma(D)$ because:$$(-\infty,a)=\bigcup_{n=1}^{\infty}[-n,a)$$
This proves $C\subseteq\sigma(D)$ and consequently $\sigma(C)\subseteq\sigma(D)$.
If $a,b\in\mathbb R$ with $a<b$ then $[a,b)\in\sigma(A)$ because:$$[a,b)=\bigcap_{n=1}^{\infty}\left(a-\frac1n,b\right)$$
This proves $D\subseteq\sigma(A)$ and consequently $\sigma(D)\subseteq\sigma(A)$.

Sigma fields and intervals on R


Qual a vantagem de se ter uma instância única quando se usa o padrão singleton no desenvolvimento web?

Question: Pesquisando um pouco mais sobre singleton achei alguns comentários a favor e contra o uso dessa abordagem.
Porém continuo na dúvida da utilidade de se instanciar uma única instância de uma classe (e fazê-la global) num cenário de desenvolvimento web, onde devería-mos carregar esse objeto entre as sessões.
Em resumo a minha pergunta seria, qual a vantagem ou o que faria um programador escolher o singleton num cenário de desenvolvimento web, já que não tem como criar objetos globais entre sessões. Uma outra abordagem seria instanciar uma classe no início da sessão e carregá-la nas variáveis globais entre as páginas.
Aqui neste cenário específico me refiro a desenvolvimento web usando php por exemplo.
Comment: Relacionado: https://pt.stackoverflow.com/q/18860/57801
Answer: O padrão singleton ajuda a aumentar desempenho do sistema em uma aplicação web, principalmente em conexões com Banco de Dados ou fontes externas.
Ao invés de criar uma conexão cada vez com o Banco de dados, será criada uma única vez para toda instância web (enquanto não voltar para tela), reduzindo o tempo de consulta e o número de conexões.


Inserção de inputs criados dimanicamente

Question: Eu estou criando campos dinamicamente assim:
<code>$(document).ready(function(){

    $('#quantidade').on('change', function(){

      var quantidade = $('#quantidade').val(),
          campos = $('#campos');

      campos.html(''); //aqui eu fiz limpar a div
      for (x = 0; x < quantidade; x++) {
        campos.append('<input type="text" id="campo-'+x+'" />');
      }

    });

});
</code>
Porém, agora não sei como inserir esses campos no banco, pois irão variar. Aceito sugestões!
Answer: Bom acredito que sua pergunta seja como recuperar isso no PHP é isso?
Para isso adicione [] depois da tag name do seu input.
Vou deixar um exemplo:
<code>$(document).ready(function(){

    $('#quantidade').on('change', function(){

      var quantidade = $('#quantidade').val(),
          campos = $('#campos');

      campos.html(''); //aqui eu fiz limpar a div
      for (x = 0; x < quantidade; x++) {
        campos.append('<input type="text" id="campo-'+x+'" name="campo[]" />');
      }

    });

});
</code>

Exemplo no PHP de como recuperar:

<code><?php

for($i = 0; $i < count($_POST['campo']; $i++) {
    echo "Campo $i = " . $_POST['campo'][$i];
}
</code>
Para salvar no banco de dados você pode fazer o uso de uma tabela 1 para N, onde nessa tabela vc coloca o id da informação principal e repete a quantidade de informações que o campo foi inserido com vários inserts.
Caso deseje estudar um pouco sobre Modelagem de dados deixo como dica o site da fundação Bradesco lá tem vários cursos gratuítos e um deles é sobre a modelagem de banco de dados.
Comment: Obrigada, funcionou corretamente.


How to see the individual fivestar ratings in a view?

Question: How do I design a view to see every user's fivestar rating? I want to see a node, and below that list all users' ratings (and not connect it to comments). The only thing I've been able to do is list every user that has rated a node and get the value of their vote (percent) but if I change the value to show the "rate widget", so that I can see the nice fivestar rating, it can either show me the logged-in user's rating or the average rating. It will not show me the actual user's rating.
Answer: I believe you can create a relationship to Votes, and then you can show the users who voted and their vote values.
Comment: Thank you for the response. That is indeed what I did, but again, it will only show the percentage (which is correct), but if I want to see the actual fivestar widget, it will only let me see the logged in user's rating or the average, not the value of the star.
Comment: Ah, your best bet then would to just build your own with a views_pre_render hook. Get the rating, then generate the number of stars based on the value.


how to save the value of a jspinner from change listener

Question: I wish to use the value created called spinnerModel but cannot seem to do so, I believe I have to declare it as a certain type which I am not sure. I want to make it into a double as it will be used later in the program.
I have the following as it stands,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

 public class UI  {

 //Need to use the spinnerModel here but cannot :(

private void weightSpinnerMetricStateChanged(ChangeEvent e) {
    JSpinner weightSpinnerMetric = (JSpinner) e.getSource();
    SpinnerModel spinnerModel = weightSpinnerMetric.getModel();
    System.out.println(spinnerModel.getValue());
}
    stonesSpinnerImperial = new JSpinner(); //Spinner created here.

stonesSpinnerImperial.setModel(new SpinnerNumberModel(3, 3, 31, 1));
            stonesSpinnerImperial.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    stonesSpinnerStateChanged(e);
                    stonesSpinnerImperialStateChanged(e);
                }
            });
}

Answer: You should retrieve the value from the spinner model, and not trying to save the event.
This is all explained in the Swing tutorial about spinners. A small copy paste of the code from that turial
public void stateChanged(ChangeEvent e) {
        SpinnerModel dateModel = dateSpinner.getModel();
        if (dateModel instanceof SpinnerDateModel) {
            setSeasonalColor(((SpinnerDateModel)dateModel).getDate());
}

Of course you will need to adjust this code to match your current setup (e.g. change the cast to SpinnerDataModel to your spinner model)
Comment: I was wondering as I am using numbers if using the SpinnerNumberModel would be any better? If so how would you use it or is it the same as the SpinnerDataModel?
Comment: What exactly is still a problem. As you set the model yourself, you can safely cast is to `SpinnerNumberModel`


Generate ssh key pairs to connect to additional remote machines

Question: I've already generated a ssh key pair to connect to a remote machine, and now need to connect to a second/separate machine using the same method.
Should I continue using the same existing key pair (by copying the public key to the new machine)? Or should I create a new key pair and use that for the new machine?
If the latter, how should I do it on my local machine without interfering the existing key pair?
Comment: possible duplicate of [SSH: Do you use one private/public key pair for each remote machine? Or a single pair for all?](http://serverfault.com/questions/80478/ssh-do-you-use-one-private-public-key-pair-for-each-remote-machine-or-a-single)
Comment: @TheCleaner, thanks for linking the other question. However, that question doesn't explain how to generate and use multiple key pairs without interfering each other. Could you shed some light on that aspect?
Comment: Sure: http://serverfault.com/questions/125672/is-it-possible-to-have-more-than-one-private-public-key-pair-per-user-for-ssh?rq=1
Comment: you can use option "-i" to use the second key, man ssh
Answer: You just need to copy your existing public key to all hosts you want to connect to. Just use ssh-copy-id to setup your public key into the remote host.
$ ssh-copy-id user@machine

By default, ssh-keygen creates the authentication key in ~/.ssh/id_rsa or similar. You can however specify a different file name.
$ ssh-keygen /path/to/new/key

And ask to your ssh client to use this key for authentication.
$ ssh -i /path/to/new/key user@machine

Answer: Generally, yes you can re-use SSH keys. I would personally consider what identities you have - e.g. Is the second system used for the same purpose? I have different keys for my work and personal servers for example.
Another question might be what would happen if your SSH keys were to be compromised? How secure would you like your security?
To answer the latter question, you can use an IdentityFile line in your SSH configuration (or specify the -i argument on the CLI) to use a different SSH key.


Alternative definitions of "internal direct product"

Question: Let be $H_1,\cdots,H_n$ subgroups of the group $G$, then we say that $G$ is an internal direct product of $H_1,\cdots,H_n$ iff

$H_j\triangleleft G$ for $1\le j\le n$, and
$G=H_1H_2\cdots H_n$, and
$H_k\cap H_1H_2\cdots \hat{H_k}\cdots H_n=\{e\}$.

Can property (3) be replaced with the following property?

$H_j\cap H_k=\{e\}$ for all $j\ne k$.

I proved 1+2+3 imply 1+2+3'. Now I have to prove the converse.

By contradiction suppose that there is a $k$ and a $h_k\in H_k$ with $h_k\ne e$ and $h_k=h_1\cdots h_{k-1}h_{k+1}\cdots h_n$.

I dont't need necessarily a proof. To know that the 1+2+3' is a rightfully alternative would suffice.

EDIT It seams that it is not correct according to this post.

Could it be an alternative in case of an abelian group?
Comment: The group in the example in the post you link to  and the group in my answer are both abelian.
Answer: Your property (4) is strictly weaker than (3). For example, take $G = \Bbb{Z}\times \Bbb{Z}$ (pairs of integers) under pointwise addition and let us write the group operation as $+$: $(a, b) + (c, d) = (a + c, b + d)$. Now take $n = 3$ and take $H_1$, $H_2$ and $H_3$ to be the subgroups generated by $(1, 0)$, $(0, 1)$ and $(1, 1)$ respectively. Then your properties (1), (2) and (4) hold, but (3) does not: $H_3 \subseteq H_1 + H_2$.


Series index on $\mathbb Z^n$..

Question: does anyone know if there is a book that deal with series of the kind, $$\displaystyle \sum_{\xi\in\mathbb Z^n}a_\xi,$$ that is, when the indices are in the space $\mathbb Z^n$. I'm looking for the theory of convergence of these series.. Thanks
Comment: I'm a little confused. First and foremost, to talk of convergence, you need to fix an ordering of $\mathbb{Z}^n$. If this sequence (with the fixed ordering) has absolutely convergent sum, then it converges in any order and your notation makes sense. But then, with this definition of your sum, this is nothing but a standard infinite series.
Comment: you mean I can apply the standard tests for checking the convergence of such a series?
Comment: May you help us about the background, where does this come from, what is the context. That would help to have a more concrete outline to support you.
Comment: Well @al-Hwarizmi this comes from periodic Fourier analysis.. If $f\in C^\infty(\mathbb T^n)$, where $\mathbb T^n$ is the $n$-torus then we can write its Fourier series representation $$f(x)=\sum_{\xi\in\mathbb Z^n}\hat{f}(\xi)e^{2\pi ix\cdot \xi}.$$ I came across this kind of things in my master thesis, which I'm still developing, about pseudo-differential operators on torus...In the proof of many theorem I must know about the convergence of series indexed on $\mathbb Z^n$...
Answer: First of all, there is no canonical ordering of $\mathbb{Z}^n$. But $\mathbb{Z}^n \cong \mathbb{Z}$ as sets. Only the cardinality of the index set plus the ordering is decisive.
There are places, where you want to consider $\mathbb{Z}^n$ as a subset of $\mathbb{R}^n$ though, as I can see from your comment. This is important e.g. for applying the Poisson summation formula. With it, you can for example compute the number of points $(k_1, \dots, k_n)$ with $k_1^2 + \dots + k_n^2 \leq D$ (Gauss circle problem) or analytically continue L-functions.

Series index on $\mathbb Z^n$..


Logic of RichTextBox.Paste() method

Question: What is the internal logic of RichTextBox.Paste() method which pastes data from clipboard to RichTextBox.
Actually I want to add text to RichTextBox at the location where cursor is there on button click. But when I add text the added text is either selected after addition or the cursoe location is at the start of added text.
Any solution for this ?
Answer: I think you don't need to know the .NET implementation of the control. It is "black box" for you and me. But, you can do unselect and move cursor to the end of text (this 2 things disturb you, not?)
Moving cursor to position 0 (start):
richTextBox1.Select(0, 0);

Moving to the end:
richTextBox1.Select(richTextBox1.Text.Length, 0);

Select all text:
richTextBox1.Select(0, richTextBox1.Text.Length);

Unselect all and move to the end:
richTextBox1.Select(richTextBox1.Text.Length, richTextBox1.Text.Length);

Logic of RichTextBox.Paste() method


select from two different tables in single query using mysql

Question: I have two different tables. One is instructor and second is student. Both table structure are as follows:
________INSTRUCTOR_________

instructorid schoolid instructorusername instructorfirstname instructorlastname instructortitle level
1             1        inst_A              first_A             Last_A              RN            3
2             1        inst_B              first_B             Last_B              TD            3
3             1        inst_C              first_C             Last_C              FP            3

________STUDENT_________

studentid   schoolid  studentusername    studentfirstname    studentlastname    level
1             1        stud_A              first_A             Last_A            4
2             1        stud_B              first_B             Last_B            4
3             1        stud_C              first_C             Last_C            4

Now, I want to select data from both tables where schoolid is '1' and the result will be like Bellow :
________RESULT_________

id schoolid username firstname lastname title level
1   1        inst_A   first_A   Last_A   RN    3
2   1        inst_B   first_B   Last_B   TD    3
3   1        inst_C   first_C   Last_C   FP    3
1   1        stud_A   first_A   Last_A         4
2   1        stud_B   first_B   Last_B         4
3   1        stud_C   first_C   Last_C         4

Is there any way to do like this? Please can any one help me for this. I have never done like this before.
Thank you in Advance
Answer: use UNION ALL (actually just UNION will do since students have no title). SInce table STUDENT doesn't have title, you need to have an empty column with alias title so it will match the column count. If you don't add extra column for title, you will have error message
The used SELECT statements have a different number of columns...

Full Query,
SELECT  schoolid,
        instructorusername username,
        instructorfirstname firstName,
        instructorlastname lastName,
        instructortitle title,
        level
FROM    instructors
UNION
SELECT  schoolid,
        studentusername username,
        studentfirstname firstName,
        studentlastname lastName,
        '' title,
        level
FROM    students

SQLFiddle Demo
Comment: Hello JW, How can I apply LIMIT to this query?
Comment: what do you mean by limit? limit all the records? by what? but to answer your question directly, `SELECT  schoolid,
        instructorusername username,
        instructorfirstname firstName,
        instructorlastname lastName,
        instructortitle title,
        level
FROM    instructors
UNION
SELECT  schoolid,
        studentusername username,
        studentfirstname firstName,
        studentlastname lastName,
        '' title,
        level
FROM    students LIMIT 10` will show 10 records.
Comment: I mean that I have many more entries in both tables above 500. Now I want to show my result in a data-table grid and apply pagination in it. So when every user go to another page I want to apply LIMIT when fetching result from database
Comment: oh i see, here's a greate article on [Pagination of MySQL Query Results](http://php.about.com/od/phpwithmysql/ss/php_pagination.htm)
Comment: Will this Limit apply to student table or whole result set?
Answer: UNION is the key here:
select schoolid, instructorusername as username,  instructorfirstname as firstname, instructorlastname as lastname, instructortitle as title
from INSTRUCTOR
UNION
select schoolid, studentusername as username,  studentfirstname as firstname, studentlastname as lastname, "" as title
from STUDENT

Comment: Hello Kris, How can I apply LIMIT to this query?
Comment: @Hardik the LIMIT can be placed at the end to limit the overall number or you can do something like [this](http://stackoverflow.com/a/1415380/2773160) by putting each query in parenthesis.


Error: No space left on device: (deleted)/dev/zero

Question: **** Hoster something changed on hypervizor but said, that nothing was changed. The problem is not on the server anymore... ****
Could someone help me to solve the following problem:
If I want to restart the daemon, I have the notification:
Error: No space left on device

lsof | grep deleted:
rewrite-0 11111 11153     nginx  mem       REG               0,96           598535772 (deleted)/dev/zero (stat: No such file or directory)
rewrite-0 11111 11153     nginx  mem       REG               0,96           598535778 (deleted)/dev/zero (stat: No such file or directory)
rewrite-0 11111 11153     nginx  mem       REG               0,96           598535776 (deleted)/dev/zero (stat: No such file or directory)

And a lot of other string for php-fpm, mysql..
This is VPS Centos.
Can't find any solution for that.
Would be very appreciate for the help!

#### UPDATED

Filesystem         Size  Used Avail Use% Mounted on
/dev/ploop16716p1  200G   11G  181G   6% /
devtmpfs           3.0G     0  3.0G   0% /dev
tmpfs              3.0G     0  3.0G   0% /dev/shm
tmpfs              3.0G  248K  3.0G   1% /run
tmpfs              3.0G     0  3.0G   0% /sys/fs/cgroup
tmpfs              615M     0  615M   0% /run/user/1000
tmpfs              615M     0  615M   0% /run/user/0

ls -la /dev/zero
crw-rw-rw- 1 root root 1, 5 Aug 21 16:21 /dev/zero

df -i
Filesystem          Inodes  IUsed    IFree IUse% Mounted on
/dev/ploop16716p1 13295616 353527 12942089    3% /
devtmpfs            786432     65   786367    1% /dev
tmpfs               786432      1   786431    1% /dev/shm
tmpfs               786432    221   786211    1% /run
tmpfs               786432     10   786422    1% /sys/fs/cgroup
tmpfs               786432      1   786431    1% /run/user/1000

[root@mail ~]# dd if=/dev/zero of=/file bs=1G count=50
50+0 records in
50+0 records out
53687091200 bytes (54 GB) copied, 168.672 s, 318 MB/s

[root@mail ~]# du -hs /file
51G     /file

[root@mail ~]# df -h
Filesystem         Size  Used Avail Use% Mounted on
/dev/ploop16716p1  200G   61G  131G  32% /
devtmpfs           3.0G     0  3.0G   0% /dev
tmpfs              3.0G     0  3.0G   0% /dev/shm
tmpfs              3.0G  252K  3.0G   1% /run
tmpfs              3.0G     0  3.0G   0% /sys/fs/cgroup
tmpfs              615M     0  615M   0% /run/user/1000
tmpfs              615M     0  615M   0% /run/user/0

For any reason:
repquota -a:
*** Report for user quotas on device /dev/ploop16716p1
Block grace time: 7days; Inode grace time: 7days
                        Block limits                File limits
User            used    soft    hard  grace    used  soft  hard  grace
----------------------------------------------------------------------
root      -- 7523364       0       0         251948     0     0
nobody    --      20       0       0              5     0     0
smmsp     --      92       0       0             23     0     0
rpc       --       4       0       0              2     0     0
apache    --      16       0       0              4     0     0
mysql     --  180824       0       0            384     0     0
named     --      12       0       0              3     0     0
user      --  236604       0       0           1081     0     0
clamupdate --  260460       0       0              5     0     0
dovecot   --       4       0       0              1     0     0
postfix   --     728       0       0             80     0     0
vmail     -- 1415436       0       0          14824     0     0
spamd     --      32       0       0              9     0     0
nginx     --  775704       0       0          57129     0     0
amavis    --    4644       0       0             31     0     0
postgrey  --   10340       0       0              9     0     0
opendkim  --      40       0       0             10     0     0
opendmarc --     212       0       0              3     0     0
redis     --     284       0       0             16     0     0
ossec     --   29108       0       0           1216     0     0
ossecr    --     284       0       0              5     0     0
ossecm    --       4       0       0              1     0     0
#500      --   97932       0       0           5318     0     0
#1001     --    7024       0       0            435     0     0
#984      --     532       0       0            136     0     0
#501      --   22356       0       0           2645     0     0

I've contacted the hosting provider and they tell me, that the problem they can't find, but logs saying:
Aug 24 07:43:17 mail yum[17224]: Installed: strace-4.12-6.el7.x86_64
Aug 24 07:53:43 mail clamd[1484]: SelfCheck: Database status OK.
Aug 24 07:55:58 mail systemd-tty-ask-password-agent: Error: No space left on device
Aug 24 07:55:58 mail systemctl: Failed to stop systemd-ask-password-plymouth.path: Unit systemd-ask-password-plymouth.path not loaded.
Aug 24 07:55:58 mail systemctl: Failed to stop systemd-ask-password-plymouth.service: Unit systemd-ask-password-plymouth.service not loaded.

And after that restart for daemons is working without any problem.
Any ideas, dear community?
ipcs -a
------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status

------ Semaphore Arrays --------
key        semid      owner      perms      nsems

Comment: Do you actually have enough space on `/`? The `/dev/ploop....` indicates a loopback file system on the VPS host and if the hoster overcommited storage, the hosting file system might be full.
Comment: OK, i re-read your question. But something important is missing: What gave you the error message?
Comment: Check if you can create a file. In the situation I mean, you would get a report that you have plenty of space left, but that's your storage quota. The host FS might be full anyway.
Comment: [root@mail ~]# touch /testfiles
[root@mail ~]# ls -la /testfiles
-rw-r--r-- 1 root root 0 Aug 23 14:14 /testfiles
Comment: succesfully created
Comment: Also nothing in /var/log/messages or in journalctl
Comment: You can create empty files all day. But can you create files with data in them? This is almost 100% your VPS provider has run out of disk space. OpenVZ VPSes lie about how much disk space they really have available.
Comment: Updated the topic. I can create files without any problem. With dd created file 50G
Comment: When I do: systemctl restart "any-daemon". I have the error message: Error: No space left on device
Comment: Normally when a process has a deleted file open the kernel will present it with ` (deleted)` appended to the name. But in your case you have `(deleted)` in the beginning (without a space). I think that difference will provide a clue. Possibly it didn't actually open `/dev/zero` but rather a path ending with `/dev/zero` in which an intermediate directory has been deleted, unmounted, or is otherwise inaccessible.
Comment: Updated the topic
Answer: Since everything else people have suggested for you has failed, I'll try a more exotic one -- has your system for some reason run out of semaphores?
If ipcs -a shows you a long list, then it might be worthwhile to remove the most obvious ones (like, semaphores existing for a user which only should run some service which has already been stopped) with the ipcrm command.
Comment: Everything is emtpy in output
Comment: OK. Well, it was worth a try.
Answer: The problem soved for now with sysctl parameter: fs.inotify.max_user_watches = 10240