How do I find new Active Directory accounts that have been made in the last 90 days?

Question: How do i find new Active Directory accounts that have been made in the last 90 days?
does anyone know who to do this? I can't figure it out.
Thanks in advance.
Answer: For posterity, dsquery is designed for this kind of search. AD does keep a 'whenCreated' field, which makes it easy to search with your tool of choice.
dsquery * -filter "(whenCreated>=20101022083730.0Z)"
As an example. You can programatically create the timestring based on now - 90days.
Comment: +1 may want to use `"(&(objectClass=user)(whenCreated>=20101022083730.0Z))"` to filter out computers and other objects.
Comment: This is extremely slow for an active directory with huge amount of accounts. It seems to do a linear pass through the data.
Answer: Try the following to pull users created in the last 30 days.
Get-ADUser -Filter * -Properties whenCreated | Where-Object {$_.whenCreated -ge ((Get-Date).AddDays(-30)).Date}

Comment: While this answer technically works, it's not very efficient particularly in large AD environments with thousands of users.  You're essentially querying AD for all users and then in memory on your local machine filtering out the ones that meet the "where" criteria.  Instead, you should actually use the Filter argument (or LDAPFilter) to filter the results before they make it back to your machine and avoid the Where pipe altogether.
Answer: An alternative to the Powershell version shown above, that is much more efficient because it does not load all users in memory before filtering them (you should do the filter on the Get-ADUser cmdlet directly and not use a Where-Object):
$now = ((Get-Date).AddDays(-90)).Date
Get-ADUser -Filter {whenCreated -ge $now}

Answer: Using PowerShell and the Quest ActiveRoles Tools for AD (found here - http://www.quest.com/powershell/activeroles-server.aspx) ,
Get-QADUser -CreatedAfter (Get-Date).AddDays(-90)

will give you output to the console or wherever you redirect of all users created in the last 90 days.
Answer: Here's an example from another site of someone retrieving all AD accounts sorted by creation date:
http://www.experts-exchange.com/Security/Operating_Systems_Security/Windows/Q_21117191.html
You can get the creation date for each account from Active Directory. Every AD object has a WhenCreated and WhenChanged attribute. You can dump these attributes into a flat file using the LDIFDE utility, or you can dump them into a comma-delimited file using CSVDE (both utilities come with Windows 2000).
Here's the syntax to dump the two attributes for the user objects in an OU called Phoenix in a domain called Company.com to the console for viewing (the entire entry should typed as a single line):
ldifde -d ou=phoenix,dc=company,dc=com -l whencreated, whenchanged -p onelevel -r "(ObjectCategory=user)"
-f con
If you wanted to save the dump to a file, change the -f switch from con to a file name.
The last logon timestamp uses this format: YYYYMMDDHHMMSS, with the hour shown in Universal Coordinated Time. A time stamp of 20040115182937.0Z corresponds to Jan 15 2004 18:29:37 UCT.
USRSTAT is slow, and the report you get has to be merged with the LDIFDE dump. So, I put together a script that searches for user objects at each domain controller, then lists the local logon time and the creation time. The user logon timestamp requires conversion from a long integer. I borrowed the conversion code comes from Richard L. Mueller (www.rlmueller.net/Programs). Richard's full script also takes the local time zone from the Registry and converts the time from UCT to local time. Nifty
Answer: Actually all these answers are not going to work for a huge production AD environments.
The answer is to use DirSync: https://support.microsoft.com/en-us/help/891995/how-to-poll-for-object-attribute-changes-in-active-directory-on-window
Here is a java implementation of this: https://docs.ldap.com/ldap-sdk/docs/javadoc/com/unboundid/ldap/sdk/experimental/ActiveDirectoryDirSyncControl.html
Basically you continuously ask AD for changes based on an incremental token.
Answer: You can do this pretty easily with dsquery
Here's an opposite but related problem
Dsquery docs


Add drush alias with arguments

Question: I'm working with drush & git and I would like to create a custom drush alias to perform a "git pull" action on a remote server.
This is possibile creating a drushrc.php file in drush home directory with this command:
$options['shell-aliases']['git-checkout'] = '!git checkout';

So if I run
drush @mysite.test git-checkout

the system performs a "git checkout" on the test server.
The problem is that I would like to send parameters, like:
$options['shell-aliases']['git-checkout'] = '!git checkout %branch';

and so:
drush @mysite.test git-checkout my_custom_branch

should checkout a specific branch.
Is there a way to do this?
Answer: Drush will pass any extra argument in the shell alias to the command. So define the shell alias as:
$options['shell-aliases']['git-checkout'] = '!git checkout';

and simply run
drush @mysite.test git-checkout my_custom_branch

Comment: Ok you are right :)
Answer: Maybe the solution is to create not an alias, but a custom command for drush (here are the instructions).
Answer: You can use special shell alias replacements such as {{sitealias-item}}, {{%pathalias-item}} or special {{@target}}, which is replaced with the name of the site alias
used.
Or maybe instead of trying to create complex alias, try creating a command file called COMMANDFILE.drush.inc (as already suggested by arrubiu).

Add drush alias with arguments


az functionapp config appsettinggs set: Will not allow me to use a variable in --settings parameter

Question: I am trying to give function configurations access to keyvault values. I want to use variables so I do not need to hard code values and can use it for multiple environments; however, when I use variables the parenthesis needed at the end of the value disappears because I can no longer use the stop-parsing parameter (--%) with the variable in the string. Is there a way to add the closing parenthesis at the end? Or is there a way to put a variable in the stop-parsing parameter? Or is there a totally different approach I should be using
I used this line below
az functionapp config appsettings set -g  $resource_group -n $function_app --settings  "firstname.lastname@example.com(VaultName=${keyvault};SecretName=CacheConnection)"
I expected my azure portal fucntionapp configuration to contain the name ("CacheConnection") and the value "@Microsoft.KeyVault(VaultName=${keyvault};SecretName=CacheConnection)"), which it does. It just does not contain the closing parenthesis which will be needed. For the value it shows "@Microsoft.KeyVault(VaultName=${keyvault};SecretName=CacheConnection".
Answer: As explained here:

Add additional double quotes for force powershell to treat the argument as a literal

So in your case that should look like that:
<code>`""firstname.lastname@example.com(VaultName=${keyvault};SecretName=CacheConnection)"`"
</code>


Is there a function to provide the first day of the month?

Question: In Java I can get the first day of the month by this way:
GregorianCalendar date;
// Some code
int first = new GregorianCalendar(date.get(Calendar.YEAR),
            date.get(Calendar.MONTH), 1).get(Calendar.DAY_OF_WEEK);

I'm wondering if there a function to do that directly, because I can't find a function that grabs this vital information.
Something similar to what I'm trying to do here:
 for (int i = 1; i < days_in_month + first; i++) {
     // Some code
     if (i - first + 1 == date.get(Calendar.DAY_OF_MONTH)) {
         // Do something
     }
 }

