Google Calendar processing same ics file differently as an import vs as a webcal stream

Question: I created a webcal stream, and Google Calendar reads it successfully, and creates events. However, the events it creates are 5 hours earlier than they should be. The event below, for instance, comes up at 1pm.
If I take the same webcal stream and save it as an .ics file, and then import that file into Google calendar, all the times are correct.
Why would Google calendar handle these differently? In the Mac Calendar application, the events come up at the right time, whether I add them via the webcal stream, or by importing the .ics file.
Both Google Calendar and Mac Calendar know that I'm in EST (via calendar settings - nothing declared in the ICS file, as you can see).
I'd like Google to handle the webcal stream correctly, so that it will auto-update as I add more events.
The start of the ICS file, and a single event, are listed here. It shows up at 6pm in Mac Calendar, and 1pm in Google Calendar.
BEGIN:VCALENDAR
CALSCALE:GREGORIAN
METHOD:PUBLISH
PRODID:iCalendar-Ruby
VERSION:2.0
BEGIN:VEVENT
DESCRIPTION: football game on Sunday at 6pm, on NBC, with dinner
DTEND:20121208T233000Z
DTSTAMP:20130124T200858
DTSTART:20121208T230000Z
CLASS:PUBLIC
SEQUENCE:0
SUMMARY:sunday 6pm football game
UID:2013-01-24T20:08:58+00:00_945022440@e8deb599-a4b6-40a3-b82c-d1baf5e9109e
END:VEVENT
END:VCALENDAR

Answer: This is because Google Calendar doesn't do floating timezones, so when there is no timezone specified it assumes to be UTC. Mac calendar assumes your timezone when you import something that does not have a specific timezone specified in the ics file. So you will have to have add timezone information to your file.
How Google Calendar works with time zones
Writing ICS files for multiple clients, including Google
Adding a VTIMEZONE section to your file should help:
BEGIN:VTIMEZONE
TZID:Eastern
BEGIN:STANDARD
DTSTART:16011104T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:16010311T020000
RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
END:VTIMEZONE

Comment: Thanks Keeg. Doesn't adding a Z to the end of the time (as in DTSTART:20121208T230000Z) indicate that the time is in UTC? I've adjusted my times assuming this would be the case.

Also, I still don't understand why Google Calendar would handle the timezone differently when it's a webcal vs when it's an imported .ics file
Comment: as far as I know google calendar is not actually RFC compliant: http://tools.ietf.org/html/rfc2445#section-4.3.5 and should not assume UTC when the time is floating
Comment: So in the end, I just manually added a chunk of time to UTC (and used Z to indicate UTZ) to account for my time zone. This works, so times are right both in gcal and mac calendar. Google Calendar's non-updatability for webcal streams makes it very hard to work with. I'd even switch google accounts, and add the same webcal stream to a different account - still wouldn't update. Not sure how Google handles webstreams like that, and would love if they'd explain it somewhere (or love it even more if they'd let users control update behavior). Thanks again for taking a look.


Scrapy: Autopopulate extracted fields

Question: To sum up my query in a few bullet points before expanding:

Target website is a sports website with 100+ fields which I want to scrape.
I would like to declare an empty class to fill with the field names and populate it with the relevant values.
I am unclear how you alter the Items file for a scenario where you are not explicitly declaring your scraped items.

Now to get down to brass tacks.
I am looking to scrape from a rugby database. A snippet of the code is below:
<TeamData Possession="0.50" Score="40" Side="Home" TeamRef="t1550" Territory="0">
  <Stat Type="restart_opp_player">0</Stat>
  <Stat Type="kick_oppn_collection">0</Stat>
  <Stat Type="kicks_from_hand">0</Stat>
  <Stat Type="penalty_conceded_killing_ruck">0</Stat>
  ...

This code continues on for around another 140 lines to make something that would be a pain to define each attribute explicitly.
Rather than extracting each attribute one by one, I would like to be able to define an empty class and then fill it with the various attributes. This is fairly easy to achieve within the shell.
class RugbyItem(params):
 def __init__(self, params)
  selc.__dict__.update(params)

home_attribute_names = response.xpath('//TeamData[@Side="Home"]/Stat/@Type').extract()
home_attribute_stats = response.xpath('//TeamData[@Side="Home"]/Stat/text()').extract()
concat = {k: v for (k, v) in (zip(home_names, home_stats))}

home_data = RugbyItem(concat)

Based on the above, could someone help me in figuring out what way I should structure the Items file
class RugbyItem(scrapy.Item):
 ??? = scrapy.Field()

and the Spider class.
class MySpider(BaseSpider):
 name        = "rugbyspider"
 allowed_domains = ["opta.net"]
 start_urls  = ["http://omo.akamai.opta.net/?feed_type=ruf9&game_id=113013&user=OWV3&psw=trDd59TW"]

 def parse(self, response):
  home_attribute_names = response.xpath('//TeamData[@Side="Home"]/Stat/@Type').extract()
  home_attribute_stats = response.xpath('//TeamData[@Side="Home"]/Stat/text()').extract()
  concat = {k: v for (k, v) in (zip(home_names, home_stats))}
  home_data = RugbyItem(concat)
  yield home_data

Thanks for the help!
Answer: you are not obliged to yield a scrapy.Item instance, you can also yield a dict, which won't be bounded to the restrictions you want.

Scrapy: Autopopulate extracted fields


A.P series. Find the value of the first installment.

Question: A man arranges to pay of a debt of Ksh$3600$ in $40$ annual installments which form an A.P series. When $30$ of the installments are paid, he dies leaving one third of the debt unpaid. Find the value of the first installment.
Answer: Hint: Sum of first 30 terms of the AP is 2400. Sum of the first 40 terms is 3600. Just equate the equations you can form from the Sum of x terms of an AP formula.
Comment: thanks ,,,,,,,,


Why did Scriabin notate the bass clef in Op 11 no 15?

Question: Why didn't he just notate it with treble clef from the start?
Comment: The grand staff ( violon and bass clef) is the definition for keyboard sheet  music. Thats all.
https://musicterms.artopium.com/g/Grandstaff.htm
Comment: Your question is not " wrong". Some composer write in such situations a violine clef for both hands. Especially in this case as it is collection of preludes for piano. I could see a reason: I had  over looked the violin clef in Bartoks mikrkosmos " in the mist." My auntie got quite angry and upset about the dissonants. She said: Don't you see, you're playing the wrong clef! Thus I changed the clef and the sound was even more awful. Since then I became a Bartok fan: You can annoy aunties.
Comment: @AlbrechtHügli *"My auntie got quite angry and upset about the dissonants. She said: Don't you see, you're playing the wrong clef! Thus I changed the clef and the sound was even more awful. Since then I became a Bartok fan"* I laughed
Comment: I see so, keyboard sheet should have both clefs and then immediately do clef change
Comment: Also keep in mind that the sheet music *publisher* is the one who did the typesetting, not the composer.
Answer: The grand staff is the definition for keyboard sheet music.
As the title of opus 11 is 24 Preludes for Piano the composer could have notated from the beginning the treble clef.
The two clefs are emphasizing that there is a change of clef.
It might also have been that he had bought empty sheet music paper with prepared grand staffs but it doesn't seem:
http://www.scriabin-association.com/the-texts-of-scriabins-works-some-observations-of-a-performer-researcher-teacher/


Can not override template for specific view

Question: I'm new to Drupal so this might be a noobish question.
I have a view called 'Category' where all posts are listed that belongs to the chosen category.
I would like to override the views-view-unformatted.html.twig as well as the views-view-field.html.twig which is working fine for other views.
When I enable the twig debug mode I see this at the top of the page:

So I thought templates with the name
views-view-unformatted--categories.html.twig
views-view-fields--categories.html.twig

would do the job. Or being even more specific:
views-view-unformatted--categories--block-1.html.twig
views-view-fields--categories--block-1.html.twig

But these templates aren't used.
I have also tried to use 'taxonomy--term' for the template names with no success.
There is also no file name suggestion for these templates.
Can anyone please tell me how I can get it working or hint me to the right direction?
Answer: You either haven't rebuilt cache, or the page you're viewing isn't being generated by your Categories Views. It seems to be generated by the default Taxonomy term Views. Or you're viewing the wrong page :)
Views templates debug info is shown further down the source HTML, you won't find it at the top of the source page. Try looking below the main page heading in the source HTML, that's there the page views will start with their own templates.
This issue is also relevant:
Views file name suggestions often missing from Twig debugging
Especially the fifth comment there:
#5
Also:
[PP-3] Twig debug output does not display all suggestions when an array of theme hooks is passed to #theme
I haven't tried this module but it may be relevant:
Views Templates
Comment: It has been a taxonomy term view. So the correct file name is 'views-view-fields--taxonomy-term--page-1.html.twig'. Thanks for your hint and links. They really helped me out.


Wsimport de múltiplos serviços iguais com várias operações desnecessárias

Question: Em Java, estou usando a ferramenta wsimport. O processo funciona. Entretanto há alguns problemas.
Tenho que fazer o wsimport nos serviços de vários fornecedores diferentes (todos eles terceiros, não tenho nenhum controle sobre eles). Os WSDLs são quase idênticos, só mudando a URL do destino.
Cada um desses WSDLs definem um monte de operações/métodos diferentes. Ocorre que dentre esse monte de operações, apenas umas 2 ou 3 eu vou realmente precisar. Quase no final de cada um desses WSDLs há isso:
  <wsdl:service name="Exemplo">
    <wsdl:port name="ExemploSoap" binding="tns:ExemploSoap">
      <soap:address location="https://www.example.com/wsIntegracao/exemplo.asmx" />
    </wsdl:port>
    <wsdl:port name="ExemploSoap12" binding="tns:ExemploSoap12">
      <soap12:address location="https://www.example.com/wsIntegracao/exemplo.asmx" />
    </wsdl:port>
  </wsdl:service>

De um WSDL para outro quase nada muda. Em geral, a única coisa que muda são essas URLs que estão no trecho aí em cima.
Eis a parte relevante do pom.xml. Eu tenho isso para cada serviço/WSDL diferente, de forma que cada um deles vai gerar um JAR distinto (há um pom.xml para cada serviço, cada um em uma pasta distinta).
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxws-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>wsimport</goal>
                    </goals>
                    <configuration>
                        <wsdlFiles>
                            <wsdlFile>servico-teste.wsdl</wsdlFile>
                        </wsdlFiles>
                        <wsdlLocation>servico-teste.wsdl</wsdlLocation>
                        <wsdlDirectory>${basedir}</wsdlDirectory>
                        <packageName>br.com.example.servico2</packageName>
                        <verbose>true</verbose>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
                <compilerArgs>
                    <arg>-Xlint:none</arg>
                </compilerArgs>
            </configuration>
        </plugin>

