Error when adding bulk users in AD with PowerShell script

Question: I'm trying to add users to AD using a PowerShell script that pulls info from a csv file.  I've got it mostly working, in that users are created and they seem to work.  However, I'm getting some exceptions when the script is run, and I need some help to debug it and figure out where it's failing.  The script, csv snippet, and errors follow.  Also note, that it looks like the errors do not occur on every user creation; I only have a few iterations of the errors.
Is there a way I can wrap this in an if/then statement to print out what's happening at the error point, or to see what AD object is failing and why?  Or some other way to debug this?
$objOU=[ADSI]"LDAP://OU=People,DC=testdomain,DC=com"
$dataSource=import-csv "test users2.csv"
foreach($dataRecord in $datasource) {
    $cn=$dataRecord.FirstName + " " + $dataRecord.LastName
    $sAMAccountName=$dataRecord.UserName
    $givenName=$dataRecord.FirstName
    $sn=$dataRecord.LastName
    $sAMAccountName=$sAMAccountName.ToLower()
    $displayName=$givenName + " " + $sn
    $userPrincipalName=$sAMAccountName + "@testdomain.com"
    $sISID=$dataRecord.Sisid
    $objUser=$objOU.Create("user","CN="+$cn)
    $objUser.Put("sAMAccountName",$sAMAccountName)
    $objUser.Put("userPrincipalName",$userPrincipalName)
    $objUser.Put("displayName",$displayName)
    $objUser.Put("givenName",$givenName)
    $objUser.Put("sn",$sn)
    $objUser.Put("description",$dataRecord.Gender + ", " + "Class of " + $dataRecord.Graduation + ", " + $sISID)
    $objUser.SetInfo()
    $objUser.SetPassword($dataRecord.Password)
    $objUser.psbase.InvokeSet("AccountDisabled",$false)
    $objUser.SetInfo()
   }

USERNAME,PASSWORD,SISID,FIRSTNAME,LASTNAME,GRADUATION,GENDER
usera,dfqt4d,1111110681,Akeem,xxxxx,2016,M
userb,nw97ph,1111166963,Ariel,xxxxx,2015,F

Exception calling "SetInfo" with "0" argument(s): "A device attached to the system is not functioning. " At C:\For Sharing\add users script.ps1:19 char:17
    + $objUser.SetInfo <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

Exception calling "SetPassword" with "1" argument(s): "There is no such object on the server. " At C:\For Sharing\add users script.ps1:20 char:21
    + $objUser.SetPassword <<<< ($dataRecord.Password)
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

Exception calling "InvokeSet" with "2" argument(s): "The directory property cannot be found in the cache. " At C:\For Sharing\add users script.ps1:21 char:26
    + $objUser.psbase.InvokeSet <<<< ("AccountDisabled",$false)
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodTargetInvocation

Answer: PowerShell 2.0 supports try/catch blocks, so you can catch and handle any exceptions.
You can put a Write-Host in your catch block to echo to the console which user is causing your script the problem.
Your script for example would look like this.
$objOU=[ADSI]"LDAP://OU=People,DC=testdomain,DC=com"
$dataSource=import-csv "test users2.csv"
foreach($dataRecord in $datasource)
{
    try
    {
        $cn=$dataRecord.FirstName + " " + $dataRecord.LastName
        $sAMAccountName=$dataRecord.UserName
        $givenName=$dataRecord.FirstName
        $sn=$dataRecord.LastName
        $sAMAccountName=$sAMAccountName.ToLower()
        $displayName=$givenName + " " + $sn
        $userPrincipalName=$sAMAccountName + "@testdomain.com"
        $sISID=$dataRecord.Sisid
        $objUser=$objOU.Create("user","CN="+$cn)
        $objUser.Put("sAMAccountName",$sAMAccountName)
        $objUser.Put("userPrincipalName",$userPrincipalName)
        $objUser.Put("displayName",$displayName)
        $objUser.Put("givenName",$givenName)
        $objUser.Put("sn",$sn)
        $objUser.Put("description",$dataRecord.Gender + ", " + "Class of " + $dataRecord.Graduation + ", " + $sISID)
        $objUser.SetInfo()
        $objUser.SetPassword($dataRecord.Password)
        $objUser.psbase.InvokeSet("AccountDisabled",$false)
        $objUser.SetInfo()
    }
    catch
    {
        Write-Host "*** Exception Handler ***"
        Write-Host "Problem username: " $dataRecord.UserName
        Write-Host "*************************"
    }
}

As for reasons the script might crash out, is the sAMAccountName unique (for example John Smith and James Smith both being jsmith) and does sAMAccountName contain any special characters (symbols, letters with accents etc)? There's a few reasons I can think off the top of my head why it might cause an exception.
Comment: You are spot on in your last paragraph.  I won't bore you with details, but I found 3 entries that had a period in the sAMAccountName (they were Jr.'s).  I removed those and it seemed to go through fine after that.  I'll play around with the try/catch handling a little later this week, but I'm confident enough to give you the points.


Hibernate validation issue for blob sql type

Question: I'm getting the following error:
Caused by: org.hibernate.HibernateException: Wrong column type in PUBLIC.PUBLIC.ALL_TYPES_ENTITIES for column blob1. Found: varbinary, expected: blob(255)
    at org.hibernate.mapping.Table.validateColumns(Table.java:383)

I'm creating table using liquibase:
        <column name="blob1" type="BLOB">
            <constraints nullable="true"/>
        </column>

The java entity has a field:
private byte[] blob1;
...
@Basic(fetch = FetchType.LAZY)
@Lob
@Column(name = "blob1")
public byte[] getBlob1() {
    return blob1;
}

I'm using hsqldb 2.2.9 as a database and Hibernate 3.5.0-Final as a JPA provider. Hibernate dialect for hsqldb is:
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>

