How do I redirect example2.com to example.com

Question: My website has 2 domain, example.com and example2.com.
example.com/node/1 and example2.com/node/1 are the same link.
How do I redirect example2.com to example.com.
When people open the linke example2.com/node/1, it will redirect to example.com/node/1
Comment: Is it only that one link you want to redirect? You can use the Redirect module to send visitors from the one page to the other. Or if you need to send all example2.com traffic to the corresponding example.com page, you can use a .htaccess directive.
Answer: There are many ways to do this. I just give you the most straightforward (of course for me!) and simplest one.
In hook_preprocess_html use this code
THEME_preprocess_html(&$var){
      $host = $_SERVER['HTTP_HOST']. request_uri();
      if(strpos($_SERVER['HTTP_HOST'],'example2') !=false)
           header("location:example.com/".request_uri());
}

I can't test this code right now, but this is the main idea:
Get current url components separately, the host ($_SERVER['HTTP_HOST']) and what comes after it (request_uri()), if its $_SERVER['HTTP_HOST'] contains example2 as a substring, then redirect the user to example.com/request_uri()
For redirection you can also use drupal_goto or anything else you want I just gave you the pure PHP.
Answer: Another method here, if you're using Apache, is to perform the redirect before it starts executing Drupal code. Place this in your site root's .htaccess file somewhere below the RewriteRule ^ - [E=protossl:s] line.
RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://example.com/$1 [R=301,L]

Note: this will redirect every request so if you're just looking to redirect URLs with valid nodes it might not be the best solution here.


Are the following graph isomorphic?

Question: I have to prove or disprove that the following graph are isomorphic?

If I will give the following isomorphism,
\begin{align*}
  a & \mapsto 1\\
  b & \mapsto 2\\
  e & \mapsto 5\\
  d & \mapsto 8
\end{align*}
then we see that $h$ has only one uncommon vertex to $a$ which is $g$ but the vertex $8$ has two vertices which is not directly connected to the vertex $1$. Hence the two graphs are Not isomorphic.
Am I correct?
Comment: Suggestion: show that just one of the two graphs is bipartite.
Comment: the cycle of longest length in graph 2 is 8 but since there is no cycle of length 8 in graph 1 so they r not isomorphic and also the smallest length cycle in graph 1 is of 4 whereas in graph 2 of length 5
Answer: You have a few problems. First, you haven't given the full map between the vertex sets.
Second, you've only argued that this map isn't an isomorphism. You haven't clearly ruled out the possibility that some other map is an isomorphism. I think you're trying to argue that the partial map you've shown is perfectly general, but you haven't started anything to that effect.
Typically, showing that two graphs are not isomorphic involves showing some invariant differs between them. Common invariants are degree sequence, diameter, connectivity, chromatic number, and Hamiltonicity.
As a hint, notice that every edge in the left graph is contained in two otherwise disjoint 4-cycles.
Comment: No I have taken an arbitrary map. Since, the first vertex can map to any vertex. Now using that I try to find the other possibilities but I got a contradiction. So, that is why I conclude that the graphs are not isomorphic.
Comment: This may be a problem of wording. You said, "If I will give the following isomorphism." That sounds like you're presenting *an* isomorphism. Even if you are making an argument about a general map, you must make that explicit.
Comment: Yeah I got your point.
Answer: Another explanation of isomorphism is :
see that for any vertex, all other vertex distances need to be same.
We choice a vertex from left graph (see that all other vertices are equivalent) : a
Vertices which have distance $1$ from a : b, d, e
Vertices which have distance $2$ from a : c, f, h
Vertices which have distance $3$ from a : g
Now let us see what happen with a vertex of right graph, vertex 1 :
Vertices which have distance $1$ from $1$ : $2,5,8$
Vertices which have distance $2$ from $1$ : $3,4,6,7$
Vertices which have distance $3$ from $1$ : no one
So, we found a invariant : "number of vertices which have a distance 3 from any vertex". For left graph this is $1$ and for right graph this is $0$
Indeed there are very similar but not isomorph :

Daniel
Answer: The given graphs are Not isomorphic.
Let me call the left graph as $G$ and right graph as $H$.
We can see that graph $G$ has no odd length cycle, so $G$ is bipartite graph (actually $G$ is a hypercube graph $Q_3$).
Graph $H$ has cycles of length $5$ (for example, take $1-2-3-4-5-1$), So, H is Not bipartite graph.
So, $G$ and $H$ are Not isomorphic.

Are the following graph isomorphic?


How to calculate inverse of hard-light composite blend mode?

Question: I have an 'old' RGBA canvas on the client and a newer version of the same image on the server. There are small visual differences between them.
I want to be able for the server to send to the client some 'diff' to be able to update it's image to match the new version, without having to send the whole image data again.
A two-frame transparent webm video would be ideal (ie. use webm to encode the differences), but hardware support for webm with transparency is abysmal, and browser support for extracting a specific frame from a video is also very poor.
Instead I am looking at using the hard light blend mode, which should allow me to send a single image to the client, and have any RGBA pixel converted to any other (with a margin of error of 1).
How should I generate the difference image though?  Which combination of blend modes can generate diff if new = hardlight(old, diff)
Comment: Note that the goal is to update alpha to a new value too.   Hardlight() cannot do that, since there is no way to reduce the opacity using a hardlight blend
Answer: Let Ch, Cw, Cd be the value you have, the value you want, and the diff value:
if (Cw > Ch)
    Cd = 1 - (1-Cw)/2(1-Ch)
else if (Cw < Ch)
    Cd = Cw/2Ch
else
    Cd = 0.5


TabStop de RadioButtons independente da propriedade Checked

Question: Possuo um conjunto de RadioButtons, Edits e Labels dentro de um GroupBox, como na imagem abaixo:

Gostaria que no uso do Tab o cursor não pare em nenhum RadioButton, pare somente nos Edits. Para isso, pensei em colocar TabStop = False em todos RadioButtons.
Curiosamente essa propriedade já é padrão False e há uma lógica (ou bug?), em que o RadioButton que esteja Checked = True funciona com TabStop = True, e todos os RadioButtons com Checked = False funcionam com TabStop = False.
Teria alguma forma em que o TabStop = False seja respeitado para todos RadioButtons, independente do Checked?
Answer: Solução que encontrei foi forçar o Tab ou Shift + Tab no Evento OnKeyUp dos RadioButtons:
if (Key = VK_TAB) and (Shift = [ssShift]) then
begin
   Perform(WM_NEXTDLGCTL, 1, 0);
end
else if Key = VK_TAB then
begin
   Perform(WM_NEXTDLGCTL, 0, 0);
end;

Comment: Bom dia Melissa.. caramba.. nunca tinha reparado isso :) . Vivendo e aprendendo..Legal a sua solução.  Por outro lado , testando essa situação aqui resolvi do seguinte modo: No ONSHOW do form coloquei todos os RadioButtons.tabstop:= False e no onclick de cada um coloquei o mesmo codigo RadioButton1.TabStop:= False.  Dessa forma tambem funciona :) . Só uma outra maneira de chegar a um resultado :)
Comment: Legal! Ainda está em tempo para que eu use uma solução melhor, posta sua resposta tb, dependendo do q for melhor, marco a sua como aceita.
Comment: essa minha solução não ficou como esperava, pq é feito um "Tab fantasma" e dá pra ver, isso me incomoda um pouco ainda
Answer: Testando essa situação aqui resolvi do seguinte modo:
No ONSHOW do form coloquei todos os RadioButtons.tabstop:= False
e no onclick de cada um coloquei o mesmo codigo RadioButton1.TabStop:= False.
Dessa forma também funciona :) .
Só uma outra maneira de chegar a um resultado :)


Use current values as placeholders in form

Question: I am almost done with a complex calculator, but have a minor issue. After the user presses the calculate button, all the values in the fields are removed. I have tried adding the appropriate variable in the placeholder, but when I do that, the placeholder displays the value that I set as default when I initialized it. I assume this is happening because the calculate button is forcing the page to refresh. What are my options here to keep the updated values in the fields.
Also ... for my future reference...is php not the way to go in this circumstance? Would java or html have been better choices?
My code can be viewed here: https://github.com/DTAngie/LearningProjects/blob/master/ComplexCalc
and you can view the result at: http://distechs.com/development
Answer: The simplest way of achieving what you want would be get the inputs from $_POST and assigning them to your default variables after their initialization (if they are set on $_POST set).
That way, on the first user interaction on the page, your default variables would fill the placeholders. After the post call, the page is reloaded and your code would assign the variables (if set) to the placeholders.
Answer: <code>"<?php echo $annlAvgFranchisees; ?>"><?php if(isset($_POST['calculate'])) {
        $annlAvgFranchisees = $_POST['Annl-avg-franchisees'];
    } ?>
</code>
You write your variable before it set.
How about
<code> if(isset($_POST['calculate'])) {
            Echo  $_POST['Annl-avg-franchisees']; } else { echo $annlAvgFranchisees;}
</code>
Or you can make it shorter with ternarry
<code>Echo (isset($_POST['calculate'])) ? $_POST['Annl-avg-franchisees']  : $annlAvgFranchisees;)
</code>


Does this expectation inequality holds?

Question: Let $X\in L_p(P), p>1$. Is the following result true?
$$E[\lvert X\rvert I(\lvert X\rvert>C)]\leq C^{1-p}E\lvert X\rvert^p.$$
where $C>0$.
It can be found in the proof of Corollary A.1 (pp. 278) of Hall & Heyde's book.
My attempt
By Markov's inequality, $E[I(\lvert X\rvert>C)]=P(\lvert X\rvert>C)\leq C^{-p}E\lvert X\rvert^p$. But $\lvert X\rvert I(\lvert X\rvert>C)> CI(\lvert X\rvert>C)$, and I can't use Markov's result to bound $E[\lvert X\rvert I(\lvert X\rvert>C)]$. How to proceed?
Answer: From Holder's and Markov's inequalities
$$E(\lvert X \rvert I(\lvert X \rvert>C))\leq \lVert X\rVert_p (P(\lvert X\rvert>C))^{1-1/p}\leq \lVert X\rVert_p [E(\lvert X \rvert^p/C^p)]^{1-1/p}=E\lvert X \rvert^pC^{1-p}$$
the desired result. The powers confused me a bit...

Does this expectation inequality holds?


C++ OpenMP object counter incorrect counts with std::vector of objects

Question: I need a threadsafe counter for the number of current objects of type Apple.  I have tried to make a simple one with OpenMP, but I don't understand why the counting is incorrect.  Here is a simplification of the class, with actual test code and actual output:
Class
class Apple {

public:

    Apple();
    ~Apple();
    static int getThreadCount();

private:

    static int threadCount;
    void threadCountIncrease();
    void threadCountDecrease();

};