As diferenças entre um pom.xml e outro são mínimas. Praticamente apenas o nome do pacote a ser gerado e o nome do arquivo WSDL.
Como já mencionei, o processo funciona. Mas deste jeito, se eu tiver 20 serviços diferentes, serão gerados 20 arquivos JAR quase idênticos. Se cada um deles tiver 100 classes, isso vai gerar 2000 classes diferentes em 20 JARs, sendo que só 3 ou 4 eu uso efetivamente.
Assim sendo, faço duas perguntas:

Há alguma forma de se otimizar o wsimport de forma a precisar executá-lo apenas uma vez quando os serviços forem iguais ou suficientemente parecidos, onde apenas a URL no soap:address location varie?
Há alguma forma de se instruir o wsimport a gerar somente as classes necessárias para uma determinada parte do WSDL, e não para tudo que for referenciado no WSDL?
Comment: @RenanCarlos Rejeitei a sua edição porque ela não me parecia estar melhorando a minha pergunta em nada, apenas acrescentando formatações onde não deveria ter. Se você acha mesmo assim que a sua edição era válida, gostaria de ouvi-lo. De qualquer forma, agradeço a atenção e o empenho.
Answer: Se você puder gerar em um jar só, não vai precisar se preocupar. Eu faço assim, tenho um jar somente com minhas classes dos webservices.
Então, tudo que é comum é sobrescrito fazendo com que as classes sejam compartilhadas.
Se quiser insistir em vários jars, eu fiz alguns testes e é possível, porém será necessário alguma "gambiarra" pra deixar redondo.
Conforme o link abaixo:
https://metro.java.net/2.0/guide/Compiling_multiple_WSDLs_that_share_a_common_schema.html
Você verá que se fizer um binding como o meu, o schema que é compartilhado irá pra um pacote especifico. No meu binding, os schemas estão dentro dos wsdls (atenção).
<bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.1">

    <bindings scd="x-schema::bons1"
        xmlns:bons1="http://www.dominio.net/services/metadata/v2.0">
        <schemaBindings>
            <package name="br.common.metada" />
        </schemaBindings>
    </bindings>

    <bindings scd="x-schema::e"
        xmlns:e="http://www.dominio.net/services/errors/v1.0">
        <schemaBindings>
            <package name="br.common.errors" />
        </schemaBindings>
    </bindings>

</bindings>

Mas não encontrei uma maneira de não gerar classes específicas, então aqui eu sugiro que você edite os schemas que serão compartilhados mantendo apenas o que você quer gerar, ou então, exclua as classes dos pacotes que você não quer.
Aí, quando gerar as classes específicas, aponte o episode gerado no xjc conforme o link.
Achei muito trabalhoso, mas já havia me feito essa pergunta e foi o mais perto que cheguei.
Comment: Ola, realizar a geração por operação é uma coisa que ainda não existe, se fosse por serviço ai sim temos alguns plugins, eu mesmo uso o [CXF da apache](http://cxf.apache.org/docs/wsdl-to-java.html) mas mesmo assim ele gera classes para todas operações, se todos os serviços dele tem a mesma estrutura até poderia ser feito de usar os obejtos gerados e alterar o endpoint e o Qname, mas podem ter outras propriedades a serem alteradas, e se caso um dos servilços mudar já quebraria o contrato, o melhor memso é como você falou, tudo em um jar e deixar a geração automática cuidar de tudo.
Comment: Gostei da resposta. Vou testar amanhã.
Answer: A resposta do btafarelo me ajudou bastante, mas ainda não era a solução ideal.
Também, esta resposta do SOen me ajudou bastante, embora ainda não fosse a solução completa.
Primeiramente, eu peguei um dos WSDLs e troquei a URL lá colocando uma URL genérica, gerando no maven as classes da mesma forma como eu já fazia.
No Java, ao invés de instanciar a classe principal do serviço a integrar usando o construtor padrão, passei a usar o construtor que recebe uma URL e um QName. Esse construtor também é gerado por padrão pelo ws-import.
Ao invocar-se esse construtor, tal como na resposta do SOen, eu passo URLs que começam com http://localhost/wsdl. Dentro da pasta META-INF, então eu crio um arquivo jax-ws-catalog.xml com o seguinte conteúdo:
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system">
    <system systemId="http://localhost/wsdl/servico1.wsdl" uri="wsdls/servico1.wsdl"/>
    <system systemId="http://localhost/wsdl/servico2.wsdl" uri="wsdls/servico2.wsdl"/>
    <system systemId="http://localhost/wsdl/servico3.wsdl" uri="wsdls/servico3.wsdl"/>
</catalog>

Dentro de uma pasta wsdls, eu acrescento os arquivos WSDL que baixei de cada serviço. Essa pasta é colocada dentro do JAR/WAR gerado da aplicação. Esse arquivo jax-ws-catalog.xml instrui o JAX-WS a procurar por esses WSDLs localmente.
Desta forma, eu só preciso usar o wsimport uma única vez. Por fim, para reduzir o número de coisas desnecessária geradas, eu posso editar o WSDL genérico.


when calling void with throws keyword, all thrown errors apply to where i call the void

Question: i am currently trying to make a shift key holder with java using the grave accent as the toggle and robot was the only way i could find that was remotely simple. the program does what the name implies, and holds down the shift key for me. making the program for starbound building if you are wondering where this will be useful, as there is capslock. however when using robot i have to throw a few exceptions, but they then appear in the place that i am calling my void
i can't find any solution for this possibly because i am using the JNativeHook  library to create a keylogger that will react to the grave symbol. i am still fairly new and i pieced a lot of this together from snippets online.
this is where my error is coming from, the full program is available here
i would post a minimum reproducible example but i cannot as i don't know what parts are crucial to the function of this one part.
//tried to put throws in nativeKeyPressed to get rid of the exceptions but then that gives me an exception saying i can't do that because it causes clashing
public void nativeKeyPressed(NativeKeyEvent e){
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == NativeKeyEvent.VC_BACKQUOTE) {
            toggle(); //get IOException, AWTException, and InterruptedException whenever i put throws on my toggle() void
        }
    }

        //throw exceptions so robot has no conflicts
    public static void toggle() throws IOException, AWTException, InterruptedException{
        bool = !bool;
        Robot r = new Robot();

        if (bool = true) {

        } else if (bool = false) {

        }

i expect it to have no errors but Robot() has exceptions if i dont throw them, and toggle(); has whatever exceptions i throw from public static void toggle(). i am open to methods other than robot, but i cant find any others.
Comment: Not sure if I'm misunderstanding here, but have you tried just surrounding your toggle() call in a try catch? It's an unhandled exception.
Comment: @amir how would i do this, i am stumbling in the dark here trying to figure this out, taking a java course and the most recent thing i have learned is how to call a void. but of couse i need the program that uses things i have not learned yet.
Comment: `if (bool = true) {` is always true, because it's an assignment, not a comparison. Use `bool == true`, or, better, `bool` (and `bool == false` or `!bool`).
Comment: @AndyTurner thank you for catching that, i would not have for a while
Comment: Related or possible dupe: https://stackoverflow.com/questions/11589302/why-is-throws-exception-necessary-when-calling-a-function
Comment: @Tom this question is completely different as i have exceptions that are known and able to be handled whereas they have exceptions that have yet to be handled and are causing them to throw an unknown exception, whereas me throwing my exceptions has caused further issue, and needs resolved. however i see why it may seem related.
Answer: Unless you are expecting any of these exceptions and know how to handle them, just wrap your exceptions
public static void rethrowException (Exception ex) {
  throw new RuntimeException(ex);
}
    //throw exceptions so robot has no conflicts
public static void toggle() {
  try {
    bool = !bool;
    Robot r = new Robot();

    if (bool = true) {

    } else if (bool = false) {

    }
  } catch (IOException|AWTException|InterruptedException ex) {
    throw new RuntimeException(ex);
  }
}

Comment: this has been tested, and has not removed the error, i actually gain more errors
Comment: @ControlAltDel I guess you meant to remove the throws too :) but why not just throw the runtime exception directly? What does the method provide?
Comment: @AndyTurner yessiree!
Comment: @AndyTurner fixed my exception handling
Comment: @AndyTurner you code seems to have worked, all exceptions are gone, and it turns out using this method prevents me from needing to catch IOException and InteruptedException! thank you to all of you!


How to receive more data (greater than, >128) at once on ESP32 UART Rx PORT?

Question: I am Unable to receive more data, Only half of data is received on UART Port. What can I do to get full data ?
I tried changing H/W FIFo (in uart.h, espressif files) to full data length (256) from 128. It did not worked.
switch(event.type)
{
    case UART_DATA:

    ESP_LOGI(TAG, "Event DATA SIZE [UART DATA]: %d", event.size);
    uart_read_bytes(UART_NUM_2, UART_event_data, event.size, portMAX_DELAY);
    printf("Received data from QR Code is ........... %s\n", UART_event_data);
    break;
}

Expected Incoming data is of full length 256 B.
Comment: What version of the ESP-IDF are you using? And, what is the definition of UART_event_data and event.size?
Comment: Version is 4.0. UART_event_data is array which will have Incoming Data and event.size is size of event ( data in this case ).
Answer: From https://www.esp32.com/viewtopic.php?t=8858 : "The FIFO's size (in byte) can be set in UART_MEM_CONF_REG configuring bits 7 to bit 10. (ESP32 TRM V4.0, page 364)
This register is 0x88 by default: 128 Byte TX FIFO and 128 byte RX FIFO. So bit 7 = 1 sets 128 Byte TX FIFO size."
Furthermore the author states that changing the size is not trivial. Long story short: your best bet is mostlikely to work around this limitation by collecting the message from the FIFO in parts and put them in another buffer together. Alternatively you can hope that they implemented a way to change the FIFO length by now. Further research in the esp forum/doc might help.
Answer: Create a proper ISR and mark it IRAM_ATTR so that it's always in the cache.
In the ISR, copy the data from uart_read_bytes into a queue (xQueueSendFromISR) and don't do any other work, to keep the ISR small and fast.
Definitely don't call printf or log from an ISR. Create another (user) task and call xQueueReceive in a loop there, where you can print the data and do any other work.
Answer: Finally, I am going with reading single byte till the string (expected data) ends.
byte by byte.


all certs and provision work done, iTunes connect configured but still getting error