When liquibase generates a table, the liquibase HsqlTypeConverter should use VARBINARY as sql type.
WHen Hibernate validate scheme it thinks that type is blob(255), compares it with VARBINARY and throws exception.
Here is code that validates the table:
public void validateColumns(Dialect dialect, Mapping mapping, TableMetadata tableInfo) {
    Iterator iter = getColumnIterator();
    while ( iter.hasNext() ) {
        Column col = (Column) iter.next();

        ColumnMetadata columnInfo = tableInfo.getColumnMetadata( col.getName() );

        if ( columnInfo == null ) {
            throw new HibernateException( "Missing column: " + col.getName() + " in " + Table.qualify( tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getName()));
        }
        else {
            final boolean typesMatch = col.getSqlType( dialect, mapping ).toLowerCase()
                    .startsWith( columnInfo.getTypeName().toLowerCase() )
                    || columnInfo.getTypeCode() == col.getSqlTypeCode( mapping );
            if ( !typesMatch ) {
                throw new HibernateException(
...

In debugger I can see when exception is thrown, that col.sqlType = blob(255), columnInfo.typeName = VARBINARY. For some reason when col.getSqlType( dialect, mapping ) is invoked to init col.sqlType, it gets blob(255).
I suppose that I should update hsqldb dialect in the hibernate configuration. But not sure.
Don't know what should I do to resolve the problem.
Answer: You are getting 255 in your validation query because it is default value for length property of @Column annotation.
As HSQLDB supports both VARBINARY and BLOB SQL types, apparently Hibernate uses BLOB as the default SQL mapping for byte[] columns.
You can explicitly tell Hibernate to use VARBINARY by specifying columnDefinition property of @Column:
@Basic(fetch = FetchType.LAZY)
@Lob
@Column(name = "blob1", columnDefinition = "VARBINARY")
public byte[] getBlob1() {
    return blob1;
}

Note, that column definitions may be changed by explicit specifying of its length, as it is described here, but usually it is related with String columns.
Comment: but if I change later hsqldb to, for instance ms sql server, that supports blob as VARBINARY(MAX), than I'll have to change the Column attibute. Can I do anything with this issue? I don't think that model updating is the best option when change database server.
Comment: The thing is, that you are creating DB with `liquibase`, but validating with `Hibernate`. In this case you either have to make sure, that `liquibase` creates type, which Hibernate is expecting, or vice versa - make sure, that Hibernates is expecting the type, which is created by liquibase. For creating everything as DB-platform independent, I would allow Hibernate to create all tables/fields by itself (i.e. `hbm2ddl=update`).
Comment: then maybe you can tell me how to make liquibase create table so it would be validated by Hibernate? In a DB-platform independent way. as soon as I set columnDefinition I remove DB-platform independence at all.
Comment: I'm not sure, but probably you should try [Hibernate integration](http://www.liquibase.org/documentation/hibernate.html) for Liquibase. If it doesn't help, then probably you can consider this as a bug of Liquibase-Hibernate.
Answer: Liquibase does not use sql BLOB type for blobs which become available in hsqldb since 2.0 version.
In hsqldb 1.8.X, the sql type that was used for blob was: varbinary.
In order to fix the problem, i've updated the hsqldb dialect used in hibernate:
public class HSQL_1_8_X_Dialect extends HSQLDialect {

    public HSQL_1_8_X_Dialect() {
        super();

        registerColumnType(Types.BLOB, "varbinary");
        registerColumnType(Types.CLOB, "varchar");
    }
}

<property name="hibernate.dialect" value="com.savdev.datasource.dialect.HSQL_1_8_X_Dialect"/>

It resolved the problem. Also, I suppose liquibase should either update the current HsqlTypeConverter or add the new one that supports hsqldb 2.X version.


Different convergence radius for different power series of the same function.

Question: i was playing around with $$\frac{1}{x^2+x+1}$$
I got 3 different series's:
$$\sum_{n=1}^\infty (\frac{x}{(x+1)^2})^n*(\frac{1}{x}) $$
which converges when $|\frac{x}{(x+1)^2}|<1$
the second one:
$$\frac{4}{3}*\sum_{n=0}^\infty (-1)^n(\frac{2x+1}{\sqrt 3})^{2n}$$
which converges when $|2x-1|^2<1$ and $x^2+x+1\neq 0$
and the third:
$$\sum_{n=0}^\infty x^{3n}-x^{3n+1}$$
which converged when $|x|^3<1$
How is that a possible? it would make sense that some of the series wont fit for some x's , but how the convergence rate be different?
thank you.
Comment: Do you really mean "convergence rate" or rather "convergence radius" (because that's actually what you are talking about in the rest of your post)?
Comment: yes, thank you, i did not notice i mixed the two
Answer: There is really no problem with your 3 examples since they are totally different representations which don't have to have the same convergence radius.
An easier example to investigate this issue would be the following:
Let $f(x)=\frac{1}{x}$. This function is defined for all non-zero $x$.
Now, by the famous geometric series, one could write this as
$$f(x)=\sum_{k=0}^{\infty} (1-x)^k$$
But this only converges iff $|1-x|<1$ i.e. $-2<x<0$.
Alternatively, we can write $$f(x)=-f(-x)=\sum_{k=0}^{\infty} -(1+x)^k$$
which converges iff $|1+x|<1$ i.e. $0<x<2$.
So this should be even more striking, since there is no value for $x$ where both the series converge.
But nonetheless, both series are perfectly well representations for $f(x)$ (though only for particular values of $x$).
Comment: Thank you! your example clarified it very well, will +1 as soon as i get 15 rep here :)


Understanding conjugacy classes in $SL_{2}(\mathbb{F}_{q})$

Question: I am trying to calculate the conjugacy classes of the group $SL_{2}(\mathbb{F}_{q})$, with the help of the knowledge of conjugacy classes of $GL_{2}(\mathbb{F}_{q})$.
I am using two of the following results:
1) Let $G$ be a group and $H$ a normal subgroup of $G$. Suppose $h\in H$. It is clear that $Cl_{G}(h)\subset H$. Then $Cl_{G}(h)$ splits into equal portions in $H$ and the number of parts into which it splits is $[G:HC_{G}(h)]$, where $C_{G}(h)$ is the centraliser of $h$ in $G$.
One can easily calculate the representatives of the split classes using the above result if one proves this result, which I have done.
2) This result in particular involves the two groups in the question in particular, and also gives knowledge about the splitting. This goes as follows:
Consider the map  $det: C_{G}(h)\to \mathbb{F}_{q}^{*}$ given by the obvious determinant map. Now, call the image of this map as $L$. Then again the number of classes into which $Cl_{G}(h)$ splits is given by the index $[\mathbb{F}_{q}^{*}:L]$.
Again if one proves this theorem then one can also find the representatives of the split classes.
Now, with these two theorems in hand, and also the fact that I know the conjugacy classes of $GL_{2}(\mathbb{F}_{q})$, representatives of those classes and the centralisers of each such representative elements, I have managed to understand the splitting of each classes in $SL_{2}(\mathbb{F}_{q})$ in all but one case. The following  is the case which I don't understand:
Consider the conjugacy class of the matrices whose characterestic polynomial is given by an irreducible polynomial of degree 2 over $\mathbb{F}_{q}$. I have found representatives of such classes, which looks as follows
 $
   M=
  \left[ {\begin{array}{cc}
   x & \epsilon y \\
   y & x \\
  \end{array} } \right]
$
Where $y\neq 0$ and $\epsilon$ is a non-square element in the field. It's centraliser is
$\{ \left[ {\begin{array}{cc}
   x & \epsilon y \\
   y & x \\
  \end{array} } \right] \}$, $x,y$ both not zero.
But using this information I have failed to apply the results 1 or 2, to understand whether this class splits as conjugacy classes of $SL_{2}(\mathbb{F}_{q})$.
So, I ask how can I solve this problem. Also a general kind of result will be nice because in that case of I can also understand the splitting in $SL_{3}(\mathbb{F}_{q})$ of these semi-simple classes, whose characterestic polynomial doesn't have all roots in the base field.
Thanks a lot in advance.
Answer: Your degree 2 case is relatively easy as it simply amounts to whether the binary quadratic form $x^2-\epsilon y^2$ represents all elements of $\mathbb{F}_q^*$.  However, $x^2-\epsilon y^2$ is basically the norm map $\mathbb{F}_{q^2}\to\mathbb{F}_q$ and thus is surjective.
This also generalizes to higher degree $n$:- if a representative has at least one semisimple Jordan block then the determinant map is basically the norm map and so is surjective.  For example, for $n=3$ the only possible splitting to investigate is with the minimal polynomial $(t-\alpha)^3$ case.
Comment: Ok I think I got it!


How to check author role in Views PHP

Question: I need to check author role using views php. I've already added a relationship and added a field(excluded from view) User: role. How can I check if author role is equal to 'administrator'?
Answer: I've added in Value Code:
<code>$user_load = user_load($row->uid);
$var = $user_load->roles;
return $var;
</code>
then I've used in Output code:
<code>print_r($value[3])
</code>
to get the string

How to check author role in Views PHP


Kernel of $\phi \colon $Hom$_R(\prod_{i \in I}A_i, B) \to \prod_{i \in I}\text{Hom}_R(A_i, B)$ is isomorphic to Hom$_R(\prod A_i/\sum^\oplus A_i, B)$.

Question: Let $R$ be a ring, $\{A_i\}, B$ be $R$-modules. Let $\iota_i \colon A_i \to \prod_{i \in I} A_i$ be the canonical injection. Let  $\phi \colon \text{Hom}_R(\prod_{i \in I}A_i, B) \to \prod_{i \in I}\text{Hom}_R(A_i, B)$ be given by $\phi(f) = (f_i)_{i \in I}$, where $f_i = f \circ \iota_i$. Prove that $\text{Ker}\phi \cong \text{Hom}_R(\prod A_i/\sum^\oplus A_i, B)$. I know that in general, the contravariant Hom-functor does not preserve the direct products. So, $\phi$ is not an isomorphism. I was trying to find an isomorphism between $\text{Ker}\phi$ and $\text{Hom}_R(\prod A_i/\sum^\oplus A_i, B)$, but it seems not easy to find one. I am guessing that I need to use the universal property of direct products??? If someone can direct me how to prove this, I will be appreciated.
Answer: Hint: If $M$ and $P$ are $R$-modules, and $N$ is a submodule of $M$, homomorphisms $M/N \to P$ are in a one-to-one corresponde with homomorphisms $M \to P$ whose kernel contains $N$, that is, if $\pi : M \to M/N$ is the canonical projection, then the map $$\operatorname{Hom}_R(M/N,P) \to \{\alpha \in \operatorname{Hom}_R(M,P) : N \subseteq \ker \alpha\}; \quad \phi \mapsto \phi \circ \pi$$ is a bijection, in fact, an isomorphism of $\mathbb Z$-modules ($R$-modules if $R$ is commutative).


Hosting site doesn't allow me to make downloadable link

Question: I created a website in 000 web host , It's free host, and I uploaded an .apk file into that host, now i want that when I type the url in the browser the file should start downloading automatically, but it doesn't start, It has some restriction on this type of files, how can i do it with html or javascript , please help
Comment: There isn't really enough information here for us to help you debug this. Can you give more information? Please also read [How to Ask a Good Question](http://stackoverflow.com/help/how-to-ask) in the help center.
Answer: Does your host let you edit MIME types?
I had to do this at a different host for .dmg files (Mac Disk Images).
<code>File Name Extension: .apk
MIME Type: application/vnd.android.package-archive
</code>
Comment: I contacted them and they told me it has restrictions that doesn;t allow me to do that, how to change MIME types, i don't know


How to minimize spectral radius in this situation?

Question: I have a Hermitian matrix $A$ ($A^{\dagger} = A$), and a diagonal real matrix $B$.
Now I need to minimize $$\rho(A - B)$$ ($\rho(\cdot)$ is the spectral radius),
when the diagonal elements of $B$ can change under the condition that $$tr(A - B) = 0.$$
Could someone offer an approach?
Answer: I have made the calculations for $2\times 2$ matrices, maybe it helps you to solve the general problem.
Let $A=\left( \begin{array}{cc} a & b\\ b & c\end{array}\right)$ be a Hermitian matrix and let
$B=\left( \begin{array}{cc} s & 0\\ 0 & t\end{array}\right)$ be such that $tr(A-B)=0$. Since $tr(A)=a+c$ and $tr(B)=s+t$ we conclude that $s=a+c-t$. Hence
$$A-B=\left( \begin{array}{cc} t-c & b\\ b & c-t\end{array}\right).$$
The eigenvalues of $A-B$ are
$$ \lambda_{1,2}=\pm \sqrt{(t-c)^2+b^2}$$
which gives
$$ \rho(A-B)=\sqrt{(t-c)^2+b^2}. $$
Of course, the minimal possible value of $\rho(A-B)$ is $|b|$, we get it if
$B=\left( \begin{array}{cc} a & 0\\ 0 & c\end{array}\right)$.
Comment: Thank you. But I think the 2-dimensional situation can not be extended to the general case. I have tried letting the diagonal elements be zero, but numerical results showed the spectral radius is not the smallest in this situation.


Clearing Cookies

Question: I have a website and I have configured it such that only once the user accepts the use of cookies on their website, cookies will be enabled.
I tried using javascript to delete all cookies on page load. But for some reason one cookie still remains.. and the cookie in itself and it's value are a string of junk characters.
Cookie name: SESSbcb9eecbd50e36ecb0e5050944c6a793
Cookie Value: r87wIdULAl26ZINb3F7QuCbajCwskPi99eEjJh6VtZ0
Based on what I have read online, cookies that are httpOnly cannot be deleted. Is this true? Can it be done through Drupal core itself? Please let me know.
Thanks.
Comment: That's your browsers session with the server the site is running on. Not sure if you can not have that set its fairly important to everything
Answer: I'm assuming you are attempting to comply with the new EU privacy laws... I suggest you use https://www.drupal.org/project/eu_cookie_compliance since they have done a lot of work to make sure that sites with this module installed are in compliance and as changes are needed the module will be updated.

Clearing Cookies


Telerik equivalent for DetailView

Question: Is there a telerik equivalent for asp.net DetailView. Or can i customize a detailview to include telerik controls for editing (with minimum effort)
Answer: Well, there's always RadGrid.
http://www.telerik.com/help/aspnet-ajax/gridoverview.html
I have bad experiences when combining standard, or other third party controls, with Telerik. They quite often act wierd, or don't work inside other controls.
Comment: Yes, and no. Both can be used for multiple rows. If I remember correctly, the GridView can read and edit db data records, while DetailsView can also create records. Don't quote me on that though. But a grid can be used for just one record with any problem.
Comment: I will just be editing one, unique record in form view. Isnt the grid supposed to be a list view for multipel records

Telerik equivalent for DetailView


Connecting Android Development Board to Ubuntu 11.04

Question: I recently received a development board from TI which is running Android on OMAP 3621 and I am trying to connect it to my machine through USB. The board says Connected in Debugging Mode.
system@system-laptop:~$ lsusb |grep Google
Bus 002 Device 006: ID 18d1:0001 Google Inc.

On the board the USB debugging is ON and so is accept from Unknown Source.
My .rule file for udev is as follows
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", ATTRS{idProduct} =="0001",SYMLINK+="android_adb", MODE="0666"

After this I restarted udev and adb servers using sudo.  Still it does not detect the dev board, but it detects my HTC Desire.  I have tried Googling but in vain, and I have even tried adding the vendor ID in the adb_usb.ini file but still in vain.
What could I be missing?
Answer: Adb does not yet know about the vendor id, so it will not connect to your device.
You only have to add the id to the file ~/.android/adb.ini and then it will work.
It should be a plain text file with all vendor id's of all android devices you work with listed one per line. If you only want your TI-board it should contain the single line:

0x18d1

If this does not work (it should, but...) try a google search on adb.ini.
Answer: You should grep Texas Instruments and use that ID I guess


How can I access user files on a disk moved from a Windows 7 machine to an XP machine?

Question: I moved the hard drive from one machine (Win 7) to another (XP) and now certain folders tell me "Access denied".  I am logged in as an administrator.  I had a different account on the other machine.  Neither account authenticated to anything besides the local machine.  The old machine is apparently dead, so I can't do anything in there like change permissions, etc.  How can I access these files?
Edit:
After changing the ownerships of all the files and folders on the drive, I am getting a different error.  And it is troubling me deeply.
"xxx refers to a location that is unavailable. It could be on a hard drive on this computer, or on a network. Check to make sure that the disk is properly inserted, or that you are connected to the Internet or your network, and then try again. If it still cannot be located, the information might have been moved to a different location."
No change after rebooting.  Any ideas?  Surely the files are still there, right?
Comment: Doesn't Win7/Vista redirect files if they were written to a non user area? (program files for example)  Could it be you're finding those links, rather than the actual files?
Comment: Also, "Check Disk" found no problems.
Comment: Crap! I think you are right. I was having this problem on D:\Users\chris\My Documents.  But the real data for that folder is in D:\Users\chris\Douments.  Thank you!
Answer: Try taking ownership of the file/folder.  In the security tab, click Advanced, select the Owner tab, and add the local administrator as the Owner of the directory.  That should do the trick.
Comment: ... and then ensure the local administrator permissions are appropriately set. They *should* be but it doesn't always work.
Comment: I'm not sure what you mean by that.
Answer: Can you try to edit the Access Control lists directly? Make sure "use simple file sharing" is disabled in the folder options, and then do:  right click->security and edit the ownership of the files/directories.
In Windows, file ownership is not determined by usernames, but by security identifiers (SID), and these are different on every installation.
Comment: SIDs, thought-- not GUIDs. Same purpose, different things.
Comment: Eeer, yep, of course you are right....


Logistic-regression probability score used for reordering rows for plotting ROC curve: is it the actual, positive, or negative class probability?

Question: I want to draw my own ROC curve, such as explained in the accepted answer to this question:
Understanding ROC curve
However, it isn't clearly explained what the 'score' used represents.  It is used to reorder the rows by their probabilities in descending order.
Does the probability score used (and, as shown in that answer) represent:

The probability of being the actual class ('C')?
The probability of being the positive class (+1)?
The probability of being the negative class (-1)?
Answer: According to this website:
http://blog.revolutionanalytics.com/2016/11/calculating-auc.html
It is the positive class probability which should be used.

Calculating AUC: the area under a ROC Curve
by Bob Horton, Microsoft Senior Data Scientist
Receiver Operating Characteristic (ROC) curves are a popular way to visualize the tradeoffs between sensitivitiy and specificity in a binary classifier. In an earlier post, I described a simple "turtle's eye view" of these plots: a classifier is used to sort cases in order from most to least likely to be positive, and a Logo-like turtle marches along this string of cases. The turtle considers all the cases it has passed as having tested positive. Depending on their actual class they are either false positives (FP) or true positives (TP); this is equivalent to adjusting a score threshold. When the turtle passes a TP it takes a step upward on the y-axis, and when it passes a FP it takes a step rightward on the x-axis. The step sizes are inversely proportional to the number of actual positives (in the y-direction) or negatives (in the x-direction), so the path always ends at coordinates (1, 1). The result is a plot of true positive rate (TPR, or specificity) against false positive rate (FPR, or 1 - sensitivity), which is all an ROC curve is."


How to practice solfege?

Question: I have a solfege test coming up and I want to practice some more.
What is a good website to practice solfege on? (Preferably free)
And what are some general tips to get better at it?
Comment: Learn Doe, a Deer from the Sound of Music.
Answer: In music theory  from Ricci Adams you have online exercise note exercise on top the is a toggle switch which you could change from letters  to solfege. I hope I was a help.

How to practice solfege?


Como customizar os plots do matplotlib, de uma forma mais voltada para clusterização?

Question: Estou trabalhando com clusterização de dados, preciso deixar os dados mais distantes dos clusters representados de alguma outra forma, como um simbolo diferente ou alguma cor mais forte, dei uma analisada na documentação mas não achei nada do gênero. A logica que pensei foi de um dado com distancia N do cluster tenha essa alteração, estou aplicando a tecnica de clustering do sckit-learn.

Os dados circulados seriam um exemplo dos que desejo aplicar isso.
Answer: Até onde eu consegui encontrar, não existe uma ferramenta que dê a diferença entre os pontos ou dizer quais estão mais perto ou longe. Minha sugestão é usar outras funções pra fazer esta diferenciação.
Existem algumas maneiras de você fazer isso. Eu usei o norm do numpy, mas talvez o transform do kmeans seja uma opção melhor no final das contas.  Depende de como você está a tratar os dados, eu prefiro via numpy pois estou mais acostumado a trabalhar direto com os números.
Trabalhei em 2D pra ser mais fácil de demonstrar, mas o método é valido pra 3D também, basta apenas mudar os plots (e os dados inicias, claro).  Minha maneira foi:

Fazer um cluster (usei o numpy),
Usar o k-means para achar os clusters e seus centros com o fit,
Separar os pontos por cluster e calcular a distância (usando o norm) entre os pontos e seus respectivos centros,
Separar os pontos que a distância é maior que a média das distâncias.
Plotar os pontos de maneira a diferenciar entre os mais próximos e ou demais.

Notas

Em geral você tem que definir onde está o seu "corte" que diferencia qual ponto está perto ou longe. Eu usei qualquer valor maior que a média, mas em geral isto não é perfeito. Já coloquei um fator (factor) multiplicando a média. Assim basta trocar o valor de factor para ter uma saída diferente, sem ter que estar mexendo nas partes mais centrais do script.
Fiz varias variáveis, basicamente uma para cada plot. Isto obviamente não é necessário, mas achei que assim é mais simples para expor como o código funciona. Se você seguir este caminho para separar os pontos, em geral só usando os indices lógicos (tal qual eu separa os pontos externos) já é suficiente.

Abaixo segue o código que fiz.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

#fator the ajuste quanto fora está seu limite
factor=1.0 #usa qq valor maior que a média

a=np.random.rand(50,2)
b=np.random.rand(30,2)*0.15+0.2  #cluster 1
c=np.random.rand(30,2)*0.15+0.6  #cluster 2
d=np.concatenate((a,b,c))

fig, ax=plt.subplots()
ax.scatter(d[:,0],d[:,1])
plt.show()

#separa os clusters
cl=KMeans(n_clusters=2).fit(d)

#só pra verificar
cl.cluster_centers_ #centros
d[cl.labels_==0].size
d[cl.labels_==1].size
d.size

#separa os dados
datac0=d[cl.labels_==0]
datac1=d[cl.labels_==1]

#segundo plot
fig2, ax2=plt.subplots()
ax2.scatter(datac0[:,0],datac0[:,1],c=[ 0, 0, 1])
ax2.scatter(datac1[:,0],datac1[:,1],c=[ 1, 0, 0])
plt.show()

#distancia dos pontos aos seus respectivos centros
distdata0=datac0-cl.cluster_centers_[0]
distdata1=datac1-cl.cluster_centers_[1]

#pontos externos
#aqui separa os valores que são maiores que a media das distâncias
#usei a "norm" pra calcular a distância absoluta entre o ponto e o seu respectivo centro
#depois comparo este valor a media das distâncias, se for maior, vai pra lista
meandist0=np.mean(np.linalg.norm(distdata0,axis=1))
meandist1=np.mean(np.linalg.norm(distdata1,axis=1))
outc0=datac0[np.linalg.norm(distdata0,axis=1) >factor*meandist0]
outc1=datac1[np.linalg.norm(distdata1,axis=1) >factor*meandist1]

#plot os pontos mais externos marcados com "x"
fig3, ax3=plt.subplots()
ax3.scatter(datac0[:,0],datac0[:,1],c=[ 0, 0, 1])
ax3.scatter(datac1[:,0],datac1[:,1],c=[ 1, 0, 0])
#Plota os pontos mais externos "marcados"
ax3.scatter(outc0[:,0],outc0[:,1],c=[ 0, 1, 1],marker='x')
ax3.scatter(outc1[:,0],outc1[:,1],c=[ 1, 1, 0],marker='x')
plt.show()

Isto dá o resultado com estes 3 gráficos

Com as imagens originais em : Pontos, Clusters, Clusters e pontos.
Comment: Opa, cara bem interessante as a ideias e os métodos que tu propôs, acho que realmente vai solucionar meu problema, vou ver as adaptações necessárias, enfim obrigado, recém to me adaptando a trabalhar com "data science".


How to resize slider images according to screens

Question: I am using Basic-slider in my project http://basic-slider.com/ as a background slider. I want to make images resize according to different windows. I am using some code but don't know whether I am right or not, as I am not familiar with javascript and jquery
Original script provided was:-

I modified it according to my requirement as below

It's not working and am not sure this code is proper or not.
Please can anyone help
Answer: That won't work, because what if someone resizes their browser after the page loads? Then it'll be the wrong size again.
In any case, most sliders aren't made to be full screen, and the particular slider you've mentioned is intentionally minimal, and therefore not a good fit for doing anything non-standard with.
A quick google search for "full screen background slider" brings up this: http://buildinternet.com/project/supersized/ which looks like a much better fit for you. It automatically handles the full screen, and resizing - see the demo at http://buildinternet.com/project/supersized/slideshow/3.2/demo.html
Good luck!
(PS - you may be using CakePHP as a framework, but this specific problem has nothing to do with CakePHP - I've retagged it as jquery / carousel)


Ear training - Did I correctly transcribe this harmony?

Question: (Not exactly sure this belongs here, but I wish there was a Code Review stack exchange site for music ..)
I'm training my ear at recognizing and transcribing vocal harmonies (because I like to analyze them later). I was listening to the chorus of Song 3 by Stone Sour and I gave it a shot at transcribing the vocal harmonies in the chorus part (from 1:14 to 1:42).
From what I could hear, there was only 2 voicings. This is what I managed to come up with :
First voicing :

Second voicing :

Is this an accurate transcription ? I still find the vocal harmonies very hard to hear in a full mix, so there might be some wrong notes.
Comment: My read of the ["what topics?" page](https://music.stackexchange.com/help/on-topic) is that as asked, the question is off topic. ("and it is not about...transcription of specific works, including identifying notes/chords/meters/other elements in songs".) However, analysis questions are okay. ("If you have a question about...technical analysis of a specific, complete work, or well defined section thereof"." I suggest going ahead with your analysis based on your transcription and then edit this or repost.
Comment: I'm not even sure it can be done, I genuinely don't have a question about theory, I just wanted to know if what I achieved correctly reflects the song. The afterward analysis would be to say "this is a major third, this is an unison, etc.", and there are already other questions on that topic. I'll leave that question for a brief moment, and remove it if no one answers by then, or if it's flagged ..
Answer: This music is in Db. C#=Db, D#=Eb, F=F, F#=Gb, G#=Ab
What concerns the rhythm I can't tell you more, but it seems to be ok
Comment: Not really related but I wanted to ask: How could you say this music is in in Db? I ask it because I want to know how to do it myself too! And by Db do you mean is it in key of Db?


Docker is running but I cannot access localhost - Flask application

Question: I built I Flask application and I am trying to make it run on a Docker file.
I run two commands:
1)
docker build -t my-api-docker:latest .

2)
docker run -p 5000:5000 my-api-docker

Both are run without errors and the output on terminal is the classic Flask:
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

HOWEVER
If I visit: http://localhost:5000 if show that:

The page is not working

requirements.txt
Flask==1.1.1
requests==2.20.1
pandas==0.23.4

Dockerfile
FROM python:3.7
RUN pip install --upgrade pip

COPY ./requirements.txt /app/requirements.txt

WORKDIR /app

RUN pip install -r requirements.txt

COPY . /app

EXPOSE 5000

CMD [ "flask", "run" ]

Answer: It should not bind with container localhost i.e

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

change the CMD in Dockerfile
CMD [ "flask", "run", "--host=0.0.0.0" ]

or
CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"]

or replace the inside your code
app.run(host='0.0.0.0').


Accessing shared resource on local computer from users of different physical location

Question: Sounds like easy task to some but such a difficult task for me to do...
The main requirement for this task is to setup something in offices located on different locations, so (1st question) users are able to log on to the domain without VPN when they are in one of the offices. Additionally, (2nd question)how they can log on to the domain server when they are on the road like in a starbuck, what do they have to do to connect to domain after VPN connection are successful.
also it's my understanding that, we can't share resource from computers on different network segments, (3rd question)what is the best solution to bridge/combine two network segments(two office in different locations) so computers of different location can see each other.
Thank you in advance for any response.
Comment: @joe. dedicated vpn boxes = good idea, having windows2003 handle vpn connections [ i assume they would come from 'road warriors' ] - not so good idea... in my opinion.
Answer: i have a bad news for you:
you actually can share resources from computers on different network segments.
obviously performance of it will depend on the protocols and requirements. access to network shares via windows networking will be quite slow on typical adsl line, but still usable.
what you need is a vpn between offices, and static routes added on the edge routers in both [or more than 2] locations. you can go for standardized ipsec solution and use hardware/software provided by many vendors or you can use openvpn which does great job for me for last 6 years or so.
so an example - technology / vendor agnostic.

full image here.
explanation:
computers in office A use r00 as default gateway [and nat router, and dns machine and maybe even dhcp server probably]. they send all packets to hosts they cannot reach within 10.0.0.0/24 to that machine. similarly computers in office b use r10 as the gateway.
r00 has a default gateway pointing to the internet service provider and additional static route telling that networks 10.0.1.0/24 and 10.0.2.0/24 can be reached via vpn. this vpn can run locally on r00 or on separate box [here r01].
r01 is using your internet connection at the office [ this part was omitted in desperate attempt to make picture a bit readable] to establish encrypted tunnel to r11. r01 forwards packet received from the tunnel to r00 and received from r00 to r11.
r10, r11 do analogical job.
now your 'road warrior' - person sitting at Starbucks and wanting to access some internal resources [exchange server? file server? intranet web page?]. she is using available internet connection to establish encrypted tunnel to your vpn concentrator [ can be separate box or one of r01/r11 ] and depending on the company policy either sends all traffic via that box or just traffic destined to 10.0.0.0/24, 10.0.1.0/24, 10.0.2.0/24. as you see 'road warrior' gets ip address from different range - 10.0.2.0/24 - one allocated to 'dial up' users.
ps. this is a simple case - you can get things more complicated [ and more secure ], but i hope this gives you the idea how things can look like to achieve what you need.
Comment: Wow, thank you so much for the fast and detail response.
Here's a draft plan, first I will put two VPN routers on each office to establish tunnel for the two distributed network to communicate. second, I will configure vpn service on a windows server 2003 machine which sits behind one of the vpn router, this server will manage all the remote vpn connection on top of its domain controller role. third, for all the connected users/computers, I will enable folder sharing on the user's local computer with restriction of DOMAIN user group (I haven't done that before), if that works, problem solved.


Erro CS0029 no Visual Studio

Question: Estou tentando fazer uma calculadora bem simples, só pra entender como programa funciona, e me deparei com o seguinte problema:
Se coloco 5+5 na calculadora ela me dá o valor de 55 como resposta. Para arrumar isso fui tentar passar os valores digitados para int, mas sempre dá o erro:

Cannot implicitly convert type 'int' to 'string'

 private void BtnSoma_Click(object sender, EventArgs e)
    {
        lblResultado.Text = Convert.ToInt32(txtNum1.Text) + Convert.ToInt32(txtNum2.Text);
    }

Answer: Precisa converter para inteiro fazer a conta e depois converter novamente para string. Nada garante que será digitado algo correto, e se o dado entrado não for um número inteiro a aplicação quebrará, para corrigir isto precisa ser feito outro código:
private void BtnSoma_Click(object sender, EventArgs e) {
    if (!int.TryParse(txtNum1.Text, out var valor1) || !int.TryParse(txtNum2.Text, out var valor2)) {
        MessageBox.Show("Pelo menos um dos valores é inválido", "Entrada inválida", MessageBoxButtons.YesNo);
        return;
    }
    lblResultado.Text = (valor1 + valor2).ToString();
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura. Ligeiramente diferente para sere facilmente testável online.

Erro CS0029 no Visual Studio


Using scrollTop to show pixels scrolled

Question: Im wanting to to display the number of pixels a user has scrolled in my site by using the scrollTop method in jQuery. I would like the number of pixels to appear in a class called 'pixels'.
Therefore I could have

 Pixels Scrolled

I found a website that does does it at it's footer. Its exactly what I want to do! You can find the site here http://chartbeat.com/
Although I have been looking and can't seem to find out how to do it. Any help would be greatly appreciated. Thanks in advance.
Answer: Next time try a little harder before you ask:
$(function(){
  var $w = $(window), display = $(".pixels");

  $w.on("scroll", function(e){
    $display.text($w.scrollTop())
  });
});

http://jsfiddle.net/Mb45L/2/
Comment: Why loading jQuery for such a simple matter?
Comment: @d4rkpr1nc3 because he taged the question with it. On the other side your answer does only half the work...
Comment: @meo Thank you, I have only started learning jQuery, I'l definitely try harder next time!
Answer: It's really as simple as the following:
(function(window, document, $, undefined) {
  $(function() {
    var win = $(window),
        ele = $('.pixels');

    win.scroll(function() {
      ele.text(win.scrollTop());
    });
  });
})(window, document, jQuery);

Comment: `.text()` is a lot faster as `.html()` what is pretty important for an event that is triggered on every scroll...
Comment: Changed to use .text() instead. I wrote it pretty quick, yeah. It could be optimized even further, if we really wanted to.
Answer: Try using document.getElementsByTagName("body")[0].scrollTop
Answer: something like this?

     Pixels Scrolled

<?php for($x=0;$x<100;$x++) { echo "
"; } ?>

Using scrollTop to show pixels scrolled


Making audio player work in swift (xcode 7.1.1)?

Question: Im having an issue with an audio player I'm trying to put together using swift, built for use in a game application. The code below is what i have. I already have all the mp3 files in separate child groups within my main sounds folder, yet I cannot understand why the NSURL cannot be identified.
import UIKit
import SpriteKit
import AVFoundation
class GameViewController: UIViewController {
var backgroundMusicPlayer:AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

        }
override func viewWillLayoutSubviews() {

    var BGMusicURL:NSURL = NSBundle.mainBundle().URLForResource("BGMusicURL", withExtension: "mp3")
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()
}

if anyone could help me update my code that would be great, (I'm a beginner with swift as I'm sure you can tell)
Thanks
Answer: Old answer:
Try using AVPlayer instead of AVAudioPlayer
Edit/new answer: Try to add ! at the end of var URLForResource, that's how you force unwrapping so maybe it will work
Like this
var BGMusicURL:NSURL = NSBundle.mainBundle().URLForResource("BGMusicURL", withExtension: "mp3")!

Comment: Thanks Petar for your response!
Ive just tried that and it just doesnt seem to be having any of it. It says that URLForResource is not unwrapped, and that it cannot invoke initialiser for AVPlayer.
Im sure I'll figure it out eventually
Comment: Unfortunately not :( I dont really know what to do!
Comment: @SamuelJones Have you tried edit/new answer solution?


Does va_copy() require va_end()?

Question: When dealing with variable arguments, is it just va_start() that needs a matching va_end() call, or does va_copy() require a matching va_end() too, i.e
void foo(char *x, ...)
{
  va_list l,c;

  va_start(l,x);
  va_copy(c,l);

  ---
  va_end(c); //is this correct ?
  va_end(l);
}

Answer: Yes, every copy and the original, requires va_end() to be called. Your example is correct, the order of your va_end() calls can be reversed.
From ISO/IEC 9899:201x:

22.214.171.124 The va_end macro
The va_end macro facilitates a normal return from the function whose variable
  argument list was referred to by the expansion of the va_start macro, or the function
  containing the expansion of the va_copy macro, that initialized the va_list ap. The
  va_end macro may modify ap so that it is no longer usable (without being reinitialized
  by the va_start or va_copy macro). If there is no corresponding invocation of the
  va_start or va_copy macro, or if the va_end macro is not invoked before the
  return, the behavior is undefined.

The last sentence states that every va_start or va_copy must be accompanied by an va_end before returning.

Does va_copy() require va_end()?


How do I get the fivestar module's vote on a review node to count towards a product node?

Question: Should be simple.
I have a content type called Product.
I have another content type called Review.
I want people to vote when they create the Review content type and have the vote count towards the Product.
When I display the Product, I want the average of the votes to appear with the product.
Problem: When I add the fivestar field to the Review content type I DO NOT see an option to set a target node.
Note: I am not using comments as reviews, I am using another content type.
I have tried to find a solution in other postings and I have no problem with a programmatic solution but I have not found anything clear.
Comment: Please specify the Drupal version you are using for clarity!
Answer: The problem was that I had just switched the links between my Reviews -> Products to use entity relationships (instead of node links) and Fivestar does not support that.
A patch that seems to work was posted two days ago.  As soon as I applied the patch, the "target node" field appeared.  http://drupal.org/node/1488914
In addition, the product's Fivestar field had to be set to "rate while viewing" and the Review's Fivestar field had to be set to edit while eediting.
Answer: Since Fivestar uses Voting API to do the heavy lifting, you can use some of Voting API's hooks to intercept votes and do your magic there.
Alternatively, when you display the Product you can implement a preproces_node to fetch all reviews for that product and manually count the votes and calculate the average.
That said, I'd create some hidden fields in the product (#access false ftw) and manually update them with every vote using the aforementioned hooks.


Autocorrelation versus ordinary correlation for Gini coefficents and discussion topics?

Question: I have a data structure like this:
countryA: 2004, 2007, 2010,...
countryB: 1999, 2005, ....

I would like to compute the correlation between the increasing of the Gini coefficient and the percentage a certain topic is discussed in the public.
I do not think that my data is balanced.
I know that most of the time people use time series cross-sectional models to compute a correlation between a Gini coefficient and a discussion topic. Yet, I have read some articles that make an appealing case for using multilevel regression models in such cases.
I am applying in Stata the following command:
xtmixed topicA gini || country:

Here are my questions:

How should I check whether my data is autocorrelated and is there a way to account for autocorrelation in those multi level models?
Does it make sense to check for autocorrelation when I have very few cases (total over all countries 126 and within countries between 3 and 10) when the time distance between the data points is kind of random?
Answer:
Given the nature of your data, and the persistence of the GINI indicator over time, it is reasonable to expect the idiosyncratic error to have serial correlation.

You can test this manually with the following code:
xtmixed topicA gini || country: // runs the model
predict res if e(sample) , residuals // predict in-sample residuals
regress res L.res if country == x, robust // test AR(1) for country x (repeat for other countries, or use by())

You can try more elaborated structure of errors.
As you model is equivalent to a panel data model with two levels, you an also run your model using xtreg, re. In this case, take a look at the user-written comman xtserial. Also, look into xtregar command, integrated in Stata, where you can do both at once. The good thing of the latter is that you can test different lag structures.
My experience is that people do not worry to much about testing serial correlation. In xtmixed and the other commands I mention you have the option of adding vce(robust) or vce(cluter id), in which case the software will internally adjust any possible autocorrelation and heteroskedasticity. Personally, there is no much information obtained from knowing that your data has serial correlation. That is pretty common. So you just need to run robust estimators.

The time pattern indicates your data is highly unbalanced. It still makes sense to account for serial correlation though. Some countries might have more balanced data than other and you don't want to manually decide which one to worry about.
Comment: Thank you for your answer. I think, i will just follow the suggestion with robust standard errors. I am probably not supposed to ask another question here, but maybe you could still help me: My multilevel intercept only model has a between variance of 0.167 and after I added the gini coefficient as the independend variable the variance increased to 0.168. what might be the reason for that? it does not seem to me logical at all.
Comment: Are you sure it is balanced? Have observations been dropped when adding GINI? Also, if the answer solved your question, don't forget to marked it as solved.


Set file description in apache2

Question: In the default file listing page (mod_autoindex) on apache2 (OS X), there is a column marked "description". Does anyone know of how you actually set what appears here? All of mine are blank, as are most of the ones on other servers that I see.
Sorry if this is really obvious but I can't find the answer anywhere else, including apache's docs
Answer: Apache's docs on mod_autoindex reveal two ways to set descriptions.
First, you can use AddDescription to set individual descriptions for files or groups of files by partial match.
Second, you can set IndexOptions +ScanHTMLTitles and Apache will use the <title> of each HTML document as its Description. This is CPU and disk intensive though.
Descriptions given by AddDescription take precedence.

Set file description in apache2


Hide Comments in Code in Unix Environment

Question: I work in a Unix environment with the typical Unix tools (emacs, vim, gvim, sunstudio, etc)
My project has huge gross boilerplate comments on every method. It makes the files thousands of lines long, with a couple hundred lines of actual code. I may be exagerrating a bit but you get the idea. I am looking for a way when viewing these files to hide (not remove) all comments so I can quickly go through the code. C++ comments '//' only.
Answer: It all depends on which editor you use. In vim, you can enable folding with :
set foldenable

Then, you'll be able to use different of folding methods, for mainstream languages, you can set :
set foldmethod=syntax

which will enable syntax folding.
There are half a dozen folding methods, I think the best would be to read
help folding

which should answer everything.


How to get the key and value type of a Map

Question: I have this code that the app needs to do some check if the key of a Map given is String or not:
    if(instance.getClass().equals(Map.class)){
        Map map = (Map) instance;
        if(keyIsString(map)){
           // do stuff with the map
           Iterator<Map.Entry> it = map.entrySet().iterator();
        }
    }

I can do it by getting the first item using the iterator and checking by instanceof however that would cause me to use two iterators. What is the best way to get the type of the Map key?
Update:  I create a MapHelper class:
public class MapHelper {
    public static String getKeyType(Map map){
        String keyKind = Object.class.getName();
        Iterator<Map.Entry<Object,Object>> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<Object,Object> entry = it.next();
            Object entryKey = entry.getKey();
            keyKind = entryKey.getClass().getName();
        }
        return keyKind;
    }
    public static String getValueType(Map map){
        String valueKind = Object.class.getName();
        Iterator<Map.Entry<Object,Object>> it = map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<Object,Object> entry = it.next();
            Object entryVal = entry.getValue();
            valueKind = entryVal.getClass().getName();
        }
        return valueKind;
    }
}

Is this good enough?
Comment: At runtime, there's no guarantee that all the keys in a Map have the same type.  AFAICS, you have no choice but to "sample" one of the keys (and then assume that it's representative of all of the keys).
Comment: If you have a huge Map, your code will take a long time setting the same value again and again...
Comment: What's with the downvote? :-)
Comment: I feel there's an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) scenario here, which makes this question hard to answer meaningfully.  From your comments further down, it sounds like you're trying to create a map with multiple key types.  What is the problem you're really trying to solve?
Comment: @OliverCharlesworth the map is coming from a method that accepts Object parameter so the type is totally lost during code time. That is from a method: put(Object obj) --> here I need to check if the object was a map then validate it, its key type etc.
Comment: Ok, but are you saying that you're expecting a map that contains *multiple* key types, or just *one unknown* key type?  Having to dynamically check the type of every single key/value type (bearing in mind that you may need to take polymorphic types into account) seems like a lot of work.  Is the use-case here really something like: `Object obj = getUntypedObjFromSomewhere(); if (notMapOfStrings(obj)) { throw new Exception(); } Map map = (Map)obj;`?
Comment: I just need to know the key type and see if its a String or not (or Long if I needed)
Comment: @xybrek: But is checking just the first key sufficient?
Comment: @OliverCharlesworth Yes I think, because if the first Map key is a String then all of the other keys are String right?
Comment: Well, not necessarily, depends on how it was created.
Comment: @OliverCharlesworth Is there such a map that have different key types?
Comment: @xybrek: Sure: `Map rawMap = new HashMap(); rawMap.put("foo", new Bar()); rawMap.put(67, new Bar());`.  So it depends where your raw object is coming from.
Comment: @OliverCharlesworth ok I see, I was thinking different. This would be a Map by default. So I guess there is no way around but to check all and just throw a RuntimeException when something fishy is found
Answer: You cannot determine the type of a map at runtime. Because of type erasure they are no longer available.
From http://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure

Generics are checked at compile-time for type-correctness. The generic
  type information is then removed in a process called type erasure. For
  example, List<Integer> will be converted to the non-generic type List,
  which ordinarily contains arbitrary objects. The compile-time check
  guarantees that the resulting code is type-correct.
Consequent to type erasure, type parameters cannot be determined at
  run-time. For example, when an ArrayList is examined at runtime, there
  is no general way to determine whether, before type erasure, it was an
  ArrayList<Integer> or an ArrayList<Float>.

If you cannot make sure your compiler is already checking all types correctly, your only chance is fetching an element and assume all other elements are from the same type.
Comment: I'm not sure that answers the question.
Answer: I disagree with previous comments. If the MapHelper class must test it on an unknown Map to be generic it must not set the generic map arguments.
If you use getValueType(Map) or getKeyType(Map) this will return the class (of key or value) of the last element in your map.
I don't think you are looking for it.
public static boolean keyIsString(Map map) {
    boolean isString = !map.isEmpty();
    String keyKind = Object.class.getName();
    Iterator<Map.Entry> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = it.next();
        Object entryKey = entry.getKey();
        if(!String.class.isInstance(entryKey)) {
            isString = false;
            break;
        }
    }
    return isString;
}

This will return true if all the keys in your map are String, false otherwise or if the map is empty.
Comment: Sure, but it's still O(N) to call `keyIsString`.
Comment: Yes but you can not verify it on generic Map (Map<>) without O(N).
Comment: I think the real problem is that the OP has an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).  So we're left guessing as to what a useful solution is.  Is it to test *all* the elements?  *Any* of the elements?  To use generics?  To refactor to be type-invariant?  Something else?
Answer: I did it in one method which returns the KEY and VALUE types names in CSV (Comma Separated Values) String like ",":
    public static String getMapKeyAndValueTypes(Map map) {
    StringBuilder sb = new StringBuilder();
    Iterator<Map.Entry> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = it.next();
        sb.append(MapsUtils.getObjectInstanceOf(entry.getKey()))
            .append(',')
            .append(MapsUtils.getObjectInstanceOf(entry.getValue()));
        break;
    }
    return sb.toString();
}

Calling the method:
Map<String, Integer> map1 = new HashMap<>();
map1.put("key1", 20); map1.put("key2", 30); map1.put("key3", 40);

String keyAndValueTypes = MapHelper.getMapKeyAndValueTypes(map1);
String entryKeyTypeName = keyAndValueTypes.substring(0, keyAndValueTypes.indexOf(","));
String entryValueTypeName = keyAndValueTypes.substring(keyAndValueTypes.indexOf(",") + 1);
System.out.println("Types Names: Key=" + entryKeyTypeName + " ; Value=" + entryValueTypeName);

And the output is:

    Types Names: Key=String ; Value=Integer

In one method we get both and can choose to use one or the other or both.


How can i check if the task is running on my User?

Question: $a = 1
while($a = 1){
    $explorer = Get-Process explorer.exe -ErrorAction SilentlyContinue -IncludeUserName
    if ($explorer.Administrator) {
    }

    else{
        start explorer
    }

    timeout 10
}

I need to get the task from my user... Any ideas.
We are in a project on one computer. My friend is connected with Remotedesktop. We troll each other with closing the explorer etc. I want to restart the explorer after he closed it. His is still running. Thats the problem.
Answer: Try Get-Process with -IncludeUserName
$explorer = Get-Process explorer -ErrorAction SilentlyContinue -IncludeUserName
$explorer.UserName

But the IncludeUserName parameter requires elevated user rights. Run script as Administrator.
UPD. This will help you with process start if there is no explorer running with your username. Replace put_your_username_here to your username.
while($true){
    $flagToStart = $true
    $explorersArray = Get-Process "explorer" -ErrorAction SilentlyContinue -IncludeUserName
    foreach($explorerProc in $explorersArray) {
        if ($explorerProc.UserName -like "*put_your_username_here") {
            Write-Output "No need to restart"
            $flagToStart = $false
        }
    }
    if($flagToStart -eq $true) {
        Start-Process -FilePath "explorer"
    }
    Start-Sleep -Seconds 5
}

Comment: Why are using the task Telegram?
Comment: When im am trying this, the explorer is just starting over and over again.... But thank you for the information.
Comment: Telegram is just an example. I tried this with explorer and it works just the same. No restarting. Keep in mind that $explorer.UserName with be with **Computer Name** like `COMP001\User`. You can split it with `$username = $explorer.UserName -split '\\'` and `$username = $username[1]`.
Comment: Do you maybe have an example in a code. I'm not that familiar with powershell scripts.
Comment: See UDP section in my answer.
Comment: Thank you i'll try that. I'm sorry for my late answers. We had some problems with our webserver :) But know i have time to get back to the little script.