Comment: To makes things clearer, you should explain what `date` variable is. It appears to be `Calendar` type, not a `Date` type. And mention whether you can use the newer `java.time` API or not, because if you can, you should.
Comment: Just curious, why are you struggling with the old and long outdated `GregorianCalendar` class? `java.time`, the modern Java date and time API, is so much nicer to work with. On top of that, its `LocalDate` class makes your job simple: `originalLocalDate.withDayOfMonth(1).getDayOfWeek()`.
Comment: Another quite similar question: [Get first date of current month in java](https://stackoverflow.com/questions/14241836/get-first-date-of-current-month-in-java). Use your search engine to find still more. And next time please search before asking.
Comment: Why the first day of the month is an integer??
Comment: @OleV.V. I'm afraid that you didn't understand the question.
Comment: In that case, @Ibrahim, please explain again. I'm here to help.
Comment: This question is not a duplicate of any question asking how to do it using `java.time`. This is specifically asking if there is a way to do it automatically using `java.util` - it turns out there isn't.
Comment: @corsiKa True, check edit, maybe there is a way to do something similar with `java.time` but I think there will be a need for much (casting).
Comment: I understood that all the time. I consider it legitimate to suggest a different/better solution from the one asked for, it's often helpful, either to the OP or to other readers, and you never know in advance whether it will be. I respect that you know best what is best on your situation. I will let my comments stand for other readers in other situations.
Comment: @Ibrahim Could you try to explain in plain words what you're looking to do? Not code?
Answer: You can convert GregorianCalendar object to the LocalDate object and use it's convenient API:
LocalDate getWithFirstDayOfMonth(GregorianCalendar c) {
    LocalDate date = c.toZonedDateTime().toLocalDate();
    return date.withDayOfMonth(1);
}

GregorianCalendar calendar = GregorianCalendar.from(ZonedDateTime.now());
LocalDate first = getWithFirstDayOfMonth(calendar);
System.out.println(first.getDayOfMonth());

Comment: `c.getTime().toInstant().atZone(ZoneId.systemDefault())` is a very long-winded way of saying `c.toZonedDateTime()`.
Answer: Simply put, no. This is the correct way to get something like this.
This is literally the functionality they put in Java for making calculations like this possible. Any sort of "direct function" would simply do this internally (which I suggest you do.)
Comment: Strictly speaking this answer is incorrect. The function is there, in `java.time`, even a couple of functions for obtaining the same.
Comment: Thanks for your comment, @corsiKa. I'm fine with different interpretations of the question. :-) Only the OP can tell what he meant. He has said already that he prefers his current (very hard to read IMHO) solution. The answers are here for future readers too.
Comment: Pretty much short answer "NO".
Comment: Right. However, if possible, consider using the `java.time` package recommended by logger (before he deleted his answer... `someLocalDate.with(TemporalAdjusters.firstDayOfMonth())` might be better for you - but if you have to replace the entire date api in your app, it might not be worth it.
Comment: I'm preferring my current solution instead of the `java.time` API. Thanks.
Comment: @OleV.V. Strictly speaking, the function in `java.time` does not return a `Date` which is the class OP is using in his entire application, and this question is specifically tagged with. I also commented (2 above yours) that he should consider using `java.time` because it is superior, although probably not worth replacing his entire date layer for. But if the question asks for answers in `Date`, then answers in `java.time` are not correct (even if they are helpful.) My comment on logger's deleted answer (which with sufficient rep you could see) would make that clear.
Comment: As Ole V.V. commented, this Answer is technically incorrect. In Java 8, Java 9, and later, there are indeed built-in functions to get the day-of-week for the first of a month: `myGregCal.toZonedDateTime().toLocalDate().with( TemporalAdjusters.firstDayOfMonth() ).getDayOfWeek().getValue()`
Comment: @BasilBourque Again, no, that's still going to the `java.time` package - the fact that you can put 5 function calls chained together on one line is not the same as making a single function call. I'm well aware of `java.time` and have advocated its use in everywhere except the answer because the question is tagged specifically as javadate.
Answer: tl;dr
To get an integer number representing the day-of-week (1-7 for Monday-Sunday), for the first day of a moment's year-month:
myGregCal                                        // Avoid troublesome legacy date-time classes such as `GregorianCalendar`.
    .toZonedDateTime()                           // Convert from legacy class to modern java.time class, a `ZonedDateTime` object.
    .toLocalDate()                               // Extract a date-only object.
    .with( TemporalAdjusters.firstDayOfMonth() ) // Adjust into first day of the same year-month.
    .getDayOfWeek()                              // Extract a `DayOfWeek` enum object for Monday, Tuesday, etc. Consider using this object directly rather than taking the next step to extract a `int` number.
    .getValue()                                  // Extract an `int` integer number, 1-7 for Monday-Sunday.

… yields a number 1-7 for Monday-Sunday.
Tip: Better to skip the last step, and use DayOfWeek object instead of int:
myGregCal.toZonedDateTime().toLocalDate().with( TemporalAdjusters.firstDayOfMonth() ).getDayOfWeek()  // Render a `DayOfWeek` enum object.

java.time
The Answer by Oleksandr may be correct, and wins points for using the modern java.time classes rather than the legacy date-time classes. But there is a simpler take on such code. Also, the Question appears to want to go a step further, to get the day-of-week for the first-of-month.
Per the comment by Andreas, you could call GregorianCalendar::toZonedDateTime as a easy way to convert from the old legacy class GregorianCalendar to the modern ZonedDateTime class. The old classes gained new methods to facilitate converting between the legacy classes and the modern java.time classes.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;  // Convert from legacy class to modern class.

From there extract a LocalDate object. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate() ;

Adjust the value to the first day of the same month. Use a TemporalAdjuster implementation found in the TemporalAdjusters class.
LocalDate firstOfMonth = ld.with( TemporalAdjusters.firstDayOfMonth() ) ;

Determine the day-of-week for that first-of-month date via a DayOfWeek enum object. That enum pre-defines 7 objects, one for each day of the week: MONDAY, TUESDAY, etc.
DayOfWeek dow = firstOfMonth.getDayOfWeek() ;

Consider using that DayOfWeek enum object instead of a mere clumsy int number to represent your day-of-week. Using objects rather than a int primitive makes your code more self-documenting, provides type-safety, and ensures valid values.
But if you insist, you may extract an int 1-7 for Monday-Sunday per the ISO 8601 standard.
int dowNumber = dow.getValue() ;

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, GregorianCalendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Comment: Good answer. I still think (and I know you agree) that one should prefer to avoid using `GregorianCalendar` in the first place if possible.


What is this linear operator/matrix?

Question: I have a linear operator with its matrix in certain coordinates to be
$$
\begin{pmatrix}
  1       & 0           & 0           & \cdots & 0 \\
  0       & \frac{1}{2} & 0           & \cdots & 0 \\
  0       & 0           & \frac{1}{3} & \cdots & 0 \\
  \vdots  & \vdots      & \vdots      & \ddots & \vdots & \\
  0       & 0           & 0           & \cdots & \frac{1}{n}
\end{pmatrix}
$$
What is this linear operator? How could I construct it without referring to coordinates?
Answer: Of course it could be any number of things, but one operator with this matrix is the one that assigns to every polynomial $p(x)$ of degree less than $n$ the polynomial $\frac1x\int_0^xp(t)\,\mathrm dt$.
Comment: That's exactly how I came to this operator in connection with http://math.stackexchange.com/questions/142941/antiderivative-of-polynomials I just hoped that there is some other interpretation I could rely on.

What is this linear operator/matrix?


Uncaught ReferenceError: function is not defined

Question: Quando chamo uma função, dá:

Uncaught ReferenceError: function is not defined

JS:
function __startGame (__nome, __pronom) {
var canvasGame = document.getElementById("__startGame");
var secondEtap = document.getElementById("scndEtapGame");
var confirmChoiceInt = confirm("Você tem certeza que deseja escolher " + __nome + " como " + __pronom + " presidenciável?");
if (confirmChoiceInt) {
    canvasGame.style.display = "none";
    secondEtap.style.display = "block";
    function showMonLvl(a, b) {
        var spanLvl = document.getElementById("uiLvlSpan");
        var spanMon = document.getElementById("uiMonSpan");
        spanLvl.innerHTML = a;
        spanMon.innerHTML = b;
    }
    function addValue(a, b, c) {
        var spanValueEleitor = document.getElementById("eleitorValueMenuContent");
        var spanValueJuiz = document.getElementById("juizValueMenuContent");
        var spanValueJorn = document.getElementById("jornValueMenuContent");
        spanValueEleitor.innerHTML = a;
        spanValueJuiz.innerHTML = b;
        spanValueJorn.innerHTML = c;
    }
    function addValueXp(a, b, c, d, e, f) {

    }
    function changep() {
        var p1 = document.getElementById("u_06");
        p1.style.display = "none";
    }
    showMonLvl(1, "$50");
    addValue("$100", "$25 000", "$15 000");
} else {}
}

HTML:

Por que será?
Answer: Quando chamas uma função desta maneira onclick="changep();", ou seja: quando chamas uma função diretamente no HTML; ela tem de estar no escopo global. Estar no escopo global quer dizer que a função deve estar fora de outras funções, ou defenida diretamente no window por exemplo assim:
window.changep = function() {
    var p1 = document.getElementById("u_06");
    p1.style.display = "none";
}

Neste caso essa função não usa nada da outra função __startGame, por isso podes mesmo defenir a função fora dessa.
Tens outra alternativa que é correres essa função, ou pelo menos o que ela faz dentro de um oscultador de eventos. Nesse caso podes saber quando o elemento é clicado e corres o código que precisas.
Assim em vez de onclick="changep();" podes fazer assim:
var sDireita = document.getElementById('imgSetaDireita');
sDireita.addEventListener('click', function() {
    var p1 = document.getElementById("u_06");
    p1.style.display = "none";
});

ou até mesmo assim, se a função estiver no escopo global:
sDireita.addEventListener('click', changep);

Answer: Ariel, o seu problema é o escopo,  a mensagem que esta emitindo é que a função que vocẽ esta chamando é indefinida, ao tentar acessar uma função/metodo da função __startGame() chamada changep().
Você pode colocar um parametro adicional a função __startGame() para executar apenas uma determinada tarefa.
Exemplo:

var el = document.getElementById('meuElemtno'); // pega o elemnto button

el.addEventListener('click', function() { // no evento click
  a('c'); // executa a função a() passando o tipo do metodo que é c();
}, false);

function a(tipo) {
  // encontra a o tipo e executa a função;
  if (tipo === 'b') {
    b();
  } else if (tipo === 'c') {
    c();
  }

  function b() {
    console.info('acessando metodo b');
  }

  function c() {
    console.info('acessando metodo c');
  }
}
<button type="button" id="meuElemtno">Click me</button>


Geometric Intuition for the Completion of a Metric Space

Question: Below, is the way I learned the completion theorem. I am wondering if this whole rigmarole has any nice geometric intuition. To get a starting point, let us think of our initial space as
$$M=\{(x,y)\in\mathbb{R}^2|x^2+y^2\le 1\}\backslash\{(0,0)\}.$$
Then what would its completion $C$ will look like in terms of the machinery used in the proof via equivalence classes?
I already know that every subset of a complete metric space is complete if and only if it is closed. So, please just don't tell me that the closure of $M$ is what I am looking for. Let us think in terms of equivalence classes.

Definition 1. A mapping $i:M\to N$ is said to be an isometry iff it is surjective and for every $x,\,y\in M$ we have $d_M(x,y)=d_N(i(x),i(y))$.
Definition 2. A completion of a metric space $(M,d_M)$ is a complete metric space $(C,d_C)$ which has a metric subspace $(N,d_N)$ which is dense in $C$ and is isometric with $M$. It is in this sense that we say $C$ is the smallest complete metric space containing $M$.
Theorem. Every metric space has a completion. Furthermore, this completion is unique up to an isometry. This means that any two completions are isometric. This is called the universal property of a completion.
The proof is a little bit lengthy so here is a sketch of different steps of the proof.

Let $\mathscr{C}$ to be the set of all Cauchy sequences in $M$. Define the relation of being co-Cauchy on $\mathscr{C}$. Show that this relation is an equivalence relation on $\mathscr{C}$. Define $C$ as the set of all resulting equivalence classes. Show that the mapping $d_C:C\times C \to \mathbb{R}$ defined by $d_C([a],[b]):=\lim_{n\to\infty}d_M(a_n,b_n)$ is well-defined and a metric on $C$.
Consider the mapping $i:M\to i(M)\subset C$ which takes every point $x\in M$ to the equivalence class $[a]$ corresponding to the constant sequence $a:\mathbb{N}\to M$ defined as $a_n=x$. This makes sense since every constant sequence is Cauchy. Verify that $M$ and $i(M)$ are isometric and $i(M)$ is dense in $C$ that is $\text{clr}\,i(M) = C$. Show that $C$ is complete.
The last step is to show that every two completions are isometric. Let $(C,d_C)$ and $(E,d_E)$ be any two completions. Then, there are isometries $i:M\to i(M)\subset C$ and $j:M\to j(M)\subset E$ such that $\text{clr}\ i(M)=C$ and $\text{clr}\ j(M)=E$. Verify that $i(M)$ and $j(M)$ are isometric by the map $g:=j\circ i^{-1}:i(M)\to j(M)$. Take any equivalence class $[a]\in C$ and let $\mathcal{A}:\mathbb{N}\to i(M)$ be a sequence of equivalence classes converging to it. Define $f([a]):=\lim_{n\to\infty}(g\circ\mathcal{A})_n$. Show that $f:C\to E$ is well-defined and is an isometry.
Answer: Firstly, let us consider what a completion of a subset of $\mathbb{R}^n$ should be:
Consider some subset $A \subseteq \mathbb{R}^n$, and then define the set
$$\tilde{A}:= A \cup \{\lim_{n \rightarrow \infty} x_n : (x_n)_{n \in \mathbb{N}}\subseteq A\} \subseteq \mathbb{R}^n$$
consisting of all the points in $A$ together with its limit points (where the sequence and limit is considered in $\mathbb{R}^n$). This makes $\tilde{A}$ closed, and thus since $\mathbb{R}^n$ is complete, it makes $\tilde{A}$ complete. In your case this $\tilde{A}$ is the unit ball in $\mathbb{R}^2$.
Since the embedding of $A$ into $\tilde{A}$ should be an isometry, there is only one choice for it, when considering elements of $A$, which $d$ itself.
Since $\tilde{d}$ is necessarily continuous, there is only one choice of metric for elements in $\{\lim_{n \rightarrow \infty} x_n : (x_n)_{n \in \mathbb{N}}\subseteq A\}$; and that is
$$\tilde{d}(\lim_{n \rightarrow \infty} x_n, \lim_{n \rightarrow \infty} y_n) := \lim_{n \rightarrow \infty} d(x_n, y_n).$$
Here it was crucial that there was an ambient space ($\mathbb{R}^n$) to makes this construction; in particular to ensure the existence of the limit points of the sequences $\{\lim_{n \rightarrow \infty} x_n : (x_n)_{n \in \mathbb{N}} \subseteq A\}$.

Now for a more general case: Let some metric space $A$ be given.
The first step is to identify what $\tilde{A}$ should be:
When there is no ambient space, the expressions $\{\lim_{n \rightarrow \infty} x_n : (x_n)_{n \in \mathbb{N}}\subseteq A\}$ are not well defined. However, recall that any convergent sequence is Cauchy. Hence may (naively) define the completion to be the set $A$ together with such elements which we identify as those "to which some Cauchy sequence converges" - i.e. the elements we adjoin are the Cauchy sequences themselves. In order to make this a metric space, the limit of any Cauchy sequence needs to be unique though, so two Cauchy sequences which "converge" to "the same point" should induce the same element. This is where the equivalence relation comes in. Since any constant sequences converges to itself, the $A$ is in bijection with the set of equivalence classes with a constant sequence.
All this amounts to the set
$$ \tilde{A} := \{(x)_{n \in \mathbb{N}} : \text{constant}, x \in A\} \cup \{(x_n)_{n \in \mathbb{N}} : \text{Cauchy}, \forall n \in \mathbb{N}: x_n \in A\} $$
On the first set, the newly defined metric is the same as the original one (which is formally expressed by the map $i$). On the second set, we use the continuity of the metric to define the distance between two adjoint elements.
How should one now think of the completion geometrically?
Visualize where points are that are limit points of sequences in $A$ and then add them to the set.

By the way, a similar (but different) construction is used when defining the real numbers via Dedekind Cuts.
Comment: @H.R. Dedekind made an *order* completion (adding suprema for sets that did not have them yet), the sequence construction is Cantor's and is a *metric* completion.
Comment: (+1) That's a good point about the existence of an ambient space! I was trying to give an example that we don't know its ambient space! But I failed to do so! :)
Comment: By the way, I don't think Dedekind cuts are related here. Using the same techniques of Cauchy equivalence classes is a way of making reals from rationals. Dedekind approach didn't include any sequence stuff.
Comment: Yeah, I think you are right there. They are in the same spirit, but not really the same construction.
Answer: Here is an interesting geometric intuition about the completion thoerem! I found this on a note by Brent Nelson. However, as links may disappear over time, I prefer to write it down here for future readers of this post.
We will imagine our initial space $M$ as a 2-dimensional amorphous blob, lying flat on the ground. If we assume $M$ is not initially complete, then this blob will have lots of tiny pinpricks/holes in it which represent missing points (points that will eventually appear in $M$). Indeed, the moral of our construction is that a metric space really only fails to be complete if it is missing "points" that its Cauchy sequences want to converge to. To produce the completion of $M$, we have to find a way to close up these pinpricks, but our only resource is the space $M$ itself. So, make a copy of our blob and place it directly on top of the previous copy. Here we should imagine they have a certain thickness to them, like a sheet of paper, so that our second copy is literally resting on top of the first. Mathematically, we have constructed $M^2$, which we can think of as length two sequences of elements in $M$. Make another copy of $M$ and set it on the top of the stack. This gives $M^3$. Iterating this procedure will obtain an infinitely tall stack of copies of our metric space, which corresponds to $M^\infty$, the set of sequences
$(x_n)_{n\in\mathbb{N}}$ with $x_n\in M$, for all $n\in\mathbb{N}$. Each sequence corresponds to choosing a point from each copy in the stack, roughly forming an vertical path up to the "top" of the stack. The Cauchy sequences are those paths that eventually start to straighten out (i.e. eventually do not jump around too much horizontally). To visualize the equivalence relation on the set of Cauchy sequences, imagine we climb under the stack and are looking up through the bottom (initial) copy. Then two Cauchy sequences (vertical paths) are equivalent if they get
closer and closer together as they near the top (which is infinitely high up). In particular, if we pick out a point on our bottom copy of $M$, say $x\in M$, and stare straight up through it, we are seeing the constant sequence $(x)_{n\in\mathbb{N}}$.
Now, if we attempt to look up through one of the pinpricks we started with, it will be very difficult to see that it actually remains a pinprick all the way to the top. In fact, due to the infinite height of the stack it will appear to close up (imagine looking down a very deep well, or up a very tall skylight). But this is precisely saying that, up to our equivalence relation, we have managed to plug all the pinpricks in $M$ and therefore
made it complete. Hence this infinite procedure was necessary, since any finite stack of copies would have still had open pinpricks.

It will be a good exercise if you try to imagine each step of the proof by this intuition!
Answer: The completion of your space will be $C=\{(x,y): x^2+y^2 \le 1\}$. You get back the point $(0,0)$ as the class of all sequences $(x_n, y_n)$ whose norm tends to $0$. The characterisation also says so: your $M$ is dense in $C$ and $C$ is compact hence complete. Unicity does the rest.
Answer: Geometrically, we can picture set $M$ as it is in $\mathbb{R}^2$, so it is a closed disc with a hole. A guess would be that the completion is just the closed disc with the hold filled in; for this you can construct a cauchy sequence in $M$ to do that. Because $\mathbb{R}^2$ is complete, cauchy sequences on the disc are convergent sequences in $\mathbb{R}^2$ so you just have to prove that all cauchy sequences in $M$ either converges at the origin or inside $M$ (because $M$+'hole' is closed in $\mathbb{R}^2$); it is automatically the smallest.


Prove $u^2_n-u_{n-1}u_{n+1}=(-1)^n$ if $u_1=1,u_2=2,u_n=u_{n-1}+u_{n-2},n>2$

Question: Prove $u^2_n-u_{n-1}u_{n+1}=(-1)^n$ if $u_1=1,u_2=2,u_n=u_{n-1}+u_{n-2},n>2$
If $n=3$ equality is true.
How to prove this by induction?
Comment: I am pretty sure that the identity should take the form $ u_n^2 - u_{n-1}u_{n+1} = (-1)^n$.
Comment: @Sangchul Lee My mistake.
Comment: Google the formula for the $n-th$ term of the Fibonacci sequence.
Comment: Search the same problem but instead of "$u$" write "$f$" (this is the Fibonacci sequence)
Answer: We may use the following famous trick: Notice that
$$ \begin{pmatrix}u_{n+2} \\ u_{n+1}\end{pmatrix} = \begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix} \begin{pmatrix} u_{n+1} \\ u_n \end{pmatrix}. $$
Recursively using this relation, we have
$$ \begin{pmatrix}u_{n+1} & u_n \\ u_{n} & u_{n-1} \end{pmatrix} = \begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^{n-1} \begin{pmatrix} u_2 & u_1 \\ u_1 & u_0 \end{pmatrix}. $$
Here, we extrapolate the sequence $(u_n)$ using the recurrence relation so that $u_0 = 1$. Now taking the determinant gives the desied result.