Question: wwdr cert
developer cert
distribution cert
developer provision
distribution provision
app id
devices
itunes connect
after all that i modified a bundle identifier in info.plist that i have in itunes connect
then archived project and through organizer i try to verify i am getting
No suitable application records were found.
Please make sure that you have set up a record for this application on iTunes Connect.
how to resolve this issue how to get exactly where the problem is?
i am using xcode 4.2 ios 5 os x lion.
Answer: Make sure the version is also set to the version number you have in iTunes Connect
Answer: When you say "iTunes Connect configured", what do you mean?
You need to have created an app, entered the description and it needs to be in the "Ready up upload" state. If it's not, Xcode won't see it.
Comment: The current status needs to be Ready for Upload. When you click on your Application in iTunes Connect, there should be a grey button on the top right which says Ready to Upload
Comment: current status = Prepare for Upload
Comment: 2 mins i am uploading the screenshots
Comment: sorry i m having prob uploading the image but there is no grey button which says ready to upload.....the top right blue button ready to upload binary
Comment: when i clicked on this button its a Export Compliance page and asking
Is your product designed to use cryptography or does it contain or incorporate cryptography? yes or no .........
Comment: So... you're not in the Ready to Upload state. You need to upload some images and press the "ready to upload" button before you can send your binary to Apple using Xcode.
Comment: "when i clicked on this button its a Export Compliance page" Yes. You need to answer these questions before you can upload. This is all covered in the iTC guide.
Comment: You need to upload some images?? i already uploaded the iTunes icon screen shots metadata etc...
Comment: The screenshots and icon are the images I was referring to.
Comment: now its talking about application loader ... whats this app? if its going to upload my app then why verify archive in organizer ... i am new to this process thats why asking many questions.
Comment: Application Loader is the old way. You can use Xcode. As noted above, this process is covered in the iTC guide.


In how many ways can we sign a checkerboard with the following conditions

Question: Say we have a checkerboard with 3 rows and 7 columns. In how many ways can we sign 6 squares on the board that every row will have 2 squared signed and every colums will have at most 1 square signed?
My calculation: $3*7 + 3*6 + 2*5 + 2*4 + 3 +2 = 62$
Can someone confirm or fix me if i'm wrong?
Thanks in advance!
Answer:
The problem can be reduced to counting the way to arrange the seven polyominos.
The six containing signed squares can be arranged in $6!$ ways, but for each arrangement $8$ are identical in appearance, so there are actually only $6!\div8=90$ distinguishable arrangements of the six.
The blank polyomino can occupy $7$ positions for each arrangement of the $6$ for a total of $90\times7=630$ arrangements.
Answer: Well, for every row we have two signed squares, for the first row we have $21$ way to do that.
The first signed square is in the first column and the second could be on all remaining $6$ or the first signed square is in the second column and the second could be on all remaining $5$ and so on, so we've got $6+5+4+3+2+1=21$.
For the second row we have also $21$ (the same argument as row $1$ apply) but now we have a pair above (in row $1$ ) the we cant be in same column as above row, so when our signed square is in the same column as the signed square above we lose $6$ places from the $21$ and when we are in the same column as the other signed square we lose another $6$ but we gain $1$ were the two signed squares in the second row are in the same column as the first row because we counted it twice, thus leaving us with $10$ possible arrangements.
For the third row we have also $21$ (the same argument as row $1$ apply) and we lose 4-times $6$ (the same argument as row $2$ apply but now we have to deal with 4 previous signed square rather than $2$ and we gain $6$ because there are 4 signed square and there is 6 possible colliding pairs),thus leaving us with $3$ possible arrangements.
So in total there is $21*10*3 = 630$ valid arrangements.
Note :
1 0 1 0 0 0 0
1 0 0 0 0 0 0
0 0 0 0 0 0 0
Here for example, i have to signed square in the same column, so it doesn't matter where will i put the fourth signed square, it will always be invalid and thus losing $6$ positions in the second row,(this what i was talking about in the answer in case if you did not fully understand the words).
also i checked it with computer program and it printed $630$ valid cases.
hope its what you are looking for.


How do I diagnose guitar effects pedal problems?

Question: At the last two performances, I've started hearing loud random pops when the stage gets warm and I'm running my signal chain.
I've swapped out pedals and changed cables and it appears to only occur when I'm using a GK MK amp and one particular pedal, an EHX C9.  How do I diagnose the popping?  It's not easily repeatable and appears to go away when I change the setup only to return again.
Is it in the amp and the pedal is causing the problem to reveal itself or is it in the pedal?  What could cause the pops?  A bad capacitor?
Comment: Narrowing it down to one pedal and one amp is a good start. If you are reasonably sure it is temperature-dependent, a hair dryer is a good tool for doing some controlled experiments. With a reasonable amount of common sense, you won't fry anything permanently. But the cause is often mechanical rather than electronic, for example a poor connection somewhere in the signal chain, which may inside the pedal or amp rather than a fault with the leads.  One of the pedal controls might have a "noisy" contact that only shows up over one part of its range, for example.
Comment: I've had this. Popping can be caused by, a bad capacitor within the guitar, bad earthing on the guitar and the strings get too static, faulty pedal and the most common cause of popping is old valves within your amplifier. If your amp has valves just look at them and if one valve is glowing where it shouldn't be then replace it. I've had the same problem on a Warwick bass with a push pull mod that coil-split the pickups which would also make bopping noises. Other than that the only other thing I that I can think of is if you have active pickups and need to replace a battery. Good luck :)
Comment: "mechanical" can also mean vibration. You might try turning the amp on in a darkened room and rap it with a rubber mallet (etc) and look for arcing. Arcing usually will increase the air gap (by vaporizing metal) and lead to more arcing more often. The "warm stage" may mean expanding metal connections, which lead to air gaps.
Answer: When I have this sort of problem, I open up each component individually, inspect the circuit board or hand wiring with a magnifying glass, looking for defective solder connections, broken circuit board traces, and dirt. I repair anything I find to be defective, and clean up the dirt. I swab the input and output jacks with a q-tip and solvent and usually find a surprising amount of dirt and corrosion there. Next I check connecting cables and often find they need replacement. These things take a lot of abuse and poor quality cables cease to function well rather quickly.
If the problem persists, then I set up my workbench to do a signal trace. I put a signal generator into the input of the component and using the probe on my oscilloscope, I can monitor circuit function through each step. When I find the problem circuit, then I can test the individual components,(capacitors, resistors, solid state devices, tubes, etc.) at this point the problem has always revealed itself and I can make the repair.
I should mention that I rarely have to do a signal trace because the problem is usually fixed when I perform the tasks in  the first paragraph.


Responsibility between script and host application

Question: I've been trying to decide how to embed Lua into my application for scripting and extension purposes.
I have a class which handles objects that have structures which resemble Lua tables. (specifically a hash map of boost::any)
Lua scripts would interact with these objects and their hash maps.
It is becoming clear to me that I could write the entirety or a large chunk of this class in Lua (and access it from C), but I am uncertain of the consequences of doing so, particularly memory usage with regard to creating the many tables to represent the hash maps.
The reason for coming to this conclusion is that I would like to store high-level structures from Lua in these C objects, but doing so would require an explicit table serialization every time a table is stored into or retrieved from a C object. Theoretically, this approach would offer less memory usage in a trade-off for higher latency per access.
What are the possible courses of action in this situation and their advantages and disadvantages?
Comment: What would be the advantage of using Lua vs the current implementation that you have in plain C? What does "storing high level structures from Lua" mean in your context?
Comment: To store tables as-is from Lua into C, most likely representing arrays, and in the rare case, hash maps.  Currently, storing any trivial POD type is simple, such as Lua's number, boolean, nil, string.  As I said earlier, storing non-trivial datatypes such as tables would require an explicit serialization to and from C.  The advantage of using Lua versus the current implementation would be that most of these operations would be internal; Lua would handle all the storage of variables at run-time.  The only time an explicit table serialization would be necessary is if C requires one.
Answer: I eventually decided to settle on programming the majority of my application in Lua using LuaJIT, for a number of reasons, including:

What I was trying to achieve through C/C++ is already there in Lua, the hash tables and metafacilities specifically, and I was basically re-inventing the wheel.
I did some simplistic benchmarking and discovered that most of my scripts would invariably end up bouncing calls to C and back to Lua very frequently, and that I could optimize away a lot of this by keeping the runtime focus limited to Lua by leveraging the bytecode compiler.
From my limited experience and research on topics surrounding Just-in-Time compilation, LuaJIT (2.0.0-beta8) proves to be quite fast enough for my needs at this point and very possibly near to C++ levels of memory usage for similar data structures.
LuaJIT also works excellently as a drop-in replacement for vanilla Lua and is easy to build; all I had to do was link to its library to get it up and running.

I feel that I am losing a little of "power-user" control over my project by doing this, but I consider this to be due to my inexperience with the intricacies of Lua versus my knowledge of C++.
Answer: If I have understood your issue correctly, you want to use Lua simply to avoid having to serialize data (to and from a file, I presume). If this is the case, you can use Lua for that, but it seems a bit overkill to me.
Answering your last question, Lua will take more memory than the native C, and will run slower (the Lua VM is slower than native C, and even if you use just C to manipulate the "jumping" from Lua to C and viceversa will have a penalty in the form of lots of pushing and popping in/from the Lua stack).
If you want to have an easier time serializing, probably it'll be better to use a library that serializes to/from C directly. For example, json.
Comment: To reiterate, what I originally wanted to do is have data in C be manipulated by scripts in Lua, functions and all. The conundrum is that I desire to flatly store (serialize) tables in C, without them being referenced somewhere in the Lua registry or such. This is what drove me to wonder if it would be better to write this class in Lua itself. There is no file serialization here, though I know json is good for that. I did some simplistic memory benchmarks for creating a few hundred thousand tables which made me believe that Lua's tables might be a bit bloated.


Função não funciona em todos os casos de teste

Question: Preciso fazer uma função pra verificar se uma matriz é quadrada:
    def eh_quadrada(matriz):
        '''Função que verifica se uma matriz é quadrada.
        list->bool'''
        if len(matriz)==len(matriz[0]):
            return True

        else:
            return False

Esse código só não funciona quando a matriz de entrada é vazia: [[]].
O que eu poderia fazer quando a entrada fosse uma matriz vazia, para esse código funcionar?
Answer: Primeiramente, [[]] não é vazia: isso é uma lista que possui um elemento (e esse elemento é uma lista vazia).
Então basta verificar essa condição, ou seja, o tamanho da matriz é 1 e o tamanho do primeiro elemento é zero.
Outro detalhe é que não adianta verificar somente a primeira linha da matriz. Pois se eu tiver algo assim:
matriz = [
  [1, 2],
  [3]
]

Sua função vai retornar True, pois você não está verificando da segunda linha em diante. Para ter certeza que a matriz é quadrada você precisa verificar todas as linhas:
def eh_quadrada(matriz):
    # caso especial de matriz "vazia"
    if len(matriz) == 1 and len(matriz[0]) == 0:
        return True
    # todas as linhas devem ter o mesmo tamanho da matriz
    return all(len(matriz) == len(linha) for linha in matriz)

