O que é o MAUI da Microsoft?

Question: Li que o MAUI da Microsoft é uma evolução do Xamarin.Forms. Eu gostaria de saber:

O que muda da versão antiga para essa?
Quais são as plataformas suportadas?
Como é feita a migração entre o Xamarin.Forms e o MAUI?
Já está pronto para ser utilizado em produção? Caso não, qual a data prevista para uma versão estável?
Comment: https://azure.microsoft.com/pt-br/updates/net-multiplatform-app-ui-net-maui-announced/
Answer:
O que muda da versão antiga para essa?

A maior mudança é a forma de fazer um código para todas plataformas. Agora fica mais fácil e intuitivo fazer um único projeto que rodará em todas plataformas. Isso pode ser visto em:

Note que algumas partes do código podem ser especializadas para a plataforma, mas está tudo no mesmo projeto e na hora de construir ele pegará as partes relevantes para o target usado no momento. Fica muito mais organizado e simples.
Haverá alguma quebra de compatibilidade. Isso é necessário para alguma evolução e para corrigir alguns erros e limpar o que já se sabia que era obsoleto. Sim, muitos problemas de design do Xamarin Forms serão corrigidos. Não sei tudo, mas ele trabalhará muito melhor com a renderização, adotará a injeção de dependência mais amplamente, algumas coisas ficarão mais consistentes ou funcionarão de forma mais geral para encaixar bem com todas plataformas. Não acho que valha a pena tentar listar tudo aqui, até porque muda todo dia, o projeto não está fechado.
Algo que acho que vale mencionar é que haverá dois novos modelos de programação, um deles é o MVU (sim, inventaram mais um MVx :D), e o Blazor que tem um jeitão de web de programar e você poderá usá-lo para programar o MAUI. Faça do jeito que esteja mais confortável.
<code>readonly State<int> count = 0;

[Body]
View body() => new StackLayout {
    new Label("Welcome to .NET MAUI!"),
    new Button(
        () => $"You clicked {count} times.",
        () => count.Value ++)
    )
};
</code>
Coloquei no GitHub para referência futura.
Vi alguns códigos como esse e ficou bem interessante usar linguagem de marcação ou de programação para construir os objetos de tela.
Obviamente que o Xamarin Forms terá muitas features normais também, continuará suportando rapidamente tudo o que vem de novo nas plataformas. Essa nova organização ajudará até o desenvolvimento interno do MAUI e contribuições da comunidade.

Quais são as plataformas suportadas?

Há uma tabela entre as diferenças entre o Xamarin Forms e o MAUI. O que muda é o comprometimento da Microsoft com certas plataformas. A maior mudança é a adição dela oficializar o MacOS e WPF, além de melhorar as ferramentas.
E claro, ele só funcionará com o One .NET (um só framework para tudo), não poderá usar versões antigas ao .NET 6, principalmente os diversos frameworks que existiam antes do .NET 5.

Como é feita a migração entre o Xamarin.Forms e o MAUI?

Muito cedo para dizer.

Já está pronto para ser utilizado em produção? Caso não, qual a data prevista para uma versão estável?

Não, ele estará disponível junto com o .NET 6 que sairá em novembro de 2021. Mas haverá previews ainda em 2020. Pode acompanhar o desenvolvimento e até construir por conta própria em https://github.com/dotnet/maui. Até lá pode ir usando o Xamarin.Forms que ainda tem evolução acontecendo normalmente. Podemos dizer que o MAUI é o Xamarin.Forms 6, mas ainda está saindo o XF 5.

O que é o MAUI da Microsoft?


What percent of shots on goal hit the crossbar in hockey?

Question: It seems like a lot of shots hit the crossbar in hockey. Is this just my mind playing tricks on me, or do more shots hit the crossbar than might be expected for a bar a few inches wide set above a goalie's shoulders.
First, what percent of shots hit the crossbar in the NHL?
And is it higher than would be expected?
The "expected" rate, I'd imagine, is the same rate as any other space on goal of equal size to the crossbar.
Comment: @SamtheBrand I cannot find anything out there officially on this topic.  The tough thing is that a shot off the post or the cross bar in hockey is not technically a shot on goal.  There isn't an official stat that keeps track, so aside from an independent study I think it would be tough to find/calculate.  [Here is an article that talks about it.](http://www.arcticicehockey.com/2012/2/16/2792419/stu-hackel-week-on-arctic-ice-hockey-posts-hit-aka-stats-the-nhl)
Comment: I suspect that more shots are directed at the top part of the net by shooters since most goalies use the butterfly technique. This technique (or style) blocks the bottom part of the net. So two things: 1) goalies make more saves on low shots thus preventing the puck from hitting the lower parts of the posts; and 2) shooters know that the upper portion of the net is more open so they choose to shoot high more frequently. This is just a hypothesis. Without running an independent study as diggers3 suggests, it's not possible to determine an answer.
Comment: @JohnCullen The easiest places to score are usually low on the stick hand side and high opposite the stick hand; up the middle either high or low and high on stick hand side are medium level; and low on blocker hand is hardest to score (as the stick covers the low on opposite side normally, so the least movement is needed to block a shot there).  Butterfly technique still gives up a fairly high number of five-hole goals if you don't time it perfectly (as if you go to early, you end up giving up a high goal).
Comment: The pictures most of the way down on [this article](http://www.secondcityhockey.com/2011/12/8/2621193/shot-quality-and-goal-trends) about the Blackhawks from a few years ago give a good example of this - note the bottom right (left hand side) being very low % of scoring shots, low left (right hand side) being fairly high %, and middle high/low being right around its expected value when you remove the one sixth of the goal that is basically not used (ie, all other 5 zones should be roughly 19% each, with the lower right being < 5%).
Answer: The NHL tracks missed shots that hit the crossbar.

What percent of shots hit the crossbar in the NHL?

In the 2015-2016 NHL regular season, 240 missed shots hit the crossbar out of 28,517 missed shots. That is 0.842%.

And is it higher than would be expected?

According to your crude measure of "it seems like a lot of shots hit the crossbar in hockey," then it is much less than expected. Also, these findings are for missed shots. Perhaps there is a percentage of shots that hit the crossbar and went in for a goal, but that is the "missing" subset.

There aren't any stats that I know of that track shots that enter "any other space on goal of equal size to the crossbar." However, let's try:

There were 6,565 goals during the 2015-2016 NHL regular season.
A NHL regulation goal opening is 72" wide and 48" high(1)
A NHL regulation crossbar is 2 3/8" in circumference(1)
Dividing 48" by 2 3/8", we get ~20 (more precisely 20.211) such segments that fits the criteria of "any other space on goal of equal size to the crossbar."
Dividing 6,565 by 20 (assuming an equalized probability), the number of goals that would enter "any [segment] (out of 20) on goal of equal size to the crossbar" is 328.25 (more precisely 324.8).

Thus, 240 missed shots hit the crossbar compared to 324.8 goals through any given segment of equal size to the crossbar means the number of missed shots that hit the crossbar is lower than expected (vs. the same rate as any other space on goal of equal size to the crossbar).
Comment: Interesting and curious. One would expect players to aim away from the centre, which presumably is easier for the goalkeeper to defend. If they aimed to near the borders of the goal, then we'd expect more shots on the crossbar (and posts) than on an average equal-sized section of the goal. Maybe the players aim mostly down, near to the ground? (note: I have never seen a ice hockey game. I saw a lot of rink-hockey, similar enough to make a educated guess, but evidently quite different)
Comment: @RolazaroAzeveires That's exactly what this...an educated guess to ascertain the number of shots that go through any given segment of equal size to the crossbar (as specified by the OP) vs. hitting the actual crossbar. That said, you're expectations on strategy is probably accurate...and if we took all shots into consideration (note that i only take missed shots and goals into consideration), then these numbers may be different.
Answer: Shots that hit either the post or the crossbar are not considered Shots on Goal. Currently, they are quantified as a Missed Shot. These shots are included with shots that miss the net entirely; as such, they will appear in both Fenwick and Corsi totals (note that Corsi is just Fenwick plus blocked shots).
There's no way to extract these data currently.
However, we can estimate the relative frequency with which shots hit the crossbar versus shots that hit either post.
The net is 6 feet wide by 4 feet high. Since there are two posts, this means that (roughly) the crossbar is 6 linear feet and the posts are 8 linear feet.
Naively, then, one would expect that the crossbar is hit at a 3:4 ratio to the posts. However, while shooting, one typically picks one side of the net to shoot at. If you miss your shot while trying to pick a side, you're probably not going to hit the post on the other side of the goal, unless you're a very bad shooter. So really, the crossbar might get hit at a rate of about 3:2 compared to the post, or about 50% more shots hit the crossbar than hit the post.
This is just a naive approximation.
Practically speaking, shooters have very small windows with which to work. Goalies cover a lot of area quickly in today's NHL, and so shooters are often gunning for extremes. The posts provide a visual reference of your target. When the goalie is moving and changing angles, the posts provide a fixed frame of reference with strong visual contrast. Many shooters try to aim for the inside of the posts with their shots, because it's usually the farthest you can target from the goalie and still hope to score.
Probably more shots miss the net entirely than hit a post, and probably close to as many shots that hit the crossbar and go out (quantified as a miss) hit the crossbar and go in (quantified as a goal and a SOG).
When weighing this approximation against all total shots, I'd say hitting the crossbar is more rare than hitting any other similarly-sized window of the net, but without very accurate puck telemetry data, it's impossible to conclude that.
Comment: @Arkamis Addressing your estimation of shots that hit the crossbar at a 3:4 (or 3:2 by isolating a side) ratio: according to missed shot statistics in my answer for the 2015-2016 season, 240 missed shots hit the crossbar and 1157 missed shots hit the post. Perhaps there is a percentage of shots that hit the crossbar or post and went in for a goal, but with respect to missed shots, the ratio is 1:5.
Comment: I think this is a good comment, but doesn't answer the question with anything other than extremely vague speculation.
Comment: @Joe Nested in my answer is the core of a Bayesian estimation (without explicitly going into the details). Since the data aren't available, this is literally the most accurate possible answer to this question. Since the OP's question involves a [Selection Bias](http://en.wikipedia.org/wiki/Selection_bias), a back-of-the-envelope estimation is often sufficient to negate that bias. For instance, suppose you buy a red Toyota, and you start seeing more red Toyotas. You don't need to have access to Toyota's production records to make an estimation to prove that you're experiencing selection bias.
Comment: And, all other commentary notwithstanding, I provided a correct answer to the question in my third sentence. Everything below that is there simply to address the perceived bias.
Comment: I'm well familiar with Bayesian estimations, but I don't agree that this is a good answer to the question.  The question doesn't have a good answer (unless the statistics _are_ out there, but I don't see them either), which to me means it shouldn't be answered.
Comment: @joe The answer "the information you're looking for is not available" is a perfectly reasonable answer on every other StackExchange site, when it is the only correct answer. If you'd like to provide a better answer to this five month old question, please feel free to do so, otherwise what I've offered is reflective of the current state of the art of hockey analytics. If you don't like the reality that the data don't exist, then vote to close the question rather than let it persist in perpetuity.
Comment: Digger offered in a comment just as much value as you did in this answer, except without the speculation.  That's the right way to handle this.  There's no reason not to leave the question open; it's a perfectly good question, and perhaps someone will find the answer.
Comment: @joe I think you mistake speculation for approximation, and I make it abundantly clear that I am doing nothing but naive approximation to address the op's self-admittef selection bias. It's in the question, it's fair game to address in the answer.
Comment: Furthermore, there are active movements on several SE sites to dispose of old unanswered questions.  There are badges for doing just that. Those factors alone provide very good reasons not to leave the question open when answers can be provided.
Comment: @ᴍᴀsᴛᴇʀᴍɪɴᴅ_ᴇᴅ Awsome! Glad there are some data that provide better detail than gross estimation :)