Apple::Apple() {
    threadCountIncrease();
}

Apple::~Apple() {
    threadCountDecrease();
}

void Apple::threadCountIncrease() {
    #pragma omp critical(AppleThreadCount)
    {
    std::cout << "## COUNT ++" << "\n";
    ++threadCount;
    }
}

void Apple::threadCountDecrease() {
    #pragma omp critical(AppleThreadCount)
    {
    std::cout << "## COUNT --" << "\n";
    --threadCount;
    }
}

Test code
std::vector<Apple> apples;
cout << Apple::getThreadCount() << "\n";
for(int i=0; i<3; ++i) {
    apples.push_back(Apple());
    cout << Apple::getThreadCount() << "\n";
}

Output that I don't understand
## COUNT ++
## COUNT --
0
## COUNT ++
## COUNT --
## COUNT --
-1
## COUNT ++
## COUNT --
## COUNT --
## COUNT --
-3
## COUNT --
## COUNT --
## COUNT --

Why are there more "COUNT --" occurrences than "COUNT ++" occurrences?  Why is the last shown count -3 instead of 3?

Thanks to the accepted answer, I ultimately discarded what I was doing in favor of this solution.
Answer: I first want to note that my explanation might not completely technical correct.
One thing that happens is that when you do apples.push_back(Apple()); then a copy of your element is created. Because you have not defined a copy constructor the threadCountIncrease is not called for this copy.
So you will end up in at least twice as many -- then ++.
In addition to this the std::vector will - when it size increases - need to allocate more memory. Depending on the implementation this will result in a reallocation or in a copy of the data. In your case an additional copy does occur.
When you add a apples.reserve(10); right before you loop you will see that the -- count will decrease, because the std::vector already reserved the space for at least 10 elements.


Is $(g^{-1})^{-1}=g \ $ always true?

Question: Let $G$ be a group, and $g$ be an element of $G$, $ \ $ then is $ \ (g^{-1})^{-1}=g \ $ always true?
I don't see any reason why this shouldn't be the case.  After all, if the inverse of $g$ is $g^{-1}$, then the inverse of $g^{-1}$ is $g$, by definition.
So it would make sense that  indeed $(g^{-1})^{-1}=g$.
What is making me hesitant nonetheless is that my textbook has a tendency of always explicitly stating $(g^{-1})^{-1} \ $ instead of $g$ $ $ when a question is about the inverse of $g^{-1}$,  $ $ as if the two were not equivalent.
Am I missing something about the notion of inverse elements of a group, or this is pure semantics?
Thanks.
Comment: Your book probably states it this way, right up until it proves that they are equal.
Comment: I see.  We have proved the uniqueness of inverses, so I doubt that's the exact reason.  Perhaps, there really isn't much to this and the text is trying to be unambiguous by distinguishing between the *purpose* of $(g^{-1})^{-1}$ and $g$ in proofs.
Comment: @Stephen That does sound a likely reason.
Answer: One group theory axiom states that for each $g$ there exists an $h$ satisfying $gh=hg=e$. We can easily prove such an $h$ is unique, so it is denoted $g^{-1}$. Since $g$ is the unique $h$ for which $g^{-1}h=hg^{-1}=e$, $g$ is the inverse of $g^{-1}$ i.e. is $(g^{-1})^{-1}$.

Is $(g^{-1})^{-1}=g \ $ always true?


samba classicupgrade from samba3 to samba4