all verifica se todos os elementos satisfazem a condição (que no caso, é ter o mesmo tamanho da matriz). Se algum deles tiver tamanho diferente, retorna False.
Comment: @LuizFelipe É uma [*generator expression*](https://docs.python.org/3/reference/expressions.html#generator-expressions) - é similar a list comprehension (leia o link, que já explica tudo) :-)
Comment: @LuizFelipe Relacionado ao assunto: https://pt.stackoverflow.com/a/193625/112052
Comment: Meio _off_, mas vou perguntar mesmo. :D O que você passou para `all`? É tipo uma _list comprehension_ implícita? É a primeira vez que vi isso. Sei que `all` espera um _iterable_, aí o Python consegue entender que aquilo é, de fato, um _iterable_?


Como inserir um elemento entre dois elementos?

Question: Explicação:
Tenho uma
 pai que contém duas
 filhas, porém eu gostaria de inserir uma
 utilizando javascript, entre, ou seja, no meio dessas duas
 filhas que já existem na
 pai.
Porém a minha
 é uma string que contem o código HTML como valor.
Código da minha
 como string:
var HTMLString = '

Código	 Nome	Cidade - Estado

';

HTML da div pai e das div filhas:

conteudo

conteudo

Exemplo no JSFiddle
Pergunta:
Como eu poderia fazer isto? Gostaria de várias soluções, citando as vantagens e desvantagens das mesmas, podendo utilizar do jQuery ou não
Comment: Tem a tag jQuery... é isso mesmo ou é pra fazer em JS puro?
Comment: pode ser em jQuery também, porém é necessário ? é mais rápido ? qual a utilidade de usar jQuery neste contexto? fica ao seu critério porem eu aceito
Comment: Uma vantagem do jQuery, considerando as respostas, é uma linha de código para quatro com JS puro.
Comment: @PauloRoberto, Javascript é sempre mais rápido que jQuery, pode porem ser mais simples pôr a funcionar em Browsers diferentes com jQuery
Comment: jQuery é javascript, não outra linguagem. A coisa tá tão feia que já vi navegador com jQuery pré-carregado, pra sair mais rápido.
Answer: Em JavaScript puro você pode fazer assim:
var HTMLString = '

Código	 Nome	Cidade - Estado

';

var ref = document.getElementById('pnlOpcoes_outer');
var div = document.createElement('div');
div.innerHTML = HTMLString;
ref.parentElement.insertBefore(div.firstChild, ref);

Demo no jsfiddle
Isto funciona neste caso porque o seu HTMLString só contém um element solto na raiz. Uma opção mais genérica:
var ref = document.getElementById('pnlOpcoes_outer');
var div = document.createElement('div');
div.innerHTML = HTMLString;
while(div.firstChild) {
    ref.parentElement.insertBefore(div.firstChild, ref);
}

Demo no jsfiddle
Tem também uma opção meio obscura, mas compatível até com browsers bem antigos, utilizando Element.insertAdjacentHTML (dica do Emerson Rocha Luiz):
var ref = document.getElementById('pnlOpcoes_outer');
ref.insertAdjacentHTML("beforebegin", HTMLString);

Demo no jsfiddle
Answer: Pega a primeira div e insere depois dela:
$('#fixedHeader_outer').after(HTMLString);

Quero participar do codegolf: se não quiser usar jQuery há essa opção, tão curta quanto a original:
fixedHeader_outer.outerHTML += HTMLString;

Como foi pedido, a tabela de compatibilidade.
Comment: A resposta é a mesma: isso é muito trivial. Tipo, muito.
Comment: Ganhou por 7 segundos...
Comment: Não se sinta morto @utluiz estou ancioso para ver a sua resposta =p
Comment: @PauloRoberto Estou me referindo ao Miguel... acho que nesse caso não tenho nada a acrescentar, considerando a resposta do bfavaretto
Comment: ah sim, agora entendi. :)
Comment: Dúvida: já tem três respostas, pela tag o OP pediu jQuery mas todo mundo quer inovar. Edito minha resposta para participar desse codegolf? Nada tão simples quanto `fixedHeader_outer.outerHTML += HTMLString;`
Comment: sim com certeza @GustavoRodrigues eu justamente quero é isto, várias soluções, mais tarde irei colocar todas no jsperf e ver qual a mais rapida =p
Comment: Poderia editar a resposta com a compatibilidade do método utilizando `.outerHTML`? gostaria de saber se este método é compativel com todos os navegadores utilizados atualmente
Answer: Pelas tags pressuponho que vocês está utilizando jQuery. Então aqui está a solução:
$('#fixedHeader_outer').after(HTMLString);

Se você não estiver usando jQuery, ficaria assim:
var referenceNode = document.getElementById('fixedHeader_outer');
var newNode = document.createElement('table');
newNode.innerHTML = '

Código	 Nome	Cidade - Estado

';

referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);


printf only prints characters up to stdout's buffer size

Question: I'm trying to use newlib's printf function to print something on a UART device. Therefor I implemented
int _write(int file, char *ptr, int len) {
  HAL_StatusTypeDef status;

  switch (file) {
  case STDOUT_FILENO: /*stdout*/
  case STDERR_FILENO: /* stderr */
    while ((status = HAL_UART_Transmit_IT(&UART_Uart2Handle, ptr, len)) == HAL_BUSY) {}

    if (status != HAL_ERROR) {
      errno = EBADF;
      return -1;
    }
    break;
  default:
    errno = EBADF;
    return -1;
  }
  return len;
}

Printing works fine until the buffer of stdout is filled, e.g. if I try
setvbuf(stdout, NULL, _IOFBF, 3);
printf("Hello World!\n");
fflush(stdout); // Just to be sure ;)

I only receive a 'Hel' on the device. A similar behaviour is observed with _IONBF or _IOLBF. When I set a breakpoint on _write in the debugger I gets called only once for the content of one buffer size.
Any ideas or hints why _write does not get called more often?
Comment: Useful? [HAL_UART_Transmit_IT: only a few bytes are sent](http://stackoverflow.com/q/33429920/2410359)
Comment: It appears `HAL_UART_Transmit_IT()` does not report how many characters were transmitted so try 1 at a time.  Instead repeatable try to send 1 character when result is `HAL_BUSY`, else then move on to the next character.
Comment: I see the same behaviour if I use HAL_UART_Transmit instead and also when transmitting one character at a time. Problem seems to be that _write only gets called once.
Answer: The problem was that _write always returned -1 as HAL_UART_Transmit_IT returns HAL_OK when everything went fine, so
if (status != HAL_ERROR) {
      errno = EBADF;
      return -1;
}

was always executed. The check needs to be changed to status != HAL_OK.


Openlayers 6 marker popup without nodejs?

Question: I'm a newbie with openlayers and a bit confused on their nodejs style, for my reasons I can't use nodejs and I'm struggling on how to find some good documentation for achieving my goal without the use of NodejS, basically I need to click on a marker and get a popup related to the marker to appear for showing some info about that marker like city name and population number, all those info are given to me by a jSon received from the server. This is my Javascript script and the small portion of Html, can anyone please explain me ho to achieve this with an example?
HTML

JAVASCRIPT

    @Scripts.Render("~/Scripts/jquery-3.3.1.js");

The above code is working very well as I'm able to display markers correctly on the map.
Comment: Take at look at the OpenLayers 4 examples for full build syntax
https://openlayers.org/en/v4.6.5/examples/icon.html  https://openlayers.org/en/v4.6.5/examples/overlay.html  https://openlayers.org/en/v4.6.5/examples/popup.html
Comment: Are you looking for something like this: http://www.geocodezip.com/OL_6.3.0_simpleMultipleMarkerExample.html
Comment: @geocodezip yep! really nice and clean solution, thanks a lot! If you also have an example on ho to add a picture inside the popup from an url that would bee veeeery sweet. Ps. If you answer I'll set it as correct solution.
Answer: Below is a code snippet that creates a popup (InfoWindow) for markers, displaying the name property of the feature.
working example
The code that creates the popup and opens it:
/**
 * Elements that make up the popup.
 */
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');

/**
 * Add a click handler to hide the popup.
 * @return {boolean} Don't follow the href.
 */
closer.onclick = function() {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

/**
 * Create an overlay to anchor the popup to the map.
 */
var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});

/**
* Add a click handler to the map to render the popup.
*/
map.on('singleclick', function(evt) {
  var name = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
    return feature.get('name');
  })
  if (name) {
    container.style.display="block";
    var coordinate = evt.coordinate;
    content.innerHTML = name;
    overlay.setPosition(coordinate);
  } else {
    container.style.display="none";
  }
});

Based on the following example:

Popup

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, "green"],
  ['Coogee Beach', -33.923036, 151.259052, "blue"],
  ['Cronulla Beach', -34.028249, 151.157507, "yellow"],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, "purple"],
  ['Maroubra Beach', -33.950198, 151.259302, "red"]
];

/**
 * Elements that make up the popup.
 */
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');

/**
 * Add a click handler to hide the popup.
 * @return {boolean} Don't follow the href.
 */
closer.onclick = function() {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

/**
 * Create an overlay to anchor the popup to the map.
 */
var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250
  }
});

var features = [];
for (var i = 0; i < locations.length; i++) {
  features.push(coloredSvgMarker([locations[i][2], locations[i][1]], locations[i][0], locations[i][3]));
}

var vectorSource = new ol.source.Vector({ // VectorSource({
  features: features
});

var vectorLayer = new ol.layer.Vector({ // VectorLayer({
  source: vectorSource
});

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({ // TileLayer({
      source: new ol.source.OSM()
    }), vectorLayer
  ],
  overlays: [overlay],
  target: 'map',
  view: new ol.View({
    center: ol.proj.fromLonLat([-0.12755, 51.507222]),
    zoom: 10
  })
});

// make the map's view to zoom and pan enough to display all the points
map.getView().fit(vectorSource.getExtent(), map.getSize());

/**
 * Add a click handler to the map to render the popup.
 */
map.on('singleclick', function(evt) {
  var name = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
    return feature.get('name');
  })
  if (name) {
    container.style.display = "block";
    var coordinate = evt.coordinate;
    content.innerHTML = name;
    overlay.setPosition(coordinate);
  } else {
    container.style.display = "none";
  }
});
map.on('pointermove', function(evt) {
  map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel) ? 'pointer' : '';
});