what would happen if you use two equals rather than only one in your execution block after an if conditional in JavaScript?

Question: I am still learning, so I'm sorry if my question is not well formatted.
I was trying to write a function to insert a word to a string in a specified position, however I made a mistake which is writing two equal signs == rather than one in the execution block and this resulted in wrong output when tested.
However, I already know that the execution of code after if/else needs to not be boolean and I noticed this typo and I corrected it by removing one equal sign and the function worked perfectly fine but I was just left wondering why have I never questioned the significance of strictly having one equal sign when executing code after if conditionals.
so here is the wrong code:
function insert(original,to_insert,position){
    if (to_insert == "undefined" && position == undefined){return original;}
    else if (position == undefined){position == 0}

    var x = original.slice(0,position);

    var y = original.slice(position);

    console.log(x + to_insert + y);
}

insert('We are doing some exercises.','JavaScript ');
//Wrong output >>>> "We are doing some exercises.JavaScript We are doing some exercises."

insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>>  "We are doing some JavaScript exercises."

and here is the correct code:
function insert(original,to_insert,position){
    if (to_insert == "undefined" && position == undefined){return original;}
    else if (position == undefined){position = 0}

    var x = original.slice(0,position);

    var y = original.slice(position);

    console.log(x + to_insert + y);
}