Question: I'm very confused with doing samba upgrade from samba 3.5 (debian squezze) to samba 4.1 (ubuntu 14.04 lts)
What i'm done now? all from official samba wiki:
[https://wiki.samba.org/index.php/Migrating_a_Samba_NT4_domain_to_a_Samba_AD_domain_%28classic_upgrade%29]
My scenario is to do backup of existing samba 3 on old machine, transfer files to new machine and do classicupgrade from this file.
I can't do classicupgrade on old machine because is on production site and can't be unavailable.
Now on new machine i have working open ldap with imported database from old one, and also have files smb.conf and /var/lib/samba/* from old machine.
I have checked ldap for duplicate names of users and groups.
To do classicupgrade i run command:
samba-tool domain classicupgrade --dbdir=/dir/with/files/from/old/machine/var/lib/samba/ --use-xattrs=yes \
--realm=office.mycompany.com --dns-backend=SAMBA_INTERNAL /patch/to/samba3/smb.conf

and the output of this command is:
    eading smb.conf
    Provisioning
    Exporting account policy
    Exporting groups
    Exporting users
      Skipping wellknown rid=500 (for username=administrator)
    Next rid = 10003
    Exporting posix attributes
    Reading WINS database
    Looking up IPv4 addresses
    Looking up IPv6 addresses
    No IPv6 address will be assigned
    Setting up share.ldb
    Setting up secrets.ldb
    Setting up the registry
    Setting up the privileges database
    Setting up idmap db
    Setting up SAM db
    Setting up sam.ldb partitions and settings
    Setting up sam.ldb rootDSE
    Pre-loading the Samba 4 and AD schema
    Adding DomainDN: DC=office,DC=mycompany,DC=com
    Adding configuration container
    Setting up sam.ldb schema
    Setting up sam.ldb configuration data
    Setting up display specifiers
    Modifying display specifiers
    Adding users container
    Modifying users container
    Adding computers container
    Modifying computers container
    Setting up sam.ldb data
    Setting up well known security principals
    Setting up sam.ldb users and groups
    Setting up self join
    Setting acl on sysvol skipped
    Adding DNS accounts
    Creating CN=MicrosoftDNS,CN=System,DC=office,DC=mycompany,DC=com
    Creating DomainDnsZones and ForestDnsZones partitions
    Populating DomainDnsZones and ForestDnsZones partitions
    Setting up sam.ldb rootDSE marking as synchronized
    Fixing provision GUIDs
    A Kerberos configuration suitable for Samba 4 has been generated at /var/lib/samba/private/krb5.conf
    Setting up fake yp server settings
    Once the above files are installed, your Samba4 server will be ready to use
    Admin password:        ..........................
    Server Role:           active directory domain controller
    Hostname:              DC1
    NetBIOS Domain:        mycompany
    DNS Domain:            office.mycompany.com
    DOMAIN SID:            S-1-5-21-2669135327-1831268680-3250772662
    Importing WINS database
    Importing Account policy
    Importing idmap database
    Adding groups
    Importing groups
    Group already exists sid=S-1-5-21-2669135327-1831268680-3250772662-513, groupname=Domain Users existing_groupname=Domain Users, Ignoring.
    Group already exists sid=S-1-5-21-2669135327-1831268680-3250772662-514, groupname=Domain Guests existing_groupname=Domain Guests, Ignoring.
    Group already exists sid=S-1-5-21-2669135327-1831268680-3250772662-515, groupname=Domain Computers existing_groupname=Domain Computers, Ignoring.
    Commiting 'add groups' transaction to disk
    Adding users
    Importing users
    Commiting 'add users' transaction to disk
    Adding users to groups
   Commiting 'add users to groups' transaction to disk
    idmapping sid_to_xid failed for id[0]=S-1-5-32-549: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-549: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-18: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-18: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-11: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-11: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-544: NT_STATUS_NONE_MAPPED
    enum_group_memberships failed for S-1-5-21-2669135327-1831268680-3250772662-500: NT_STATUS_NONE_MAPPED
    Fall back to unix uid lookup
    idmap range not specified for domain '*'
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
    account_policy_get: tdb_fetch_uint32 failed for type 1 (min password length), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 2 (password history), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 3 (user must logon to change password), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 4 (maximum password age), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 5 (minimum password age), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 6 (lockout duration), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 7 (reset count minutes), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 8 (bad lockout attempt), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 9 (disconnect time), returning 0
    account_policy_get: tdb_fetch_uint32 failed for type 10 (refuse machine password change), returning 0
    idmapping sid_to_xid failed for id[0]=S-1-5-32-544: NT_STATUS_NONE_MAPPED
    enum_group_memberships failed for S-1-5-21-2669135327-1831268680-3250772662-500: NT_STATUS_NONE_MAPPED
    Fall back to unix uid lookup
    idmap range not specified for domain '*'
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-549: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-549: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-18: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-18: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-11: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-11: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-544: NT_STATUS_NONE_MAPPED
    enum_group_memberships failed for S-1-5-21-2669135327-1831268680-3250772662-500: NT_STATUS_NONE_MAPPED
    Fall back to unix uid lookup
    idmap range not specified for domain '*'
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
Fall back to unix uid lookup
idmap range not specified for domain '*'
idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[0]=S-1-5-32-544: NT_STATUS_NONE_MAPPED
enum_group_memberships failed for S-1-5-21-2669135327-1831268680-3250772662-500: NT_STATUS_NONE_MAPPED
    Fall back to unix uid lookup
    idmap range not specified for domain '*'
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
    idmapping sid_to_xid failed for id[0]=S-1-5-21-2669135327-1831268680-3250772662-512: NT_STATUS_NONE_MAPPED
    ERROR(<class 'passdb.error'>): uncaught exception - Unable to get id for sid
      File "/usr/lib/python2.7/dist-packages/samba/netcmd/__init__.py", line 175, in _run
        return self.run(*args, **kwargs)
      File "/usr/lib/python2.7/dist-packages/samba/netcmd/domain.py", line 1318, in run
        useeadb=eadb, dns_backend=dns_backend, use_ntvfs=use_ntvfs)
      File "/usr/lib/python2.7/dist-packages/samba/upgrade.py", line 983, in upgrade_from_samba3
        result.names.domaindn, result.lp, use_ntvfs)
      File "/usr/lib/python2.7/dist-packages/samba/provision/__init__.py", line 1581, in setsysvolacl
        set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, use_ntvfs, passdb=s4_passdb)
      File "/usr/lib/python2.7/dist-packages/samba/provision/__init__.py", line 1511, in set_gpos_acl
        passdb=passdb)
      File "/usr/lib/python2.7/dist-packages/samba/provision/__init__.py", line 1474, in set_dir_acl
        setntacl(lp, path, acl, domsid, use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=service)
      File "/usr/lib/python2.7/dist-packages/samba/ntacls.py", line 104, in setntacl
        (owner_id, owner_type) = passdb.sid_to_id(sd.owner_sid)

After that samba-tool can list users and group but can't add computers, and command
samba-tool ntacl sysvolreset

exit with error:
ERROR(<class 'passdb.error'>): uncaught exception - Unable to get id for sid
  File "/usr/lib/python2.7/dist-packages/samba/netcmd/__init__.py", line 175, in _run
    return self.run(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/samba/netcmd/ntacl.py", line 208, in run
    (BA_gid,BA_type) = s4_passdb.sid_to_id(BA_sid)

Can someone help me with understanding what i'm doing wrong or what i shut to do more ?
When i'm trying to log as someone to network share in samba4 logs i have this:
idmapping sid_to_xid failed for id[2]=S-1-5-21-2669135327-1831268680-3250772662-520: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[3]=S-1-5-21-2669135327-1831268680-3250772662-572: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[4]=S-1-5-21-2669135327-1831268680-3250772662-519: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[5]=S-1-5-21-2669135327-1831268680-3250772662-518: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[7]=S-1-1-0: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[8]=S-1-5-2: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[9]=S-1-5-11: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[10]=S-1-5-32-544: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[11]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[12]=S-1-5-32-554: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[6]=S-1-1-0: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[7]=S-1-5-2: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[8]=S-1-5-11: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[9]=S-1-5-32-545: NT_STATUS_NONE_MAPPED
idmapping sid_to_xid failed for id[10]=S-1-5-32-554: NT_STATUS_NONE_MAPPED

I think is something with groups mappings but don't know how to fix that.
Is there possibility to edit some samba3 or ldap files , even manually to correct this problem ?
Regards
Comment: anybody ? i think is something with gorup mappings but not understand how to fix that
Answer: OK got it, i should not copy all files from /var/lib/samba from old server but only this files:
# secrets.tdb
# schannel_store.tdb
# passdb.tdb
# group_mapping.tdb
# account_policy.tdb
# smb.conf

and use only this file for classic upgrade procedure.


Most instant way to stream live video to iOS and Android

Question: I'm making an app that needs to send a video feed from a single source to a server where it can be accessed by desktop browsers and mobile apps.
So far, I've been using Adobe Media Server 5 with a live RTMP stream. This gives me about a 2.5 second delay on desktop browsers, which gives me no native support for iOS, but leaves me with the option to use Air to export the app for iOS, which produces a minimum 5-6 second delay.
The iOS docs strongly recommend the use of HTTP Live Streaming which segments the stream into chunks and serves it using a dynamic playlist in a .m3u8 file. Doing this produces a 15+ second delay in desktop browsers and mobile devices. A Google search seemed to reveal that this is to be expected from HLS.
I need a maximum of 2-4 second delays across all devices, if possible. I've gotten poor results with Wowza, but am open to revisiting it. FFMpeg seems inefficient, but I'm open to that as well, if someone has had good results with it. Anybody have any suggestions?? Thanks in advance.
I haven't even begun to find the most efficient way to stream to Android, so any help in that department would be much appreciated.
EDIT: Just to be clear, my plan is to make an iOS app, whether it's written natively or in Air. Same goes for Android, but I've yet to start on that.
Answer: In the ios browser HLS is the only way to serve live video. The absolute lowest latency would be to use 2 second segments with a 2 segment windows in the manifest. This will give you 4 seconds latency on the client, plus another 2 to 4 on the server. There is no way to do better without writing an app.
Comment: I'll edit the question to be more clear... I am making an app, so I'm not confined to using the iOS browser, but as far as I can tell, it wouldn't matter because HLS is still the only format natively supported, whether in an app or in the browser.
Comment: In ios8 you can access the video decoder directly, so any protocol should be technically possible. Whether apple allows a non HLS protocol in the App Store is still unknown. My guess is it would be limited to wifi.
Answer: 15 Second delay for HLS streams is pretty good, to provide lower latency you need to use a different streaming protocol.
RTP/RTSP will give you the lowest latency and is typically used for VoIP and video conferencing, but you will find it very difficult to use over multiple mobile and WiFi networks (some of them unintentionally block RTP).
If you can write an iOS app that supports RTMP then that is the easiest way to go and should work on Android too (only old Androids support Flash/RTMP natively).  Decoding in software will result in poor battery life.  There are other iOS apps that don't use HLS for streaming, but I think you need to limit it to your service (not a generic video player).
Also please remember that higher latency equals higher video quality, less buffering, better user experience etc. so don't unnecessarily reduce latency.


Can we say there is High Bias if we have high training error due to small training data size?

Question: If for a very small dataset we have a high training error, can we say that we are underfitting or have a high bias because of the low amount of training data?
Or do we use these terms (underfitting  and high bias) only for referring to issues due to low model complexity?
Comment: Small dataset --> high variance. Overly simple/inflexible model --> high bias. Yours is the first case.
Comment: James et al. ["An Introduction to Statistical Learning"](https://static1.squarespace.com/static/5ff2adbe3fe4fe33db902812/t/601cc86d7f828c4792e0bcae/1612499080032/ISLR+Seventh+Printing.pdf) has some material on the bias-variance trade-off and related stuff, so it could be helpful.
Comment: This is correct but is it relevant? As the sample sizes shrinks, variance grows regardless of whether bias is small or large. The way you have framed the question (small training sample, no mention of test sample) suggests the problem is variance. It is still possible that bias is high, too, but the result should hold regardless of the size of the bias.
Comment: @DhruvMullick Suppose you estimate a ridge regression with an absurdly large regularization term. You can always choose a regularization which is large enough that the model coefficients are constrained to small values near zero. This model exhibits high bias, no matter what the size of the data.
Comment: @Richard But doesn't high training error signify high bias?
Comment: Not necessarily.
Comment: Okay, wouldn't high variance come into picture if we were talking about high test error?  Also is there any resource you can point me to for understanding why high training error may not necessary signify high bias?
Comment: My source of confusion is this (not sure of the reliability): "If both, the training and test set error are high, then it symbolizes that the machine learning model has not properly learnt the input-output mapping on the training set and is also unable to generalize on the test set. … Such a model is said to underfit on both, the training and test dataset and suffers from high bias." —  https://towardsdatascience.com/contents-9b2e49f49fe9
Comment: On the other hand, all is relative. It is easier to tell the source of the problem when you vary something (the sample size or the model complexity) and observe how the results change. In your example, there is no variation, thus hard to identify the issue.
Answer: The bias and variance are not connected to your specific sample, but to the estimation method and the underlying distribution. The variance is most often connected to the sample size, however. High training error does not automatically signify high bias, high training error can be the result of low sample size.
If you have a point estimator, say the sample mean $\bar{x}$ for the distribution mean $\mu$, then the bias is the difference between the expected value of $\bar{X}$ and $\mu$. It can be shown that the expected value of $\bar{X}$ is $\mu$, and hence, the sample mean is an unbiased estimator of the distribution mean. If you are not used to providing mathematical proofs, you can think of it this way: What happens if your sample size grows towards infinity? Will the difference between your estimator and the parameter you are trying to estimate eventually become 0?
The variance of your estimator says something about how much you can expect your estimator to vary from sample to sample, and this is often used to say something about the uncertainty of your results. Back to $\bar{X}$ as an example: Say you have a sample that gave you $\bar{x} = 13.5$. If you took another sample of the same size, how much would you expect $\bar{x}$ to differ?
Because bias and variance are connected to the underlying distribution, in most cases you cannot know their exact values, but the theoretical results can help you choose an estimator with low bias and variance.
If you have a model that you are training for classification/prediction, the same principles apply.
Some models will give you zero training error if you add enough parameters (e.g. an n-1 polynomial for an n-sized training set), at the cost of huge variance. An unbiased model could give you training error if you simply do not have enough data to train the model (e.g. $n<p$), and you have to use some default parameters to fill in.
There are no universal results you can lean on, since "model" does not have a specific definition.


Invalid address: return even on successfully sent e-mail

Question: Need help ASAP.
My function is sending e-mail on successful quit. E-mail is sent well. The problem is that i'm always getting "Invalid address:" before my normal exit message.
Code is following:
<code>$message_text = array(
'id' => 'modulename' . '_' . 'key',
'to' => 'firstname.lastname@example.com',
'subject' => "OK",
'body' => array("OK"),
'headers' => array(
    'From' => 'email@example.com',
    'Sender' => 'email@example.com',
    'Return-Path' => 'email@example.com',
          ),
);
$system = drupal_mail_system($module, $key);
$message = $system->format($message_text);
$system->mail($message);
</code>
Thanks.
Comment: Well. Not the best solution. I know, but currently I managed to avoid this by cleaning output buffer with ob_clean();
Answer: This is because of the absence of $message_text['from'];
In SMTP module smtp.module.inc line 74-85 there is hack that handles the absence of 'Reply-To' by setting it to $message['from'] which is also absent, consequently 'Reply-To' will be empty hence throwing the error Invalid address:.
add $message_text['from'] = 'your from address' this will solve the issue.
Answer: Try at last
<code>$system = drupal_mail_system($module, $key);
if ($system->mail($message)) {
  // Success.
}
else {
  // Failure.
}
</code>


how to get data out of .then function

Question: trying to read outside of a then/catch statment.  It works fine inside .then but doesn't work inside of react html
class DashboardPage extends Component {
...

  componentDidMount() {
    axios.get('http://localhost:3000/users/me', this.yourConfig)
  .then(function (response) {
    // handle success
    console.log(response.data.name)
    console.log(response.data.email)

  })
 ....

  render() {
    return (

Welcome {this.response.data.name}

Your email is {this.response.data.email}

      this is your token {this.tokenCookie}

    );
  }
}

Comment: Use the `state` of a React component. https://reactjs.org/docs/state-and-lifecycle.html
Comment: You wont be able to do that, you might be able to assign a `this` property inside the `then` function
Comment: For other cases, see [_How do I return the response from an asynchronous call?_](https://stackoverflow.com/q/14220321/1218980)
Comment: `this.response` no where is response set to this. And you should not be using this, should be using state.
Answer: You need to save response to the state. Something like this should work:
class DashboardPage extends Component {
    constructor(props) {
        super(props);
        this.state = {response: null};
    }

...

  componentDidMount() {
    axios.get('http://localhost:3000/users/me', this.yourConfig)
    .then((response) => {
      // handle success
      console.log(response.data.name)
      console.log(response.data.email)
      this.setState({ response });
    });
  }
....
  render() {
    if (this.state.response == null) {
      return (

Response not loaded

); // Whatever you want to render when there is no response yet
    } else {
      return (

Welcome {this.state.response.data.name}

Your email is {this.state.response.data.email}

        this is your token {this.tokenCookie}

      );
    }
  }

Note: I changed the function (function (response)) to the ES6 arrow function so this can be used. You can also set a variable like var that = this and change this inside function (response) to that.
Comment: Be careful, setting the state in an async callback may happen after the component was unmounted. https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
Comment: I tried your way and now i am getting  TypeError: Cannot read property 'data' of null
Comment: My bad @ChrisAllen, I forgot to update render to test for that. If `response` is null, you have to render something else. I updated the code to reflect it.
Answer: You cannot use response variable outside that function
The best way around is use state
 Example in doc -> https://reactjs.org/docs/faq-ajax.html
 componentDidMount() {
        fetch("https://api.example.com/items")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: result.items
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }

Comment: Be careful, setting the state in an async callback may happen after the component was unmounted. https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html

how to get data out of .then function


Manipulação Imagens JavaScript

Question: Alguém conhece alguma biblioteca para manipulação de imagens em JavaScript?
Queria juntar duas imagens em uma, em determinadas posições pré-fixadas.
Um exemplo são aqueles testes para facebook, que pega a imagem do perfil de uma determinada pessoa e adicionada em outra imagem de fundo.
Answer: Este exemplo no jsfiddle http://jsfiddle.net/sqJtr/ creio que pode lhe ajudar, coloca uma imagem sobre outra com "div" mas pode mudar para "img" que vai funcionar também.
Comment: Mas no caso eu precisava manipular duas imagens ou mais para criar uma outra, não só colocar uma encima da outra.
Como se fosse automatizar um processo que poderia fazer com o Photoshop, Firework...

Manipulação Imagens JavaScript


Normal approximation of binomial distribution.

Question: The probability that a shooter strikes a target is 0.4.
By using a suitable approximation,find the probability that he will strike the target 220 times out of 500 shots.
Comment: You should write a better title and add probability as a tag. You should also add your thoughts to the exercise: what have you tried so far? What approximations do you have in mind?
Comment: Thanks for the suggestion. I'm not sure what cld be the suitable title, and this question actually comes with 2 sub question, but I only know the first sub question. The one I asked, I seriously have no thoughts about it ><
Answer: This problem is about normal approximation of binomial distribution. This is known as De Moivre - Laplace theorem. When you have very large no. of binomial trials in an experiment it will be difficult to evaluate factorials and thus making it difficult to evaluate exact values. As per the theorem you can approximate the distribution as normal distribution.
We have event X: Shooter hits the target. p=0.4 and n=500 => np=200 and npq= 120. So X ~ B (500,0.4) can be approximated as X ~  N (200, 120). Where B is binomial distribution and N is normal distribution with mean 200 and variance 120. Now you need to find P(X=220) in normal distribution . But you know that normal distribution is continuous distribution whereas binomial was discrete. So you do something called continuity correction which tells you that in a normal approximated binomial P(X=n) --> P(n-0.5 < X < n+0.5). So find P(119.5 < X < 220.5) using the standard distribution table method.


webgrid witha horizontal scrollbar?

Question: I am using webgrid of asp.net mvc 3.0 razor view to display a dataset. The dataset has 36 columns and so the webgrid goes beyond the visible window. How can I display it within the visble window with a horizontal scrollbar. I'll appreciate any help. Thank you.
vks
Comment: possible duplicate of [Does MVC3 WebGrid support horizontal scrollbars?](http://stackoverflow.com/questions/7844655/does-mvc3-webgrid-support-horizontal-scrollbars)
Answer: You can not have scrollbars directly on webgrid. It is rendered as table anyway. However, you can wrap a div around webgid and apply scrollbars to div. Not a very elegant solution but works fine.

webgrid witha horizontal scrollbar?


Can I alias a database name or create a synonym for a database?

Question: I am trying to sync data from an on-premise SQL Server to an Azure SQL Server using Microsoft SQL Data Sync 2.0.   The problem is my database name has a . in it (MyDatabase.V2), this is not allowed.
Is there a way for me to have a secondary name for this database for the Sync tool to reference?
Comment: Pretty sure you can't. Can you not quote your database name(I.e. `[MyDatabase.V2]`)? Generally, however, as you have found out, it is a bad idea to use special characters in an object's name. If you can rename the database, I would.
Comment: Yeah, 8 years into using this database, used in 100 connection strings - I am stuck with it
Answer: Looks like this is not currently a possibility with SQL Server
Answer: Create an SQL Server job to back up MyDatabase.V2 and restore it as MyDatabaseV2. Then, use this new MyDatabaseV2 with Data Sync 2.0. Basically, a work-around. If you need more frequent data replication in the new MyDatabaseV2, look into log shipping or replication.


While statement trouble Java

Question: While I was working on a program that simulates a dice, I encountered a problem.
This is the code I wrote (I know it is not good programing at all but I'm learning). It works and of course I know that there is unnesecary parts in it, but is not the problem.
 double x ;
 String z ;
 x = Math.random() ;
 z = Double.toString(x) ;
 z = z.substring(2, 3) ;

 while (x>6 || x<1) {

     x =Math.random() ;
     z = Double.toString(x);
     z = z.substring(2, 3) ;
     x = Integer.parseInt(z );
 }

 z = Double.toString(x );
 z = z.substring(0, 1) ;

 JOptionPane.showMessageDialog(null, "Antal prickar: "+z);

The problem is that saw that I erlier had an if statement in the while loop and it worked a couple of weeks ago and now when I rewrote the code it is not working.
double x ;
String z ;
x = Math.random() ;
z = Double.toString(x) ;
z = z.substring(2, 3) ;

while (x>6 || x<1) {

    if (x>6) {
        x =Math.random() ;
        z = Double.toString(x);
        z = z.substring(2, 3) ;
        x = Integer.parseInt(z );
    }
}

z = Double.toString(x );
z = z.substring(0, 1) ;

JOptionPane.showMessageDialog(null, "Antal prickar: "+z);

Can anyone explain why it is not working because I should be able to put the if statement inside the while loop without it giving me errors right?
Comment: Why are you simulating the roll of a dice like that ?
this line does about all that: int dice1=(int)(Math.random()*6+1);
Comment: What errors do you get? What is going wrong?
Comment: You say, "now when i rewrote the code it is not working". What does that mean? What errors or unexpected behavior are you experiencing?
Comment: How can you guarantee  z = z.substring(2, 3) ; z length is >4
Comment: Formatting your code might be a start, e.g. in order to see where the matching closing braces are. - I did it for you, please check for correctness.
Comment: Simply calling `Math.ceil(Math.random()*6)` would do the trick.
Answer: Assuming your previous code was working (and skipping comments on style etc.) the main problem seems to be the added if-statement.
Consider the case where x = 0:
while( x > 6 || x < 1) will run since the condition is satisfied (x is smaller than 1).
if(x > 6) is not satisfied though (x is not greater than 6) and thus x will never be updated, resulting in an endless loop.
Btw, I'd not use Math.random() but rather create a new instance of Random and then call nextInt(6) + 1 to get a random integer between 1 and 6 (both inclusive):
Random rand = new Random(); //you might want to store this elsewhere and reuse the instance
int dice = rand.nextInt(6) + 1; //done, random integer between 1 and 6

Answer: It seems you are using java.lang.Math.random() to generate a number between and 1 and 6. As that random() call returns a value normalized in the 0.0 to 1.0 interval, you choose the first decimal as your candidate value and in the case it is off limits, you repeat the random() call to get a new candidate number.
In the second snippet you sent post (the one you say is not working), the formatting shows that the while loop only contains the if statement, and this statement will only do something if x > 6, but x will never be over 6 as the value is between 0 and 1.
You might be missing this line in the first block before the while loop:
x = Integer.parseInt(z );

And the if condition within the loop shall be removed.
Edit: to produce a random value between 1 and 6 the simpliest piece of code I can thing about is:
new java.util.Random().nextInt(6) + 1

While statement trouble Java


Como passar um valor de um método para outro método dentro da mesma classe ? C#

Question: Gostaria de passar a variável tot que está em CadastroDespesas em float para o método MostrarDespesas. Alguém pode me ajudar ??
class Ex4
{
    List<String> descricaodespesas = new List<string>();
    List<float> valordespesas = new List<float>();
    List<String> descricaoreceitas = new List<string>();
    List<float> valorreceitas = new List<float>();

    public void CadastroDespesas()
    {
        string descricao;
        float valor;
        float soma = 0,tot;
        Console.Write("Informe o valor: ");
        valor = Convert.ToSingle(Console.ReadLine());
        valordespesas.Add(valor);
        Console.WriteLine("Informe uma descrição:");
        descricao = (Console.ReadLine());
        descricaodespesas.Add(descricao);
        foreach (float som in valordespesas)
        {
            soma += valor;
        }
        tot = soma;
    }

    public void MostrarDespesas()
    {
        Console.WriteLine("------Despesas Informadas------");
        Console.WriteLine();
        for(int i = 0; i < descricaodespesas.Count; i++)
        {
            string desc = descricaodespesas.ElementAt(i);
            float valor = valordespesas.ElementAt(i);
            Console.Write("Descrição: "); Console.WriteLine(desc);
            Console.Write("Valor: "); Console.WriteLine(valor);
        }
        Console.ReadLine();
    }

Comment: coloque ela fora do método no escopo geral da classe ai todos os métodos terão acesso.
Comment: declara fora, igual ao que fez para o descricaodespesas
Comment: resolveu seu problema?
Comment: Sim. Obrigado a Todos pela ajuda.
Comment: Veja: [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/a/1079/3117)
Answer: Existem algumas maneiras de fazer isso. Vou apresentar duas:
Primeira solução:
 public void MostrarDespesas(float tot)
 {
     // Agora você tem acesso ao valor que está no tot, faça o que quiser com ele
     Console.WriteLine("------Despesas Informadas------");
     Console.WriteLine();
     for(int i = 0; i < descricaodespesas.Count; i++)
     {
         string desc = descricaodespesas.ElementAt(i);
         float valor = valordespesas.ElementAt(i);
         Console.Write("Descrição: "); Console.WriteLine(desc);
         Console.Write("Valor: "); Console.WriteLine(valor);
     }
     Console.ReadLine();
}

A partir de agora, na hora que quiser chamar o método MostrarDespesas(float tot), terá que informar um valor float por parâmetro. Utilizei como exemplo a sua váriavel tot:
tot = 100;

MostrarDespesas(tot);

Segunda solução:
Ou utilizando a ideia dada pelo @Virgilio, declare a variável tot como uma variável de classe, podendo utilizá-la em qualquer lugar da sua classe:
class Ex4
{
    List<String> descricaodespesas = new List<string>();
    List<float> valordespesas = new List<float>();
    List<String> descricaoreceitas = new List<string>();
    List<float> valorreceitas = new List<float>();
    float _tot; // Variável tot declarada como variável de classe
}

Não é mais necessário declarar a tot aqui pois já foi declarada no topo da classe (código acima):
public void CadastroDespesas()
{
    string descricao;
    float valor;
    float soma = 0; // Declaração removida 'tot''
    Console.Write("Informe o valor: ");
    valor = Convert.ToSingle(Console.ReadLine());
    valordespesas.Add(valor);
    Console.WriteLine("Informe uma descrição:");
    descricao = (Console.ReadLine());
    descricaodespesas.Add(descricao);
    foreach (float som in valordespesas)
    {
        soma += valor;
    }

    // Utilize a variável _tot
    _tot = soma;
}

A partir de agora, você consegue acessar a variável _tot de qualquer lugar da sua classe, contento o valor da soma.
Comment: Show de bola galera, agradeço a todos pela ajuda.
Comment: Sem problemas! Se a resposta te ajudou, marque ela como a correta para ajudar outras pessoas com a mesma dúvida!
Answer: Você esta fazendo algumas coisas desnecessárias no seu método.
public void CadastroDespesas()
{
    string descricao;
    float valor;
    float soma = 0,tot;
    Console.Write("Informe o valor: ");
    valor = Convert.ToSingle(Console.ReadLine());
    valordespesas.Add(valor);
    Console.WriteLine("Informe uma descrição:");
    descricao = (Console.ReadLine());
    descricaodespesas.Add(descricao);
    foreach (float som in valordespesas)
    {
        soma += valor;
    }
    tot = soma;
}

Vamos simplificar para;
public void CadastroDespesas()
{
    string descricao;
    float valor;
    Console.Write("Informe o valor: ");
    valor = Convert.ToSingle(Console.ReadLine());
    valordespesas.Add(valor);
    Console.WriteLine("Informe uma descrição:");
    descricao = (Console.ReadLine());
    descricaodespesas.Add(descricao);
}

E no seu outro método basta acessar sua lista para recuperar os valores usando o Sum().
   public void MostrarDespesas()
    {
        Console.WriteLine("------Despesas Informadas------");
        Console.WriteLine();
        for(int i = 0; i < descricaodespesas.Count; i++)
        {
            string desc = descricaodespesas.ElementAt(i);
            float valor = valordespesas.ElementAt(i);
            Console.Write("Descrição: "); Console.WriteLine(desc);
            Console.Write("Valor: "); Console.WriteLine(valor);
        }

// Basta usar o Sum do linq na sua lista para recuperar o valor total
        var tot = valordespesas.Sum();
        Console.ReadLine();
    }

Answer: Você pode retornar o valor de tot de dentro da função CadastroDespesas trocando void pelo tipo de variávell que você quer retornar, no seu caso é um float, sua função teria esse cabeçalho:
public float CadastroDespesa(){

}

E no fim dela você retorna tot:
return tot;

Agora você precisa alterar o método MostrarDespesas pedindo um float para ser exibido:
 public void MostrarDespesas(float valorTotalDespesas)
 {
 }

O mais correto é primeiro você receber o valor de CadastroDespesa e depois chamar MostrarDespesas passando o valor recebido:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Ex4 DespesaManager = new Ex4();
            float tot = DespesaManager.CadastroDespesa();
            DespesaManager.MostrarDespesas(tot);
        }
    }
}

Esse é o modo como você utilizaria as alterações. O seu código em sí fica assim:
class Ex4
{
    List<String> descricaodespesas = new List<string>();
    List<float> valordespesas = new List<float>();
    List<String> descricaoreceitas = new List<string>();
    List<float> valorreceitas = new List<float>();

    public float CadastroDespesas()
    {
        string descricao;
        float valor;
        float soma = 0,tot;
        Console.Write("Informe o valor: ");
        valor = Convert.ToSingle(Console.ReadLine());
        valordespesas.Add(valor);
        Console.WriteLine("Informe uma descrição:");
        descricao = (Console.ReadLine());
        descricaodespesas.Add(descricao);
        foreach (float som in valordespesas)
        {
            soma += valor;
        }
        tot = soma;
        return tot;
    }

    public void MostrarDespesas(float valorTotalDespesas)
    {
         Console.WriteLine("------Despesas Informadas------");
         Console.WriteLine();
         for(int i = 0; i < descricaodespesas.Count; i++)
         {
             string desc = descricaodespesas.ElementAt(i);
             float valor = valordespesas.ElementAt(i);
             Console.Write("Descrição: "); Console.WriteLine(desc);
             Console.Write("Valor: "); Console.WriteLine(valor);
          }
          Console.WriteLine("Valor total: ");
          Console.WriteLine(valorTotalDespesas);
          Console.ReadLine();
     }

Essa é a sua maneira de fazer, porém eu acho que seria mais interessante você utilizar a própria lista valordespesas para somar, você pode utilizar o LINQ assim:
valordespesas.Sum();

Sendo assim você não precisaria retornar nada nas suas funções, MostrarDespesas fica assim:
    public void MostrarDespesas()
    {
         Console.WriteLine("------Despesas Informadas------");
         Console.WriteLine();
         for(int i = 0; i < descricaodespesas.Count; i++)
         {
             string desc = descricaodespesas.ElementAt(i);
             float valor = valordespesas.ElementAt(i);
             Console.Write("Descrição: "); Console.WriteLine(desc);
             Console.Write("Valor: "); Console.WriteLine(valor);
          }
          Console.WriteLine("Valor total: ");
          Console.WriteLine(valordespesas.Sum());
          Console.ReadLine();
     }

Comment: Não consigo marcar as respostas como corretas, talvez seja pq fiz a pergunta como visitante, porém já solucionou meu problema, agradeço a todos pela ajuda. (Criei uma conta agora mas ele não reconhece essa pergunta como minha.)


Calculating trendlines using slope and y-intercept

Question: I have a requirement in one of my project to draw trendlines on charts. I need to know in the below equations (where $a$ is slope and $b$ is y-intercept):

[Linear Trendline]: $y = ax + b$
[Logarithmic Trendline]: $y = a \log x + b$
[Polynomial Trendline]: $y = a(n)x^{n} + a(n-1)x^{n-1} + a(1)x + a(0)$
[Power Trendline]: $y = ax^b$
[Exponential Trendline]: $y = ab^x$

Does the value of $m$ and $b$ can be calculated once and used in all of the equations or the values of $a$ and $b$ are calculated in a different way for every equation. If they are calculated differently for every equation, how are they calculated? Can someone provide me a link for that. Currently, I am using this method to calculate $a$ and $b$.
Another question is how accurate are the other equations to calculate trendlines? Is there any other method that is more accurate than this?
Answer: Your first question: in the models you have provided, all coefficients must be recalculated from scratch when switching models.
There do exist models with the property that the coefficients that you calculated can be re-used when switching to another model. A famous example is the Newton polynomial that runs through $N$ points $(x,f(x))$:
$$
\hat f (x) = \sum_{k=0}^{N} a_k \cdot \begin{cases} \prod_{m=0}^{k-1} (x - f(x)) & k \ge 1 \\ 1 & \text{otherwise .}\end{cases}
$$
The $a_k$ that causes $\hat f (x)$ to run through all of the points $(x,f(x))$ are given by a formula that depends only on $(x_0, f(0))$ through $(x_k, f(x_k))$, so adding more points to the right (increasing $k$ from $k_0$ to $k_0+b$) will introduce new coefficients $a_{k_0+1}$ through $a_{k_0+b}$ without changing any of the existing coefficients $a_0$ through $a_k$.
For probably most models, all the existing coefficients must be adjusted in some way. An example is an $N$-term Fourier series that runs through $N$ equispaced points $(x,f(x))$:
$$
\hat f (x) = \sum_{k=-(N-1)/2}^{(N-1)/2} a_k \cdot e^{i (2 \pi / N) k x}
$$
The $a_k$ that causes $\hat f (x)$ to run through all of the points $(x,f(x))$ are given by an $O(N^2)$ algorithm:
$$
a_k = \sum_{x=x_0+0}^{x_0+N-1} f(x) \cdot e^{-i (2 \pi / N) k x}
$$
If you double the number of samples over the same time interval from $N$ = $N_0$ to $2N_0$, it can be shown that $a_k$ changes to $a_k^* = a_k + \left(e^{-i(2 \pi / (2N_0))k} \right) \cdot b_k$ where $b_k$ are the coefficients of the $N$-term Fourier series over just the new samples. This property is the basis of the Cooley—Tukey FFT algorithm which turns the calculation of $a_k$ for any $N$-term Fourier series where $N$ is a power-of-2 into an $O(N\,log\,N)$ algorithm.
Now, I think that answering your second question will answer the rest of your first question. Accurate is subjective. For $n$ points $(x_i, y(x_i))$, you can come up with all sorts of "doodles", in a sense, all of which have the property that they run through or near all of the points (but some will be better looking to the human eye than others). Similarly, for a real-valued function $f(x)$, the most accurate trend line would be $f(x)$ itself. But say that you have decided that the data "looks linear" or "looks exponential", or "should theoretically be following this equation within uncertainty for some unknown parameters $a, b, c$". The most common way of picking the parameters in practice is to ask which set of parameters minimizes the sum of squared error between the model and the original data at each point:
$$
a, b, c \text{ are defined such that } \sum_{k=1}^{N} (\hat f(x_k) - y_k)^2 \text{ is minimized.}
$$
It's under this criteria (the "least squares" criteria) that the formulas for calculating the parameters for models are derived (using calculus to differentiate the expression with respect to $x$ and isolate $a, b, c$). Problems of this nature are known as optimization problems, and in case general formulas to find $a, b, c$ can't be determined, $a, b, c$ can be approximated by a computer using simulated annealing and gradient descent.
There is no necessarily right or wrong criteria for $a, b, c$, and least squares is not valid for all situations. For example, humans perceive certain types of distortion in an image or an audio signal more than other types of distortion, even if those distortions have a smaller sum of squared error than the latter. The choice of error criteria in image processing is discussed in the magazine article Mean Squared Error: Love It or Leave It?.
(Also, to answer your question, I believe all the formulas you stumbled upon most likely calculate the same parameters in different ways arriving at the same exact numbers; if that's the case, they're equally accurate because they satisfy the same least squares criteria, but they might not be as accurate in all situations if a computer calculates them using floating point arithmetic, because some algorithms might have better numerical stability than others, but that's a separate problem that I don't think you're talking about.)
There are some other models that you didn't mention. The most popular general interpolating curves these days are cubic splines (just a bunch of piecewise cubic polynomials of the form $a + bx + cx^2 + dx^3$ spliced together), and Bézier curves. There also always exists an ($n+1$)-degree polynomial that runs through $n$ points on a graph, and finding the coefficients of that polynomial can be done by solving an ($n+1$) by ($n+1$) system of equations, but then there's the unfortunate Runge's phenomenon.
Comment: If I have a set of values for x and y coordinates say (1,2)(2,3)(3,4) then the calculated values of 'a' and 'b' are going to be always the same if I use the approach mentioned at http://classroom.synonym.com/calculate-trendline-2709.html< /a>. Then what is the use of calculating them for scratch? I have only one set of values for which I need to generate y coordinate based on the value of x for each type of trendline.


Some rows giving "String or binary data would be truncated" error when editing in Management Studio

Question: When trying to add data to a newly created column using SQL Server Management Studio (edit rows), I am getting the following error:

No row was updated.
The data in row 1 was not committed.
Error Source: .Net SqlClient Data Provider.
Error Message: String or
  binary data would be truncated.
The statement has been terminated.
Correct the errors and retry or press
  ESC to cancel the change(s).

The datatype for the column is nvarchar(150).

UPDATE:
I am inserting only a few ascii characters (example: abc).
This is someone else's database who asked me to look into it... I discovered:
a) only some of the rows give this error
b) the rows giving this error have long strings in two other columns (one is a nvarchar(max), and one is ntext).
Comment: Is there only a single column in that table?  What are the types and lengths of all the columns and what does your insert/update statement look like?
Comment: There are multiple columns, see my update above.
Answer: This error typically occurs when you exceed the length of the data type for the column.  Are you inserting more than 150 characters into the column?
Comment: I'm only inserting a few characters. I updated some new findings in the post.
Comment: Hmmm - It's possible to ignore the 'String or binary data would be truncated' message by setting ANSI_WARNINGS to OFF. This will truncate fields where they don't fit. ANSI_WARNINGS OFF has drawbacks and it is better to correct a problem rather than ignore it. Another thing to check is whether the table update is firing any triggers that insert or update another table.
Answer: I've experienced this on occasions when a table had a mixture of ntext and nvarchar(MAX) datatypes. Changing all the ntexts to nvarchar(MAX)s fixes the problem.
Answer: I got this error when I mistakenly exceeded the number of characters that a field could hold. In Visual Studio, I had mistakenly inserted a field with its datatype as nvarchar(1) and was trying to save a word with 6 characters to that field. Once I changed to nvarchar(50),  it worked fine. Hope this helps someone.
Comment: Whoever designed a table with a **nvarchar(1)** column lacked some very basic knowledge about databases.
Answer: Usually this occurs when tried insert more symbols, what is given to this field.
go to Design, check the Data Type of field
for Example your Data Type = nvarchar(20) and your tried set the 30 characters

Microsoft SQL Server 2014
Answer: I encountered this error when trying to edit a row in a table that had even one field of type text.  It still seems to be an issue even in SSMS 18 (in 2021).


CloudPebble Crash Logs

Question: I've written a pebble watch face in the CloudPebble IDE. I got a message on the watch that the app had crashed, is there a way to view the crash logs?
In CloudPebble, When I go to Compilation -> View App Logs
I don't see any logs.
Answer: You need to be connected to CloudPebble at the moment of the crash to get any logs. If you are, you should see something like this:
<code>
[INFO    ] E ault_handling.c:68 App fault! {0a7575eb-e5b9-456b-8701-3eacb62d74f1} PC: 0x8019c3d LR: ???
[WARNING ]    Program Counter (PC):  0x8019c3d ???
[WARNING ]      Link Register (LR):        ??? ???
</code>
(This is the raw output - CloudPebble will actually improve this output a little bit and point to the line number if the crash is in your application.)
Comment: Ok, the crash seems to happen at random, so I'm guessing it may be memory related.

CloudPebble Crash Logs


How to view large time series data interactively?

Question: I often deal with reasonable sized amount of time series data, 50-200 million doubles with associated time stamps and would like to visualize them dynamically.
Is there existing software to do this effectively? How about libraries and data formats? Zoom-cache is one example of library focusing on large time series. In Zoom-cache the data is summarized at several resolutions to make it easier to view at different resolutions.
Edit: Also if there is anywhere else I should ask this question or seek an answer please let me know.
Comment: Although I have no idea about how it will scale with such huge number of data points, you might want to take a look at [Cubism.js](http://square.github.com/cubism/).
Comment: You might be interested in Zoomdata https://www.zoomdata.com/product/fast-data-sharpening-visualization/ Their pricing is quite high though.
Comment: I took a look at Cubism, which looks good for incremental updating graphs from serial streams of data, but with my short search I did not see anything about caching multiple resolutions or summary data to speed up large data sets. Thats for the pointer though it looks like a cool library.
Comment: @chhantyal - Thanks! That does look like the kind of tool I was looking for.  Though I am no longer working with the same data sets I am still interested in the space so I will probably try out zoomdata's trail at some point.
Answer: Sorry for self-ad, but Thunderplot (thunderplot.com) would be good candidate for it. I wrote it exactly for interactive plotting of large datasets. I didn't test it with 200KK rows datasets, but it works fine with ~10KK rows. Also there's "read every Nth row" feature, so you can reduce amount of data to store/visualize. I can send you the registration key in exchange to one of those large datasets. :-)
Comment: https://thunderplot.com/ says THUNDERPLOT PROJECT CLOSED
THANK YOU FOR YOUR SUPPORT
BYE
Answer: There are a set of research tools called TimeSearcher 1--3 that provide some examples of how to deal with large time-series datasets. Below are some example images from TimeSearcher 2 and 3.
Comment: "November 21, 2005" :/ and if I try to open something, it just locks up.
Answer: Another self-promoting post because I work for this company, but SensorCloud (sensorcloud.com) uses smart algorithms to graph massive datasets very quickly. It was originally designed with our physical sensors in mind, but it has a CSV uploader to handle any timeseries data.
For example, we uploaded a dataset that had 100 billion data points (over 1 terabyte of timestamp + data values) and you can graph it and interact with it very quickly.
Here's a public link to that dataset:
https://sensorcloud.microstrain.com/SensorCloud/data/Z3MFURATHIB8A032/
The link above uses our flash viewer. If you don't want to use flash, here's the javascript viewer: https://sensorcloud.microstrain.com/SensorCloud/data/Z3MFURATHIB8A032/js/
Use the scroll wheel, or Shift+left click to zoom in.
Comment: So you mean FastGraph?  "SensorCloud's Timeseries Data Widget was built from the ground up with speed and data in mind. Our unique algorithms allow you quickly view your data, no matter how large. No other visualization software comes close."


How to use a variable for training a model but not for making predictions?

Question: I'm trying to predict the click through rate (CTR) of a product listing. As an input to train my model, I want to use the position of the product in the listing (if it's the first product listed, or if it's the second listed and so on), since that is an import component for CTR.
The problem is that I don't have the position when making predictions for new products (because I don't know where they will be placed in different search filters). Ideally, I would predict all positions and use the median value of those predictions as the CTR result, but that's not feasible computational-wise.
It seems like it should be a common problem when dealing with CTR forecasting. So I'd like to ask for suggestions about how to handle that situation, where I have a variable on my training data but I don't know it's value for making predictions.
Thanks!
Comment: In my opinion, it's too simple a model of 'CTR' that the product's list position chiefly determines the click-through rate of webshop visitors. I would recommend you going back to the drawing board and and model CTR from variables that are more meaningful, and which are always known before the new product is being launched in the webshop..
Comment: Please say more about the nature of your model and the way that you account for list position in the model. With models that return things like coefficients for list position you might have a built-in solution that doesn't require re-computation.
Comment: @MatchMakerEE One important detail that I left out is the reason for not just outright removing the "position" variable. The CTR prediction is what will define the ordering of the listings (higher CTR, higher position). So if I don't take the position into consideration, I'll be introducing an undesirable feedback to my model in future re-trainings.

Products that initially had higher CTR predictions and got a higher position as a result, will have higher actual CTR values, and that entails skewed predictions when I re-train the model using that data.
Comment: @EdM I'm using a gradient boosting tree based model. Since the resulting model will be very much so a "blackbox", I don't think I can deal with the issue in the manner that you suggested, unfortunately.
Answer: I have no experience with modeling CTRs, but one thought that comes to mind is to use the flexibility of gradient boosting trees to handle missing values. As I understand it, the model building assigns directions at each node to missing values, even if there aren't any missing in the training set. CTR could still be predicted based on the other characteristics of the listing but without values for the list position. So if all of the new candidate listings that you want to rank are treated the same in this respect, that would provide a way to rank them for the initial ranking.
You would have to do a good deal of testing, however, to see if this approach gives reasonable results for your application. As the page I linked above puts it:

Be careful if your scoring data has its missing values distributed differently from your training data. xgboost's missing handling is convenient but doesn't protect against masking.
Comment: Searching to try to understand that a bit better, I found this discussion: https://github.com/microsoft/LightGBM/issues/2921 So it seems like when you don't have null values in your training data, any null values are replaced by zero when making predictions (at least in LightGBM), sadly.
Comment: @Celio even in that case, the prediction would be for the CTR if the candidate were at the head of the list (if you treat list position as numeric with 1 at the top of the list, a split by `position <2` would be the same for values of 0 or 1). That might not be a bad thing for determining initial ranking of new candidates. Or if you have a fixed number of list positions, renumber so that 0 is in a middle position. Or perhaps you could remove some fraction of list position values from the training data. Play a lot with your training data before you give up on this.


Trocar estrutura de icones no javascript

Question: Estou iniciando em desenvolvimento e estou com uma missão que to batendo cabeça e não sei como terminar.
Preciso trocar tag´s  por <svg><use></svg>. Dessa forma deixo de chamar por class e passo à chamar pelo id, conforme segue código abaixo.
Gostaria de manipular pelo js. Onde houver  no HTML, fosse alterado para
<svg class="icon"><use xlink:href="icons/icons.svg#icon-nomedoicone"/></svg>

Alguém poderia me ajudar com uma idéia de código?
Pensei em algo assim...
var i = document.querySelectorAll("i");
        for(var i=0;i<=i.length;i++) {
            if(i[s].className == "ico-") {
            i[i].innerHTML = "<svg class='icon'><use xlink:href='icons/icons.svg#icon-italic'/></svg>";
        }
    }

Comment: Tem 2 problemas: você usa `i` para duas coisas diferentes, e a comparação com `==` não vai considerar coincidência parcial das strings.
Answer: Você pode utilizar o método replaceWith.
<!DOCTYPE hml>

        <title>Title of the document</title>

        Span (Not replaced)
        Italic (Not replaced)
        Icon (Replace)
        Icon (Not replaced)
        Second Icon (Replace)

        <button type="button">Substituir icons</button>

É necessário que você crie um elemento (com o document.createElement) temporário, caso você passe o html "direto" o JavaScript irá considerar como string e escrever o código na tela.
Para demonstração siga os passos abaixo:

Copie e cole o código acima em uma página .html
Baixe a imagem https://cdn.svgporn.com/logos/android-icon.svg
Adicione a imagem baixada no mesmo diretório onde você criou o .html acima.
Acesse através do seu servidor.
Comment: Agradeço a ajuda, testei aqui, mas nada ainda, não aparece o icone!
Comment: @PriscilaNeu O código está tudo OK. Verifique se apenas o código `` funciona. Adicionei um passo a passo para você checar a demonstração.
Answer: Uma outra forma é usando createDocumentFragment(). No exemplo abaixo incluí um <circle> apenas para ilustração, você deve apagar.

let els = document.querySelectorAll("i[class*='icon-']");
let frag = document.createDocumentFragment();

for(let item of els){
   let svg = '<svg class="icon"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /><use xlink:href="icons/icons.svg#'+item.classList+'" /></svg>';
   item.innerHTML = svg;
   frag.appendChild(item.removeChild(item.firstChild));
   item.parentNode.replaceChild(frag, item);
}
elemento 1
elemento 2


Como fazer um LOOP ser executado de acordo com o retorno de um Promise (promessa)?

Question: Como consigo fazer meu loop esperar pelo retorno de uma promise?
Digamos que tenho o seguinte código:
for (var i = 0; i < 10; i ++) {
   // algumalógica
   fazAlgumaCoisa(array[i]);
}

var fazAlgumaCoisa = function(obj) {
   $http.get(url).then(function success(response) {

   }, function error(response) {

   });
}

Minha dúvida é: como faço pro meu for aguardar o retorno dessa chamada http?
Comment: Podes explicar em que contexto queres usar essa funcionalidade? Sem saber o que queres fazer vamos estar a adivinhar uma solução que pode não ser útil.
Comment: Você poderia especificar que esta usando um script de http: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise#Creating_a_Promise_2
Comment: tenho um videoplayer onde a configuração do que irá tocar é descrita em diversos arquivos. Eu preciso, antes de tocar, garantir que todos os arquivos tenham sido lido em memória. Para pegar o arquivo, eu tenho que acessar a um WS que me retorna isso.
Answer: Coloco uma resposta com uma ideia que ainda ninguém referiu, e que penso ser a melhor opção. Usando Promise.all.
Quando descreves que precisas "antes de tocar, garantir que todos os arquivos tenham sido lido em memória." isso é exatamente o que o Promise.all faz.
Passando uma array de Promises a essa Promise.all ela espera que todas estejam resolvidas e retorna uma Promise que recebe como argumento do método de sucesso uma array com os valores das Promises passadas. Se passares valores estáticos (Strings, Objetos, ou outras variáveis que não sejam assíncronas) ele usa na mesma, chamando o Promise.resolve imediatamente. Por isso a Promise.all aceita uma array mista, com Promises ou não.
Um exemplo simples seria assim: https://jsfiddle.net/4s5L4s7c/, o que precisas no teu caso seria algo assim:
var urls = ['/pasta/a', '/pasta/b' /* etc... */ ];