How do I establish a minimum time for thread completion?

Question: I'm using multithreading to download videos from a website, however sometimes if the video is too small, the program starts another thread too fast, and the server blocks my request.
I don't want to use time.sleep because that will slow down requests that are not required to be slowed down.
So basically I need a command to establish a minimum execution time, like.
Pseuco code
minimum time = 20 seconds
If thread ended has been completed faster than minimum time:
     wait until minimum time has been reached

Comment: can you show the code that does the multi-threading
Comment: Without trying something overly complex to achieve this, you could just start a timer when the thread starts. And when the thread finishes, sleep for only the remainder of time. `start = ...; ; duration = now - start; if duration < minimum: time.sleep(minimum - duration)`. Which is basically slightly less-pseudo pseudo code of what you've put in your question.
Answer: Without trying something overly complex to achieve this, you could a) start a timer when the thread starts b) when the thread finishes, sleep for only the remainder of the time needed to reach the minimum duration:
start = ...
<threading code>
duration = now() - start
if duration < minimum:
    time.sleep(minimum - duration)

Which is basically slightly less-pseudo pseudo code of what you've got in your question.
Comment: I guess that works for me


Name of the highest power of 2 smaller than or equal to a given number

Question: For a number $x$, I would like to know whether there is a common name for the number $2^n$ such as $2^n \leq x < 2^{n+1}$ (e.g. If $x = 7$, then $2^n = 4$, $n = 2$).
I have some computer science related article where I extensively use such a number and I need a name to give it in order to explain how an algorithm works without having to repeat the number definition over and over every time I need to use it. I currently call it a "base $2$", saying for example that "$4$ is the base $2$ of $7$" (see example above), and that we need to "compute the base $2$ of the number", but this name feels wrong. Do you know whether a common name exists for such a number?
Note: actually, the article I am talking about deals with Gray codes. I am looking for a term that looks like it comes from math and not from computer science since many terms from computer science that deal with powers of two tend to be references to the usual binary representations of numbers. As an example, with Gray codes $2^3$ is 0b1100 and not 0b1000 so I am trying to avoid names that would literally mean the $n$th set bit, hence the question on Math.SE.
Note 2: as it has been highlighted in the many answers and comments, the goal of this question, once clearly reformulated, is to find a terse, pronounceable name for the function $2^{\lfloor \log_2(x) \rfloor}$ so that it is possible to say that "some number is the [insert name here] of $x$".
Comment: For what it's worth, [_octave_](http://en.wikipedia.org/wiki/Octave_%28disambiguation%29) and [_binade_](http://en.wikipedia.org/wiki/Binade)? They are used to describe ranges rather than a specific value, but you could say that the value is the octave's or binade's base. _Let u define the octave of an integer N as the set of numbers [2^n, 2^n+1) that contains N, and the base of an octave as the lowest integer contained in that set..._
Comment: call it the two-power of x. You can easily modify that for other numbers then as well
Comment: @IwillnotexistIdonotexist I like the term octave and find it clear, but it may be because of my musical background more than because of my computer science background :)
Comment: What about *flog* (and *ceilog*) ?
Comment: Here's a question stated differently, but in terms of content inherently the same: http://math.stackexchange.com/questions/1292951/floor-function-to-the-base-2/1292957
Comment: @SMF It is indeed a question about the same function and it also asks for a name. However, only "How would I do this?" part of the question is answered and not the "What is the name of this problem?" one, which is precisely what I would like to know.
Comment: "with Gray codes $2^4$ is `0b1100` and not `0b1000`": that should be $2^3$. Also, `0b1100` is unambiguously $12$; I think you mean "the Gray code of $2^3$ is `0b1100`".
Comment: @TonyK Oops, you're right with $2^3$, my mistake, will fix it. The thing with Gray codes is that I consider them as an alternative bit representation of an integer, but it may be better to call $2^3$ `0g1100` instead of `0b1100` then.
Comment: Note that the word or phrase need not exactly describe the number. For instance you could use the word subordinate and include a line: Definition: A subordinate of a number x is the number such that...
Comment: I like how "exponential floor" (and the related "exponential ceiling") sound.
Comment: Also *geometric* floor/ceiling as opposed to the *arithmetic* floor/ceiling; the values of the a-floor function follow an arithmetic progression of common difference $1$, and those of the g-floor a geometric progression of common ratio $2$.
Comment: I would call it "binary floor".
Comment: When you drop the decimals of a real number, what is left is the *integer part*, as it is the closest non-larger integer. Then the *dyadic part* is the closest non-larger power of two.
Answer: In the context of data structures - specifically, the van Emde Boas layout - I've heard this referred to as the hyperfloor of $x$. See "Cache-Oblivious B-Trees (Wayback Machine) by Bender, Demaine, and Farach-Colton for details - it defines the hyperfloor of $x$, denoted $\lfloor \lfloor x \rfloor \rfloor$, to be $2^{\lfloor \log_2 x \rfloor}$.
Hope this helps!
Comment: As much as I like the *binadic floor* proposal, it seems that the name *hyperfloor* is indeed used to represent this function (and *hyperceiling* to represent the the upper bound of the *binade*). I think that it's the term that I will use from now on. Thanks again :)
Comment: On a side note, I guess that the internet needs to be updated so that searching for *hyperfloor* in our favourite search engine returns an accurate definition of the function.
Comment: Also, I've seen `flp2` as the function name (standing for "floor to the next power of 2").
Answer: If $x$ is an integer, then $n+1$ is the bit length of $x$.
Comment: I don't understand. The question explicitly asks for a name for $2^{\lfloor \log_2 x\rfloor}$, not for $\lfloor \log_2 x\rfloor+1$.
Comment: I don't understand why a high-rep user is posting something that manifestly doesn't answer the question, and getting a bunch of upvotes for it. Or are you implicitly answering "two to the bit-length-minus-1"?
Comment: @DavidRicherby: That's three questions! To answer them in order: (i) I posted it because I thought it might help. (ii) I have no idea why I got a bunch of upvotes. (iii) Yes.
Comment: @Morwenn: "Bit length" works perfectly fine with Gray codes, what makes you think it doesn't?  The [wikipedia article](http://en.wikipedia.org/wiki/Gray_code) even uses the equivalent term "bit width" at the top of the page.
Comment: Well, I would like to find a name that reminds of maths and not of computing. Actually, I'm dealing with Gray code where $2^4$ is `0b1100` for example so names that were chosen for computer science with regular binary representation in mind can be can misleading. I reckon that it wasn't clear from the question though, I will add a note.
Comment: I know it's my fault, the bit-length would have been a good term for the usual binary representation but it does not work anymore when we switch to a Gray code representation. I didn't think that mentioning Gray codes in the question would make a difference, but I was wrong, sorry :/
Comment: @DavidRicherby: I think my answer is clear enough, including the fact that it doesn't answer the OP's question explicitly. So what don't you understand? I was only trying to help, after all.
Answer: You could call it $2^{\lfloor \log_2(x) \rfloor}$.
Comment: It's pronounced Frederick
Comment: "Two to the Power of the Floor of the Base-Two Logarithm" = TPFBTL of x, pronounced kinda like "top of bottle".
Comment: And how is it pronounced? ;-)
Comment: I am really in favor of introducing the name 'top of bottle' for this! It is clear that this function is useful in more (mostly CS-related) situation and top of  bottle is an easy to remember name that also relates directly to the proper description of this function. I say we all start plugging in into casual conversation over the next weeks! Thanks Dan for coming up with it!
Comment: Since this function is well defined for all the numbers you are treating, you could simply introduce the function $\mathbb{R}\rightarrow 2^{\mathbb{N}}$ $\text{Fred}(x)=2^{[\log_2(x)]}$ and recall it in this way.
Comment: @barto 2 to the power of floor of the base-2 logarithm of x.
Comment: Well, that does not improve things when pronounced... It's shorter on the paper though :)
Answer: Moved from comment
I suggest derivations from octave or binade. These words are typically used to describe ranges spanning powers of two rather than a specific value within them, but because a power-of-two uniquely defines an octave/binade (it is its lowest value; in other words, it is a base value, or a floor), you could use the same word for both the interval and this defining value.
For instance, you could name it the binadic floor. I favour this expression because the concept of binades is clear once formulated, and the concept of floor is unambiguous and generally well-understood. The rarity of "binade" means that "binadic floor" is sufficiently unusual as to not be confused with the regular floor, and "binadic floor" rolls quite well off the tongue.
Another possibility is octaval base/root/floor, but "octave", "base" and "root" all have pre-existing connotations, and when spoken, octaval floor doesn't sound right because the -al and fl- interact poorly, forcing a break.
Let us define the binade of a positive integer $N$ as the set of integers $[2^n, 2^{n+1})$ that contains $N$, and the binadic floor of an integer $N$ as the lower bound of $N$'s binade...
Comment: After reading the (draft) Wikipedia article, *binade* seems quite excellent. We would just have to tweak the definition to make it more general, with open and closed binades to make it clear that we're not including the upper bound. Also, while it applies to floating point numbers, I don't see why it couldn't be expanded to arbitrary numbers. Seems like a good fit. Introducing the *floor* and *ceil* of a *binade* could be meaningful in our case :)
Comment: I definitely like the proposed name, but @templatetypedef found the equivalent *hyperfloor* which seems to already be used in some research papers and sparsely around the web. As much as I like *binadic floor*, I will go with *hyperfloor* for consistency :/
Comment: @Morwenn And, if you ever need it, you can talk of trinades, quadranades, 5-nades… (or pentanades, but you have to stop with the Latin somewhere).
Comment: @Morwenn Actually, _binade_ already implies closed-at-bottom, open-at-top intervals; The reason being that all values in such an interval share the same IEEE-754 exponent. A power of two is the lowest-valued floating-point number to have any given exponent in IEEE-754 representation.
Comment: @Morwenn I've brooded on this topic for some more time and settled on a name I like a lot, and edited it in above: _binadic floor_.
Answer: I would just describe it as the "largest power of two not exceeding $x$". See A053644 in OEIS for other names and information.
Comment: That seems to be my OEIS entry, where I called it the ***most significant bit*** of $n$.
Answer: I don't know a standard term, but "dyad" might be a good choice. The word roughly means "twoness", and is used for example in dyadic decompositions in a manner similar to the one you want.
A less exotic name would be "order of magnitude". (Explaining that it is with respect to base $2$.)
Comment: Order of magnitude is spot on, but you do need to be clear that's is base-two, because almost evey body will interpret it as base 10.
Comment: While it sounds cool (I really mean it), almost everywhere I checked, it was more used to represent a pair of things :/
Answer: The term I have always been using for that number is x rounded down to a power of two. I can't imagine a term which would be shorter to pronounce. The shortest symbolic notation suggested in other answers, would be pronounced as two raised to the log base two of x rounded down, which is a bit longer to pronounce and harder to understand when you hear it said.
Comment: Even shorter (but perhaps less clear): **power of 2 below**, would only use this in speech, not in a definition: 'Here we have 16, the power of 2 below 18'. You may want to include 'greatest' and if you are talking about 16, just state that it is a power of 2.
Answer: Why not something like "binary downscale", since you're basically treating the powers of two as a scale for rounding down. It's not all too descriptive, but it sounds like you want something short.
When using it, you could say "14's binary downscale is 8".
Answer: I might call it the "logarithmic floor", although this term is not well known (I just coined it),  It could perhaps be misinterpreted to mean $e^{\lfloor \ln x \rfloor}$ or $10^{\lfloor \log_{10} x \rfloor}$, but in the context of Gray codes I'd think base-2 would be semi-implied.
Comment: I think "exponential floor" would make more sense (since you always end up with something like $2^n$), but that's just me.
Comment: @columbus8myhw, nice point. Maybe "binary floor" is good enough in this case.
Answer: You're after the arithmetic value of the most significant digit of the number, when written in binary. As a digit it is always 1, of course (unless the number is zero), but if you're inventing terminology you can say "the most significant (binary) digit of 7 has value 4", and kind of make sense.
Comment: Wouldn't it make more sense to say "the most significant bit"? "Bit" being short for "binary digit".
Comment: It would in a programming context, but in mathematics we used to just talk about digits regardless of base. E.g., [Cantor's diagonalization proof](http://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument) is about binary digits, not bits.
Answer: You could maybe use the fact that the upper end-point is twice as large as the lower end-point. Something like even interval or double interval ..
Answer: I think it is called Binary logarithm.
Wikipedia page:
http://en.wikipedia.org/wiki/Binary_logarithm
Comment: As you can see from @cxseven's answer, I'm looking for a cool name for $2^{\lfloor \log_2(x) \rfloor}$, not for $\log_2(x)$.
Comment: @Morwenn If you want it to be short and simple to read, why not "Let $f(x) = 2^{\lfloor\log_2 (x)\rfloor}$. Then we have $f(7)=4$"?
Comment: @ace That's what I would have done if there wasn't already a recognized terse name for the function :)
Answer: It seems like your n + 1 is the most significant bit, so maybe a good name would be the second most significant bit, or maybe the almost significant bit?
Comment: isn't the first bit most significant though?
Answer: How about truncate? That is, you truncate all but the most significant digit to 0.