insert('We are doing some exercises.','JavaScript ');
//correct output >>>> JavaScript We are doing some exercises."

insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>>  "We are doing some JavaScript exercises."

would you please explain what happens inside my wrong code, like what causes the function to not run properly when booleans were used, obviously the function runs once at a time, so what difference would an absolute value of position make compared to a variable value of position.
Thanks in advance
Comment: `position == 0` is wrong in your case, because is evaluating equality, not assigning, like `position = 0`
Comment: Downvoters, would you please comment what you disliked in my question so I can try to improve the quality of my questions later, thanks
Comment: thanks alot Santiago
Answer: One equal is to assign values to variables, two equals are for camparing two variables. This is the simplest way to explain it.
=  -  assigning operator
==  -  comparing operator
Answer: else if (position == undefined){position == 0}
In your wrong code, position remains undefined since you did not do an assignment, you simply checked if position (which is undefined) is equal to  0
So, when you did var x = original.slice(0,position); slice() simply ignored the 2nd argument, which in this case is undefined and sliced from start to end, which is the default behaviour in case the 2nd argument is not used.
From MDN:

The slice() method extracts a section of a string and returns a new string.
str.slice(beginSlice[, endSlice])
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).

In your case, since you pass undefined (because position == undefined), it's like you omitted it
Answer: if (position == undefined){position == 0}
This mean if your position is undefined position must be 0. Like it should be 0 but you are not defining it. Two equals is usually use to do comparution actually :  does position is equals to 0
However one equal mean you assign the value 0 to position.
Answer: I can see two problems in your code.
if (to_insert == "undefined" && position == undefined){return original;}

Here you are checking if to_insert is equal to the string "undefined", but not undefined.
else if (position == undefined){position == 0}

Writing position == 0 will just return a boolean. So in this case, it'll return false (because it execute only if position == undefined returns true).
So it's like if in your code, you had a false between two lines, and you don't change the value of any variable.
else if (position == undefined){position = 0}

By writing only one =, you assign the value 0 to the variable position.
So, when you call the slice() method, the second argument is still undefined, so the method ignore it and just slice the string to the end.
Hope I helped you understand !
Answer: You're essentially asking, "What is the difference between using one equals sign (=) and using two equals signs (==)?"
Assume we have the following initialization for both examples:
var pikachu_hp;

One equality sign (=):
pikachu_hp = 50;

This sets the variable, pikachu_hp, to have the Number data type with a value of 50.
Two equality signs (==):
pikachu_hp == 60;

This compares the value (not data type, that's three (===) equals signs in JavaScript) of pikachu_hp against what is on the right hand side; in this case, that's the Number 60. If pikachu_hp has a data value of 60, the expression returns true. If pikachu_hp has a data value of anything else but 60, the expression returns false. Again, I call this an "expression" because it does not equate to anything; it represents either a true or false value.
Comment: well, OP asked _"... would you please explain **what happens inside my wrong code**, like what causes the function to not run properly ..."_, so OP _essentially_ asked how writting `==` instead of `=` affects the next lines of code
Comment: OP's title question, which is typically the most significant part of any Stack Overlfow question, was "what would happen if you use two equals rather than only one in your execution block after an if conditional in JavaScript?" If I literally answered with emphasis on "execution block", it would be too broad; a LOT of different things could happen depending on the code. All the OP needs to understand is exactly what I explained- which provids them the ability to understand why their specific code is broken _while_ effectively answering this question for others.
Comment: @8protons Thanks alot for your answer I actually wanted to know what Santiago have explained, I explained in my question that I understand that == is a boolean that returns true or false and = is assignment, I just wanted to know how relevant it is to my code.
I understand you probably got it from my question title which poorly formatted (I'm new to stack overflow) so I'm sorry about  this.


How do I show an image using a relative or external url?

Question: Seems like a simple issue but can't find a simple solution.
Basically I have the feeds module populating a content type from another database which has relative URLS of images. ie. /images/image1.jpg
I'm storing this value in a text field type.
Is there a way to easily translate the output of this field into  ?
Answer: Sure, assuming Drupal 7, you can create your own field formatter for this in a custom module:
/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {

  $info = array();

  $info['image_source_formatter'] = array(
    'label' => t('Image Source Formatter'),
    'description' => t('Display the image sourced in this field.'),
    'field types' => array('text'),
  );

  return $info;

}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'image_source_formatter':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'image',
          '#path' => $item['safe_value'], // you can also set '#height', '#width', '#alt', '#title' and '#attributes' here as well, see theme_image() for more details
        );
      }
      break;

  }

  return $element;

}

Clear your caches to be on the safe side, and then you can use this new field formatter for this field, eg, you can go to the Manage Display in your Content Type and select this:

for the plain text field and instead of outputting the text, it will theme the text as the path to an image.
In this field, you can have sites/default/files/foo.jpg if you want and it will source it locally, or you can have http://www.example.com/foo/bar/baz.jpg and that'll work as well, as this will call theme('image', $variables) with the path set to the value of this field.
ADDITION:  The URL Formatter and Simple Field Formatter modules appear to do this for you if you don't want to create your own custom module.
Answer: The easiest way to do this would be overwritting the field template
field-name-[field_name].tpl.php
You can then just simply add your markup
Example:
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><img src="<?php print render($item); ?>" />

    <?php endforeach; ?>

The $items array provides an array of information for that item and uses render to render the output.  See the field template in the drupal api for more information
https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7
If you are using Display suite https://drupal.org/project/ds then you can create a custom field  to output that value alongside the token module.  See this blog post for more details on that: http://www.elevatedthird.com/blog/using-custom-fields-display-suite-drupal-7


CI for hotswapping non-compiled files into VSO and Octopus pipeline

Question: Context:
Currently we manually get a git dev branch built into a package into VSO, and once that package is built it deploys to Octopus and takes down the site for a good amount of time as all the built packages are loaded into each server the site sits on... But, honestly, a lot of the bug fixes end up being in js files that could easily just be hot swapped in... and it's just so annoying to have to wait for poor OPs and support to do all of this just for a teensy tiny change.
The pipedream:
I would like to set up CI that allows hot swapping of js,css,cshtml,html files to VSO and Octopus... This will allow small petty changes in javascript files to be issued out fast and without deployments...
...and also have another option that allows me to say, "look, i've changed some csharp files so i need a built package to be pushed up into VSO and Octopus". A manual rebuild if you will.
Question:
I'm missing the vocabulary to search for this in Google and wondered if you guys can help me on a path to setting this up.
Answer: You can just include the modified files (remain folder structure) in the package, then push this package to Octopus server and deploy with this package, then the necessary files will be replaced.
My workflow of IIS deploy:

New Deployment Target with Listening tentacle mode
Add Deploy to IIS process template for Octopus project
Enable Custom installation directory feature in Configure Features window of Process
Specify Custom Install Directory path in process

Build tasks:

Add Copy Files task to copy necessary files (e.g. js)
Add Package Application task to package these files (remain folder structure)
Add Push Packages to Octopus task
Add Create Octopus Release task

On the other hand, you can include all published files to package (tested with File System publish), then deploy with that package, the Octopus can compare files and just replace the modified files ({webapp}.dll will be replaced too, checked the Created, Modified time on target server)
Regarding get changed files during build, you can call Get commit with Changed items REST API, then create/modify the build variable (e.g. depAll) through Logging Command (e.g. PS: Write-Host "##vso[task.setvariable variable=depAll];]Yes") per to the changed files result, then using this variable in task condition (Control Options of each task) to determine which tasks need to be run. Specify conditions for running a task
Comment: Ah, okay, that sounds pretty simple. Thank you! I'll give it a try