function coloredSvgMarker(lonLat, name, color, circleFill) {
  if (!color) color = 'red';
  if (!circleFill) circleFill = 'white';
  var feature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat(lonLat)),
    name: name
  });
  var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 30 30" enable-background="new 0 0 30 30" xml:space="preserve">' +
    '<path fill="' + color + '" d="M22.906,10.438c0,4.367-6.281,14.312-7.906,17.031c-1.719-2.75-7.906-12.665-7.906-17.031S10.634,2.531,15,2.531S22.906,6.071,22.906,10.438z"/>' +
    '<circle fill="' + circleFill + '" cx="15" cy="10.677" r="3.291"/></svg>';

  feature.setStyle(
    new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [0.5, 1.0],
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        src: 'data:image/svg+xml,' + escape(svg),
        scale: 2,
        imgSize: [30, 30],
      })
    })
  );
  return feature;
}
html,
body {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.map {
  height: 100%;
  width: 100%;
}

.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 80px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: "x";
}
<link rel="stylesheet" href="https://openlayers.org/en/v6.3.0/css/ol.css" type="text/css">


Can a power series of $x$ converge to $\log(x)$?

Question: I found the following equation, to solve for $\{c_k\}$, with $0<x<1$:
$$ \sum_{k=0}^{\infty} c_k x^k = \log x $$
I know that $\log x$ does not have a Taylor series expansion around $x=0$.
Does this mean that no $\{c_k\}$ can be found such that the equality holds?
Note that the equality is not required to hold for $x=0$, where $\log x$ is not defined.
Answer:
Does this mean that no $\{c_k\}$ can be found such that the equality holds?