function get(url, i) {
    return $http.get(url); <-- isto será o que queres
}

Promise.all(urls.map(get)).then(function(res) {
    console.log(res); // aqui "res" é uma array com a resposta de cada "$http.get", na mesma ordem da array "urls".
}, function() {
    console.log('Algo falhou!');
});

Comment: Eu acho essa a melhor solução, ela é simples, usa recursos da própria linguagem e tem algo que não foi citado que ela tem vantagem comparada as outras respostas: aqui temos diversas requisições em paralelo, usando a verdadeira vantagem do assincronismo do JS a seu favor. As outras soluções (que são ótimas também) efetuam uma requisição por vez.
Comment: Não conhecia isso, achei bem interessante e funcional!!
Comment: Sergio, dentro desse Promise.all(), onde tu esta passando uma urls.map(get), eu poderia passar promises criadas na mão?
Comment: @PauloGustavo exato. O método .all aceita uma array, de Promises ou de valores/objetos.
Answer: Você pode utilizar o conceito de filas (queues).
Prepare uma coleção contendo os itens que deseja processar, e execute processamentos individuais até que a fila se esgote.
Uma das vantagens deste padrão é que ele permite que você inclua novos itens na fila mesmo durante execução do laço principal.
Abaixo, um exemplo de fila serial FIFO (First In, First Out - ou entre primeiro, saia primeiro):