Melhor forma de distribuir programa que usa uma shared library

Question: Escrevi um programa que usa uma biblioteca chamada curlpp. O programa é bem simples e tudo que ele faz é fazer um requisição HTTP que retorna um JSON (uso a curlpp para realizar essa requisição), parsear esse JSON (uso a jsoncons para isso) e imprimir na tela um dos valores dele. O programa tem apenas um arquivo de 50 linhas. Estou desenvolvendo no Linux Mint e compilo com o seguinte comando:
g++ -o wrapper main.cpp -lcurl -lcurlpp -std=c++11

O executável gerado funciona normalmente em meu computador, no entanto quando tento executa-lo em outros computadores ele diz que a biblioteca compartilhada curlpp não foi encontrada. Eu sei como funciona e quais são as diferenças entre bibliotecas compartilhadas e estáticas, mas minha pergunta é:
Tenho que obrigar meu usuário a instalar a curlpp antes de executar meu programa? Posso/devo distribuir a curlpp junto com meu programa? Existe alguma forma de "juntar" esse biblioteca ao meu programa em tempo de compilação?
Answer: Você precisa distribuir a biblioteca junto com sua aplicação. Não precisa necessariamente instalar nada, apenas a biblioteca deve estar junto com sua aplicação, não importa a forma como você vai fazer isto. Pode ser uma simples cópia.
Pelo que li na documentação dela, a licença permite que você a distribua livremente sem restrições.
Aparentemente ela possui dependências. Então as bibliotecas também precisam estar junto da sua aplicação. A licença da libCURL também não tem restrição que impeça a distribuição.
É possível linkar a biblioteca estaticamente, aí os binários dela serão incorporados ao executável da sua aplicação evitando dependências externas. Para isto ao invés de utilizar a biblioteca compartilhada, você precisa usar a biblioteca pura.
Precisa dar uma lida na documentação como fazer isto para esta biblioteca especificamente. E se é possível, embora quase certo que é. A licença permite fazer assim.
Normalmente basta usar a diretiva -static mas não garanto. Você precisará ter a curlpp.a.
Só me preocupa se o autor sabe o que está fazendo. Ele diz