Flowcharts to help selecting the proper analysis technique and test

Question: As someone who needs statistical knowledge but is not a formally trained statistician, I'd find it helpful to have a flowchart (or some kind of decision tree) to help me choose the correct approach to solve a particular problem (eg. "do you need this and know that and that and consider data to be normally distributed? Use technique X. If data is not normal, use Y or Z").
After some googling, I've seen several attempts of various coverage and quality (some not available at the moment). I've also seen similar flowcharts in statistics textbooks I've consulted in libraries.
A bonus would be an interactive site that, besides just having a chart, would provide extra info (such as assumptions) and would point to how to perform those techniques in popular stat packages. "Need to do ANOVA in R? You need package X and here's a tutorial".
I'm asking as a community wiki question in the hope there are better resources I couldn't find. Since statistics is a large subject, I think such a flowchart would be suitable for techniques that can be approached by someone who has beginner or intermediate-level knowledge. Anything more complicated would need someone with formal training.
Answer: These are not really interactive flowcharts, but maybe this could be useful: (1) http://j.mp/cmakYq, (2) http://j.mp/aaxUsz, and (3) http://j.mp/bDMyAR.
Comment: @chl Maybe you should consider pasting them into your answer and providing reference for them?
Comment: Not bad at all. The format is static, but the information is very useful.
Answer: You can look at the solution given on the question "Statistical models cheat sheet"
Answer: I have made this https://www.statsflowchart.co.uk, an interactive stats test flowchart. Let me know what you think. (This is based on an Andy Field flowchart from a text-book, linked on the site).
Comment: Might be worth mentioning in your answer that this is based on the flowchart put together by Field (presumably in one of his statistics for psychology books?)
Comment: the link is dead
Comment: Hi, Thanks for highlighting. It has now moved to a dedicated URL: http://www.statsflowchart.co.uk


How to I make my object stay still after it levitates up/down?

Question: people of stack overflow. I am trying to make a drone game for my personal project and I need some help. I want to make a drone game, but I am stuck at a certain bit. Being that I am unable to make a drone stay in the same position after it levitates up or down. After I press the selected button for levitation the object simply either keeps going up or keeps going down. I was wondering if somehow I would be able to keep the drone in the same Y position after I bring it up or down to a certain point. Any help would be appreciated, thank you for your time and have a good day!!
Code ->
public class Levitating : MonoBehaviour
{
Rigidbody ourDrone;

private void Awake()
{
    ourDrone = GetComponent<Rigidbody>();
}

private void FixedUpdate()
{
    MovementUpDown();

    ourDrone.AddRelativeForce(Vector3.up * upForce);
}

public float upForce;

void MovementUpDown()
{
    if (Input.GetKey(KeyCode.E))
    {
        upForce = 15;
    }
    else if (Input.GetKey(KeyCode.Q))
    {
        upForce = -3;
    }
}

}
Answer: You could set some height limits, and set the drone's speed to 0 once they're reached. Or you could toggle the rigidBody's isKinematic as well.
float upperLimit = 10;
float lowerLimit = -10;

void MovementUpDown()
{
    if (transform.position.y >= upperLimit || transform.position.y < lowerLimit)
    {
        ourDrone.velocity = Vector3.zero;
        ourDrone.angularVelocity = Vector3.zero;
    }

    if (transform.position.y < upperLimit && Input.GetKey(KeyCode.E))
    {
        upForce = 15;
    }
    else if (transform.position.y > lowerLimit && Input.GetKey(KeyCode.Q))
    {
        upForce = -3;
    }
}

Answer: The reason it keeps going in the same direction is that the upForce is never resetted when the user stops pressing the up/down keys.
A "real-world" approach would be to make the default velocity of the drone a Vector3 with the same value as the gravity force.
This makes the drone levitating.
You can put this logic right after the Input check
// Make the drone default velocity the same value of the gravity acceleration, with opposite direction
private const Vector3 DRONE_DEFAULT_VELOCITY = new Vector3(0, 9.81f, 0);

public float upForce;

private void Update()
{
    MovementUpDown();
}

private void FixedUpdate()
{
    ourDrone.AddRelativeForce(DRONE_DEFAULT_VELOCITY * upForce);
}

void MovementUpDown()
{
    if (Input.GetKey(KeyCode.E))
    {
        upForce = 15;
    }
    else if (Input.GetKey(KeyCode.Q))
    {
        upForce = -3;
    }
    else
    {
        // Resetting the force muultiplier
        upForce = 1
    }
}

As I did in the example above, it's also suggested to put the Input check logic into Update() method, and the physical logic into FixedUpdateMethod().
The Update() method is called each frame, while the FixedUpdateMethod() is called only for objects physical update.


SSAS - MDX - Read multiple attributes from a dimension

Question: For example, taking into account the Adventure Works database, I would like to display on rows the hierarchy of accounts and on columns i would like to show "Account Type" property.
This MDX shows an "#Error" on the Account Type column:
WITH MEMBER [Measures].[Account Type] AS [Account].[Accounts].[Account Type].CurrentMember.Name
SELECT
    {[Measures].[Account Type]} ON 0,
    (
        [Account].[Accounts].Members
    ) ON 1
FROM [Adventure Works]

Any idea how this can be improved?
Answer: If you execute your query in Management Studio and either hover the mouse over the "#ERROR" or double click a cell showing "#ERROR", the error message is shown, which states that you use an element expression for CurrentMember while it was expecting an hierarchy. You should use
[Account].[Accounts].CurrentMember.Properties("Account Type", TYPED)

instead of
[Account].[Accounts].[Account Type].CurrentMember.Name

to access properties. In this specific case, the second argument to Properties can be omitted, as it states that the result should be returned as the data type of the property (e. g. integer or date). But here, the original is a string anyway, hence you could simply use
[Account].[Accounts].CurrentMember.Properties("Account Type")

which always returns the property as string, independent of its type.


Continuous time signal and Discrete time signal

Question: I know that all periodic continuous time signal have discrete spectral representations, but are all discrete spectral representations periodic in continuous time?
Also, can all periodic signals be represented by a fourier series?
Comment: This is a fine question. I think the reason people are downvoting you is because of the allcaps title. There is also another website u could ask this on instead: dsp.stackexchange.com
Answer: Nope! Consider:
$$\cos(t)+\cos(\pi t) $$
It's Fourier transform is certainly discrete, but the signal isn't periodic because $\pi$ is irrational. No integer multiple of periods is going to get you back to where you started.


The vectors a and b are non-collinear. For what value(s) of m is it true that (m^2 + 2m - 3)a + (m^2 + m -6)b = 0?

Question: Since they are both non-collinear they can never be equal to zero. So what do i do now?
Any help is appreciated. Thank you very much!
Comment: you might want to recheck your statement "Since they are both non-collinear they can never be equal to zero"... what do you have in your mind...
Comment: if you add non collinear vectors, it can never equal zero
Comment: it would be better if you write it in the question just to make it look better... :)
Comment: you might even want to make " $a,b$ are non zero vectors"....
Comment: @PraphullaKoushik why doesnt the direction change when you multiply a vector by a positive scalar though?
Comment: direction changes when you multiply a vector by a negative scalar
Answer: Hint: Two vectors are non-collinear if and only if they are linearly independent (prove this!). Linear independence in this context means
$$c_1 a + c_2 b = 0 \iff c_1 = 0 = c_2$$
Comment: Should i factor both sets?
Comment: @T.Bongers : You are too fast.. :D
Comment: @PraphullaKoushik The faster I go, the quicker I can procrastinate :)
Comment: @Jessica Yes, that's one way to solve for the values of $m$.
Comment: so how do i solve values for a and b?
Comment: given that i solved for m?
Comment: @Jessica $a$ and $b$ aren't numbers, and can't be solved for here. They're abstract vectors - the *only* salient piece of information is that they aren't collinear.
Comment: oh so a and b are unit vectors
Comment: so i would have 4 values for m and that is it?
Comment: @Jessica It's never given that $a$ and $b$ are unit vectors - they are *just* vectors. You won't have $4$ values of $m$, since it's necessary that $m^2 +2m - 3 = 0 = m^2 + m - 6$.
Comment: so m just equals -3 and thats the answer?
Comment: @Jessica Yes, that's it.
Comment: dont you need to consider cases?
Comment: rather m^2 + 2m - 3 = 0, where m = 1, -3
Comment: and m^2 + m - 6 = 0, where m= 2, -3
Comment: wait nvm the other values dont work! why not??
Comment: @T.Bongers ey who knows! Thank so much for helping me out!
Answer: You need both
$m^2+2m-3 = 0$
and
$m^2+m-6=0$.
Since
$m^2+2m-3
=(m+3)(m-1)
$,
the first equation is true
when
$m=-3$ or $m=1$.
Since
$m^2+m-6
=(m+3)(m-2)
$,
the second equation is true
when
$m=-3$ or $m=2$.
They two equations are both true
only when $m=-3$.


How do I display a help text with field form?

Question: Is there a way to bring up a help message next to a form field as below?
FooForm.php
<code>$form['field_foo'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Foo'),
    '#required'      => true,
    '#default_value' => 'foo',
    '#help_text' => 'Help text for Foo field',
);
</code>
Answer: Use #description attribute.
<code>$form['field_foo'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Foo'),
  '#required'      => true,
  '#default_value' => 'foo',
  '#description' => t('Help text for Foo field'),
);
</code>