Exactly.  If it would hold for some $x \neq 0$, then it would also hold for any $z$ with $|z| < |x|$.  As it is a power series, this would mean that $\ln$ is analytic on the disc $|z|<|x|$ which is not the case because $\ln x$ has a singularity at $x=0$.  Not even a radius of convergence of $0$ would work because $\ln 0$ is not defined.
And not even a Laurent series does work, because if such a series converged on some annulus around $0$, it would be analytic there.  But you would hit a branch cut somewhere.
Comment: For a proof of "converge for some $x\neq 0$, also converges $\forall z$ with $|z|<|x|$" see the proof of Note 10.1.1 in [this link](https://math.libretexts.org/Bookshelves/Calculus/Book%3A_Calculus_(OpenStax)/10%3A_Power_Series/10.1%3A_Power_Series_and_Functions). This bit is exactly what I was looking for. Thanks!


MAX number from an inventory stock

Question: My database has these tables:

Productos
Productos_Presentaciones

This is an inventory and I want to know from all the products (productos), which one has more stock. So this is the last thing I could think of:
SELECT MAX(pp.Existencias), p.Nombre as PRODUCTO FROM Productos_Presentaciones pp
full join Productos p on pp.Id_Producto = p.Id_Producto
group by p.Nombre;

And this is the result:

I just need to be shown a single result. In this case, the #9 from the image shown:
PRODUCTO                        EXISTENCIA
Carne de cangrejo de Boston        123

Which is the product with the most available stock.
Answer: You can use Order by clause and limit for getting just one row
SELECT MAX(pp.Existencias) AS pex, p.Nombre as PRODUCTO FROM Productos_Presentaciones pp
FULL JOIN Productos p on pp.Id_Producto = p.Id_Producto
GROUP BY p.Nombre ORDER BY pex DESC LIMIT 1;

Comment: It worked! I just had to do some research, because I'm using MSSQL and it doesn't support LIMIT, so I removed it and added SELECT TOP 1 at the beginning. I appreciate your help!
Comment: I thought MySQL is your DB.

MAX number from an inventory stock


Why does my trait definition compile with the 2015 edition but not with the 2018 edition?

Question: I wrote this simple program:
trait Command<T> {
    fn execute(&self, &mut T);
}

fn main() {
    let x = 0;
}

I compiled this with rustc --edition=2018 main.rs and get the error message:
error: expected one of `:` or `@`, found `)`
 --> main.rs:2:29
  |
2 |     fn execute(&self, &mut T);
  |                             ^ expected one of `:` or `@` here

Compiling via rustc --edition=2015 main.rs or rustc main.rs doesn't cause this error, although there are some warnings.
What's the problem with this code?
Answer: Anonymous trait parameters have been removed in 2018 edition: No more anonymous trait parameters.
Add _: before &mut T if you want to ignore the parameter:
trait Command<T> {
    fn execute(&self, _: &mut T);
}

Compiling with rustc main.rs works, because it defaults to --edition=2015.

Indeed, if you put your main.rs in a new Cargo project, then remove edition = "2018" from Cargo.toml, and run
cargo fix --edition

then Cargo will add the missing _: automatically. See Transitioning an existing project to a new edition.


Why I cant programmatically change the width of UITextField?

Question: I am trying to programmatically change the width of a UITextField using the following code:
<code>myText.frame = CGRectMake(myText.frame.origin.x, myText.frame.origin.y, 280 ,myText.frame.size.height);
</code>
The code above is executed on a "touch up inside" button action.
myText has its border style property set to UITextBorderStyleNone
Any ideas are welcome!
Comment: First of all : are you sure that 280 isn't your default width ? It might happen ! Else, do you have auto layout enabled maybe ? Some constraints might generate troubles with frames.
Answer: if you are trying to set frame programmatically just disable the autolayout for your .xib
Comment: Autolayout was the problem. Is there a way to have both (autolayout and the abillity to set gram in code)?
Answer: My first thought is that either you never linked the IBAction to the UIButton, or there is no IBOutlet pointing to the UITextField.
You can verify that the IBAction is getting called on button press simply by adding an NSLog statement to it, or you can check that both are linked from the "Connections Inspector" in Interface Builder.
Side note Since your text field is set to have no border, it is possible that you just can't tell it is growing. To verify, I would trying setting the text field's background color to something obvious.


Mvc 4 customize routes

Question: I have a website that any user can have few companies.
I want to make custom rote where the company will be part of the route:
~/{CompanyName}/{Controller}/{Action}/Id

Can I do it? how?
Thanks for the answers
Comment: http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs
Answer: You can define a route
routes.MapRoute(
  name: "CompanyRoute",
  url: "{companyName}/{controller}/{action}/{id}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional}
);

Then define your action methods with a companyName parameter
public ActionResult Index(string companyName)
{
  ....

public ActionResult Details(string companyName, int ID)
{
  ....

so /Acme/Home/Details/4 would call the Details method, passing "Acme" and 4

Mvc 4 customize routes


Passing a local variable from one function to another

Question: I am a beginner in JavaScript and wanted to ask the following: I have two simple functions and was wondering if there is any way to pass a variable value from one function to another. I know I can just move it outside the function to be used in other functions as well but just need to know the way how I can have one local variable and manipulate with it in my second function. Is this possible and how?
Here is some code:
window.onload = function show(){
    var x = 3;
}

function trig(){
    alert(x);
}
trig();

The question is: how do I access variable x (declared in the function show) from my second function trig?
Comment: A straighforward way is to use the window object. Wherever you are inside your function use: `window.var1=42;` (var1 is your variable and 42 is your value. You can retrieve this variable from any other functions in your program. Easy !
Comment: It's not very clear what you're asking... are you calling one function from within the other? Post some example code.
Comment: dont forget to mark answer as accepted if you got the info you want...
Answer: First way is
function function1()
{
  var variable1=12;
  function2(variable1);
}

function function2(val)
{
  var variableOfFunction1 = val;

// Then you will have to use this function for the variable1 so it doesn't really help much unless that's what you want to do.
    }
Second way is
var globalVariable;
function function1()
{
  globalVariable=12;
  function2();
}

function function2()
{
  var local = globalVariable;
}

Comment: @user2585548 The first one does exactly what the question asks. It creates a local variable and passes its value to another function. The second function creates a global variable and sets a value in the first function. When the second function is called from the first function, a local variable is declared using the value of the global variable (set in the first function).
Comment: i used the second way and it worked. I dont come to this site just to "borrow" code. i like to understand exactly what occurs so i can see where the fallacy in my logic was. if anyone can explain further please do. In the second way, what i am seeing is a global variable being declared, a function that assigns that global variable a value of 12 and then a function being called within a function to concatenate the 2 functions together. then a function that is able to store the global variables value into a local variable. is that right??
Answer: Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
    var x = 15;
    return x;
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue();

Comment: Thank you. I followed this method. And it worked well for me.
Answer: You can very easily use this to re-use the value of the variable in another function.
// Use this in source
window.var1=  oEvent.getSource().getBindingContext();

// Get value of var1 in destination
var var2=  window.var1;


Organização de arquivos em PHP

Question: Tenho a seguinte estrutura de pastas.
   classificados
   index.php
   login.php
     -->config
          -->conecta.php
     -->funcoes
          -->banco-usuario.php
     -->headers
          -->cabecalho.php
          -->menu.php
          -->rodape.php
     -->front
          -->painel.php
          -->outrasPaginas.php

Se eu incluir no arquivo painel.php o codigo assimrequire_once("../headers/cabecalho.php"); vai da erro sempre, pois o arquivo cabecalho.php que esta na pasta headers, chama o arquivo menu, então o arquivo painel.php não encontra o menu, queria fazer isso da forma correta, como eu faço isso?
Alguém pode me ajudar?
Comment: use o caminho absoluto, evite voltar
var/www/html/headers/menu.php
não é melhor forma de fazer isso, use alguma Fw que cuide desses detalhes para você
Comment: Usar um framework, adotar arquitetura XYZ... muitas vezes não precisamos disso. Para fins de aprendizado acho super válido o caminho das pedras.
Comment: Já pensou em MVC?
Comment: Já guilherme, mas ainda não aprendi, então estou fazendo como dá hehehe
Answer: Uma forma de trabalhar com os caminhos é definir antes dos seus require uma constante com o caminho para o diretório raiz do seu projeto. A partir dai você não precisa se preocupar aonde seu script está.
<?php

define('ROOT_PATH', '../'); // para os arquivos em um nível em relação a raiz
                            // para subpastas adicione alguns '../' extras

require ROOT_PATH . 'config/conecta.php';
require ROOT_PATH . 'headers/cabecalho.php';

Lembre-se que o require depende da localização do arquivo atual. Se você está no arquivo cabecalho.php, sabendo que ambos estão no mesmo diretório, você pode usar o caminho relativo entre os arquivos:
Arquivo headers/cabecalho.php
<?

define('ROOT_PATH', '../');

require 'menu.php'; // Irá incluir o arquivo headers/menu.php

require ROOT_PATH . 'headers/rodape.php'; // Irá incluir o arquivo headers/rodape.php
                                          // Porém antes ele irá subir um diretório e
                                          // voltar para headers em seguida
                                          // 'headers/../headers/rodape.php'

Organização de arquivos em PHP


what is the best way to show settingoptions in fragment

Question: I have a fragment where the user need to add data that wil be saved.
But there is a switch where the user can choise if he want to add info.
If he wants to, it need to add some Edittext fields in de fragment.
Otherwhise it doesn't need to show those fields.

What is the best way to do this properly?
Comment: If you are using a [`PreferenceFragment`](https://developer.android.com/reference/android/preference/PreferenceFragment.html), you are looking for [android:dependency](https://developer.android.com/reference/android/preference/Preference.html#attr_android:dependency)
Answer: Add this EditText in your XML but set their visibility to gone and then when the user clicked on switch just visible the items
Answer: When the add "info button" is toggled to show the info buttons, set the visibility property on the "Add info A/B here" TextViews to Visible.  When the "info button" is toggled to not show the info buttons, set the visibility to Gone.
<code>myTextView.setVisibility(View.GONE);
myTextView.setVisibility(View.VISIBLE);
</code>


Vertical Scalability with multiple app pools

Question: We are running a ASP.Net application that is also calling some legacy  COM objects.  We are running into an issue where with increased number of users COM object is creating a bottle neck since it is executing on same thread/process as the app pool.
We currently have a hardware load balancer in place and use sticky sessions to balance the load between 2 servers.  Unfortunately this does not seem to be enough.  We did some testing using multiple app pools, each running same application, and performance seems to improve significantly.
I have couple of questions.

Is it wise to add multiple app pools, all pointing to the same physical files?
We would still use hardware load balancer.  All requests comming to app.xxxxxx.com would get redirected to for example app1.xxxxxx.com, app2.xxxxxx.com, app3.xxxxxx.com, app4.xxxxxx.com .  Each one being an app pool on the same server.  Is this a common practice?
Server has 16 cores.  Would setting processor affinity make sense, to dedicate each app pool to run on 4 cores?
We are stuck using InProc sessions.  Because of this we are not even considering using Web Garden.  Plus from what I read Web Garden is more for improving availability than performance.

I am a developer by trade and it fell on me to research/perform these tasks and a lot of this has been a learning process for me.
Thanks
Answer: You have a fairly unique situation where COM becomes a bottleneck so that you can't simply scale up.  Ideally improving performance with the COM objects or replacing them with managed code would scale even better, but you're on the right track for a COM performance workaround.

IIS is able to handle hundreds of app pools, so that's not a problem.  It will add a few MB of RAM with each app pool but no extra performance overhead.
Sure.  By app pool, I assume that each is a full site with its own app pool.  That's all good.
If you don't have to, don't change the processor affinity because it means that you need to maintain and tweak it forever.  If the CPU utilization is pretty flat, then you're good with the defaults.  If you have other applications on the server or if you see a big imbalance, then consider processor affinity.  IIS does a good job of utilizing them for the most part though, so it's best to let it do the heavy work if possible.
As you say, sticky sessions addresses that, so you're good.  Web gardens may have solved your COM issues if you didn't have InProc session state to worry about.  As a side, you can consider using ASP.NET's state server.  Have each server use the local state server and have the load balancer use sticky sessions with 1 binding per server.  That would address session state (as long as everything serializes, which it usually does) and it will allow you to easily play with the web garden settings without having to mess with the load balancer.
Comment: Thanks.  We are planning to rewrite COM object but the estimate is up to 6 months to do it.  Hopefully implementing this will at least help us out until we rewrite it.


Will Google Chrome Frame be Installable on Locked down Windows Machines?

Question: Does anyone know if Google Chrome Frame will be installable onWindows machines in the dreaded Corporate IT World where machines are locked down with a Khaki Fist?
I suppose that's really two questions

Can Windows be locked down to prevent IE from installing plug-ins?
Is Google being clever and finding a way around this? (i.e., is the Google Chrome Frame install process somehow working around these restrictions)

(this is borderline Server Fault, but as it involves a programming run time and I'm interested in this from a programmers perspective, I ask here)
Comment: interested in this too. Unless it can be installed on PCs behind corporate firewalls I just cannot see the point of it at all.
Comment: Well, it gives corps the option.  They may have an "IE 6" only policy that can't bend, but a more flexible plug-in policy, and it looks like GCF features are off by default unless you include a special meta-tag on your page.
Answer: It will very much depend on the network in question and how draconian (i.e. sensible) they are being with Internet Explorer.  IEs plugins have often been a source of major security flaws in the browser so a lot of networks do restrict the ability to install plugins.
When I worked in a large secondary school as an IT technician (equivalent to a High School) we had things locked down pretty tightly.  If we needed to install updated versions of Flash or similar we had to go round logging in as Administrators (thankfully we had remote management software to allow partial automation of this) to do it because ordinary users couldn't install plugins to IE.
I would think most corporate networks would restrict the ability to install plugins similarily.
With regards to part 2 of your question no Google are not since they can't, they're basically providing a plugin that basically lets the Chrome rendering and Javascript engine run inside IE.  This allows them to use standards compliant HTML5 which IE is very behind on implementing and has only as of a couple of weeks ago actually committed to implementing some of the key multimedia features of the specification which are needed for things like Google Wave and future web apps.
See http://arstechnica.com/microsoft/news/2009/09/ie-program-manager-endorses-html-5-multimedia-tags.ars
Comment: +1 for good info, but I think you misunderstood #2 (have clarified).  I was asking if the Google Chrome Frame install process somehow worked around standard browser security setting.  Unlikely, but certainly possible.
Comment: No I don't think it can because it is a full blown plugin and I think it unlikely that Google of all people would attempt to circumvent security


Absolute continuity of induced measures

Question: Let $g : [a,b] \rightarrow \mathbb{C}$ be of bounded variation and let $1_A$ denote the indicator function of $A$ for measurable subsets of $[a,b]$.
We put
$$m_g(A) := \int 1_A dg,$$
i. e. $m_g(A)$ is the Lebesgue-Stieltjes integral of $1_A$ with respect to $g$. Then $m_g$ is a Borel measure on $[a,b]$.
I know that if $g$ is differentiable, then $m_g$ is absolutely continuous (=dominated by Lebesgue measure).
Now I wonder if this is always true? If not, what are conditions on $g$ that ensure that $m_g$ is absolutelly continuous?
Note: This is not a homework but I'm just interested and I am a little bit rusty on measure theory. Any reference or hint is welcome.
Answer: Lat $a<c<b$. If $g(x)=0$ for $x <c$ and $1$ for $x \geq c$ then $g$ is of bounded variation and $m_g$ is the delta measure at $c$. [This means $m_g(A)=1$ if $c \in A$ and $0$ otherwise].  This measure is singular w.r.t. Lebesgue measure. A sufficient condition  for absolute continuity is $g$ continuously differentiable, as you have observed.
A necessary and sufficient condition is the so-called absolute continuity of the function $g$: For every $\epsilon >0$ there exists $\delta >0$ such that for any finite disjoint collection $(a_i,b_i):  1\leq i \leq n$ of intervals with $\sum (b_i-a_i) <\delta $ we have $\sum |g(b_i)-g(a_i)| <\epsilon$.
Comment: Thanks for your answer. Do you know of any weaker conditions on $g$? Is maybe continuity sufficient?
Comment: @BrunoKrams Continuity is not sufficient.

Absolute continuity of induced measures


Let $G$ act smoothly on $M$, $(g,m) \rightarrow t_g (m) $ from the left. Why is $t_g \simeq id $ if $G$ connected?

Question: Let $G$ act smoothly on $M$, $(g,m) \rightarrow t_g (m) $ from the left. Why is $t_g \simeq id $ if $G$ connected? I've seen this statement, but have no idea how to use connectedness here. Does anyone has hints?
Comment: Please repeat the question in the body of your post. For those of us who read MSE on mobile devices, the TeX codes in the title are not translated into mathematical notation, but those in the body are.
Comment: Also, by $t_g\cong id$, do you mean that $t_g$ is homotopic to the identity? The symbol for that is $\simeq$ (`\simeq`), not $\cong$.
Comment: Yeah, indeed, I meant that $t_g $ is homotopic to the identity, thanks for that correction.
Answer: $G$ is connected implies it is connected by arcs, you have a path $c:[0,1]\rightarrow G$ such that $c(0)=e, c(1)=g$, you can define $H(t,x)=t_{c(t)}(x)$. $H(0,x)=t_{c(0)}x=x$ and $H(1,x)=t_{c(1)}x=t_g(x)$.
Comment: Because it is a manifold (I assume $G$ is a Lie group).
Comment: Why connectedness implies path connectedness here?
Comment: Thanks, I did not know that. Then, it is clear now.


How to fix the no dbm clone found error in pyinstaller

Question: I have made a GUI app which uses subliminal in it . Then i tried compiling the program using PyInstaller . When i run the exe, it gives me the following error :-
Traceback (most recent call last):
  File "main.py", line 375, in <module>
  File "main.py", line 144, in __init__
  File "site-packages\dogpile\cache\region.py", line 237, in configure
  File "site-packages\dogpile\cache\backends\file.py", line 158, in __init__
  File "site-packages\dogpile\cache\backends\file.py", line 182, in _init_dbm_file
  File "dbm\__init__.py", line 75, in open
ImportError: no dbm clone found; tried ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
Failed to execute script main

After this i tried explicitly importing dbm in my application as like :-
import dbm . But this also gives the same error.
Then I tried import dbm.gnu , dbm.ndbm , dbm.dumb .
This gives another error as shown below :-
Traceback (most recent call last):
  File "main.py", line 3, in <module>
  File "c:\program files\python35\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
    exec(bytecode, module.__dict__)
  File "userinterface.py", line 312, in <module>
  File "c:\program files\python35\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
    exec(bytecode, module.__dict__)
  File "main.py", line 9, in <module>
  File "c:\program files\python35\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
    exec(bytecode, module.__dict__)
  File "dbm\ndbm.py", line 3, in <module>
ImportError: No module named '_dbm'
Failed to execute script main

Some googling and i found that it uses _dbm package from dbm.gdbm . so instead of import dbm.gnu , dbm.ndbm , dbm.dumb , I used import dbm.dumb .
Surprisingly, doing this started my application . But the subliminal doesn't find any subtitle now. So it's total useless now .
What i am doing wrong . whats the right way to fix this problem. while compiling , i have also tried giving --hidden-import dbm with no luck.

Here is the command that i use to compile using pyinstaller :-
pyinstaller main.py --hidden-import dbm --hidden-import dogpile.cache.backends.file  --additional-hooks-dir=. --add-data guessit;guessit --add-data babelfish;babelfish -i vid2.ico -n Subtitler

I would be grateful for any clue or help :)
Answer: I found that , in _dbm package only works in UNIX like systems .
After some fiddling with it and finally fixed it .
In your main python file just use this import :-
import dbm.dump


Disable positive/negative button in DialogFragment

Question: I mimicked what I thought was fairly standard Dialog code:
public class DChooseSeparator extends DialogFragment
{
    // ...
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();

        builder
            .setTitle("My Title")
            .setView(myDialogLayout)
            .setPositiveButton(getString(R.string.sOKButton), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    if(myEditText.getText().toString().equals("")) // disable positive button if this is empty
                    {
                        Toast.makeText(getActivity(), "enter something!", Toast.LENGTH_SHORT).show();
                    }
                    else { myListener.onSet(myEditText.getText().toString()); }
                }
            })
            .setNegativeButton(getString(R.string.sCancelButton), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });

        return builder.create();
    }
}

And in onStart of the Fragment that shows it:
sepButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        MyDialog myDialog = new MyDialog();
        myDialog.show(getFragmentManager(), "tMyDialogTag");
        myDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);   // DOES NOT WORK
    }
}