I don't have any licence of VC++ and I don't want to buy one"

Não é necessário comprar licença alguma para ter um compilador da Microsoft. Na verdade não só o compilador é grátis quase desde sempre, mas o Visual Studio simplificado também. E já faz um tempinho que o VS quase completo (antigo Professional) também é gratuito.
Documentação da libcURL onde explica o que fazer para compilar estaticamente.
Comment: Obrigado! Optei por distribuir a biblioteca (libcurlpp.so.0) juntamente com o programa e explicar como proceder no README


Web Deploy randomly stopped working - maximum number of sync passes '10' has been exceeded

Question: We have a Windows Server 2022 and Windows Server 2019 servers with Web Deploy 3.6 installed. Everything has been working perfectly and we had been able to deploy perfectly without issue. We have been able to deploy manually from Visual Studio (publishing a site). We can also deploy using Github actions such as this:

dotnet build WebsiteProjects\Website.Site\Website.Site.csproj
/p:Configuration=Release
/p:PublishProfile=WebsiteProjects\Website.Site\Properties\PublishProfiles\LIVE.pubxml
/p:DeployOnBuild=True /p:Password="${{ secrets.PROD_PASS }}"

However over the last month, we just simply cannot deploy things any more.
When deploying from Visual Studio we get this error:

C:\Program
Files\dotnet\sdk\8.0.100\Sdks\Microsoft.NET.Sdk.Publish\targets\PublishTargets\Microsoft.NET.Sdk.Publish.MSDeploy.targets(140,5):
Error : Web deployment task failed. (The synchronization is being
stopped because the maximum number of sync passes '10' has been
exceeded even though all the changes could not be applied. This could
occur if there are external changes being made to the destination.)
Publish failed to deploy.