Changing a Property of a control in Javascript does not take effect When Reading from ASP.NET

Question: I have a button that is linked to a checkbox via a javascript code, meaning that when the checkbox is checked, the button is enabled and vise versa. The initial value of the button (in ASP markup) is disabled, as well as the chekbox
Now when postback, whichever the button is enabled or not (after playing in javascript), the button is read as (enabled false) in server side (which is the initial value)
can I read the last client-side .disabled value of the button from within ASP.NET (server side)? If so I can assign the client-side value (the real value of the button) to the server side 'enable' property.
Comment: can't help without code... both server and client side code please.
Answer: All asp.net controls are initialized using their earlier states when a postback happens. THat means the enabled="false" value will be used to reinitialize the button control when your page postback happens. So the enabling done by your javascript code will not have any effect there.
You will have to make some tweaks to your code so that this can be achieved.

create a hiddenfield on your page
set a value in the textbox 1/0 OR true/false whenever you are trying to enable/disable the button.
in your page_load ()

if(ispostback){ //read the value of the hidden control and set the enabled/disabled property of the button accordingly. }


Nested PCA : is it the same to reduce dimension one time by m and to reduce m times by 1?

Question: My data is initially represented in a vector space $E$ of dimension $n$.
I want to reduce the dimension by $m$, so I apply a PCA process to obtain a vector space $E'$ of dimension $n-m$.
If I had applied PCA $m$ times but reducing the dimension only by $1$, I would have obtained another vector space $E''$ of dimension $n-m$.
Question : is $E'$ the same vector space as $E''$ ?
I would say no, because in the second case, when reducing the dimension at the $i^{th}$ step, the covariance matrix is estimated using data that has already been distorded by the previous steps... Is that correct ?
Answer: Yes, the result should be the same (aside from any computation round-off error). Go ahead and try it!
PCA is simply a singular-value decomposition on the centered data matrix, X.
Thus, it amounts to an additive representation of orthogonal components:
$$\textbf{X} = \textbf{U}\textbf{D}\textbf{V}^T = \sum_{i=1}^n \sigma_i\textbf{u}_i\textbf{v}_i^T$$
Where $\textbf{D}$ is a diagonal matrix with diagonal elements $\{\sigma_1,\dots,\sigma_p\}$
and $\textbf{u}_i$ are the left singular vectors (columns of $\textbf{U}$) and $\textbf{v}_i^T$ are the right singular vectors (rows of $\textbf{V}$).
Therefore, the n-m dimensional representation truncates this sum after n-m terms.
The n-1 representation truncates this sum after n-1 terms. By taking away the last term in the sum, you've reduced the dimensions by 1. If you were to compute another SVD on the resulting matrix, you'd end up with the same exact terms in the summation.
(Of course when trying this out, you have to keep in mind that singular vectors (and thus PCs and scores) are unique up to a sign (+/-) (in most practical cases, that is - when geometric multiplicity of all eigenvalues is 1, if people want to get pedantic - otherwise they are not unique at all)
So try this out on the iris data in R:
x=princomp(iris[,1:4])
y=princomp(x$scores[,1:3])
round(abs(x$scores[,1:2])-abs(y$scores[,1:2]),13)==0
Take the absolute value because the sign of second PC of y is actually opposite the
 second PC of x. Round the difference between the values to 13 decimal places because,
 like I said, roundoff error bound to be an issue. Then test that there is no difference.
Comp.1 Comp.2
  [1,]   TRUE   TRUE
  [2,]   TRUE   TRUE
  [3,]   TRUE   TRUE
  [4,]   TRUE   TRUE
  [5,]   TRUE   TRUE
  [6,]   TRUE   TRUE
  [7,]   TRUE   TRUE
  [8,]   TRUE   TRUE
  [9,]   TRUE   TRUE
 [10,]   TRUE   TRUE
 [11,]   TRUE   TRUE
 [12,]   TRUE   TRUE
 [13,]   TRUE   TRUE
 [14,]   TRUE   TRUE
 [15,]   TRUE   TRUE
ETC.


Showingthat $\mathbb{R}^2$ with operation $\langle (a,b), (c,d) \rangle = ac - bd$ is not an inner product space

Question: We define the "inner product" as $\langle (a,b),(c,d)\rangle = ac-bd$ on $R^2$
We want to verify if this is an inner product space. I'm saying it's not because it does not satisfy the positivity property of inner products, that is:
An inner product space $\langle x,x\rangle > 0$ if $x\not=0$.
I tried to prove this by letting $x=(a,b)=(c,d)=(5,5)$ so that we have the inner product $\langle x,x\rangle = \langle (5,5),(5,5)\rangle=5\times 5-5\times 5 = 0$ contradicting the positivity property of inner products.
Does this proof make sense?
Thank you!
Comment: It should be fine. Nothing went wrong, in my opinion.
Answer: Yes, your proof is correct.
Also, you might notice that $\langle (1,10), (1,10) \rangle < 0$, which also contradicts nonnegativity.
As an aside, if you rephrase your question as a question and write your proof as an answer, we could come along and upvote it to indicate that it is an answer. Writing yes, you're correct always feels like a somewhat unhelpful answer.
Comment: That's a nice idea but I don't really care for the points, haha. Unless you meant it so other people who view this will see it's the answer.
Answer: You are correct: this is not an inner product. Your argument is sufficient.
In fact, this is a particular instance of a metric which appears in General and Special Relativity. We say that $v$ is a spacelike vector if $\langle v,v \rangle > 0$ or $v=0$, $v$ is lightlike if $\langle v,v\rangle = 0$ but $v \neq 0$, and we say $v$ is timelike if $\langle v,v\rangle < 0$. People work in $4$ dimensions: $$\langle (x_1,y_1,z_1,t_1),(x_2,y_2,z_2,t_2)\rangle = x_1x_2+y_1y_2+z_1z_2-t_1t_2,$$ usually.
In this terminology, $(5,5)$ is a lightlike vector. There is a whole area worth studying about these bilinear forms.
Comment: I'm just giving you a motivation. Inner products aren't the only interesting bilinear maps :)
Comment: I appreciate it :). I always like knowing the reason behind things.
Comment: Thank you! That's a lot of information I don't yet know about but I'm sure I'll learn about it soon enough :P. Thanks again.


Equation of a cylinder with a profile / ellipsoid

Question: I have a geometry of a cylinder that is curved along both the lengths where there is generally a height of a cylinder. I am aware of the equation of a cylinder. I wanted to know what could the equation of a curved cylinder be as a function of the x,y, and z coordinates.? Also, could this curved cylinder be called an ellipsoid?
I have attached a geometry herewith along with the dimensions.
2D