However, this does not work, as the getButton function is not available for my DialogFragment. I can also not do this in the DialogFragment class, as I need to show() it first.
So...where exactly can/should I disable the Button? Do I really have to move the whole creation of the Dialog to the onClick method?
Thank you in advance for your help.
Answer: You can enable or disable the Button after the view of the FragmentDialog has been created. So you have to call it in the onStart() method of your Dialog.
See my code:
public class DChooseSeparator extends DialogFragment
{
    // MEMBER
    private AlertDialog dialog;
    private static boolean mEnableButton;

    // You need an empty constructor: "All subclasses of Fragment must include a public empty constructor. "
    // like it's described in the Fragment API -> so create a new Insatnce with this static methjod
    public static DChooseSeparator newInstance(boolean enableButton){
        mEnableButton = enableButton;
        return new DChooseSeparator();
    }
    // ...
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();

        builder
            .setTitle("My Title")
            .setView(myDialogLayout)
            .setPositiveButton(getString(R.string.sOKButton), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    if(myEditText.getText().toString().equals("")) // disable positive button if this is empty
                    {
                        Toast.makeText(getActivity(), "enter something!", Toast.LENGTH_SHORT).show();
                    }
                    else { myListener.onSet(myEditText.getText().toString()); }
                }
            })
            .setNegativeButton(getString(R.string.sCancelButton), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });

        dialog = builder.create()

        return dialog;
    }

    @Override
    public void onStart(){
        super.onStart();
        dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(mEnableButton);
    }
}

Now you can call your Dialog like this:
sepButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        MyDialog myDialog = new MyDialog(false);
        myDialog.show(getFragmentManager(), "tMyDialogTag");
    }
}

Comment: Thank you very much for you detailed answer and for taking the time to work that in the example! That did indeed work (though I thought I had tried this as well). I wonder...is this the recommended approach or are you supposed to create the code for the `Dialog` directly in the `Fragment`?
Answer: you need to call this after the view of the dialog has been created, in the oncreateview  function of the dialogfragment class
Comment: But then where do I put the show()? I had it in the `Fragment` that created the `Dialog` but now this doesn't work anymore if I want to do stuff in `onCreateView`.
Comment: keep it where it is, add a function to ur MyDialog class setOkEnabled(bool val), and then store this flag value somewhere and then override the oncreateview, if the flag is false disable the ok button
Comment: Alright, I have done what you suggested and added that function and called that after `myDialog.show(...)`. However, this does not work either as the app crashes ass soon as I call it.


Visualizing standard deviation on a Cartesian plot

Question: I came across an example where standard deviation was being plotted on a Cartesian plot (standard 2D with X and Y axes.)
This seems like a valid thing to do but in this case the example only had a single line running across the graph to "indicate" standard deviation. This to me seems not very useful, possibly dangerous and misleading. Don't you need three lines plotted to properly visualize standard deviation on a graph? Thusly:

The mean
The mean plus one standard deviation value
The mean minus one standard deviation value

P.S. I am a software developer working on a data visualization package so please take my use of stats terminology with a grain of salt. Any corrections and feedback will be sincerely appreciated.
Rephrasing the question:
If I had a set of five data points to plot on a cartesian plane:
X:    10    20    30    35    50
Y:    20    40    5     55    10

For this sample data set (the Y values) the mean is 20 and the stdev is ~21.036 (x values plotted along the X axis and y values plotted along the Y axis.)
What would a proper plotting of the mean and the stdev on top of the X/Y data set look like?
Comment: No, what was on the axes definitely does matter.  Based on what you've written, I can imagine two different plots: one that is illustrating change in the variability of Y as X increases (in which case a simple line might be valid), and one that's illustrating the actual relationship of X and Y, which might include the mean and and SD lines... or might not.  Why 1 SD?  Why not 2?  We can only give plotting advice with some kind of context.  If people will be plotting whatever they want, all you can do is make it as flexible as possible.
Comment: What was on the x, what was on the y, and what was the point of the graph?
Comment: @Andy: It doesn't matter. This is a software package which customers will use to their own needs with figures that can represent literally anything. In my test case I have a set of six points of data which are all positive and sit in the upper, right cartesian quadrant.
Comment: Perhaps, the line is drawn such that it is consistent with your points 1, 2 and 3. In any case, your question is so vague that I am not sure a reasonable answer can be given.
Comment: Added a rephrase of the question to hopefully clarify via an example.
Answer: Probably a line for the mean and a line for +/- twice the standard deviation.  That would be the "default" plot for that.
That said, I think you may be missing the point of the plot with the single line for the standard deviation.  If what you're trying to represent is change in the variability of Y over X (i.e., heteroscedasticity), then a line plotting SD over X might work.  It really does depend on the data and the questions that you're trying to ask.  There just isn't a set of rules that you can follow to produce good plots every time, and in general the more automated the plotting system gets, the more useless I find it.
Comment: Thanks. That's exactly what i'm wrestling with. I have a deprecated app from a defunct company that i'm supposed to resurrect while at the same time troubleshooting their original intent. For example, the only clue (and the basis of my question) is a check box on a graph titled "show standard dev." Now, i'm supposed to recreate the functionality. Thanks for your patience btw. Any further insight is greatly appreciated.
Comment: Wow.  I don't even you that task.  In that context, I think what I'd do is have use the mean line + 2 SD for continuous X, and then use bars like csgillespie's for categorical data.  Not sure how you'd be able to differentiate reliably between cont. and cat., but I'm sure many of attempted that before.
Comment: Er... don't envy, I meant.
Answer: What about plotting the point with error bars, say mean +/- sd. Here's what your example data would look like:

Here's the R code I used to generate the plot:
library(ggplot2)
df = data.frame(values=c(10, 20, 30, 35, 50, 20, 40, 5, 55, 10),
  type=rep(c("X", "Y"),  each=5))

means = tapply(df$values, df$type, mean)
sds = tapply(df$values, df$type, sd)
df_summary = data.frame(means, sds, type=c("X", "Y"))

g = ggplot(data=df_summary, aes(y=means, x=type)) +
  geom_point(data=df,aes(y=values, x=type), col=2) +
  geom_errorbar(aes(ymax = means + sd, ymin=means - sd)) +
  ylab("Values")

g

Comment: I don't know... Paul provided xy coordinates but not SD for all the points. We should see a graph with 5 points with perhaps some error bars (assuming we know the SD).


Flash cs3 registration screen crashing/not responding after startup - since flash player update 16 May 2013

Question: Flash CS3 has stopped responding after startup.  The registration screen appears but is blank and Flash stops responding.  Windows can not find a solution.
I reinstalled Flash CS3 and checked installed fonts to no avail.
SOLUTION:
After a system restore backdated to 16 May 2013 before the Flash Player update, Flash CS3 appears to be working fine.
Answer: The bulk of the answer is here thanks to Mylenium:
http://forums.adobe.com/message/1640108?tstart=0#1640108
The file I needed to delete was:
adobe_registration.dll
This is found in:
Program Files/Adobe/Adobe Flash CS3
or wherever you installed Flash.
This stops the error associated with the registration screen.
Hope this helps!


Um timer para um serviço ler uma tabela no BD

Question: Preciso fazer com que um serviço leia uma tabela no BD, a cada 5 ou 10 segundos. Não vejo outra forma de fazer isso. Quando nessa tabela uma determinada Flag for alterada, aí o serviço empurra uma mensagem para um App. Não sei se essa é a melhor forma de automatizar meu App, mas é o que tá vindo na cabeça agora e não tenho idéia de como fazer. A lambda que verifica a tabela ok, não sei se o timer ou outra coisa, como fazer. Como implemento esse timer? A idéia seria criar uma Task(async) que lesse a table, mas o problema está no temporizador. Uso Web Api com REST e C#.
Comment: Blz, repare no q o Albano falou, isso não deve estar na api e sim no seu servidor
Comment: deixa a Task async rodando o tempo todo... `while(true)` e dentro dela coloca o Task.Delay(5000); pra esperar o tempo
Comment: Valeu, @RovannLinhalis, vou fazer esse teste e postar o result.
Answer: Usar um timer em um uma web API não é uma boa ideia. Eu iria de criar um outro projeto, do tipo windows service, e ai sim usar um timer.
Outra opção, e isso depende do seu banco de dados, seria criar uma trigger que faz a chamada da sua web api no ato da mudança que você espera. Para SQL Server de uma olha aqui. Resumindo:
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
                 'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Select @ResponseText

Exec sp_OADestroy @Object

Agora, sinceramente, eu nunca, jamais, sob hipótese alguma, usaria um while(true). Além de ser deselegante, e ter outras alternativas, a web api espera por uma primeira requisição para ser iniciada. Sendo assim seu while(true) só começará a funcionar depois desta requisição, o mesmo se aplica ao timer.


Heat equation derivation Taylor expansion

Question: I was watching a derivation of the heat equation here, and at 4:36 he takes the Taylor Series for $q_x|_{x+dx}$, which I think means expanding the function $q_x$ at $x+dx$.
In the video he writes $$q_x|_{x+dx}=q_x|_{x}+\frac{\partial q_x}{\partial x}dx$$
This seemingly conflicts with the definition of the Taylor Series of a function at a point, in this case being
$$q_x({x+dx})=q_x({x+dx})+\frac{\partial q_x}{\partial x}(x-(x+dx))$$
Comment: It's just $q_x|_{x+dx} = q_x(x+dx)$, the vertical bar is used as "evaluated at". The Taylor series is correct. Yours is correct too, but it's around $x+dx$ instead of being around $x$.
Answer: It holds
$$
q_x|_{x+dx}=q_x|_x+\left.\frac{\partial q_x}{\partial x}\right|_{x} dx + o(dx)
$$
if you expand around $x$. It holds too
\begin{align}
q_x|_x&=q_x|_{x+dx}+\left.\frac{\partial q_x}{\partial x}\right|_{x+dx} (x-(x+dx)) + o(dx)\\
&=q_x|_{x+dx}-\left.\frac{\partial q_x}{\partial x}\right|_{x+dx} dx + o(dx)
\end{align}
if you expand around $x+dx$ (which is the same).


If a batted ball strikes a runner on the offensive team and is caught before hitting the ground by the defense, is this an out?