If we use GitHub actions, we get this error:

MSDEPLOY : error : The synchronization is being stopped because the
maximum number of sync passes '10' has been exceeded even though all
the changes could not be applied. This could occur if there are
external changes being made to the destination.
[C:\actions-runner_work\Site\Site\WebServiceProjects\WebService.SiteApi\WebService.SiteApi.csproj]

Absolutely nothing has changed on these servers for years, with exception of Windows Updates, and adding/removing sites. The publish profiles have not changed either.
Disabling Windows Defender does not help. Restarting the Web Deployment agent does not help. Restarting the server does not help. Restarting IIS or disabling the site while deploying does not help.
Sometimes if I stop the site and delete all the files in the inetpub folder the deploy will work - this seems to be the only way to get web deploy to work, but its not consistent.
Note we tried this with .NET 7 and .NET 8 SDKs - same issue. I logged this through Visual Studio as I initially thought it was an issue from one of their updates. I also don't see anything interesting in the event viewer.
Really am at a loss as we are now unable to run GitHub actions for deployments and cannot even deploy manually from Visual Studio to the servers. Any suggestions on how to fix or diagnose what is happening?

Example publish profile:
<code><Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>MSDeploy</WebPublishMethod>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish>https://...</SiteUrlToLaunchAfterPublish>
    <LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
    <ExcludeApp_Data>false</ExcludeApp_Data>
    <TargetFramework>net7.0</TargetFramework>
    <ProjectGuid>2ca81a89-d8b9-4f72-ba22-dd26757ef8d6</ProjectGuid>
    <SelfContained>false</SelfContained>
    <_IsPortable>true</_IsPortable>
    <MSDeployServiceURL>...</MSDeployServiceURL>
    <DeployIisAppPath>...</DeployIisAppPath>
    <RemoteSitePhysicalPath />
    <MSDeployPublishMethod>WMSVC</MSDeployPublishMethod>
    <EnableMSDeployBackup>true</EnableMSDeployBackup>
    <UserName>Administrator</UserName>
    <_SavePWD>true</_SavePWD>
    <SkipExtraFilesOnServer>false</SkipExtraFilesOnServer>
    <EnableMSDeployAppOffline>true</EnableMSDeployAppOffline>
    <MSDeployUseChecksum>true</MSDeployUseChecksum>
    <AllowUntrustedCertificate>True</AllowUntrustedCertificate>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
  </PropertyGroup>