var app = angular.module("exemplo", []);

app.controller("filaController", function($scope, $http) {

  var that = this;

  // Itens iniciais a serem processados
  this.ZipCodesAPesquisar = [77379, 77380, 77381];

  this.processaProximaEntrada = function(){
    //Existem itens na minha fila? Se sim, processe o primeiro.
    if (that.ZipCodesAPesquisar.length > 0){
      that.processaFila(that.ZipCodesAPesquisar[0]);
      return;
    }
  }

  this.processaFila = function (unidade){

    this.removeDaFila = function(unidade){
      //Localiza a posição da unidade na fila
      var indice = that.ZipCodesAPesquisar.indexOf(unidade);

      //Caso encontrado, remova:
      if (indice != -1) {
        that.ZipCodesAPesquisar.splice(indice, 1);

        // Verifique se ainda existem itens na fila.
        that.processaProximaEntrada();
      }
    }

    console.log("Processando " + unidade);

    $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + unidade + '&sensor=true')
    .then(function success(response) {
      console.log(response.data.results[0].formatted_address);
      that.removeDaFila(unidade);
    }, function error(response) {
      that.removeDaFila(unidade);
    });
  };

  //Inicializa processamento da fila
  this.processaProximaEntrada();

})

Comment: Bonito. Esse negócio da fila eu gostei :D
Answer: Você pode trabalhar com recursividade. Você usa uma função anônima nomeada para fazer referência a ela mesma e, se estiver dentro das condições, você executa ela novamente. A condição colocada evita a recursividade infinita.
var exemplo = function next(i) {

    $http.get(url).then(function success(response) {

        next.loop >=  i && next(++i);

    }, function error(response) {

        next.loop >= i && next(++i);
    });
}