SQL Server 2012 which user is using Memory and CPU

Question: For sql server 2012 I am looking for a way to see which active user logins are using how much memory and cpu.  I have done a search but it seems there is only a way to see aggregates or how much each database uses for memory.  Any help would be appreciated.
Answer: run sp_who2 active to see all active usage.
Answer: sp_who2 can provide some information.
But generally the question makes no sense for memory. Memory is MOTLY used as page cache and that is never user specific but always database specific. A data page in the database is not owned by a user. They also get dropped as needed and are kept as long as possible - so if you try to find out why your server uses so much memory, totally wrong approach.
Similar for CPU - that is a question of query efficiency. It should not be started from the user, but from the SQL query. A specifi user may execute a crappy SQL query that burns tons of CPU, but it is not the fault of the user and you CAN see which sql statements blow all the CPU in terms of processing efficiency.


Custom username paths?

Question: I want to be able to create paths like this:
/guy1
/guy2
/guy3

It's easy enough if I want /profile/guy1 ... then I can just do this:
gg_profile.viewUserProfile:
  path: '/profile/{username}'
  defaults:
    _controller: '\Drupal\gg_profile\Controller\GGProfileController::viewUserProfile'

But I want it to work with the /profile bit. Changing it as follows doesn't work:
  path: '/{username}'

How do I make it work without having the extra /profile bit?
Comment: Perhaps you should create routes specific to your module, so that they would use a unique pattern. Then in your module you could suggest desired route as a Pathauto pattern. So, `/guy1` would be an alias to your route.
Answer: You cannot: The part of the path after the first slash cannot be dynamic, so you cannot use /{username} as path. This is explicitly stated in Structure of routes, which describes path as follows.

path (required): The URL to the route, with a leading forward slash (e.g., path: '/book'). You can use dynamic properties by including them in curly braces. (e.g., path: '/node/{node}/outline'). These will be passed along as arguments via parameter converters to the controller/form (see below). Note that the first item of the path must not be dynamic.

You can use /profile/{username}, but /{username} doesn't work.
Comment: That is why a path like /{username} would not work. Drupal would not be able to understand if node in /node/1 is a username, or user in /user/1 is a username.
Comment: I get that, but I thought i could have custom logic and basically tell it to skip my logic if a certain condition is not met.
Comment: So to do this, I would need to not use Drupal? That sucks...
Comment: You could implement the equivalent of Drupal 7 `hook_url_inbound_alter()` but be careful of what you would alter, which means any route defined from other modules still have to work properly.
Comment: For that, you should alter the way Drupal checks for routes, if it is possible. By default, Drupal doesn't have an _apply my logic if some conditions are met_ mechanism.
Answer: Perhaps the Pathauto Module could come in handy for this.  https://www.drupal.org/project/pathauto
Your use case is kind of vague so I don't know exactly what you want but you can use Pathauto to create 'dynamic' URL endpoints when creating new content/users.  You can use tokens within the URL to add variables.
Comment: Pathauto supports any entity type but it looks like that is some special thing. The same still applies. You can't have top-level routes like that, but you can have aliases, you just have to create them yourself then
Comment: I would have to use nodes if I want to do this. Which is probably what I'm going to end up doing anyway.

Custom username paths?


issues with Apache2, modwsgi, Python3.6 and Bottle integration , Seeing Module not found error in Apache2 logs

Question: Overview:
I am trying to have a simple Python bottle application to be available as a backend to a chatbot which sends json response back when called.
I have chosen the solution Apache2 + mod WSGI(4.8.0) and Python3.6 after doing some research.
Issue:
When accessed the python app  through browser I get 500 Internal server error.
Below is the module not found error from Apache2 logs
Error in Apache2 logs:
[Wed Jun 16 17:38:56.152523 2021] [wsgi:error] [pid 8878:tid 140503309027072] [remote 10.137.190.184:51146] mod_wsgi (pid=8878): Failed to exec Python script file '/opt/software/apache/httpd-webserver/httpd/wsgi-scripts/myapp.wsgi'.
[Wed Jun 16 17:38:56.153460 2021] [wsgi:error] [pid 8878:tid 140503309027072] [remote 10.137.190.184:51146] mod_wsgi (pid=8878): Exception occurred processing WSGI script '/opt/software/apache/httpd-webserver/httpd/wsgi-scripts/myapp.wsgi'.
[Wed Jun 16 17:38:56.154245 2021] [wsgi:error] [pid 8878:tid 140503309027072] [remote 10.137.190.184:51146] Traceback (most recent call last):
[Wed Jun 16 17:38:56.155012 2021] [wsgi:error] [pid 8878:tid 140503309027072] [remote 10.137.190.184:51146]   File "/opt/software/apache/httpd-webserver/httpd/wsgi-scripts/myapp.wsgi", line 6, in
[Wed Jun 16 17:38:56.155605 2021] [wsgi:error] [pid 8878:tid 140503309027072] [remote 10.137.190.184:51146]     import bottle
[Wed Jun 16 17:38:56.156093 2021] [wsgi:error] [pid 8878:tid 140503309027072] [remote 10.137.190.184:51146] ModuleNotFoundError: No module named 'bottle'
Current Apache,modWSGI and Python system settings:
Apache version:2.4.41
Mod WSGi version: 4.8.0
Python version : System has 2 versions, python2.7 and python3.6
I intended to use python3.6 so compiled modwsgi with python3 as below. I have another sandbox with similar config and did not explicitly mention python3.6 as below which made WSGI compile against python2.7 and the my bottle python script works fine there.
sudo ./configure --with-apxs=/opt/software/apache/httpd-webserver/httpd/bin/apxs --with-python=/usr/bin/python3.6
httpd.conf setting related to wsgi: (using WSGIDAEMON mode)
WSGIDaemonProcess wsgi-scripts user=webadm group=webgrp processes=1 threads=5
WSGIProcessGroup wsgi-scripts
WSGIScriptAlias /myapp "/opt/software/apache/httpd-webserver/httpd/wsgi-scripts/myapp.wsgi"
<Directory /opt/software/apache/httpd-webserver/httpd/wsgi-scripts>
<IfVersion < 2.4>
  WSGIProcessGroup wsgi-scripts
  WSGIApplicationGroup %{GLOBAL}
  Order allow,deny
  Allow from all
</IfVersion>
<IfVersion >= 2.4>
  WSGIProcessGroup wsgi-scripts
  WSGIApplicationGroup %{GLOBAL}
  Require all granted
</IfVersion>
</Directory>

Apache2 logs show that Apache is able to load the required versions of python and modwsgi
[Wed Jun 16 17:57:51.974604 2021] [mpm_worker:notice] [pid 10040:tid 140640770721664] AH00292: Apache/2.4.41 (Unix) OpenSSL/1.0.2k-fips mod_wsgi/4.8.0 Python/3.6 configured -- resuming normal operations
However when the script is accessed through UI, I see the above bottle module not found error in apache logs.
Bottle module is available in both 2.7 and 3.6 versions of python on the system.
Also, Verified by running the below test WSGI script to confirm that Apache is using python3.6
#!/bin/python3
import sys

def application(environ, start_response):
  status = '200 OK'

  output = u''
  output += u'sys.version = %s\n' % repr(sys.version)
  output += u'sys.prefix = %s\n' % repr(sys.prefix)
  output += u'sys.path = %s' % repr(sys.path)
  response_headers = [('Content-type', 'text/plain'),
                    ('Content-Length', str(len(output)))]
  start_response(status, response_headers)
  return [output.encode('UTF-8')]

Output of the test WSGI script:
sys.version = '3.6.8
sys.prefix = '/usr'
sys.path = ['/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages']
Looks like Apache/python is unable to load the required module during runtime, however not able to figure out how to enable python/apache to find the required module. I ran through several posts and tried few things which did not work out. Any help would be greatly appreciated. thank you!
Below is my bottle and wsgi code:
hello.py:
#!/bin/python3
from bottle import route, run, template,error
import json

headers = {
'Accept': 'application/json',
}

environment = 'qa'
def verification(user):
 user = "profile of user " + user + " for environment " + environment + " looks good"
 ops=[{'fname':'john','lastname':'Doe','Remark':'updated'}]
 return json.dumps(ops)

@route('/troubleshoot/<user>')
def troubleshoot(user):
 return verification(user)
 ops=[{'fname':'harsha','lastname':'sri','Remark':'updated'}]

@error(404)
def error404(error):
 return '404, Please use the right context /troubleshoot/<user>'

myapp.wsgi:
#!/bin/python3
import sys

sys.path.insert(0, "/opt/software/apache/httpd-webserver/httpd/wsgi-scripts")
import bottle
import hello
application = bottle.default_app()

Answer: First thing I noticed was you need to add your page to the bottle.app()
I am not sure however if the .wsgi file is supposed to be in Python?
hello.py:
helloRoute = Bottle()

myapp.wsgi:
from hello import helloRoute
application.merge(helloRoute)


How can a superview interecept a touch sequence before any of its subviews?

Question: I have a view hierarchy that is layed out as follows:
parentView
 scrollView

    contentViewA

    containerView

         contentViewB

         contentViewC