</Project>
</code>
Comment: `cannot even deploy manually` not sure what that means, but what about a robocopy of a staging folder to production? Or checking a target server to see if there are any open handles to anything in the target folder?
Comment: By manually, I mean using the Publish to IIS process in Visual Studio. Automatic would be using a CI pipeline (in my case Github). But to emphasize again, this is a relatively new error which has stumped me.
Comment: It should be relatively easy and straightforward to use handle.exe or process explorer to determine what has an open handle for the file(s).
Answer: Changing the MSDeployUseChecksum to false seemed to fix this for me:
<code> <MSDeployUseChecksum>false</MSDeployUseChecksum>
</code>
No idea why though.
Comment: Interesting. When checking files for overwriting, the default is a modified date check. This setting uses a checksum test. My guess would be the locking semantics for the code for the checksum is incompatible with the current state of any files with open handles. The default/no checksum shouldn't be a problem if only one person deploys, or if you have fixed releases and deploy a known fixed set of files for a given release. Procmon on the target host should show the state of any files/handles during the deployment.


Equivalence of the Parallel Postulate and Existence of Rectangles.

Question: How can I prove that these statements are equivalent?
Comment: A proof is given on page 4 of www.msu.edu/~ottensam/NonEuclid.doc
Answer: "A proof is given on page 4 of www.msu.edu/~ottensam/NonEuclid.doc " - Gerry Myerson, in comments.


Spring WS Security WSS4J with SAML from WSO2

Question: Earlier I was in assumption that, WSS4J is not compatible with SAML, but as I see this http://jaminhitchcock.blogspot.in/2014/05/creating-and-validating-saml-assertions.html , I hope to give a try. But I want to use a Identity Provider(WSO2) to generate SAML token. So I should be able to configure WSS4J with a SecurityPolicy.xml file which verifies the token from Identity Provider. Please let me know where can I start looking for it?
Thanks
Answer: There are two ways that you can generates SAML tokens with Identity Server.

Use Identity Server as SAML2 SSO IDP that implements SAML2 SSO web browser based profile.

Use Identity Server as STS (Security Token Server) with WS-Trust specification.

I think,  It is more likely that you are hoping to use Identity Server as STS. With STS,  Identity Serve provides a web service to retrieve SAML tokens. This STS web service can be secured with WS-Security mechanism by default. As an example, you can secure STS service with user name token.  Then client needs to send the RST request with user name token. Once user it authenticated,  client would be received a SAML token.  I think,  you can find some information about STS service from here
Comment: Thank you very much.As you said I now understand the flow from Web service client end.That is client requests the token from STS using web service, embeds the token into actual service request and sends to service provider.But I couldn't find a suitable example to work from Service end. that is how the service verifies the token received in request with IDP. Is it also a web service call? will The 'https://localhost:9444/services/wso2carbon-sts' in security policy helps service to verify it?Any Spring-ws or CXF as service example?