exemplo.loop = 10;

exemplo(0);

No caso acima, enquanto a propriedade da função loop for maior que i, a recursão será aplicada. A função anônima nomeada internamente de next, será executada apenas quando o success ou error for chamada por $http.get.
Eu fiz um pequeno exemplo para você entender o funcionamento disso. É uma função que escreve um valor no HTML. Ela vai escrever enquanto o valor do loop for maior que o de i. É o mesmo caso acima, mas aplicado com um  setTimeout para você entender a lógica da minha recursão:

var counter = function _fn(i) {

    _fn.loop > i && setTimeout(function () {
     _fn(++i)
         document.body.innerHTML = i;
    }, 1000);
}

counter.loop = 10;

counter(0)
Comment: Só gostaria de entender o por quê do -1, já que a resposta faz com que o loop seja executado apenas quando termina a requisição anterior. Não entendo mesmo
Comment: Pra mim, a resposta ta ótima. Só estou testando no meu caso pra ver como vai se comportar :)
Comment: Acho a resposta interessante mas em vez de iterar sobre numeros era bom receber uma array com arquivos ou url para esses arquivos e depois mapear tudo para a callback final que executa quando essas promisses tiverem resolvido. Há várias maneiras de fazer isso. Se o @PauloGustavo esclarecer mais a pergunta junto também uma resposta mais logo.
Comment: @Sergio agora entendi. Talvez o problema seja que a resposta foi dada em cima de uma pergunta que não tem muito detalhes.
Answer: Similar a resposta do @WallaceMaxters, mas na pratica com o script que você esta usando.
function loopPromise(url, start, end, callSuccess, callError){

    $http = new $http(url); // Gera a promise para a url solicitada

    var func = function(obj){
        $http.get().then(function success(response){
            if(typeof callSuccess == 'function'){
                callSuccess('loaded'+start);  // chama sua função de sucesso, caso tenha sido definida
            }
            if(start++ < end){
                func(); // gera o loop ate start ser = a end
            }
        }, function(response){
            if(typeof callError == 'function'){
                callError(response); // chama sua função de erro, caso tenha sido definida, e não propaga mais o loop
            }
        });
    }
    func();
}