I want contentViewB to respond to touches. Unfortunately scrollView makes this almost impossible because it tries to ingest the touches itself making touch response of contentViewB spotty.
So, instead, I want to intercept all touches in the parentView, manipulate contentViewB directly, and  then pass the touches on to scrollView so it can do its thing.
Can someone please show me the correct way to pull this off?
Thanks in advance.
Cheers,
Doug
UPDATE:
I did a bit more digging and found the property canCancelContentTouches which seems to work wonders. I'm using IB so I unchecked "Cancellable Content Touches" in IB - first tab of the Scroll View Attribute Inspector. Now, when I run the app, touches appear to be arriving at contentViewB reliably.
Here's how the UIScrollView docs describe this property:
Discussion
If the value of this property is YES and a view in the content has begun tracking a finger touching it, and if the user drags the finger enough to initiate a scroll, the view receives a touchesCancelled:withEvent: message and the scroll view handles the touch as a scroll. If the value of this property is NO, the scroll view does not scroll regardless of finger movement once the content view starts tracking.
Rather opaque huh? Anyway, it seems to work.
Comment: having read your update I think I may have misunderstood your original problem. So you want to detect "tap"-like touches on subviews, but drag-touches should cause scrolling. In that case canCancelContentTouches should be the way to go (actually I thought that was set by default). That's pretty much what I do in my game, vConqr (www.vconqr.com)
Comment: Sorry to confuse you Phil. Actually contentViewB detects both a single tap as well as a vertical - y-axis - drag gesture. I may not have made this clear, but I've implemented a bare bones vertical scroller in contentViewB since I don't need the complexity - and headache - of nested scrollViews. The scrollView superview in my diagram is configured to drag/zoom horizontally - along the x-axis.

Thanks for the assist Phil.
Answer: To stop the scroll view from intercepting the touch events, set the userInteractionEnabled property like so:
scrollView.userInteractionEnabled = NO;
Comment: Thanks Phil. Which view in the hierarchy should toggle scrollView.userInteractionEnabled?
Comment: Also, via what method - hitTest:?, touchesBegan:withEvent:?. Thanks.
Comment: Who owns the scroll view (usually a view contoller). When it's first created and set as a subview is usually when you'd do it - or do you need to update this at different times?
Comment: Indeed a viewController owns the scrollView. The challenge is I need to toggle the scrollView.userInteractionEnabled. This is because I have configured the scrollView to only scroll horizontally but have implemented a trivial vertical scroller from scratch for contentViewB.
Comment: ok. At some point you must know when to switch. You can then call a method on the view controller (which you will implement) that will toggle the property. Best to store the scroll view as a member of the view controller if you're not already doing so.
Comment: see my comment to your original question
Comment: Phil, See the update to the question I wrote. What do you think of this approach?
Comment: Ok, lets see if I've got this. If I go with your approach, I would set scrollView.userInteractionEnabled = NO in my implementation touchesBegan: and scrollView.userInteractionEnabled = YES in touchesEnded:. I would implement the touch sequence methods in some reasonable class such as parentView. Sound about right?
Comment: no, now that I have a slightly better understanding of what you're trying to do (I think), I don't think this is the right approach. The ability to intepret touches by a scroll view and its subviews, depending on whether you are actually scrolling, is baked in. I don't have access to my dev machine at the moment to check the specifics, but will have a look later if you're still having trouble
Answer: Another way of doing this is to add another subview to your ui so it looks like so :
parentView
  scrollView
    contentViewA
      containerView
        contentViewB
        contentViewC
  touchGrabber

and, in touchGrabber, detect all the touches that you want (by subclassing UIView)
This is more complicated than Phil Nash's solution but has the advantage that you can add/remove other views from your parentView without having to deal with their userInteractionEnabled value - this is useful if you have a third party library adding views for example.
However, if you definately only going to have the scrollView, Phil Nash's answer is the way forward!
Thanks,
Sam


IIS7 w3wp process hung on recycle

Question: A single server has started to sometime leave zombie w3wp.exe processes when trying to recycle. A new process is spawned properly and everything seems to work, except the old processes are still present and take up memory. Task manager reports there's only a single thread left, far from the active ones that have between 40 and 70 threads usually.
Using ProcDump I've taken a full memory dump to analyze further in WinDbg. The machine is a Server 2008 R2 x64 8 core machine as stated by WinDbg:
Windows 7 Version 7600 MP (8 procs) Free x64

After loading sos a printout of the managed threads reveals the following:
0:000> !threads
ThreadCount: 19
UnstartedThread: 0
BackgroundThread: 19
PendingThread: 0
DeadThread: 0
Hosted Runtime: no
                                              PreEmptive                                                Lock
       ID OSID        ThreadOBJ     State   GC     GC Alloc Context                  Domain           Count APT Exception
XXXX    1  9d0 000000000209b4c0      8220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX    2  c60 00000000020c3130      b220 Enabled  000000013fbe5ed0:000000013fbe7da8 000000000208e770     0 MTA (Finalizer)
XXXX    3  a24 00000000020f0d60   880a220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 MTA (Threadpool Completion Port)
XXXX    4  97c 0000000002105180    80a220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 MTA (Threadpool Completion Port)
XXXX    5  c28 000000000210bfe0      1220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX    6  d40 00000000053f9080   180b220 Enabled  00000001bfe75d20:00000001bfe767c8 000000000208e770     0 MTA (Threadpool Worker)
XXXX    7  c18 00000000053f9b30   180b220 Enabled  00000000fff95880:00000000fff97210 000000000208e770     0 MTA (Threadpool Worker)
XXXX    8  f7c 00000000053fa5e0   180b220 Enabled  000000011fbea268:000000011fbea920 000000000208e770     0 MTA (Threadpool Worker)
XXXX    9  91c 00000000053fb090   180b220 Enabled  00000001dfc39138:00000001dfc39670 000000000208e770     0 MTA (Threadpool Worker)
XXXX    a  fb0 00000000053fbd20   180b220 Enabled  00000000fff922b0:00000000fff93210 000000000208e770     0 MTA (Threadpool Worker)
XXXX    b  fc8 00000000053fc9b0   180b220 Enabled  0000000160053ea0:0000000160054778 000000000208e770     0 MTA (Threadpool Worker)
XXXX    c  538 00000000053fd460   180b220 Enabled  000000017fd8fc98:000000017fd911f8 000000000208e770     0 MTA (Threadpool Worker)
XXXX    d  604 00000000053fdf10   180b220 Enabled  000000019fd7aa78:000000019fd7c648 000000000208e770     0 MTA (Threadpool Worker)
   0    f  2cc 0000000005514c60       220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX   10  9bc 00000000020a90c0       220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX   11  9c0 00000000056b7a00       220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX    e  9d4 00000000056b7fd0       220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX   12  9d8 00000000056b85a0       220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn
XXXX   13  cb8 00000000056b8b70       220 Enabled  0000000000000000:0000000000000000 000000000208e770     0 Ukn

Of more interest however is probably the output of a stack backtrace for the single unmanaged thread remaining:
0:000> ~* kb 2000

.  0  Id: 85c.2cc Suspend: -1 Teb: 000007ff`fffd3000 Unfrozen
RetAddr           : Args to Child                                                           : Call Site
000007fe`fdcc1843 : 00000000`00fd6b60 00000000`00fd6b60 ffffffff`ffffffff 00000000`77bc04a0 : ntdll!ZwClose+0xa
00000000`77ab2c41 : 00000000`77bc1670 00000000`00000000 00000000`77bc04a0 7fffffff`ffffffff : KERNELBASE!CloseHandle+0x13
000007fe`f56537c6 : 00000000`00000000 00000000`00000000 00000000`012da080 000007fe`f5442eac : kernel32!CloseHandleImplementation+0x3d
000007fe`f54443d2 : 00000000`00000007 000007fe`f5443d3c 00000000`00000000 00000000`77bc9997 : httpapi!HttpCloseRequestQueue+0xa
000007fe`f54444c3 : 00000000`00000000 00000000`012e6900 00000000`00000000 00000000`77bd5afa : w3dt!UL_APP_POOL::Cleanup+0x62
000007fe`f549384a : 00000000`012da080 00000000`00c93a28 00000000`012e6900 00000000`00000000 : w3dt!WP_CONTEXT::CleanupOutstandingRequests+0x83
000007fe`f549417a : 00000000`00000000 00000000`0000ffff 00000000`00000000 00000000`77bcf9fd : iiscore!W3_SERVER::StopListen+0x4a
000007fe`f562b5bf : 00000000`012d2f30 00000000`00000000 00000000`00000000 00000000`0000ffff : iiscore!IISCORE_PROTOCOL_MANAGER::StopListenerChannel+0x5a
000007fe`f5626e8f : 00000000`012d2f30 00000000`00000000 00000000`00424380 00000000`00000000 : w3wphost!LISTENER_CHANNEL_STOP_WORKITEM::ExecuteWorkItem+0x7b
00000000`77bcf8eb : 00000000`021782b0 00000000`021782b0 00000000`00000000 00000000`00000001 : w3wphost!W3WP_HOST::ExecuteWorkItem+0xf
00000000`77bc9d9f : 00000000`00000000 00000000`012d2f30 00000000`00424380 00000000`010aa528 : ntdll!RtlpTpWorkCallback+0x16b
00000000`77aaf56d : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!TppWorkerThread+0x5ff
00000000`77be3281 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : kernel32!BaseThreadInitThunk+0xd
00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!RtlUserThreadStart+0x1d

From the stack trace it's obvious that the w3wp process is trying to shut down and perform its cleanup tasks, but for some reason ntdll!ZwClose is hanging up. It's been hung for several days without change - and without apparent side effects besides an increased amount of memory usage.
The w3wp processes do not hang up all the time, I have yet to find a reproducible pattern. In the meantime, any suggestions for further debugging?
Comment: Unfortunately I haven't been able to solve this yet. I'm also seeing this on multiple servers (clean installs), so either it's our code, or we're hitting the same bug on multiple servers. I've yet to open a PSS case for it as it's not a critical issue for us, just an annoyance - especially so since I can't explain what's going on.
Comment: Were you ever able to determine what this is from? I'm seeing the same behavior and so far I've found nothing that helps.
Answer: Impressive research.
Check RSCA to see if it still has a handle to that app pool and can tell you if there are any running pages still.  It may turn up a pattern or lead.  You can drill into that at the top level of IIS and open "Worker Processes" and then double-click on the app pool if it shows up there.
Comment: What's RSCA? The IIS manager does not show the hung w3wp processes so it seems to be detached / not serving any appdomains any longer.
Comment: Runtime Status Control API (RSCA) is new in IIS7. Even though the acronym mentions that it's an API, it's what's used in IIS 7 manager too.  It sounds like it's not going to help in this case though since you confirmed that it doesn't show the app pool in IIS Manager.
Answer: Did the problem appear at the same time as a new version of the web site was deployed?
As the worker process is being closed down, the objects are being cleaned out of memory. If a developer has written code which runs when the object is being "finalized" / "Disposed", and this code throws an exception, the object will not be removed from memory. If you cannot remove all objects from memory this may block the shutting down the worker process.
Then there is the problem of why it does not happen everytime. It could be that this code is in a part of the system that is not used often, and therefore the type of object that causes this problem is not allways present.
The way to test this would be to:

start the system
use a small part
manually recyle the application pool
check for zombie process
if not check a different part of the system
....