Copy line-by-line from one large file to another?

Question: I want to process a large file line-by-line with Node.js. It's 100MB in size with 500,000 lines. I found this solution for reading lines in the input file
javascript - node.js: read a text file into an array. (Each line an item in the array.) - Stack Overflow
Now it's about writing each line into a new output file so I try
function readLines(input, func)
{
    var remaining = "";

    input.on("data", function(data)
    {
        remaining += data;
        var index = remaining.indexOf("\n");
        var last = 0;
        while (index > -1)
        {
            var line = remaining.substring(last, index);
            last = index + 1;
            func(line);
            index = remaining.indexOf("\n", last);
        }

        remaining = remaining.substring(last);
    });

    input.on("end", function()
    {
        if (remaining.length > 0)
        {
            func(remaining);
        }
    });
}

function write(data)
{
    var written = output.write(data);
}

var fs = require("fs");
var input = fs.createReadStream("input.txt");
var output = fs.createWriteStream("output.txt", {flags: "w"});
readLines(input, write);

However the script is really slow, it takes over 1 hour to process the input file completely and costs a lot of CPU and RAM usage (the amount of CPU is 25 and the amount of memory usage is up to 200MB). So can anybody tell me if there is any way to optimize it?
Comment: Did you check some of the other answers here? For example http://stackoverflow.com/questions/9486683/writing-large-files-with-node-js?rq=1
Answer: The problem you're facing is that you're constantly 1) appending to a string and 2) slicing a string. Both of these operations are probably causing new strings to be allocated and the old data to be copied across, this is a slow. The old strings are no longer referenced so are eventually freed up by the Garbage Collection but this takes time, hence the large memory usage.
There are simpler ways to do this of course but I assume you're wanting to learn how to do it using the streams in Node.JS. The general technique you can use to replace lots of appends and slices in this sort of situation is to accumulate your data in an array of strings. You can join an array of strings into a single array later on with mystring.join("") which would transform ["hello, ", "world"] into "hello, world". It's much faster to create an array of strings then join them all at once into a big string than it is to create the string my appending each string to the last.
Hope that helps and is enough for you to solve this problem and still learn something from it!


Expanding CodeMap as output from Architecture in vs2017

Question: How to view the complete expanded DGML generated from Architecure - CodeMap menu , till fields/methods.
For each level currently we are required to select and click on expand in Group menu and it expands one level.
How to drill down to all levels at once.
Answer: You can't do that, you have to expand level by level. The reason we didn't put something like this in the product was that as you drill down more and more graph elements are created on the screen and it becomes unmanageable / unusable fast.
Alternatively, there are a few code queries you can use, if you right click on a class etc. you see options such as "Show all classes derived from this" etc.


The convergence of the series $\frac{n}{2(n+1)(n+2)}$ using difference method

Question: Checking the convergence of the series:
$$\sum\frac{n}{2(n+1)(n+2)}$$
I proved that the series is divergent using limit comparison test with the simple harmonic series:
$$lim_{n\to\infty}\frac{n^2}{2(n+1)(n+2)}=1/2$$
The series diverges since the harmonic series diverges.
My problem is that when I try the difference method , I find that the series converges
$$\frac{n}{2(n+1)(n+2)}=\frac{1}{2}(\frac{-1}{n+1}+\frac{2}{n+2})$$
The partial sum
$$S_n=\frac{1}{2}[(\frac{-1}{2}+\frac{2}{3})+(\frac{-1}{3}+\frac{1}{2})+(\frac{-1}{4}+\frac{2}{5})+(\frac{-1}{5}+\frac{1}{3})+(\frac{-1}{6}+\frac{2}{7})+(\frac{-1}{7}+\frac{1}{4})+...+(\frac{-1}{n+1}+\frac{2}{n+2})]$$
$$S_n=0.5 [ \frac{2}{3}+\frac{2}{5}+\frac{-1}{n+1}]$$
I got the sum of the series by taking the limit of the partial sum when n goes to infinity:
$$S=lim_{n\to\infty}S_n=\frac{8}{15}$$
I would like to know what is wrong with the difference method ( telescoping series) .
Comment: It doesn't telescope that much. You don't cancel $\frac{2}{2k+1}$ that way. If you regroup $-\frac{1}{2} + \bigl(\frac{2}{3} - \frac{1}{3}\bigr) + \bigl(\frac{2}{4} - \frac{1}{4}\bigr) + \dotsc$, you see that your partial sum is actually $\frac{1}{2}\bigl(-\frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \dotsc + \frac{1}{n+1} + \frac{2}{n+2}\bigr)$.
Comment: you can not group/ungroup series which are not absolutely convergent.
Answer: The problem is that the terms do not telescope. While the partial fraction decomposition
$$
\frac{n}{2(n+1)(n+2)}=\frac12\left(\frac2{n+2}-\frac1{n+1}\right)
$$
is valid,
$$
\begin{align}
\sum_{n=0}^\infty\frac{n}{2(n+1)(n+2)}
&=\sum_{n=0}^\infty\frac12\left(\frac2{n+2}-\frac1{n+1}\right)\\
&=\frac12\left(\sum_{n=0}^\infty\frac1{n+2}+\color{#C00}{\sum_{n=0}^\infty\left(\frac1{n+2}-\frac1{n+1}\right)}\right)\\
&=\frac12\left(\sum_{n=0}^\infty\frac1{n+2}\color{#C00}{-1}\right)
\end{align}
$$
That is, it is divergent since it is the sum of a divergent, harmonic series and a convergent, telescoping series (in red).


Open map to show direction from current location through intent-Android

Question: I have many latitude longitude in my android app. I want to know how to open a chooser or Google map App through intent and show direction from current location to that latitude and longitude.Like i have lat=28.605989,lon=77.372970 and my current location is somewhere so when i click on button in my app these lat lon pass through intent and will show direction from my current location to these lat lon. Thank you.
Answer: To navigate user to destination lat long, we can use something like this
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?daddr=28.605989,77.372970"));
startActivity(intent);

Here . we are passing just destination lat long daddr=28.605989,77.372970, so by default, your current location will be source location.
To add extra information with your url .
String my_data= String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=20.5666,45.345(My Destination Place)");

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(my_data));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

Comment: @GouravManuja sure thing. maek sure you have installed google map in your phone . otherwise you have to handle `ActivityNotFound` Exception
Comment: sir i m trying your code but my studio says not responding that's why its take so longer but i want to know one more thing...can i pass info window through intent on google map ???
Comment: like i want to show some information about location but i m using google map through intent so i want to know can i show my information on google map???
Comment: @GouravManuja . for information im updating my answer
Comment: sir you are great,done  current location to end points,but suppose i have lat lon of a doctor,i want to show the name of doctor the no of doctor and the time to meet him...so explain how can i show ???
Comment: sir i am passing data like this but where would show data which i passed on maps???
Comment: Sir String is not showing anywhere in map...where can i see that string which i pass in map ??
Comment: you can modify your string like this .
`String my_data= String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=20.5666,45.345",20.5666,45.345, "Doctor Name \n 10 docs \n 12:30PM");`
Comment: Sir i cant see anywhere...firstly i want to know where can i see these all data on map....how can i see...i passed data hardcoded but it is not visible anywhere...where is it visible??
Comment: You have to encode your string `Uri.encode() `. please visit [This](https://developers.google.com/maps/documentation/urls/android-intents) link . see URI encoded query strings part .you will get clear idea .
Comment: sir i encode my string
            Uri.encode("1st & Pike, Seattle")
like this...but i m not able to see data anywhere...
is it okay to unicode string ???
where would show my data ???
Comment: @GouravManuja updated my answer . pass with `lat,long(label)`
Comment: Sir where can i see my string on map ??
Comment: @GouravManuja on the destination address pin
Comment: sir i can't share the image of map...here is showing nothing...which string i passed
Comment: @TejasPandya Is there any official documentation of this URL which you added as String in Uri.parse?
Comment: @MustufaAnsari I would suggest you to please go through this [answer](https://stackoverflow.com/a/46910653/6880611).
Answer: You can send intent to Google Map android application by following code:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=22.458,34.34&daddr=75.124,35.448"));
startActivity(intent);

In the above URI saddr represents the source address i.e. your current location and daddr represents the coordinates of the destination location.
Comment: i think u define here your current location but i don't have current location i just have end points so what should i do for current location bcz i can be anywhere so this is not fix i want from my current location to my end points which i have,show direction
Comment: eventually, there is no such intent URI provided according to android documentation. you need to fetch current co-ordinates before redirecting to the google map.
Comment: you mean i should find out current location and pass with saddr  and end points pass with daddr ?
through intent in map i can't find my current location?
Comment: you can try the answer submitted by Tejas. if it doesn't work then you need to retrieve the current location first. try passing only the destination co-ordinates.
Comment: sir i m trying your code but my studio says not responding that's why its take so longer but i want to know one more thing...can i pass info window through intent on google map ???
like i want to show some information about location but i m using google map through intent so i want to know can i show my information on google map???


From Love Story. How to play this measure showed in the picture with left hand?

Question:
How to play this measure with left hand? Also which finger for each note?
Thank you!
Comment: I agree with Todd's comment: you have to be more specific what your problem is. If it's a generic "I don't know how it play it", you may need to step back a bit. As for fingering: 5-2-1-2-1 or 5-2-1-3-2 works for me. If about the bass note: since you'll be using the sustain pedal, you can leave the pinky off that note once you've moved to the next notes.
Comment: In asking how to play that measure, what exactly are you asking about? To me it seems straightforward. When you think about playing it, what specifically isn't clear to you about it?
Comment: Which bar no. is this - I can't work out why the next bass note would be a G followed by an F#.
Comment: @Tim Probably a dominant chord above a tonic pedal in the bass.
Answer: Pretty straightforward - pinky for the low G, pedal down immediately, to hold it. Then choice - either move l.h. to play the arp. starting on D with pinky again, then middle, index, thumb; or D with middle,thumb plays upper G, then over with whatever you fancy for the last two. The pedal stays down until the beginning of the next bar, and changes just after you hit that low G again, as the whole bar makes a G minor.
With fingering 'problems' like this, it's far better that the player works out his/her own. After all, they're the one playing it, and a little experimentation is good for progress and experience. After all, you could have two concert pianists with completely different ideas with such as this. Which might you choose?
Comment: The question still remains - what number bar is it?


How to perform discriminant analysis in R software?

Question: I would like to perform discriminant analysis in R language. Please let me know the code  and related packages for it.
Comment: That's a pretty vague question which is likely to elicit generic answers without much interest for future readers. Would you mind giving more information on the context of your study or application? Also, do you mean Fisher, linear, quadratic discriminant analysis?
Answer: You can try the lda() function in package MASS which should come with all R installations as it is a Recommended package.
Load the package via:
library("MASS")

Then read the help page for lda()
?lda

paying particular attention to the example section. When back at the prompt you can run the examples using example(lda)