url = 'https://code.jquery.com/jquery-3.0.0.js';
loopPromise(url, 0, 10, function(response){
    console.log(response);
}, function(response){
    console.log(response);
});

Comment: @WallaceMaxters ou nos dois estamos :P
Comment: Então quer dizer que minha resposta não tá errada :D. +1


What statistical analysis to use for a particular research question?

Question: I am having trouble with figuring out which statistical analysis would be appropriate for a study that I am currently running. What I want to be able to compare is profiles of scores from a measure at two different time points.
I.e. I have data from T1 and T3 of a measure that has 19 scales. I want to be able to test if there is a significant difference between the two profiles... But I do not have two groups for my IV (i guess I could) but I am still struggling with this analysis.
Any help would be greatly appreciated!
Comment: Two time points of the same individuals with one measure? Can you explain "a measure that has 19 scales"? One  variable or several?
Comment: yes so basically I have a personality measure that has 19 scales on it... so I want to compare the whole profile of the measure. But I have data from two different time point on the same measure.
Comment: Are you sure there are 19 _scales_, and not 19 _items_ (i.e., questions) which measure some <19 personality traits?
Answer: If I understand correctly, you have a group of individuals tested at two time point on (an aggregated) independent variable. Such research designs are testing for significant changes in a mean independent variable such that: $H_0:\mu_1 =\mu_2$. As you are testing the same individuals at different points, the measures are dependent. If you have only two time points, you can use a paired t-test. If you have more than two, you can use repeated measures ANOVA.


Add nodejs and npm to Jenkins docker image

Question: I'm trying to do a quick experiment or two with Jenkins. For this I intended to use the jenkins image and add nodejs and npm to it. Here's what I'm trying to do:
FROM jenkins

USER root

RUN curl -sL https://deb.nodesource.com/setup_6.x | bash - \
    && apt-get update \
    && apt-get install -y \
        nodejs

RUN npm install -g npm

RUN npm --version

USER jenkins

The npm --version call will fail though, with this error:
Step 5/6 : RUN npm --version
 ---> Running in 48a250a4fdb8
module.js:471
    throw err;
    ^

Error: Cannot find module 'process-nextick-args'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/lib/node_modules/npm/node_modules/readable-stream/lib/_stream_readable.js:26:23)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
The command '/bin/sh -c npm --version' returned a non-zero code: 1

What is the proper way (if any) to fix this?
Comment: Its been a while so I'm not 100%, but its possible you could fix this by installing node using the --without-npm flag, and then run a command line install (`curl -L https://www.npmjs.com/install.sh | sh`). I had a similar error installing through homebrew a while back and that helped fix it.
Comment: @DLowther Thx for your suggestion, but I couldn't get it to work unfortunately.
Answer: Try the following, it uses docker multi-stage build to copy dependencies from one image to another. This will allow you to avoid all the special things that need to be done to install node in docker. There is an official docker image that is built by the docker team, so you use that as follows:
FROM node

FROM jenkins
USER root
COPY --from=0 /usr/local  /usr/local
RUN npm --version
USER jenkins

npm --version will output 5.3.0
Answer: Jenkins image by docker uses minimal installation for running Jenkins
FROM node:15.4 as nodejs
ENV JENKINS_HOME /var/jenkins_home