You could also check with the developers if they have any special code for cleaning up objects.
Comment: Not a new version. Brand new server that's setup with the same sites as our other servers are, happened from the beginning. If it was some of our code hung in finalization, shouldn't there be a managed thread? There's only a single thread left and it's unmanaged.
Comment: Then it is something specific to that server installation. Could be related to lack of Windows Update / Configuration / User rights.
Answer: In IIS 7.0, WWW service no longer manages worker processes. Instead, WWW Service is the listener adapter for the HTTP listener, HTTP.sys. As the listener adapter, WWW Service is primarily responsible for configuring HTTP.sys, updating HTTP.sys when configuration changes, and notifying WAS when a request enters the request queue.
What specifcally are you running on this server? Applications pools, are they integrated mode or classic mode?
Comment: I'm running  ~500 ASP.NET applications across three identical application pools. Using integrated mode, running under a custom AD user that has all necessary rights through aspnet_regiis -ga. No other services or applications is running.
Comment: Does that same thing happen when you run the applications in classic mode?
Comment: Sorry for the slow response. I'm not able to test it in classic mode unfortunately as the app's written to run in integrated mode.

IIS7 w3wp process hung on recycle


How to get Excel cell row and col based on cell value using python

Question: How to identify cell row and cell col based on xl cell value in python...
sheet.cell(row,col) gives value but if we have value then how to get that corresponding row and col value of the shell
i searched but i could know how to identify cell details based on cell value..
pls help me thanks in advance
Comment: which python module are you using to access excel files? the answer will partly depend on that.
Comment: perhaps I'm mistaken, but I don't think you can unless you loop over all cells and check each value against the target. See http://stackoverflow.com/questions/778093/pyexcelerator-or-xlrd-how-to-find-search-a-row-for-the-given-few-column-data
Comment: @Oz123  i am using xlrd module........ any other good module to read from excel
Comment: @Fredrik while we read from sh.row(some row) we get a list of values but from that how to get col name and row name together for each value
Comment: See this: http://stackoverflow.com/a/958903/297323 or did I misinterpret you?
Comment: @Fredrik do u know how to get "name range" given for a  particular cell
Comment: @Oz123 hey do u know how to get name range for a particular cell
Comment: @user1182090, no sorry. I am excel free, but my question was necessary. If you want people to be able to help you, you got to help them help you. Providing broad information can ease the process. It is certainly possible that module A does that differently than xlrd.
Answer: You will have to iterate over the worksheets, then over the rows in a worksheet and then over the cells in a row. You have to keep track of the row and column number as the xlrd Cell class does not seem to store that:
import sys
import xlrd

_ordA = ord('A')

def find_val_in_workbook(wbname, val):
    wb = xlrd.open_workbook(wbname)
    for sheet in wb.sheets():
        for rowidx in range(sheet.nrows):
            row = sheet.row(rowidx)
            for colidx, cell in enumerate(row):
                if cell.ctype != 2:
                    continue
                if cell.value != val:
                    continue
                if colidx > 26:
                    colchar = chr(_ordA + colidx / 26)
                else:
                    colchar = ''
                colchar += chr(_ordA + colidx % 26)
                print '{} -> {}{}: {}'.format(sheet.name, colchar, rowidx+1, cell.value)

find_val_in_workbook(sys.argv[1], float(sys.argv[2]))

call the script with the name of the .xls file and the value to search for


split/regex apenas na primeira barra vertical "|"

Question: Quero dividir a string em 2 partes (sempre será uma array divida em duas partes - ou dois elementos) toda vez que uma barra vertical | (somente no primeiro caso).
Por exemplo: tenho uma string
var string = "João|23anos";
posso dar um string.split("|") e retorno será uma array ["João", "23 anos"]. Porém, eu gostaria de dar split apenas no primeiro caso de barra vertical | e copiar o restante da string para a array;
Por exemplo:
var string = "João|||23anos|"; <- Neste exemplo ele retornará essa array: ["João", "", "", "23anos", ""].
Array que eu desejaria ser impresso:
["João", "||23anos|"]
A primeira barra vertical só vai servir para dar split e o restante das barras verticais deverão estar dentro da array.
Answer:

var str = 'João|||23anos|';
var splits = str.match(/([^|]*)\|(.*)/);
splits.shift();
console.log(splits);

Explicação:

str.match(/([^|]*)\|(.*)/); retorna 2 Groups mais o Full Match, então o Array irá conter o texto mais os 2 groups:

Use shift() para remover o primeiro elemento do Array que é o Full Match.

Caso queria testar algum Regex recomendo usar essa ferramenta Regex101.
Comment: +1, mas é _full match_, com "TCH" ;-)
Comment: tem alguma dica para aprender ``regex``? desde as básicas até as avançadas
Comment: @Wtrmute Obrigado, tinha escrito errado!
Answer: Utilizando indexOf para procurar a primeira ocorrência do caractere e dividir o texto, slice, nesta posição:

const text = "João|||23anos|";

let firstMatch = text.indexOf('|');
let parts = [text.slice(0, firstMatch), text.slice(firstMatch+1)];

console.log(parts);
Answer: Um maneira bem simples seria de obter o comprimento da primeira parte (João) e então usa-la para pegar todo o resto.
Por exemplo:

texto = "João|||23anos|";
partes = [];

partes.push( texto.split('|')[0] );
partes.push( texto.substring(partes[0].length + 1) );

console.log(partes);

Acredito que o código esteja auto-explicativo. Primeiro ele obtêm a primeira parte (até o primeiro |), depois ele usa o comprimento do texto (neste caso 4) e soma com 1, então ele pega todo o texto a partir do quinto caractere.
Como comentado pode utilizar somente indexOf, ignorando o split, como respondido pelo @Anderson Carlos Woss
Comment: No JS num teria o equivalente ao `indexOf`? Isso seria mais direto ao assunto do que usar um split
Comment: vou te dar positivo por ser o primeiro a dar a resposta.
Answer:

var string = "João|||23anos|";

var ret = string.split(/\|(\|*\s*[\w.]+\s*\|*)/, 2);

console.log(ret);

Explicando:
No regexp a barra vertical(|) será nosso separador e entre parênteses o que queremos capturar.
O segundo argumento de split limita o número de divisões.
Answer: Você também pode desejar fazer assim usando .shift para pegar o primeiro item e .join para "restaurar" o resto como string novamente:

var str = "João|||23anos|";

//Divide a string
var results = str.split('|');

//Pega o primeiro resultado
var first = results.shift();

//Unifica os resultados restantes em uma nova string
var last = results.join('|');

//Cria um array baseado nos resultados
var result = [first, last];

console.log(result);

Nota: o .split tem um parâmetro chamado limit:
str.split([separator[, limit]])

No entanto o que ele faz é limitar os resultados
Answer: Como se trata da primeira ocorrência, você poderia fazer assim :

text = "João|||23anos|";
console.log(text.replace('|', '{spl}')); // SUBSTITUI A PRIMEIRA OCORRENCIA
console.log(text.replace('|', '{spl}').split('{spl}')); // DIVIDE PELO SEPARADOR

Explicação

.replace('|', '{spl}') - o replace vai substituir o primeira ocorrência pelo nosso separador {spl}
.split('{spl}') - O split vai dividir a sentença pelo nosso separador.

Nota

{spl} - é meramente ilustrativo, poderia ser um simples $ ou @.
Answer:

texto = "João|||23anos|";
console.log(texto.split(/\|(.*)/,2));
Answer: Usando slice e split

var texto = "João|||23anos|";
var resultado = texto.split("|", 1).concat([texto.slice(texto.indexOf("|") + 1)]);

console.log(resultado);


Problems with permanent caching

Question: My requirement is to update some params in the script for a some specific nodes. If a set of nodes is attached to an X content type, it should take some params in a script. For this purpose I am running a cron job every 10 min as new contents can be attached to that X content type. In this cron job, I am fetching all nodes belonging to X content type and also from these nodes, I am getting set of nodes attached to each X node. I am storing the corresponding param value for a node in the cache using the function cache_set().
cache_set(node id, X node id, MY_CACHE_NAME, CACHE_PERMANENT)

But the problem is that some nodes are not taking the param sometimes. I think that it is setting the cache, but in the cache table something wrong is happening. But when I run 3 or 4 times the nodes which were not taking param started taking. I am not getting what is happening that cache table.
I am not getting where it is writing to the database. How can we test the problems related to these caching?
I am clearing the corresponding MYCACHE  before every cron runs.
hook_cron {
  cache_clear_all('*', MY_CACHE, TRUE);
  take_params();
}

What am I doing wrong?
Comment: cron only runs a certain number of items at a time, otherwise users could be stuck waiting for it. Have you tried or considered using Rules? having it run on new content or update of content? then you don't need to worry about cron at all - it would occur immediately.
Comment: Hi @Geoff, it won't do anything to the content.It will take node ids and use it as a cache id and set the value to the X content type node id (as i mentioned in the question) .Can you please tell me what is actually happening in cache_set() and where it stores my data?
Comment: Good guide https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
Answer: Your use of the functions cache_set() and cache_clear_all() does not look right.
First let us look at cache_set(). It stores some serialized data in some persistent cache bin.
Its arguments are:

$cid - a string that identifies the stored data.  The same string is stored in the $cid field in the database table named by the $bin argument.
$data - the data to cache.  This is stored in the data field identified by $bin and $cid, usually as a serialized object.
$bin - The name (a string)  of the cache bin to use.  This corresponds to a database table with that name.  It should either be 'cache' or start with the string 'cache_'.
$expire - when should the item expire. If set to CACHE_PERMANENT, the item can only be expired by calling cache_clear_all().

You want to cache some parameters attached to some node.  To do that, you may use:
$cid = 'mymodule:node_' . $nid;
$data = ...; // Set it to hold whatever object you want to cache.
$bin = 'cache';
cache_set($cid, $data, $bin, CACHE_PERMANENT);

Note that $bin need to be set to the name of one of the bins (i.e. cache database tables) that are already defined.
Now, to clear out this particular item, you need to call cache_clear_all() with the same $cid and $bin as was you to set the cache.  The final parameter to cache_clear_all() can indicate that $cid is a wildcard (in your case, it is not). I.e.:
cache_clear_all($cid, $bin, FALSE);

Comment: Hi @Free Radical ,Sorry for the incompletion of the function.I have written the cron as you mentioned.I believe that problem is with cache_set() function.Can you tell me what is actually happening in cache_set() ? I am not aware of the third parameter in cache_set ,is it a table?
Comment: HI @Free Radical ,Can i see the values stored in the $bin in a database table??
Comment: @Vishnu, Of course. The table has the same name as the `$bin`, and the string that makes up the `$cid` can be inspected in the field `$cid`.  So the `$cid` `'mymodule:node_69'` stored in the `$bin` `'cache'` is stored in a table named "cache", and you should be able to see the `'mymodule:node_69'` in `$cid` field. Then, the  `$bin` `'cache_block'` is stored in a table named "cache_block", etc. Note that field $data will hold serialized values, so you need to un-serialize to actually see the values.
Comment: HI @FREE RTADICAL ,sorry i have updated this question and made it as a seperate question     "http://drupal.stackexchange.com/questions/120134/drupal-memcache-is-not-updating-cache-values-sometimes" ,           I found that there were no tables instead it is using a memcache and is it an issue with memcache as i am new to memcache?,
Comment: Hi @Free Radical ,my issue is resolved ,i was using memcache module for caching.After cache_clear_all() function cacheflush time is set by memcache object in seconds ,then take_params() function contains cache_set() as it also sets cache created time in seconds,memcache will reject the cache if cacheflushtime is equalto or greater than cache created time, so if cache_clear and cache_set are running at same seconds ,then we won't get the cache while calling cache_get() ,i resolved the issue by adding sleep(1) after cache_clear all ,