3D
Comment: The shape is called a double radius (or a football shape). This is because it is a rotation of an arc and you need two radii to describe it.
Comment: @John Alexiou I have never heard the name "double radius" for such shapes. It could be called indeed **truncated** (at both ends) football shape. A "barrel shape" as given by Suzu Hirose is a very good choice.
Comment: @JeanMarie - I work with needle bearings which are [cylinders with a profile](https://d3i71xaburhd42.cloudfront.net/b2f49178334922478818e232f8f0fc97c9dc98e6/2-Figure1-1.png) or drop as it called. The contact surface is called a double radius because mathematically [it looks like this](https://www.tribonet.org/wp-content/uploads/2017/10/Spherical-Contact-678x381.jpg.webp).
Comment: @John Alexiou Thank you for the explanation.
Answer: That would probably be called a "barrel shape". The equation depends on the type of curve you choose for the barrel. If it's a circular curve, if the $y$ axis is along the axis of symmetry of the barrel and we count the centre of the barrel as the origin. then the equation for the barrel would be something like
$$x^2+z^2=r^2$$
for the $x$ and $z$ coordinates, and
$$(r+h)^2+y^2=R^2$$
Here $R$ is the radius of curvature of the barrel side and $h<R$ is a constant which expresses an offset from the origin of the centre of the radius of curvature.
So we end up like
$$(\sqrt{x^2+z^2}+h)^2+y^2=R^2.$$
In the case of your diagram, it looks like you have $h=80 \text{mm}$ and $R=90 \text{mm}$.
I couldn't persuade Wolfram Alpha to do a 3D plot of this, but here is a 2D version.

In practice you would do this parametrically.
Comment: Thanks.  I am confused in the 2 equations by you and by @John? How can they be different although logically correct?
Comment: @user1085879 John Alexiou's equation is the same as mine. My $h=R-r$ in John Alexiou's notation, then just take square roots.
Comment: I see it now..Thanks
Answer: Consider the blue curve first

In my notation the small radius is $r=0.01$ and the large radius is $R=0.09$
It is an arc, of radius $R$ and center at $x=R - r$
I use the parameter angle $\theta$ for the sweep angle of the arc from the center.
The coordinates of the arc are
$$ \pmatrix{x \\ y \\ z} = \pmatrix{ (R-r) - R \cos \theta \\ R \sin \theta \\ 0} $$
Now apply a rotation about the y-axis to this arc to get the coordinates of the shape. The parameter angle of the rotation is $\varphi$
$$ \pmatrix{x \\ y \\ z} = \begin{bmatrix} \cos \varphi & 0 & \sin \varphi \\ 0 & 1 & 0 \\ -\sin \varphi & 0 & \cos \varphi \end{bmatrix} \pmatrix{ (R-r) - R \cos \theta \\ R \sin \theta \\ 0}$$
or
$${\rm surf}( \varphi, \theta) = \pmatrix{x=-\cos \varphi ( R \cos \theta - R + r) \\ y=R \sin \theta \\ z=\sin \varphi (R \cos \theta -R + r)} \tag{1} $$
The surface is fully described by the parameters $\theta$ and $\varphi$. If you limit the length of the shape to $\ell$ then you find the limits of $\theta$ from
$$ \tfrac{\ell}{2} = R \sin \theta \tag{2} $$
So $\varphi = 0 \ldots 2\pi$ and $\theta = -\arcsin \left( \tfrac{\ell}{2 R} \right) \ldots \arcsin \left( \tfrac{\ell}{2 R} \right)$.
Here are the results of the parametric surface as viewed from the z-axis, for $R=10$ and $r=1$

From the y coordinate use $\theta = \arcsin \left( \tfrac{y}{R} \right)$
From the z coordinaten use $\varphi = - \arctan \left( \tfrac{z}{x} \right)$
the end relationship is
$$ \boxed{ \sqrt{R^2-y^2}-\sqrt{x^2+z^2}-R+r = 0 } \tag{3} $$
Comment: Thank you for the response! I was wondering why your equation is different from the equation by Suzu Hiroze given in this same section? I put values for the 2 equations and they dont seem to be equivalent.
Comment: I am not convinced @Suzu is correct. I can only see the plot when $z=0$ which is a  special case. I plotted mine for various values of $z$ and I get the shapes I expected.
Comment: @user1085879 - if you plug (1) into (3) you can prove they are identical. (1) is the parametric form, and (3) is the implicit form. With some simplifications, you arrive at $R \cos \theta - ( R \cos \theta - R  +r) -R + r =0$ or $0=0 \; \checkmark$.
Comment: Yes, you are right, although I don't see any flaw in that equation as even if z is varied the maths is taken into consideration. But for my specific geometry if I put the values in the equations, for the Suzu equation I get 0, and for your equation, I get 1e-18 which we can say is almost zero. But I am interested as to which one is the correct one. Also in the cylindrical system for x coordinate, it should be r - R(1-cos(theta)),right? instead of R(1-cos(theta))-r?
Comment: Thanks. I understood that parametric and implicit form are same. But I am confused in the 2 equations by you and by @Suzu? How can they be different although logically correct?
Comment: @user1085879 the surface is symmetric for $x$ and $-x$, so either one would work. It depends on the convention for $\varphi$ used.
Answer:
Btw, if the equation is sought for finding volume of a Barrel it can be done by integration with attention to limits, resulting in the formula
$$ V= \frac{\pi h }{12}\cdot (2D^2+d^2)$$
where $D$ is mid diameter, $d$ is top/bottom diameter and height $h$.


Split line into multiple parts using regex

Question: I have a string like
BK0001 My book (4th Edition) $49.95 (Clearance Price!)

I would like a way to split it into different parts like
[BK0001]
[My Book (4th Edition)]
[$49.95]
[(Clearance Price!)]

I'm pretty new at regex and I'm using this to parse a line on a file. I managed to get the first part BK0001 by using
$parts = preg_split('/\s+/', 'BK0001 My book (4th Edition) $49.95 (Clearance Price!)';

then getting the $part[0] value but not sure on how to split it to get the other values.
Comment: Try spelling out the subpatterns. Say, `preg_match('~^(?<code>\S+)\s+(?.*?)\s+(\$\d[\d.]*)\s*(?.*)$~', $text, $matches)`, see [demo](https://regex101.com/r/EF0I6W/1).
Comment: have you used regex101 yet?  Great resource for both learning regexes and developing for a particular need .
Comment: @Dan Farrel I have but I don't use php and regex often, I code mostly in python and usually use string.split() for tasks such as these. This is one of those rare moments when I need regex and investing time learning it fully really a good option right now.
Comment: @WiktorStribiżew works perfectly. Thanks
Comment: `learning it fully really a good option right now`  it's always good to learn Regex, most languages have some flavor of it and it's incredibly powerful and useful.
Answer: You may match the specific parts of the input string using a single pattern with capturing groups:
preg_match('~^(?\S+)\s+(?<name>.*?)\s+(?<num>\$\d[\d.]*)\s*(?.*)$~', $text, $matches)

See the regex demo. Actually, the last $ is not required, it is there just to show the whole string is matched.
Details

^ - start of a string
(?\S+) - Group "code": one or more non-whitespace chars
\s+ - 1+ whitespaces
(?<name>.*?) - Group "name": any 0+ chars other than line break chars, as few as possible
\s+ - 1+ whitespaces
(?<num>\$\d[\d.]*) - Group "num": a $, then 1 digit and then 0+ digits or .
\s* - 0+ whitespaces
(?.*) - Group "details": any 0+ chars other than line break chars, as many as possible
$ - end of string.

PHP code:
$re = '~^(?\S+)\s+(?<name>.*?)\s+(?<num>\$\d[\d.]*)\s*(?.*)$~';
$str = 'BK0001 My book (4th Edition) $49.95 (Clearance Price!)';
if (preg_match($re, $str, $m)) {
    echo "Code: " . $m["code"] . "\nName: " . $m["name"] . "\nPrice: " .
         $m["num"] . "\nDetails: " . $m["details"];
}

Output:
Code: BK0001
Name: My book (4th Edition)
Price: $49.95
Details: (Clearance Price!)

Answer: Try using preg_match
$book_text = "BK0001 My book (4th Edition) $49.95 (Clearance Price!)";
if(preg_match("/([\w\d]+)\s+(.*?)\s+\\((.*?)\\)\s+(\\$[\d\.]+)\s+\\((.*?)\\)$/",$book_text,$matches)) {
    //Write code here
    print_r($matches);
}

$matches[0] is reserved for the full match string. You can find the split parts from $matches[1]...
Array ( [0] => BK0001 My book (4th Edition) $49.95 (Clearance Price!) [1] => BK0001 [2] => My book [3] => 4th Edition [4] => $49.95 [5] => Clearance Price! )

$matches[1] is "book number"
$matches[2] is "book name"
$matches[3] is "edition"
$matches[4] is "price"
$matches[5] is "special text"


Who will enter into the final in case of rain in first qualifier?

Question: What happens if it rains in the first qualifier in IPL 2014 match between KKR and KXIP?
Who will enter into the final? On what basis?
Answer: If the match abandoned due to rain, then the match will be postponed to May 28(reserve day for first qualifier match).
If the match still abandoned on the reserve day, then the team(KXI Punjab) which finished in the higher position in the points table  will be deemed the winner of the match.
Ref: IPL Playing Conditions 21.10


"for" com step "float": TypeError: 'float' object cannot be interpreted as an integer

Question: Quero fazer um loop de 0 a 100 com step 0.1:
for x in range(0, 100, 0.1):
    a = cos(radians(x))

Mas eu recebo este erro:

TypeError: 'float' object cannot be interpreted as an integer

Como posso fazer um loop com step float?
Comment: Já pensou em implementar um `generator`?
Answer: Consegui fazer algo que possivelmente seja o que você necessita.
from math import cos, radians

for x in (x * 0.1 for x in range(0, 1000)):
    print(x)
    a = cos(radians(x))

print(a)

Código ficaria algo nesse sentido
SUGESTÃO
A utilização de um número decimal neste caso pode acarretar em possíveis erros com a questão do ponto flutuante. Você pode utilizar a biblioteca Numpy fazendo uso da função arange que funciona de forma parecida ao for.
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

Dica Extra
Para evitar a questão de erro com ponto flutuante, pode-se utilizar a função linspace do Numpy.
>>> import numpy as np
>>> np.linspace(0, 1, 11)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])

Fonte: https://docs.scipy.org/doc/numpy/user/quickstart.html
Comment: No primeiro exemplo `for x in [x * 0.1 for x in range(0, 1000)]:`, é melhor `for x in (x * 0.1 for x in range(0, 1000)):` - esse segundo é um "generator expression":  cada elemento só é criado quando for ser usado no `for`. Com `[ ] `, o Python cria primeiro uma lista com todos os elementos - alocando memória pra tudo, e só depois consome os elementos no laço `for` externo. A diferença de consumo de memória é significativa.
Comment: Ok, editei o exemplo acima para ficar mais claro. Não vejo sentido em usar numpy se eu quero apenas calcular o `cos` de cada número no intervalo de `0.1`... teria alguma outra forma?
Comment: @RogérioDec editei a resposta, espero que possa ter solucionado seu problema
Comment: @jsbueno sim verdade, não me atentei nesse ponto.
Answer: Somente para fins de amostragem perceba a inconsistência do resultado dessa implementação de um gerador que realiza a soma de números inteiros e de ponto flutuante.
def _range(initial, end = float("inf"), step = 1):
    act = initial
    while (act < end):
        yield act
        act += step

for x in _range(0, 1, 0.1):
    print(x)

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Leia essa resposta para mais informações: https://pt.stackoverflow.com/a/11328/88315
Answer: É possível alcançar o resultado desejado usando um gerador de ints e dividir o resultado:
    for x in range(1001):
         x = x/10
         print(x)

0.0
0.1
0.2
(...)
99.9
100.0
[Finished in 0.196s]


Bareos / Bacula backup of virtualbox?

Question: I just backed up a vm using bareos (a fork of Bacula) and it appears to have worked, but I installed the file daemon on the vm itself, and it doesn't feel right;  I ended up with what appeared to be a looping directory in the /var/lib/docker/devicemapper/devicemapper/data directory of the vm (the file-daemon just kept backing that up forever until the backups that filled up the directory were larger than the drive being backed up), so I excluded it and the backup completely very quickly.
Instead, should the File Daemon be halting or pausing the Virtual Box machine, and then backing up the VM disk file?
This can be accomplished using the ClientRunBeforeJob directive of a Job, and then it can be run again using the ClientRunAfterJob directive of a Job along with the vboxmanage command.
In short, which is a more reliable way to do this for bareos backups?
Comment: What is your strategy for restoring? Actually _execute it_ once, and then try it again via the other method you've proposed. You will then know exactly what you need to know (and as a bonus you'll learn why VirtualBox is still not taken seriously).
Comment: @MichaelHampton Well I was initially going for restoring the entire VM in case I needed to, back to the vm...but really I'm just trying to learn the different ways in which one can backup and restore machines and VMs in BareOS.   So I want to know how to do it both ways.  Up to this point I've only really restored files back to /tmp/bareos/<path-to-file/file in bareos.  That's not really a catastrophic failure restore...
Answer: Well, depends on you backup/restore strategy. We have 16 active virtual machines. The initial steps on our backup strategy are:

shutdown the virtual machine (ACPI)
backup the directory containing the virtual machine
restart the virtual machine

the steps 1 & 3 assures the health of the always unstable Windows servers.
On our case, the virtual machines do not contain a large quantity of data. The container directory are about 150 GB each.
But you could make a full backup on monday and the rest of the days do several snapshots.
In our case, we prioritize the fast recovery of the full backup done every night.
We do a restore simulation every month to assure the backup/restore procedures are working fine.
Comment: +1 from me for the "test frequently" advice!

Bareos / Bacula backup of virtualbox?


How to fix TypeError: unsupported operand type(s) for +: 'int' and 'list'

Question: Hello i am setting a code for rmse but it happen error
import numpy as np

import matplotlib.pyplot as plt

import random

data=[[235,591],[216,539],[148,413],[35,310],[85,308],[204,519],[49,325],[25,332],[173,498],[191,498],[134,392],[99,334],[117,385],[112,387],[162,425],[272,659],[159,400],[159,427],[59,319],[198,522]]

x_data=[x_row[0] for x_row in data]

y_data=[y_row[1] for y_row in data]

a=np.random.randint(0,10)

b=np.random.randint(0,100)

def f(x):
    return b+a*x

def E(x,y):
    return 0.5*np.sum((y-f(x))**2)

n=1e-3

D=1

count=0

error=E(x_data,y_data)

while D>1e-2:

    tmp0=b-n*np.sum((f(x_data)-y_data))
    tmp1=a-n*np.sum((f(x_data)-y_data)*x_data)
    b=tmp0
    a=tmp1
    current_error=E(x_data,y_data)
    D=error-current_error
    count=count+1
    if count % 100 == 0 :
        print(count,a,b,current_error,D)

error is
Traceback (most recent call last):
    return b+a*x
TypeError: unsupported operand type(s) for +: 'int' and 'list'

Comment: You are trying to multiply and sum a **list** and an **integer**... You cannot multiply lists... So can you explain what are you trying to do?
Comment: `x` is a `list`, you can't use it in a calculation with `int`s - what are you trying to do with it?
Answer: The problem is with
def f(x):
    return b+a*x

In this context, a and b are being interpreted as integers while x is being interpreted as a list.
If your intent is to apply the calculation to every element in x, try something like this:
def f(x):
    out = []
    for i in x:
        out.append(b+a*i)
    return out

You will have similar errors when trying to do more calculations later on where you are using lists in calculations. You will have to make similar changes.
For example:
def E(x,y):
    return 0.5*np.sum((y-f(x))**2)

Will have to be changed to something like:
def E(x,y):
    out = []
    for xi, yi in zip(y, f(x)):
        out.append(0.5*np.sum((yi-xi**2)))
    return out

To avoid a TypeError: unsupported operand type(s) for -: 'list' and 'list'


Is there a package include Phi and Crame v?

Question: With different data, we need to use different correlation function ,such as pearson,phi, Cramér's V.
Correlation is a basic statistic method.
Is there a package include pearson,phi, Cramér's V and other correlation function?
I googled but cannot find a solid and completed answer.
Comment: `questionr` has a Cramér's V calculation, though I  wouldn't load a whole package to calculate it -- you could write a function and verify it works properly in less time than would take to load the package and read the documentation to call the function in it. As for why something like Cramer's V isn't in vanilla R, an econometrician would as easily ask why something as "standard" as Jarque-Bera tests weren't there, while a medical statistician would wonder why something as "standard" as Bland-Altman plots aren't there. What looks "standard" depends on vantage point.
Comment: If you have questions about programming you should post them on stackoverflow. In case of questions about R go to https://stackoverflow.com/questions/tagged/r
Comment: stats::cor() include the most common methods for numeric variables e.g. pearson, kendall, etc. I don't think any base/stats R function will include all the possible variations.
Comment: `assocstats()`from `vcd`,`cramer.v`from`questionr`,and `lsr`,`rcompanion`,so many functions to calculate crame V.Why so many choices to a simple function? Is there a best one? That's the pain when I use R.We just need all-in-one-best statistic tool.I think R should forbidden duplicated function!!
Comment: `vcd` is a useful package for working with categorical data.  I didn't realize there was a function with Cramer's V in there.  I would use that one.  The package has other useful functions that are worth investigating.
Comment: [assocstats](https://www.rdocumentation.org/packages/vcd/versions/1.4-3/topics/assocstats)
Comment: @SalMangiafico,I revised this question,pls reopen it.
Comment: @kittygirl , I didn't vote to close the question.  But I suspect the reason it was closed is that it [still] is written as a question about  R functions. Questions about software are off topic on this site.  I think the heart of the question is actually about statistics, and so could have been left open.
Answer: So, for continuous variable R has the function cor() even within that you need to define a method. Because you apply different types of correlations for different types of data. Take phi and Cramer's V : they're both chi-sq based, but phi is used for 2x2 matrices and Cramer's V for more than 2x2. Tetrachoric is more nuanced where you're finding similarity in continuous variables based on ordinal variables.
As for why they exist in different packages: R is open sourced, people contribute what they feel the need to.
Comment: 'Programming language A does not have feature X from programming language B' does not directly imply 'Programming language A is worse than programming language B'
Comment: @kittygirl you may appreciate package:imports and/or package:strict in R. BTW, Python packages duplicate tons of function names (only hidden because of conservative namespacing), nevermind the rampant abuse of the bit shift operator. Just sayin'.
Comment: agree but hate the duplicate function name in vary packages,that's bad idea.Maybe it's better to  use python instead of r.


Node.js promise request return

Question: I'm using the promis module to return my json data from the request module, but every time i run it, it gives me this.
Promise { _45: 0, _81: 0, _65: null, _54: null }

I can't get it to work, any one know the problem? here is my code:
function parse(){
return new Promise(function(json){
    request('https://bitskins.com/api/v1/get_account_balance/?api_key='+api+'&code='+code, function (error, response, body) {
        json(JSON.parse(body).data.available_balance);
    });
});
}

console.log(parse());

Comment: Promises return a promise, a contract that it will resolve (.then) or reject (.catch) with some data at a later point. I suggest reading up on them. Your logging the returned promise. Your request hasn't returned at that point.
Answer: A promise is an object that serves as a placeholder for a future value.  Your parse() function returns that promise object.  You get the future value in that promise by attaching a .then() handler to the promise like this:
function parse(){
    return new Promise(function(resolve, reject){
        request('https://bitskins.com/api/v1/get_account_balance/?api_key='+api+'&code='+code, function (error, response, body) {
            // in addition to parsing the value, deal with possible errors
            if (err) return reject(err);
            try {
                // JSON.parse() can throw an exception if not valid JSON
                resolve(JSON.parse(body).data.available_balance);
            } catch(e) {
                reject(e);
            }
        });
    });
}

parse().then(function(val) {
    console.log(val);
}).catch(function(err) {
    console.err(err);
});

This is asynchronous code so the ONLY way you get the value out of the promise is via the .then() handler.
List of modifications:

Add .then() handler on returned promise object to get final result.
Add .catch() handler on returned promise object to handle errors.
Add error checking on err value in request() callback.
Add try/catch around JSON.parse() since it can throw if invalid JSON
Answer: Use request-promise:
var rp = require('request-promise');

rp('http://www.google.com')
    .then(function (response) {
        // resolved
    })
    .catch(function (err) {
        // rejected
    });

Answer: // https://www.npmjs.com/package/request
const request = require('request')

/* --- */

/*
    "Producing Code" (May take some time)
 */
let myPromise = new Promise( function( resolve, reject ) {

    request( 'https://example.com', function ( error, response, body ) {

        if ( error ) return reject( error )

        try {

            resolve( body )

        } catch ( error ) {

            reject( error )

        }

    } )

} )

/* --- */

/*
    "Consuming Code" (Must wait for a fulfilled Promise)
 */
myPromise.then(

    function( success ) {

        /* code if successful */
        console.log( success )

    },

    function( error ) {

        /* code if some error */
        console.error( error )

    }

)

Node.js promise request return