USER root
RUN rm -rf /var/lib/apt/lists/*
RUN rm -rf /etc/apt/sources.list.d/*
RUN apt-get update

#INSTALL NODE
COPY --from=nodejs /usr/local  /usr/local

RUN node -v
RUN npm -v

Comment: Thanks for taking the time to respond, but this isn't really helpful. I know how to execute commands in a container, but the problem is what those commands should be. Anything that I would do interactively like that is something I could also do in the Dockerfile...
Comment: The -u root flag was very helpful, this allows me to test the required steps!


How can I count all the numbers in a text file?

Question: I have a text file like below read.txt:
1.0 2.0 3.0 4.0
2.0 3.0 4.0 6
5.0 7 1.0 5.0

calc.cpp:
void main()
{
    FILE *fp;
    fp=fopen("read.txt","r");
    double *read_feature = new double*[3];

    for(i = 0; i<3; i++)
        read_feature[i] = new double[3];

    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            fscanf(fp,"%lf",&read_feature[i][j]);
        }
    }
}

I want to count all the numbers in my text file (read.txt). Read text file consist of floating and integer number. Answer for the above file would be 12.
How can I count floating number in a file using c++ dynamically? That means without giving the value of i and j. I need program will automatically calculate total number of i and j.
Comment: I thought it's 12 instead of 9. :)
Comment: Also, besides the use of `new` this isn't much C++, more like basic C.
Comment: How do you get 9 out of those numbers?
Comment: Instead of having a separate loop to allocate `read_feature[i]`, why not do it in the outer loop before reading?
Comment: Is it always a matrix input? or can you have different number of inputs per line?
Comment: yes, always matrix input.
Comment: @user2036891 You can't assume that.  You're reading from outside the program, and who knows what a user might do.  _If_ there is a requirement that it be a matrix, and if there is a requirement that the file not contain any other text than floating point, you can probably just output an error and abort if this is not the case, but you still have to check for it.
Comment: @billz Depending on what he means, it's either 12 or 5.  It's still not clear to me what he's trying to do.  (There are only five floating point numbers in his example, although some of them occur multiple times.)
Comment: Your use of the words `calculate` and `total` is ambiguous. `Calculate` usually means carry out some arithmetic, `total` can mean `all`, or `to add up`. So when you say `calculate total` it sounds like you want to add up the values. However, you really want to count how many values you have. This is why I changed the title of your question. Please don't put the word `total` in again.
Answer: Do you need to build the array?
Or just count the number of floats?
 int main()
 {
     std::ifstream   file("read.txt");
     std::cout << std::distance(std::istream_iterator<double>(file),
                                std::istream_iterator<double>());
 }

Comment: This is clearly the best solution, but it's lacking any error checking.  You probably want to check `file.eof()` _after_ calling `distance`, to ensure that you stopped because of end of file, rather than because of something that couldn't be parsed as a floating point.
Comment: In my file, I have 907 lines and each line has 1000 elements. So the value would be 907000. But your program gave output 907440. It seems wrong.
Comment: I have changed my problem statement. Now, how can i calculate total number in my file? File consists of integer and floating point number.
Comment: @user2036891: If the output was 907440 I would suggest that your file contains that many numbers in sequence. The above code is not complicated enough to contain errors. (if the input file contains errors it may not notice `25.567.567` would be parsed as `25.567` and `0.567` for example unless you turned on some specific local (to make `.` the thousands separator or something).
Answer: If you are interested in counting the number of elements (floating point numbers in this case) in a file, you can read the file into an std::ifstream, then use a std::istream_iterator to get iterators to the first and the equivalent of one past the end elements. Using these with std::distance steps through the elements and returns the number of steps. This is a working example:
#include <iostream>
#include <iterator>
#include <istream>
#include <fstream>

template <typename T>
int count_elements (std::istream &is)
{
   std::istream_iterator<T> start(is), end;
   return std::distance(start, end);
}

int main()
{
  std::ifstream is("read.txt");
  std::cout << "Number of numbers " << count_elements<double>(is) << std::endl;
}

Note: I have omitted error checking here, I leave it up to the user. Also note that if there is an element that cannot be interpreted as a floating point number, the algorithm stops counting. So you get a non-zero result corresponding to the number of elements until the illegal one.
Comment: In my file, I have 907 lines and each line has 1000 elements. So the value would be 907000. But your program gave output 907440. It seems wrong.
Comment: @user2036891 I would suspect there is something wrong with your file. I will try to reproduce it though.
Comment: I have changed my  problem statement. Now, how can i calculate total number in my file? File consists of integer and floating point number.
Comment: @user2036891 well, you could use `count_elements(is)`, although that will accept non-numeric stuff too. If you are sure you only have floating point or integers in the file, then it is OK. But if you have any other stuff in there by error, it will count it too.
Comment: In my file, I have 907 lines and each line has 1000 integer or floating point number. So the total number of value would be 907000. But your program gave output 906132.
Comment: @user2036891 open the file in an editor, go to line 906, and see what happens to element 133.
Comment: I don`t understand "see what happens to element 133.". Would you please explain?
Comment: @user2036891 I mean there must be some weird character in your file, straight after element 132 in line 906.
Answer: Suppose that the file contains only floating numbers, in order to find total numbers of floating number, you can count the dots from your file:
FILE *fp;
fp=fopen("read.txt","r");
char c;
int nFloat=0;
while(!feof(fp))
{
   fscanf(fp,"%c",&c);
   if (c=='.')  //is a dot from a floating number
       nFloat++;
}

Comment: @user2036891 It's not C++ though.
Comment: @user2036891 note that idiomatic C++ (see Loki and my answer) allow you to do this in 2 lines of code, without need for explicit loops or counters. This is a C solution.
Comment: @AlexChamberlain It's not correct, either.  Looping with `!feof(fp)` in C is the same as looping with `!f.eof()` in C++.  And it's not idiomatic for C either; you don't use `fscanf` to read a single character, you use `getc`.  And finally, not all dots are necessarily floating point numbers, and not all floating point numbers contain dots.
Comment: In my file, I have 907 lines and each line has 1000 elements. So the value would be 907000. But your program gave output 906537. It seems wrong.
Comment: @user2036891 Than your file doesn't have only floating point number. Look at loki answer.
Comment: I have changed my problem statement. Now, how can i calculate total number in my file? File consists of integer and floating point number.
Comment: @user2036891 Yes, you can count the spaces:D
Answer: Working on the answer from banuj. You can count the number of floats in one line and number of lines
FILE *fp;
fp=fopen("read.txt","r");
char c;
int nFloatrow=0,nfloatcol=0,count=1;
while(!feof(fp))
{
   fscanf(fp,"%c",&c);
   if (c=='.'&&count==1)  //is a dot from a floating number
       nFloatrow++;
   if (c=='\n')  //is a newline
   {
       nFloatcol++;
       count=0;
   }
}

Comment: Another answer which is simply incorrect (and is C, rather than C++).  I'm curious where people learn this.  I'm used to seeing `while ( !f.eof() )` in C++, because there are a couple of web sites out there that do this, even though it is incorrect.  But until this question, I'd never seen `while ( !feof( fp ) )`;  all of the traditional C tutorial texts do it correctly, and C programmers generally learned the language before the web became widespread.
Comment: I have changed my problem statement. Now, how can i calculate total number in my file? File consists of integer and floating point number.


Links displaying as plain text, and html tags not applying, no matter which text format is selected

Question: I have a text field type, that I'd like to be able to include links within. It appears that all of the formatters should be able to do this by default, and that the full/filtered html formatters should be able to handle html tags. However, for some reason, my text field is not doing either of these things. Links are simply appearing as plain text.
I think that they did work before, although I can't exactly remember where else in the site these filters are used to double-check, but they are no longer honoring links or html. Additionally, if full/filtered html is selected, then any html tags are hidden from view but are not being applied to the text. This leads me to believe that the formatter is recognizing the tags, but for some reason is failing to process them. Any suggestions?
So, just in case I wasn't clear at all:

Links are displaying as plain text (e.g. typing in http://www.google.com simply renders as http://www.google.com - plain text, no link). This is occurring with all formatters, including the "Plain Text" formatter, even when "Convert URLs into links" is selected. This is occurring with email addresses as well.
All html tags are being ignored (e.g. entering Google or Local Link displays only as Google or Local Link, without rendering the link. Additionally, something like Bold renders as Bold, without the style applied).
Answer: It's hard to suggest a solution without examples, but I'd suggest you check the order of your text format filters (/admin/config/content/formats/full_html) and see if:

Convert URLs into links is still turned on
There are no additional filters acting on links or  tags that would cause them to be killed or hidden
Make sure your links look like links! Obscure ones like bit.ly/4321 or even google.com won't get picked up. If they aren't getting picked up, adding http:// to the front of it normally triggers the auto URL filter.

If that doesn't work, see if you can post some example code. If we can see how they are being hidden, we might be able to assist better.
Comment: If it's relevant, I've also realized that links are not being converted when "plain text" is selected either. 1. Yes, convert URLs into links is still turned on for all types. 2. I don't see any other filters affecting the  tag or any other tags. 3. The links are prefaced with http:// except for if the link is a local path, in which case it does or does not start with a leading slash. I'd be happy to post some example code, but which code are you referring to?
Comment: Not sure what's causing it right now. Probably an example of how it's being output vs the raw text or html you are putting in would be useful.
If you can provide a list of the filters you have turned on that might help too.
Comment: I edited the original issue earlier to help clarify input vs. output. As for filters, the issue is happening with all formats no matter which filters are enabled. For example, in `Full HTML` I have "Convert line breaks into HTML (i.e.  and )", "Convert URLs into links", and "Correct faulty and chopped off HTML." However, the problem persists even if I disable all filters, or all filters except for "Convert URLs into links."  I also just realized that the issue may have started to occur after migrating my 7.12 dev site onto my 7.14 server. Could this be part of the problem?
Comment: Gah, turns out that for some reason, Display Suite had the fields set as plain text. Don't know how! I'll give you the answer anyway. :)


What type of URL is "www.example.com/#/bar/1"?

Question: I've seen few URLs of the form
www.example.com/#/bar/1

How would this URL be interpreted? As far as I know the # represents a fragment of the page, but here it looks completely different.
Answer: Note that this is not a URL, as it misses a scheme. I'm assuming you mean http (or https), so the URL would be
http://www.example.com/#/bar/1

The (first) # starts the fragment identifier component.
So /bar/1 is the fragment of that URL. (The / is allowed in a fragment; see a list of all allowed characters in the fragment identifier component.)
It's up to the site if and in which way to make use of this fragment. Commonly this URL design is used by sites that serve the content via JavaScript.
Answer: It's used for page reloading with a hash.
See Mozillas window.location for more information.