Problems with permanent caching


Are the residuals of quasipoisson regression in logged scale?

Question: I was interested in knowing if for a quasipoisson regression, the residuals are on a log scale
If this is my model
mdl<-glm(y ~ x1 +x1, family="quasipoisson")

To get the slope on the response scale, I do this
exp(mdl$coefficients[2])-1

If I want the residuals as well on the response scale, do I have to do the same thing?
exp(mdl$residuals)-1

Answer:
$\exp(\beta_1)-1$ is not "the slope" -- the model with the canonical link isn't linear on the scale of the response, so what would it be a "slope" of?
There are a variety of kinds of residuals commonly associated with a GLM (deviance, Anscombe, Pearson, working). None of them are on the log scale.

The ones you're referring to there would be the working residuals (whereas if you had done residuals(mdl) you'd get deviance residuals by default).
For a Poisson model, the working residuals are $\frac{y_i-\hat{\mu}_i}{\hat{\mu}_i}$.
[For a quasiPoisson model they'd presumably be scaled to adjust for the dispersion.]
Comment: Thanks. I didn't know the difference between different type of residuals in glm. I will have a read now.


Ajuda no codigo java (Iniciante)

Question: Escrevi esse código em java, para estudar. (Estou aprendendo),porem quando eu tento criar um novo objeto da erro.
Class Empresa :
class Empresa {
  String nome = "";
  String cnpj = "";
  int numeroDeFuncionario = 1;
  Funcionario[] funcionario = new Funcionario[numeroDeFuncionario];

Porem tenho que criar um "funcionario[i] = new Funcionario" ?
tentei usar :
for (int i = 0; i <= numeroDeFuncionario; i++) {
  this.funcionario [0] = new Funcionario();
}

Codigo Completo:
Classe Funcionario:
class Funcionario {
  String nome = "";
  String departamento = "";
  double salario = 0;
  Data dataDeEntrada = new Data();
  String rg = "";

  void recebeAumento(double aumento) {
    System.out.println("O salario atual e: "+this.salario);
    this.salario += aumento;
    System.out.println("O novo salario e: "+this.salario);
  }

  void calculaGanhoAnual() {
    System.out.println("O salario anual e: "+12*this.salario);
  }

  void mostra() {
    //escreve todos os parametros de Funcionario
    System.out.println("Nome e : "+this.nome);
    System.out.println("Departamento e : "+ this.departamento);
    System.out.println("Salario e : R$"+this.salario);
    System.out.println("Ganho anual de : R$"+this.salario*12);
    this.dataDeEntrada.getData();
    System.out.println("Rg e : "+this.rg);
  }

}

Classe Data:
class Data {
  int dia = 01;
  int mes = 01;
  int ano = 1900;

  void peencheData (int dia,int mes,int ano){
    this.dia = dia;
    this.mes = mes;
    this.ano = ano;
  }

  void getData() {
    String data = dia+"/"+mes+"/"+ano;
    System.out.println("Data de Entrada e : "+data);
  }

}

Classe Empresa:
class Empresa {
  String nome = "";
  String cnpj = "";
  int numeroDeFuncionario = 1;
  Funcionario[] funcionario = new Funcionario[numeroDeFuncionario];

//   if (this.funcionario == null) {
    for (int i = 0; i <= numeroDeFuncionario; i++) {
      this.funcionario [0] = new Funcionario();
  }
//
// }

//   void adicionarFuncionario() {}
//
}

class TestaFuncionario{
  public static void main(String[] args) {
    Funcionario f1 = new Funcionario();

    Empresa emp1 = new Empresa();

    System.out.println(emp1.funcionario);
    System.out.println(emp1.funcionario[0]);

    emp1.funcionario[0] = new Funcionario();

    // f1.nome = "Hugo";
    // f1.salario = 100;
    // f1.recebeAumento(50);
    //
    // f1.calculaGanhoAnual();
    //
    // f1.mostra();
    // System.out.println("\n\n");

    // Funcionario f2 = new Funcionario();
    // f2.nome = "Hugo";
    // f2.salario = 100;
    // f2.recebeAumento(50);
    // f2.mostra();

    // Funcionario f2 = f1;
    //
    // if (f1 == f2) {
    //   System.out.println("Iguais");
    // } else {
    //     System.out.println("Diferentes");
    //   }
  }

}

Comment: `this.funcionario[i] = new Funcionario();`
Comment: `this.funcionario [0] = new Funcionario();` dentro do `for` ele vai instanciar várias vezes a posição inicial e não inicializa o resto
Comment: Sua duvida é porque você que precisa criar os objetos dentro do array `funcionarios[]` usando laço ao invés desses objetos serem criados junto com o array?
Comment: Qual é o erro ?
Answer: Penso que o problema deve estar sendo indicado no fim dessa linha
Funcionario[] funcionario = new Funcionario[numeroDeFuncionario];

O real problema é a linha seguinte - para esclarecer vou repetir a parte em questão (algumas linhas apagadas):
// parte para mostrar o erro - não é a solução
class Empresa {
    ...
    Funcionario[] funcionario = new Funcionario[numeroDeFuncionario];

    for (int i = 0; i <= numeroDeFuncionario; i++) {

Aqui fica claro que o comando for está diretamente dentro da classe, fora de um método ou construtor. Em Java os comandos de execução (não os de declaração) devem vir dentro de um método, construtor ou bloco de inicialização.
Esse código deve
ou ir em um método que deve ser chamado em outro lugar:
class Empresa {
    ...
    Funcionario[] funcionario = new Funcionario[numeroDeFuncionario];

    void inicializar() {
        for (int i = 0; i <= numeroDeFuncionario; i++) {
            ...
    }

ou no construtor que é executado quando a instância for criada (new Empresa()):
class Empresa {
    ...
    Funcionario[] funcionario = new Funcionario[numeroDeFuncionario];

    Empresa() {
        for (int i = 0; i <= numeroDeFuncionario; i++) {
            ...
    }

Answer: Vi a pergunta e penso que ninguém reparou que não existiam construtores para a classe Funcionario. Getters e Setters também são úteis e boas práticas para assignar o valor de variáveis fora da classe. Por isso criei o código seguinte para testar de maneira simples o que precisas. Usei listas, porque é o recomendado para tratamento de vários objetos do mesmo tipo. Espero ter ajudado.
    package empresa.funcionario;

    import java.util.ArrayList;
    import java.util.List;

    public class Funcionario {
    //dados
    String nome;
    String departamento;
    double salario;
    String rg;
    int numero;
    //construtor por defeito
    Funcionario() {
    }
    //construtor com parametros
    Funcionario(int numero) {
        this.numero = numero;
    }
    //getters e setters
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getDepartamento() {
        return departamento;
    }
    public void setDepartamento(String departamento) {
        this.departamento = departamento;
    }
    public double getSalario() {
        return salario;
    }
    public void setSalario(double salario) {
        this.salario = salario;
    }
    public String getRg() {
        return rg;
    }
    public void setRg(String rg) {
        this.rg = rg;
    }
    public int getNumero() {
        return numero;
    }
    public void setNumero(int numero) {
        this.numero = numero;
    }
    void recebeAumento(double aumento) {
        System.out.println("O salario atual e: " + this.salario);
        this.salario += aumento;
        System.out.println("O novo salario e: " + this.salario);
    }

    void calculaGanhoAnual() {
        System.out.println("O salario anual e: " + 12 * this.salario);
    }

    void mostra() {
        // escreve todos os parametros de Funcionario
        System.out.println("Nome e : " + this.nome);
        System.out.println("numero e :" + this.numero);
        System.out.println("Departamento e : " + this.departamento);
        System.out.println("Salario e : R$" + this.salario);
        System.out.println("Ganho anual de : R$" + this.salario * 12);
        System.out.println("Rg e : " + this.rg);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //inicalizar lista de funcionarios vazia
        List<Funcionario> funcionarios = new ArrayList<Funcionario>();
        //preencher funcionarios
        for (int i = 0; i < 5; i++) {
            funcionarios.add(new Funcionario(i));
        }
        //mostrar lista de funcionarios
        for (int i = 0; i < funcionarios.size(); i++) {
            funcionarios.get(i).mostra();
        }
    }

}

Ajuda no codigo java (Iniciante)


Where have I gone wrong in calculating norm residue symbol.

Question: It is well known that the reciprocity map in local class field theory gives reciprocity map in Global class field theory. Namely, if $(\cdot,L_\beta/K_P):K_P^\times \rightarrow G(L_\beta/K_P)$ is the local reciprocity map for place $P$ in global field $K$, then global Artin map $[\cdot,L/K]$:$I_K\rightarrow G(L/K)$ is given by $\prod_P (\cdot,L_\beta/K_P)$. The kernel of this contains $K^\times$ and I understand this. But I tried to verify something explicitly and getting negative result so I would like to know where I have gone wrong.
So now let $K$ be a rational function field over one variable over finite field $\mathbb{F}_q$ where $q=p^n$ for a prime $p$ and $L$ be its constant extension of degree $m$.
Let $Q$ be a place in $K$ which does not split in $L$ and $f_Q$ be corresponding irreducible polynomial.
Then $[f_Q,L/K]=\prod(f_Q,L_\beta/K_P)$ where $\beta|P$. All factors in the right hand side is 1 except for the case $P=Q$ and $P=\infty$ as all extension $L_\beta/K_P$ is constant and hence unramifed and image of $f_Q$ in those field is a unit. In the infinity case I get $\phi^{-deg(Q)}$ and when $P=Q$ we get $\phi$ where $\phi$ is used to denote the generator of $G(L/K)$. This is because $G(L/K)\cong G(L_{\beta'}/K_Q)\cong G(L_\infty/K_\infty)$ as those places do not split. (Also because $(a,\bar{\mathbb{F}_q}((T))/\mathbb{F}_q((T)))=\phi^{v(a)}$ where in this case I mean $\phi$ as a generator of $G(\bar{\mathbb{F}_q}((T))/\mathbb{F}_q((T)))$
But there is no reason $-\deg(Q)+1$ must be divisible by $n$. Obviously I am wrong somewhere but I can't seem to figure out at the moment.
Answer: You are beginning with a global field $K$ of char. $p$, containing $\mathbb F_q$ as its maximal finite subfield, and forming the (everywhere unramified) extension $L = \mathbb F_{q^m} \otimes_{\mathbb F_q} K.$
If $\mathfrak p$ is a prime of $K$, with residue field $\kappa(\mathfrak p)$,
then the primes $\mathfrak q$ of $L$ over $\mathfrak p$ correspond to the
various field factors of the tensor product $\mathbb F_{q^{m}} \otimes_{\mathbb F_q} \kappa(\mathfrak p).$
Note that Gal$(L/K)$ is canonically isomorphic to Gal$(\mathbb F_{q^m}/\mathbb F_q)$. If $\mathfrak q$ lies over $\mathfrak p$, then the extension $\kappa(\mathfrak q)/\kappa(\mathfrak p)$ is a direct factor of $\mathbb F_{q^m} \otimes_{\mathbb F_q} \kappa(\mathfrak p).$  This tensor product has an obvious action of Gal$(\mathbb F_{q^m}/\mathbb F_q)$ (via its action on the left factor in the tensor product),
and the decomposition group $D_{\mathfrak q}$ is the subgroup which preserves
$\kappa(\mathfrak q)$.
In particular, if $\kappa(\mathfrak p)  = \mathbb F_q$, then the tensor product is just equal to $\mathbb F_q$, and so there is a single prime $\mathfrak q$ over $\mathfrak p$, of degree $n$.   Furthermore, in this case $D_{\mathfrak q} = $ Gal$(L/K)$.

As in your post, let's now take $K = \mathbb F_q(x)$.
If $\mathfrak p$ corresponds to the point $x = 0$, then the residue field is $\mathbb F_q,$ and so there is a single prime lying over infinity, of degree $m$.
If $\mathfrak p$ is the point at infinity, then $\kappa(\mathfrak p) = \mathbb F_q,$
and thus there is also a single prime lying over infinity, of degree $m$.
In each case the decomposition group is equal to all of Gal$(L/K) =$ Gal$(\mathbb
F_{q^m}/\mathbb F_q)$.
In particular, in each case the Frobenius element at $\mathfrak p$ is equal
to the Frobenius element Frob${}_q$ in Gal$(\mathbb F_{q^m}/\mathbb F_q)$.
Let's take $f = x$.  Then the norm residue symbol of $x$ at $\mathfrak p$ is trivial except for $\mathfrak p$ corresponding to $0$ or $\infty$.
At $0$, we see that $x$ has a zero of order $1$, while at $\infty$, it has a pole of order $1$.  Thus the Artin map sends $x$ to Frob${}_q \cdot $Frob${}_q^{-1}$, i.e. to $1$, which is what you wanted to check.
You should try some other examples yourself.  E.g. if $f$ is irreducible of degree two, and $n$ is odd, then there will again be a unique prime $\mathfrak q$ over $\mathfrak p$, and $\kappa(\mathfrak q) = \mathbb F_{q^{2n}}.$   The Frobenius element Frob${}_{\mathfrak p}$ is then equal to Frob${}_{q^2} = $Frob${}_{q}^2$.
The order of the pole  of $f$ at $\infty$ is $2$, so in this case the global Artin map takes $f$ to Frob${}_{q^2}\cdot $ Frob${}_q^{-2} = $ Frob${}_q^2 \cdot$
Frob${}_q^{-2} = 1$ (as it must!).
Comment: I had figured this out yesterday. I had some misunderstanding but your answer has cleared up some ambiguity I had. I was confused as I wrongly thought that $G(L/K) \cong G(L_\beta/K_P)$ means that Frobenius of $G(L/K$ needs to be sent to Frobinius at $G(L_\beta/K_P)$ but it's clearly not the case as you said!
Answer: I am not 100 percent sure but I think I figured it out.
This happens because image of $\phi$ in $G(L_{\beta'}/K_Q)$ isn't necessarily cannonical Frobenius generator. As those two groups are isomorphic it will be a generator but not necessarily the one we want to make use of local theory.


php_excel07- How to make grow the height of cell based on cell data(xls)

Question: In my application i need to export to xls file in a predefined format.
so I just integrated php_excel2007. I am using one template with a predefined format.
The problem here is the cell data may change dynamically. if data is much bigger than cell height then data is collapsing.
So is ther anyway to increase the height of cell based on content of the cell(in XLX not xlsx)?
Answer: The only way is as described in this answer to your previous question on this topic: setting the row height to autofit, and the cell alignment to wrap. This should work the same way, whether you use the Excel5 Writer or the Excel2007 Writer.
$objPHPExcel = new PHPExcel();

// Set some long string values in some cells
$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("This is a large block of text,\ncomprising several lines,\nthat will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A2')->setValue("This is a large block of text that will NOT be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('B1')->setValue("This is another large block of text without any line breaks, that will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A3')->setValue("This is another large block of text,\ncomprising several lines,\nthat will be set to autofit.");
$objPHPExcel->getActiveSheet()->getCell('A4')->setValue("This is another large block of text without any line breaks, that will be set to autofit but not wrap.");
// Fix the column width to a reasonable size
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
//  Set text wrap for cells A1 and B1. This forces the text to wrap, but doesn't adjust the height of the row
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getAlignment()->setWrapText(true);
// Set rows 1, 3 and 4 to autofit the height to the size of text
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getRowDimension(4)->setRowHeight(-1);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('testAutoHeight.xls');

EDIT
Added comments to the code sample to explain what each called method actually does
Comment: the function call $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1); does not work; i am testing it now, with latest version of PhpExcel; It does not adapt the height of the line to fit the height of the text. I mention i test this for XLS not XLSX
Comment: I've tried this but if I open the file in LibreOffice Calc, the row height is not set. Any idea what could be wrong? Here's a link to [my code](https://gist.github.com/mikehaertl/280455b503dc8c4ccddd)
Comment: Sorry, i tried this but it has no effect. The height of the row does not adapt to text content height :(
Comment: @AndreiDiaconescu - the code I quoted works, if you think otherwise then provide specifics..... "it don't work" is not acceptable as an error report
Comment: Have you set text wrap? And do you have new lines in your cell content? Simply specifying that single line of code doesn't cause the row height to adjust without the additional settings
Comment: @AndreiDiaconescu - Take a look at row 10 (cell A10) in [Examples/01simple.php](https://github.com/PHPOffice/PHPExcel/blob/1.8/Examples/01simple.php) that has an
Comment: thank you. Yes i am using textWrap. I do not have new lines in cell content. What i was looking for is the same functionality that Excel or Open Office has: double clicking on the separation line between 2 rows auto adjust the height of the row above.
Answer: <?php
error_reporting(E_ALL);
require_once ROOT.'/PHPExcel.php';

function down($details)
{
    // Create new PHPExcel object
    $objPHPExcel = new PHPExcel();
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(ROOT."/templates/project_report1.xls");

    // Set properties
    $p_i=5;$alpa="B";$row_no=5;$mil="";$d_cel="B";
    $objPHPExcel->setActiveSheetIndex()
                ->setCellValue('K1', $details['report_details']['cur_time']);
    $objPHPExcel->setActiveSheetIndex()
                ->setCellValue('C2', 'REPORT START DATE:'.$details['report_details']['start_date'])
                ->setCellValue('H2', $details['report_details']['details'])
                ->setCellValue('C3', 'SHOWING:'.$details['report_details']['showing']);
    foreach($details as $p_name=>$date){
        //thisis to display date at the top
        foreach($date as $p1=>$m_name1){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($d_cel.'4', $p1);$d_cel++;//to display date in the top
        }
        break;
    }

    foreach($details as $p_name=>$date){
        if($p_name=="report_details")break;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$p_i, $p_name);
        $objPHPExcel->getActiveSheet(0)->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('A5'), 'A'.$p_i );
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A'.$p_i)->getAlignment()->setWrapText(true);

        foreach($date as $p=>$m_name){
            $mil=$tic=$st=" ";

            foreach($m_name as $name=>$val){

            if($name=="milestone")
            foreach($val as $in_det=>$det){
                if($det && isset($det['start_date']))
                    $mil.=$det['name']."\n".$det['start_date']."\n";
                else
                    $mil.=$det['name'];
            }
            if($name=="ticket")
                foreach($val as $in_det=>$det){
                    if($det)
                        $tic.=$det['name']." ".$det['start_date']."\n";
                }
            if($name=="task")
                foreach($val as $in_det=>$det){
                    if($det)
                        $st.=$det['name']." ".$det['start_date']."\n";
                }
            }
            $summary=$mil.$tic.$st;
            $objPHPExcel->getActiveSheet(0)->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('B5'), $alpa.$p_i );
            $objPHPExcel->getActiveSheet(0)->getRowDimension($p_i)->setRowHeight();
            $objPHPExcel->getActiveSheet(0)->getStyle('A'.$p_i.':'.'M'.$p_i)->getAlignment()->setWrapText(true);
            $objPHPExcel->setActiveSheetIndex(0)->getStyle($alpa.$p_i)->getFont()->setSize(5);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($alpa.$p_i, $summary);
            $alpa++;
        }
        $alpa="B";
        $p_i++;
    }
    $objPHPExcel->setActiveSheetIndex(0);
    $objPHPExcel->getActiveSheet()->setTitle('Report');
    // Set active sheet index to the first sheet, so Excel opens this as the first sheet

    // Redirect output to a client's web browser (Excel2007)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="project_report.xls"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}
?>

Comment: It would be useful to highlight just the code where you make grow the height of cell based on cell data...
Answer: setRowHeight to -1 for make auto height (based on cell data)
// auto-size on row 1

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

Comment: Sorry, i tried this but it has no effect. The height of the row does not adapt to text content height :(
Comment: @AndreiDiaconescu - the code I quoted works, if you think otherwise then provide specifics..... "it don't work" is not acceptable as an error report
Comment: the function call $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1); does not work; i am testing it now, with latest version of PhpExcel; It does not adapt the height of the line to fit the height of the text.  I mention i test this for XLS not XLSX


How to find the equation of a parabola given the tangent equations to two points?

Question: I am trying to find the equation of a parabola with the two tangent equations to two points.
I found this post (Find the equation of the parabola given the tangent to a point and another point.) but it did not really help me so I tried to do the math on my own.
First:

I have two points whose coordinates I know,
I have two lines passing through these points whose slope I know because of their angles of inclination.

Let's say that these lines are tangents to a parabola in these two points.
How can I find the equation of this parabola given the two tangent equations and the two points ?
Here is a picture of my calculations:
A picture of my calculations
According to the picture I drew I am suppose to get the following equation:
$f(x) =\dfrac{\tan(\alpha)-\tan(\beta)}{2 \cdot x_1}\cdot x^2 + \tan(\beta)\cdot x + y_2$
When I plot $f(x) =\dfrac{\tan(60)-\tan(30)}{-2 \cdot 10}\cdot x^2 + \tan(30)\cdot x + 10$ I get the following graph:
Plot picture 1
As you can see I do not get the graphic drawn in the first picture, and if I set the window to $x\in\left[x_1,0\right]$ and $y\in\left[0,y_2\right]$ I get an empty window:
Plot picture 2
What am I doing wrong ?
I hope my explanations are good enough. Please tell me if I was not clear so that I can modify my post for you and others.
Comment: Are you looking for a parabola in the form $y=ax^2+bx+c$?
Comment: Yes, but I have been wondering if it is the right form or not... what do you think I should use ?
Comment: For arbitrary point-tangent pairs, that form of equation won't work.
Comment: @amd Yes indeed I was asking for that, we have too many conditions!
Comment: Allright thank you, I am not home for now but once I get back I will try with a cubic function.
Comment: @DOugM "Bits" isn't a good word to use, since it can also mean one-eighth of a byte. And there are six pieces of information, x1, y1, m1, x2,y2,m2.
Comment: @Acccumulation Using "byte" when you really mean "octet" isn't great, either.
Answer: Your solution is correct assuming that that parabola's axis is parallel to the $y$-axis. This is not the case for arbitrary point-tangent pairs, though. In particular, with $x_1=-10$, $\alpha=60°$, $y_2=10$, $\beta=30°$, the parabola's axis is tilted 45° from the $y$-axis, so can't be represented by an equation of the form $y=ax^2+bx+c$.
You need to start with a more general equation of a parabola, such as $(Ax+By)^2+Dx+Ey+F=0$. Another approach is to use a quadratic Bézier parameterization, for which you have enough information, and eliminate the parameter to get an implicit Cartesian equation for the parabola.
Using the latter method with your example, the third control point is the intersection of the two tangent lines, which you can find to be $\left(-15+5\sqrt3,15-5\sqrt3\right)$, which produces the parameterization $$x = -10(1-t)^2+10(\sqrt3-3)(1-t)t \\ y = -10(\sqrt3-3)(1-t)t+10t^2.$$ Eliminating $t$ yields the equation $$x^2+2xy+y^2-20(2+\sqrt3)x+20(2+\sqrt3)y-500-200\sqrt3=0.$$
Answer: Your boundary conditions are more than enough, that's exactly the cubic spline:
\begin{align*}
  p(x) &=
   \frac{x-b}{a-b}f(a)+\frac{x-a}{b-a}f(b) \\
  & \quad +
  (x-a)(x-b)\left \{
              \frac{x-b}{(a-b)^{2}} \left[ f'(a)-\frac{f(a)-f(b)}{a-b} \right]+
              \frac{x-a}{(b-a)^{2}} \left[ f'(b)-\frac{f(b)-f(a)}{b-a} \right]
            \right \}
\end{align*}

Unless $\dfrac{f'(a)+f'(b)}{2}=\dfrac{f(b)-f(a)}{b-a}$ which gives an upright parabola.
Answer: A polynomial through the point $(x_1,y_1)$ with slope $m,$ and $(x_2,y_2)$ with slope $n.$
$f(x) = y_1 + m(x - x_1)+ \frac {(x-x_1)^2}{(x_2-x_1)^2} (y_2-y_1)+\frac {(x-x_1)^2(x-x_2)}{(x_1-x_2)^2}(n-m)$
Answer: The general equation for a parabola is
$$ax^2+by^2+cxy+dx+ey+f=0, \quad ab-c^2=0$$
By the $4$ given condition, setting for example $f=1$ we should find the solution.
Comment: You mean either $\color{red}{4}ab-c^2=0$, or else $a x^2 + b y^2 +\color{red}{2} c x y + \cdots = 0$.


How to speed up boot sequence on a Dell PowerEdge 1950

Question: Everytime I had to reboot one of the Dell PowerEdge 1950 we have, there are very long tests and with them the boot sequence becomes incredibly long.
Is there a way to turn off all these tests (or at least speeding them up) ?
Comment: Do you have a PERC or any other RAID controller?  Those add a good amount of time because it spins up each disk separately.
Answer: If you mean incredibly long as in 2 or 3 minutes before you reach the OS loading, this is normal.
If you mean over 10 minutes before the OS begins to load, there's either a hardware problem, or some diagnostics have been enabled and not disabled again.
What information is coming up on the screen during these 'tests'? Can you reset the BIOS to clear it back to how it should operate?


How do I create templates in my custom module?

Question: I've created a custom module that has a bunch of PHP functions whose main purpose is basically to output HTML. For example:
function showRecentActivity($tid, $recordStart, $count){
    //do some db_select stuff to get an array of node IDs...

    foreach($nids as $nid){
        $node = node_load($nid);

        //now that we've loaded the node, 100 lines of if, echo, etc. will follow in order to output the HTML to the page
}

Perhaps you can already see the problem. While echoing HTML is fine for small pieces of markup, constructing full pages with echo statements is horrible to code, maintain, and very bug-prone.
Obviously what is needed is a pre-defined template file, written in HTML with just small places for echoing the necessary PHP variables. Just like my theme's template files.
But I have no idea how to do this with my custom module.
Answer: hook_theme is your friend, it allows you to modularize your markup in two ways:

Allows you to define a template file for your markup.
Allows you to define a theme function.

No matter which way you go, you will call for the markup the same way. so lets say you wish to modularize markup for recent activity. You will do the following in your custom module:
function custom_module_theme() {
   return array(
     'activity' => array(
       'variables' => array('variable1' => NULL, 'variable2' => NULL),
       'template' => 'custom-module-name-recent-activity',
     ),
   );
 }

You will create custom-module-name-recent-activity.tpl.php in your module directory where you will have $variable1 and $variable2
Your custom-module-name-recent-activity.tpl.php will look something like this:

 <?php print $variable1; ?>

 <?php print $variable2; ?>

And then from your module when you have done your processing and have established $variable1 and $variable2 (you can pass as many as u want), you will simply do:
theme('activity', array('variable1' => $variable1, 'variable2' => $variable2));

Hope this helps, I wonder now if I should have linked to some tutorial. But hey its Saturday :)
(And if you are using Drupal 6, change 'variables' to 'arguments' in the code above.)


How can we prevent console windows from being displayed under Visual Studio?

Question: Is it possible (and how) to disable the display of the Console window when we launch an application under Visual Studio?
EDIT:
Some precisions:
I have at the beginning of this project no GUI system.
In a second time I have added QT gui to this project.
Currently when I launch my application, I have the console system and the QT's MainWindow
I would like to disable console system
Comment: There are a lot of different ways to answer this question... Which one is correct depends on what exactly you're trying to accomplish. Can you please edit your question to give us more details?
Comment: Ah, then simple enough. You need to convert your application into a standard Windows application, rather than a Console application. [Als's answer](http://stackoverflow.com/questions/6055026/how-can-we-prevent-console-windows-from-being-displayed-under-visual-studio/6055094#6055094) has you covered.
Answer: You will have to use just an application and not a console application. To do that:
Change SubSystem to Windows. You can find it under:
Properties ---> Linker ---> System

and replace
int _tmain(int argc, _TCHAR* argv[])

with
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)

Comment: I am under VS2010 I can't manage to find SubSystem/Windows option
Comment: For future googlers: You don't have to change the subsystem. If no subsystem is selected (default for console project), just replacing `_tmain` with `_tWinMain` is enough.
Comment: VS2013: Project > Properties > Linker > System then set SubSystem to Windows
Answer: You cannot (but see below) and this has nothing to do with Visual Studio, but with how Windows differentiates Console and "non Console" applications.
A console application has some kind of flag set in it's executable so that Windows knows that it's a CLI and Windows will then always open up a console and attach it to this process.
A GUI app doesn't have this flag and therefore Windows will not attach a console (and when run from the Windows cmd.exe shell, the shell won't attach to this app either.)
You can control Console attaching and detaching from your app with the AllocConsole and FreeConsole Windows API functions, but what you really want to do is probably what Als describes in his answer.
Answer: If it is a windows application then yes - you control the UI. If it is a console application then you get a console with stdin, stdout, etc. If you are looking for something with no UI at all then maybe a Windows Service is what you are after.
Comment: Or simply a standard Windows application that doesn't specify `WS_VISIBLE`. No reason to create a Windows Service just to get an app without a UI.


Re-use Eigen::SimplicialLLT's symbolic decomposition

Question: I am struggling a bit with the API of the Eigen Library, namely the SimplicialLLT class for Cholesky factorization of sparse matrices.
I have three matrices that I need to factor and later use to solve many equation systems (changing only the right side) - therefore I would like to factor these matrices only once and then just re-use them. Moreover, they all have the same sparcity pattern, so I would like to do the symbolic decomposition only once and then use it for the numerical decomposition for all three matrices. According to the documentation, this is exactly what the SimplicialLLT::analyzePattern and SimplicialLLT::factor methods are for. However, I can't seem to find a way to keep all three factors in the memory.
This is my code:
I have these member variables in my class I would like to fill with the factors:
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> choleskyA;
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> choleskyB;
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> choleskyC;

Then I create the three sparse matrices A, B and C and want to factor them:
choleskyA.analyzePattern(A);
choleskyA.factorize(A);
choleskyB.analyzePattern(B); // this has already been done!
choleskyB.factorize(B);
choleskyC.analyzePattern(C); // this has already been done!
choleskyC.factorize(C);

And later I can use them for solutions over and over again, changing just the b vectors of right sides:
xA = choleskyA.solve(bA);
xB = choleskyB.solve(bB);
xC = choleskyC.solve(bC);

This works (I think), but the second and third call to analyzePattern are redundant. What I would like to do is something like:
choleskyA.analyzePattern(A);
choleskyA.factorize(A);
choleskyB = choleskyA.factorize(B);
choleskyC = choleskyA.factorize(C);

But that is not an option with the current API (we use Eigen 3.2.3, but if I see correctly there is no change in this regard in 3.3.2). The problem here is that the subsequent calls to factorize on the same instance of SimplicialLLT will overwrite the previously computed factor and at the same time, I can't find a way to make a copy of it to keep. I took a look at the sources but I have to admit that didn't  help much as I can't see any simple way to copy the underlying data structures. It seems to me like a rather common usage, so I feel like I am missing something obvious, please help.
What I have tried:
I tried using simply choleskyB = choleskyA hoping that the default copy constructor will get things done, but I have found out that the base classes are designed to be non-copyable.
I can get the L and U matrices (there's a getter for them) from choleskyA, make a copy of them and store only those and then basically copy-paste the content of SimplicialCholeskyBase::_solve_impl() (copy-pasted below) to write the method for solving myself using the previously stored L and U directly.
template<typename Rhs,typename Dest>
void _solve_impl(const MatrixBase<Rhs> &b, MatrixBase<Dest> &dest) const
{
  eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()");
  eigen_assert(m_matrix.rows()==b.rows());

  if(m_info!=Success)
    return;

  if(m_P.size()>0)
    dest = m_P * b;
  else
    dest = b;

  if(m_matrix.nonZeros()>0) // otherwise L==I
    derived().matrixL().solveInPlace(dest);

  if(m_diag.size()>0)
    dest = m_diag.asDiagonal().inverse() * dest;

  if (m_matrix.nonZeros()>0) // otherwise U==I
    derived().matrixU().solveInPlace(dest);

  if(m_P.size()>0)
    dest = m_Pinv * dest;
}

...but that's quite an ugly solution plus I would probably screw it up since I don't have that good understanding of the process (I don't need the m_diag from the above code since I am doing LLT, right? that would be relevant only if I was using LDLT?). I hope this is not what I need to do...
A final note - adding the necessary getters/setters to the Eigen classes and compiling "my own" Eigen is not an option (well, not a good one) as this code will (hopefully) be further redistributed as open source, so it would be troublesome.
Answer: This is a quite unusual pattern. In practice the symbolic factorization is very cheap compared to the numerical factorization, so I'm not sure it's worth bothering much. The cleanest solution to address this pattern would be to let SimplicialL?LT to be copiable.
Comment: So I did some measurements and the symbolic decomposition actually takes more time than numerical for my case (the sparsity pattern is given by mesh connectivity of a rather ordinary triangular manifold mesh, e.g. one of the matrices is the Laplacian). For example it takes 0.013s for symbolic (analyzePattern()) vs 0.001s for numeric (factorize()) factorization for a 14758x14758 matrix or 0.169s / 0.023s for 1255265x1255265 (that one is bound to be veeery sparse though). The good part is that those are quite good times in general so if there is no other solution I can live with that.
Comment: I'm surprised by your result, I thought there was one order of magnitude for such matrices, but with equal time it might be worth implementing `operator=`. Patch welcome.
Comment: Ah, I haven't actually measured if the symbolic factorization takes a lot of time for my problem or not, I am just a coding monkey that does what is told and I've been told that it should be done only once...I will take a look on Monday, if it takes negligible amount of time I will just not bother with it and do it three times, thank you.
Comment: Nevermind hte previous comment, there was a numerical issue and the factorization actually wasn't finished. Now with succesful factorization, the times are roughly the same for both.


Symfony does automatic unit tests?

Question: I noticed that symfony automatically creates functional tests for all module actions, but i'm curious if it creates unit tests too. Maybe through a plugin or something.
Comment: For the models, forms, validators and modules it generates.
Comment: Automatically creates unit tests? For what?
Answer: The functional tests you mean are stubs - they do a very basic test, nothing else. There is no way to get unit or functional tests autogenerated for you - how would symfony know what's the expected behaviour of your appication?
Comment: It could at least create a test that instantiates one object from every model it has, just to be sure they work.

Symfony does automatic unit tests?


Modify date popup structure

Question: I would like to modify the date popup structure, in the image below you can see how date module builds the element. Drupal's default label is hidden, and it generates other to display the title. I want to show that label, and hide the date module label. Where should i modify this? Using some hooks in a .module, create a custom template or just overwrite it with css? Thanks all for help!
PD: This change must concern to every page in my site.
Comment: This is for D7 or D8 ?
Comment: Yep, i forgot it. Drupal 7
Answer: Override theme_date_popup in your theme or custom module.
See the following tutorial how to do it.
Comment: You are welcome, i'm glad that help.

Modify date popup structure


function in recipe not overridden

Question: I want to override a function in a recipe (bb) that inherits from a bbclass, but it doesn't work -- the function from the bbclass (superclass) is executed instead of the new one.
Here is an minimal (non-)working example.
Class:
# myclass.bbclass

do_compile() {
    echo MyClass
}

Recipe:
# myrecipe.bb

do_compile() {
    echo MyRecipe
}

inherit myclass

After I compile the recipe, the log file looks like this:
$ cat temp/log.do_compile
DEBUG: Executing shell function do_compile
MyClass
DEBUG: Shell function do_compile finished

Why doesn't overriding of do_compile work?
Answer: The position of inherit in the recipe file is important. If you put it in the beginning of the file (before the function do_compile is defined in the (subclass) recipe), it works.
Recipe:
# myrecipe.bb

inherit myclass

do_compile() {
    echo MyRecipe
}

After compiling the recipe the log file looks like this:
$ cat temp/log.do_compile
DEBUG: Executing shell function do_compile
MyRecipe
DEBUG: Shell function do_compile finished

function in recipe not overridden


EntityFieldQuery: Load all revisions

Question: I have a self-defined entity with revisions called command. The instance with id=1 has 3 revisions. Now I want to load all these revisions. Tried this:
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'command')
  ->propertyCondition('id', 1)
  ->age(FIELD_LOAD_REVISION)
  ;
$result = $query->execute();

but it gives me still only one revision, the current one. There's no difference to calling it without ->age(FIELD_LOAD_REVISION).
What am I doing wrong?
Comment: OK, so tried that code
    `$query->entityCondition('entity_type', 'command')->propertyCondition('id', 1)->age(FIELD_LOAD_REVISION);
    $result = $query->fetchAll();`
and still got `Call to undefined method...`. Maybe you're mixing it up with `db_select()`?
Comment: I also can't get this working...
Comment: Are you cycling through all the results? i.e. `$query->fetchAll();`
Comment: Just thought "OMG, right!" But then adding `$result = $result->fetchAll();` to the code above just gave me the error `Call to a member function fetchAll() on a non-object`. And it seems that `EntityFieldQuery` [doesn't have a fetch function](http://api.drupal.org/api/drupal/includes%21entity.inc/class/EntityFieldQuery/7).
Comment: I'm pretty sure you can just drop the `execute()` and do `$result = $query->fetchAll()`
Comment: @pcambra's solution works.
Answer: Solution: Use a regular query instead of a EntityFieldQuery to load all entity revisions.
Explanation:
In the age function on entity.inc there's this comment:

Blockquote
     * Note that this only affects field conditions. Property conditions always
     * apply to the current revision.

So as long as you provide a property condition, you will get only the last revision id. If you query with fieldCondition, you will get the revisions, as the age method is actually querying the field revision table and not the node revision one (field_sql_storage.module):
  else {
    $tablename_function = '_field_sql_storage_revision_tablename';
    $id_key = 'revision_id';
  }

Otherwise, the entity table is queried so it will always return the entities and not the revisions.
You could do a addTag and modify the query object there but at this point the modifications will be so big that it's actually better to do a regular query instead.
Example using generic info for the entity and entity api entity_revision_load.
  $entity_type = 'command';
  $value = 1;
  $entity_info = entity_get_info($entity_type);

  $query = db_select($entity_info['revision table'], 'revision');
  $query->fields('revision', array($entity_info['entity keys']['id'], $entity_info['entity keys']['revision']))
    ->condition('revision.' . $entity_info['entity keys']['id'], $value);
  $revisions = $query
    ->execute()
    ->fetchAllAssoc($entity_info['entity keys']['revision']);

  $entities = array();
  foreach ($revisions as $key => $revision) {
    $entities[] = entity_revision_load($entity_type, $key);
  }

EntityFieldQuery: Load all revisions


How to get nodeid?

Question: How to get nodeid in Drupal for the current page without using the information from the page url? I.e.:
if(arg(0)=='node' && is_numeric(arg(1))){
  $nid = arg(1);
}

I do not want to use the above approach.
Answer: Still comes through the URL indirectly, but this is the easiest way to get it: menu_get_object.
<?
if ($node = menu_get_object()) {
 $nid = $node->nid;
}
?>

Note that if there is a node, it was already loaded by the menu system anyway and this is loaded from the static cache.
Comment: This approach makes sure the id is valid and accessible, as @chx points out. But can also be very heavy: it often results in many DB-calls. Just last week I replaced one `$node = menu_get_object()` with something similar to code original question, saving **500+** database requests **per page**. Use with care!
Answer: Unless there is some technical reason why the arg() method is unavailable (or you NEED to check access as in other posts), the arg() method is the simplest and quickest.
If you then need additional properties you can run a node_load() to get the ID. Assuming you are trying to get the current node, this has pretty much no performance hit.
Answer: You can get the node's ID by calling $node->nid. Indeed, getting the ID from the URL is not the best solution because you may some day switch to more SEO-friendly URLs.
From this documentation, it looks like $node is defined in page.tpl.php, so it should be available to you.
<?php
  // In a template file...

  if ($node) {
    echo $node->nid;
  }
  else {
    // you are viewing taxonomy, view, etc
  }
?>

Comment: I need to access it outside of the template file.
Comment: Where are you trying to access it from, a module? Under what context are we talking about the "current page"?
Comment: It should be noted that if the 'internal' url is node/12 and you use path to create a clean url the original code still works this is because the drupal node/12 path is still the url as far as the system is concerned.
Answer: Yes, that confused me for ages, but using the arg array should work in almost all circumstances, and Drupal takes care of the conversion from the actual url created by path or pathauto.
Answer: Easiest way to do this in Drupal 8:
$path_args = explode('/', current_path());
print $path_args[1];

Answer: Another pretty straight forward and reliable approach in D7 would be
<?php
if (isset($node->nid) && count($node->nid) > 0){
  $nodeid = $node->nid;
}
?>

Zourtney's suggestion causes an undefined index error in my case.

How to get nodeid?


eCommerce tracking code not firing in Google Analytics 4 implementation

Question: I am currently migration to Google Analytics 4 and have placed the following code on my page. I should point out that one property is a "rollup" property and the other is for the
section of the application, so there are intentionally two properties (and two measurement IDs on this page).

The code above works, but when I add the following code further down the page the code does not fire and no eCommerce transaction is recorded. The code looks correct based on the documentation, so I am struggling to see what is missing here.

Comment: what documents are you following exactly
Comment: @LindaLawton-DaImTo The official documentation provided by Google. https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag#purchase
Answer: You're missing item_ids. Read the documentation carefully, it lists mandatory fields: https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag#purchase
Also, when testing, check your Network tab for Collect events, or install adswerve datalayer explorer extension. The extension will show actual events in the console. Mind you that GA4 introduces event batching, so your purchase event may take a few seconds to dispatch after the page is loaded.
Comment: Thanks, but I note the documentation states: `*One of item_id or item_name is required.`


How to represent data graphically in which a respondents can choose more than one group?

Question: I am analyzing a survey in which one of the questions was (What is the industry segment of your company?) and the respondents can choose more than one category.
I have used a pie chart to represent that data but then I thought this is not very accurate, since one company can choose more than one option. Any suggestion on what can I do to improve the representation?
Comment: Are you just interested in total counts or in comparing respondents?
Answer: There are numerous ways how to deal with this:

The pie/bar chart might consider not original $n$ categories, but all $2^n$ combinations.
To consider the Carnaugh maps where the color intensity shows the number of answers for given combination of categories.
Under some conditions, you can use some kind of 2D map where each category has a region (Venn diagram) and you put a marker per record in to the categories (intersections).
The assigmenent to the categories can be considered as a usual vector and then self-organizing maps can be employed. This will be most likely related to some information loss, but it can cope with complex data approximately.