Question: If a batted ball strikes a runner on the offensive team (assume that the ball already went by an infielder, nullifying any interference) and is caught before hitting the ground by the defense, is this an out?
Conversely, what happens if the ball strikes a runner leading off third completely in foul territory and is caught before hitting the ground? Is this just an immediate dead ball since it struck a person in foul territory?
Comment: Second part of question is duplicate of https://sports.stackexchange.com/questions/16416/third-base-runner-gets-hit-by-a-foul-ball-is-he-out/
Answer: Live ball, no out.
From MLB (6.09)(a)(4) When the Batter Becomes a Runner

A fair ball, after having passed a fielder other than the pitcher, or after having been touched by a fielder, including the pitcher, shall touch an umpire or runner on fair territory;
Comment: There's a huge amount of context missing because of the limited rule quote. You haven't explained why this rule excludes the out either.


Problema com regex para UserAgent Android

Question: Estou tentando criar uma regex ( para usar em PHP ) que consiga casar os grupos corretamente e extrair as informações que preciso. Neste caso é para obter informações de useragent android.
Quando o userAgent é assim:

User-Agent: Mozilla/5.0 (Linux; Android 5.0.2; SM-G530BT Build/LRX22G; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/56.0.2924.87 Mobile Safari/537.36

da certo, porém tem userAgent que tem um dado a mais, o "pt-br" , como esse:

User-Agent: Mozilla/5.0 (Linux; U; Android 4.1.2; pt-br; LG-E467f Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

eu não consegui porque o "pt-br" é opcional.
Segue o que ja tentei
https://regex101.com/r/6TRsM2/1
meu regex é este:
(?P<browser>Android)\s(?P<major_version>\d+)\.(?P<minor_version>\d+\.?\d?);(?P<lang>\spt-br)?(?P<device>[ \w\-?]+)\s

Alguém pode me ajudar a concluir esse regex? sendo que preciso que ele case com todos os grupos, e quando não tiver o pt-br, apenas retorne vazio.
Answer: Tente usar essa Regex
(?P<browser>Android)\s(?P<major_version>\d+)\.(?P<minor_version>\d+\.?\d?);(?P<lang>\spt-br){0,1};{0,1}(?P<device>[ \w\-?]+)\s

Você pode testar o funcionamento dela aqui.
O que eu fiz de diferente?
eu incluí {0,1} após o [...](?P<lang>\spt-br) e ;{0,1} tornando opcional a existência de pt-br; após o minor version, agora ele irá capturar somente caso exista o pt-br.
Considerações
Não sei se existe a possibilidade, porém é bom considerar a existência de outros browsers e outras lang's, caso tenha essa possibilidade use o operador "OU" (|) como neste exemplo.
Comment: Você tem razão, não me lembrei de que outras linguagens podem vir ou mesmo outra estrutura de user agent. O ideal era uma que casasse com qualquer lang que vier. Mas no momento, para o que preciso deu certo. Obrigado.


Running linear regression with 3 predictors and term interaction

Question: I'm trying to ascertain which portions of my social networking web app are driving user retention (so I can fine tune my site).
Step 1 (in my view) is to do an inference on what predictors are correlated to user retention. I'm taking the linear regression route for this.
Consider that my web app has 3 sections: A1, A2 and A3. Roughly speaking, one can start by testing the hypothesis whether engagement in any of these sections determines user retention. I.e. one can say:
Y^ = B0 + B1*A1 + B2*A2 + B3*A3

But what if there's interaction (or synergy) between these sections? As in all three sections feed the other two as well, creating a multiplier effect.
In that case, how would I model the regression? Would it be something like:
Y^ = B0 + B1*A1 + B2*A2 + B3*A31+ B4*A1*A2*A3

Secondly, wouldn't R^2 go up anyway as I add more and more predictors? For instance, imagine section A3 of my website is actually a dud. Would this fact appear in the coefficients once I run the inference (given I'm also including interaction terms)? Or in other words, how to play around with my model to remove weak predictors?

Sorry for the noob question, I'm getting back into statistics after a long hiatus. Would love a layman's explanation here.
Answer: So, the R^2 does increase anyway when you add more variables, but instead you can use the Adjusted-R^2 or AIC that penalize the models that include weaker predictors.
Concerning the interactions, I would start with lower level interactions, i.e A1*A2, A2*A3, A1*A3, and then move on to the higher-level ones, by comparing the AICs of each model (or some other sort of forward variable selection method). Remember, the AIC is a comparative measure of fit, which means it tells you which model is better than the others, but not how good it is. Also, the lower the AIC, the better.


FatalExecutionEngineError was detected

Question: I am facing a problem while using an unmanaged dll in my .net application and getting the exception
"The runtime has encountered a fatal error. The address of the error was at 0x79e71bd7, on thread 0xbb4. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack."
my code is below....
[DllImport("ITMSDLL.dll")]
internal static extern int get_month_mask(ref String theMask,ref  String theByt, int theSt_Dow, int theSt_Week, int theEn_Dow, int theEn_Week);

and callng this method by following method in C#
public int GetMonthMask(ref String theMask,ref  String theByt, int theSt_Dow, int
        theSt_Week, int theEn_Dow, int theEn_Week)
        {
            return CITMSDLLMethods.get_month_mask(ref theMask, ref theByt, theSt_Dow,
                theSt_Week, theEn_Dow, theEn_Week);
        }

above two methods are from wrapper dll made in .net.
and the above method is called by following code
aRc = Utility.objCITMSDLL.GetMonthMask(ref aRetMask,ref aMByte, aSt_Dow, aSt_Wk, aEn_Dow, aEn_Wk);

when calling this method it throws exception "FatalExecutionEngineError was detected" and the exception message specified in the top.
Answer: When an unmanaged method returns a string in a char buffer, it is usually mapped to a StringBuilder in .NET, not a String.
Here is an example for GetWindowText, straight from pinvoke
int GetWindowText(HWND hWnd, LPTSTR lpString, int nMaxCount);
becomes:
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
Comment: Hi,
Thanks for your answer. I tried by using String bulder but it was also not helpfull and throwing same error.
Comment: You should publish the C definition of the method; this way, people here could have a look and suggest a different mapping.
Comment: Actually I dont have the definition of method, I have only .dll file.
This dll was previousely used in oracle .fmb application. The following is the used definition in oracle .fmb file.
Comment: fh_itms_get_mon_mask :=
ORA_FFI.REGISTER_FUNCTION(lh_USER,'get_month_mask',ORA_FFI.C_STD);
ORA_FFI.REGISTER_PARAMETER(fh_itms_get_mon_mask,ORA_FFI.C_CHAR_PTR);
ORA_FFI.REGISTER_PARAMETER(fh_itms_get_mon_mask,ORA_FFI.C_CHAR_PTR);
ORA_FFI.REGISTER_PARAMETER(fh_itms_get_mon_mask,ORA_FFI.C_INT);
ORA_FFI.REGISTER_PARAMETER(fh_itms_get_mon_mask,ORA_FFI.C_INT);
ORA_FFI.REGISTER_PARAMETER(fh_itms_get_mon_mask,ORA_FFI.C_INT);
ORA_FFI.REGISTER_PARAMETER(fh_itms_get_mon_mask,ORA_FFI.C_INT);
ORA_FFI.REGISTER_RETURN(fh_itms_get_mon_mask,ORA_FFI.C_INT);
Comment: The string parameters seem to be input only, so do not use ref in the method definition (and call), but keep using String as data type.

FatalExecutionEngineError was detected


Enviar parametros de uma url para outras urls do site ficarem com esses mesmos parametros para uso das variaveis

Question: o exemplo seria essa url abaixo com os parametros= dia=4&mes=Janeiro&ano=1948&nome=Anderson.
https://numerologia.com.br/personalizando/?dia=4&mes=Janeiro&ano=1948&nome=Anderson.
esses parametros vieram de um formulario, porem qdo eu clicar para enviar o formulario esses parametros não vai aparecer na pagina de destino. exemplo https://anumerologia.com.br/teste ela vai aparecer sem os parametros, como eu envio os parametros para ficar visivel em outras paginas
Answer: coloca os parâmetros no atributo action do formulário:
<code><form method="POST" action="/teste?dia=4&mes=Janeiro&ano=1948&nome=Anderson">
</code>


How to Exit Installer on Button Click Without Confirmation During Modify Process?

Question: I'm working with Advanced Installer to create a setup package for my application. During the modification process, I've introduced a scenario where users can update their data through a custom UI. In this UI, there's an "Exit" button that, when clicked, should immediately close the installer without prompting any confirmation dialogs and effectively abort the installation process.
My current implementation involves adding a "Terminate Process" custom action, specifying "MyInstaller.exe" as the parameter. This custom action is triggered by the "Exit" button at the end of the modify dialog. While this method works, it forcibly terminates the installer process, which doesn't seem like the most graceful way to exit.
I'm seeking a more elegant solution that allows the installer to close immediately upon the button click, without navigating to the exit page or displaying any confirmation prompts to the user. Is there a better approach to achieve this behavior in Advanced Installer?
Note: The requirement is to ensure that the installer exits directly without any further user interaction or displaying the exit page.
Answer: A more elegant solution solution would be to trigger the "Close the current dialog -> Exit" event from your UI Exit button.
This way the installation process will be naturally stopped by the Windows Installer service.
Also, in case you do not want to display the UserExit dialog you should simply make sure the AiSkipUserExit property is set to 1. Something like below:


Solving the equation $ XA = A + 2X $

Question:
How to solve $XA = A + 2X$ if $A$ being:
  \begin{equation}
A=
\begin{bmatrix}
    1    & 0   & 1 \\
    0    & 2   & 1 \\
    0    & 1   & 1 \\
\end{bmatrix} \\
\end{equation}

I tried going $X = (A+2X)A^{-1}$ but I don't know how to get the 2X out from there.
Comment: Hint: write this as $X (A - 2 I) = A$.
Answer: So you have $X(A-2I)=A$ thus $$ X = A\cdot (A-2I)^{-1}=...$$
Notice that $ (A-2I)^{-1}$ exists since $$A-2I =
\begin{bmatrix}
    -1    & 0   & 1 \\
    0    & 0   & 1 \\
    0    & 1   & -1 \\
\end{bmatrix} \implies \det(A-2I)= 1$$
Comment: $2X = 2I\cdot X= X\cdot 2I$, the $X$ and $2I$ comute
Comment: Where do I have $AX$?
Comment: If we have $X\cdot B = A$ then $XB\cdot B^{-1} = AB^{-1}$ so $X= AB^{-1}$
Comment: Oh nevermind sorry I just got it, mindfart :'(
Thank you for the help!
Comment: I understand the rest of the steps you showed, but when you get $X(A−2I)=A$ where does the $X$ go from the right hand side?
Comment: Oh sorry I meant the right hand side of his equation, how $AX$ becomes $A$

Solving the equation $ XA = A + 2X $