.NET Chart Class - how to display different kind of intervals on the same chart

Question: I'm currently working on a project that I need to display a consolidate version of 2011 and 2012 data on this year's chart. This year's chart is monthly displayed.
This is my data. It's coming like this from the procedure, so no worries there:
<code>Date        Value   Coefficient
01/01/2011  15,6    0,1586
01/01/2012  17,88   0,1468
01/01/2013  11,92   0,1872
01/02/2013  1703,85 0,17
01/03/2013  1693,49 0,16
01/04/2013  1716,1  0,17
01/05/2013  1732,31 0,17
01/06/2013  1692,79 0,17
01/07/2013  1691,38 0,17
</code>
See that the first two rows are the consolidate of the entire year, and the rest month by month.
The Value column should populate a column series attached to the primary Y-Axis. The Coefficient is a line attached to the secondary Y-axis.
I have this piece of code, that is currently showing everything messed up, with the monthly interval:
<code>    <asp:Chart ID="Chart4" runat="server" CssClass="Chart" BorderlineDashStyle="DashDotDot"
        Palette="Pastel" DataSourceID="ObjectDataSource2" ImageStorageMode="UseImageLocation"
        Height="650px">
        <Series>
            <asp:Series Name="value" XValueMember="date" Legend="Legend1"
                YValueMembers="value" YValueType="Double" ChartArea="ChartArea1" Color="CornflowerBlue"
                IsValueShownAsLabel="True" LabelFormat="{0:0.##}">
            </asp:Series>
            <asp:Series Name="coef" XValueMember="date" Legend="Legend1" YValueMembers="coefCost"
                YValuesPerPoint="4" XValueType="Date" Color="YellowGreen" ChartType="Line" IsValueShownAsLabel="True"
                MarkerColor="Green" MarkerStyle="Diamond" YAxisType="Secondary" YValueType="Double"
                LabelFormat="{0:0.##\%}" BorderWidth="4" ChartArea="ChartArea1">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1" BackColor="Transparent" ShadowOffset="5">
                <AxisY Title="US$ / 1000">
                    <MajorGrid Enabled="False" />
                    <LabelStyle Format="{0:#,##0}" />
                </AxisY>
                <AxisX Interval="1" IntervalOffsetType="Months" IntervalType="Months">
                    <MajorGrid Enabled="False" IntervalOffsetType="Auto" IntervalType="Auto" />
                    <LabelStyle Interval="Auto" Format="{MMM/yy}" />
                    <ScaleBreakStyle Spacing="1" />
                    <ScaleView SizeType="Months" />
                </AxisX>
                <AxisX2>
                    <MinorGrid Enabled="True" />
                    <MajorTickMark Enabled="False" />
                </AxisX2>
                <AxisY2 Title="(%) Coef">
                    <MajorGrid Enabled="False" />
                </AxisY2>
            </asp:ChartArea>
        </ChartAreas>
        <Legends>
            <asp:Legend Name="Legend1" Alignment="Center" Docking="Bottom">
            </asp:Legend>
        </Legends>
        <Titles>
            <asp:Title Font="Arial Narrow, 14pt" Name="Title1">
            </asp:Title>
        </Titles>
    </asp:Chart>
</code>
As you can see, I have the ObjectDataSource2 set to populate the series and, therefore, the chart.
I have already tried to mess with the interval things and all, but I couldn't achieve what I want.
This is a picture of what I got so far:
https://i.stack.imgur.com/3eYkn.png
To recap: I need this chart to display only what I bring back from my procedure. I know the problem is in the interval properties of the axis (interval monthly, interval = 1, etc), but I just can't seem to find a way around.
If someone has been through something similar and might have some pointers, that'd be great!
Thanks in advance!!!
[EDITED]
I got a little closer to what I need to achieve.
Check out this picture:
https://i.stack.imgur.com/KRYcX.png
I added this to the X-Axis (among other modifications to the properties, but this is what did the trick):
<code>    <AxisX IntervalAutoMode="VariableCount" Interval="0">
</code>
... and it's "skipping" a few months by itself. Not sure where to go now, but I'm searching through the WebSamples application downloaded from MSDN (couldn't find the link, so sorry), maybe there's something there.
Comment: After spending almost the whole business day working on this, I finally found a workaround. Will post the final result first thing tomorrow.
Answer: Well, here it goes.
I decided to rewrite the whole thing without using ObjectDataSource.
I took all the properties off of Chart4 object (all that interval, monthly stuff and whatnot), and wrote everything on the code behind. I also had to format the X-Axis accordingly.
PS: I'm feeling kind of stupid cause I didn't think this through, and it doesn't look pretty, but since I've been struggling for three days straight, it'll have to do. Once I have some time, I'll re-factor and make it more elegant and efficient. Also, I'm so sorry this is VB.NET, I didn't have a saying on the choosing of the language lol.
Check it out:
<code>    <asp:Chart ID="Chart4" runat="server" CssClass="Chart" BorderlineDashStyle="DashDotDot" Palette="Pastel"
                ImageStorageMode="UseImageLocation" Height="650px">
        <Legends>
            <asp:Legend Name="Legend1" Alignment="Center" Docking="Bottom">
            </asp:Legend>
        </Legends>
        <Titles>
            <asp:Title Font="Arial Narrow, 14pt" Name="Title1">
            </asp:Title>
        </Titles>
    </asp:Chart>
</code>
On the back-end, this is what I did:
<code>    Dim date As String
    Dim value As Double
    Dim coef As Double

    Dim chartArea As New ChartArea("chartEficOp")
    chartArea.BackColor = Drawing.Color.Transparent
    chartArea.ShadowOffset = 5

    Dim valueSeries As New Series("valueY")
    valueSeries.ChartArea = "chartEficOp"
    valueSeries.Color = System.Drawing.ColorTranslator.FromHtml("#4f81bd")
    valueSeries.YAxisType = AxisType.Primary
    valueSeries.IsValueShownAsLabel = True
    valueSeries.ChartType = SeriesChartType.Column
    valueSeries.Legend = "Legend1"
    valueSeries.YValueType = ChartValueType.Double

    Dim serieEfic As New Series("valueY2")
    coefSeries.ChartArea = "chartEficOp"
    coefSeries.Color = System.Drawing.ColorTranslator.FromHtml("#9bbb59")
    coefSeries.YAxisType = AxisType.Secondary
    coefSeries.IsValueShownAsLabel = True
    coefSeries.ChartType = SeriesChartType.Line
    coefSeries.Legend = "Legend1"
    coefSeries.YValueType = ChartValueType.Double
    coefSeries.BorderWidth = 4
    coefSeries.LabelFormat = "{0:0.##\%}"

    Dim targetSerie As New Series("0,15%")
    targetSerie.ChartArea = "chartEficOp"
    targetSerie.Color = System.Drawing.Color.Red
    targetSerie.YAxisType = AxisType.Secondary
    targetSerie.IsValueShownAsLabel = False
    targetSerie.ChartType = SeriesChartType.Line
    targetSerie.Legend = "Legend1"
    targetSerie.YValueType = ChartValueType.Double
    targetSerie.BorderWidth = 2
    targetSerie.BorderDashStyle = ChartDashStyle.Dash

    Dim dt as DataTable = <called  the stored proc here>

    For Each item As DataRow In dt.Rows

        date = String.Format("{0:MMM/yy}", item("DATA"))

        Select Case <date here, to sort the x-label out>

            Case "01/01/2013"

                If date = "jan/11" Then
                    date = "2011"
                ElseIf date = "jan/12" Then
                    date = "2012"
                End If

            Case "01/01/2012"
                If date = "jan/11" Then
                    date = "2011"
                End If

        End Select

        value = item("VALUE")
        coef = item("COEF")

        valueSeries.Points.AddXY(date, value)
        coefSeries.Points.AddXY(date, coef)
        targetSerie.Points.AddXY(date, 0.15)

    Next

    Chart4.ChartAreas.Add(chartArea)

    Chart4.Series.Add(valueSeries)
    Chart4.Series.Add(coefSeries)
    Chart4.Series.Add(targetSerie)

    Chart4.ChartAreas(0).AxisX.MajorGrid.Enabled = False
    Chart4.ChartAreas(0).AxisX.Interval = 1

    Chart4.ChartAreas(0).AxisY.MajorGrid.Enabled = False
    Chart4.ChartAreas(0).AxisY.Title = "US$ / 1000"

    Chart4.ChartAreas(0).AxisY2.MajorGrid.Enabled = False
    Chart4.ChartAreas(0).AxisY2.Title = "% Cost"
    Chart4.ChartAreas(0).AxisY2.Interval = 0.04
</code>
... and the result was:
https://i.stack.imgur.com/HGKCa.png
Hopefully, this will help someone in the future.


A base de dados não reconhece texto com caracteres especiais mesmo em UTF-8

Question: Já fiz muitas mudanças ao código e já pesquisei por vários sites e nada resolveu o meu problema!
Código HTML:

Sobre o site

    <?php
            $sql_sobre = "SELECT sobre_home FROM campos";
            $sql_sobrequery = mysqli_query($conn, $sql_sobre) or die (mysqli_error($conn));
            $row = mysqli_fetch_row($sql_sobrequery);
            $decoded = utf8_encode($row[0]);
            echo $decoded;
    ?>

<form method="POST" action="confirmarEdicao.php"><textarea class="textboxEditar" name="edicaoSobreHome"><?php echo $decoded ?></textarea> <input class="buttonEditar" type="submit" value="Confirmar"></form>

Código PHP:
    session_start();
    $servername = "localhost";
    $username = "root";
    $password = "";
    $db = "aeac";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $db);

    // Check connection
    if (!$conn) {
        die("Connection failed: " .  mysqli_connect_error);
    }
    else{
      if (isset($_POST['edicaoSobreHome'])){
      $editar = $_POST['edicaoSobreHome'];
      $editar_encoded = utf8_encode($editar);
      $query = "UPDATE campos SET sobre_home = '$editar_encoded'";
      $result = mysqli_query($conn, $query);
    }
  }

O objetivo deste div é editar o texto no próprio site através de uma textarea escondida que aparece após clicar num botão com uma função em JS.
O meu problema aqui é que ao inserir caracteres especiais como letras com acentos, o texto na base de dados não reconhece os caracteres e retorna texto como o seguinte:
  "pode encontrar informação sobre as"

Comment: Caro(a) RedCandy não use UTF8_DECODE OU UTF8_ENCODE, siga as instruções: https://pt.stackoverflow.com/a/43205/3635
Comment: Como ta o cabeçalho do seu html?
Comment:
Comment: Qual o charset da tabela no banco?
Comment: utf8_spanish_ci
Answer: Só remover o utf8_encode no update e do select.
Coloca na conexão do banco mysqli_set_charset($conn, "utf8") para definir o charset do mysqli
  $conn = mysqli_connect($servername, $username, $password, $db);
  mysqli_set_charset($conn, "utf8");

      $editar = $_POST['edicaoSobreHome'];
      $editar_encoded = utf8_encode($editar);  //<-- remover essa linha
      $query = "UPDATE campos SET sobre_home = '$editar'"; //<-- aqui $editar

      var_dump($query); //<-- aqui tem que estar correto
      $result = mysqli_query($conn, $query);

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/93059/discussion-on-answer-by-leonardo-barros-a-base-de-dados-nao-reconhece-texto-com)
Answer: $pdf->load_html(utf8_decode($html));
Retire do código o "utf8_decode" e deixe desta forma---->>>>>>>>  $pdf->load_html($html);
Depois vai pegar caracteres especiais a vontade.


Need to restate left side in JS and/or?

Question: I'm having a brain cramp here for some reason. Does the left hand side need to be repeated when using AND/OR on the same property?
For example, is this fine:
if(name === 'Bob' || 'Bill')

or is this the correct way:
if(name === 'Bob' || name === 'Bill')

Comment: `if(name === 'Bob' || name === 'Bill')` is the correct way
Answer: If you want to compare between two the second one is correct
name === 'Bob' || name === 'Bill'

Above checks if name is equal to Bob or name is equal  to Bill return true
While this one
name === 'Bob' || 'Bill'

Above says if name is equal to Bob return true otherwise return Bill.
Answer: The second one is correct if you want to check for equality of both names with name, though I'd prefer the following
if (~['Bob','Bill'].indexOf(name)) {}

as its a little shorter and easier to extend.

Need to restate left side in JS and/or?


Issue with put closest() and html() together in jQuery

Question: I have created a voting system for my project. I have tried using the below code which is working properly but html() is not working with this. Can anybody help me with this?

$(document).ready(function() {
  $(".up").click(function() {
    $(this).addClass('active_vote');
    $('.active_vote').closest('.rating').html('18');
  });
});

          10

        Voted

hii

desc1

    UP VOTEDOWN VOTE

          8

        Voted

hello

desc2

    UP VOTEDOWN VOTE

Answer: The issue is because .rating isn't a parent of the .up element which triggers the click event.
To fix this you could use closest() to get the nearest common parent, the li in this case, then find() to get the .rating. Also note that both statements in the event handler can be combined. Try this:

let result2 = "Lorem ipsum";

jQuery(function() {
  $(".up").on('click', function() {
    $(this).addClass('active_vote').closest('li').find('.rating').html(result2);
  });
});

          10

        Voted

hii

desc1

    UP VOTEDOWN VOTE

          8

        Voted

hello

desc2

    UP VOTEDOWN VOTE

Answer: Use parent with find.

$(document).ready(function() {
  $(".up").click(function() {
    $(this).addClass('active_vote');
    $(this).parent().find('.rating').html('result2'); // Your upvote logic goes with result2
  });
});

          10

        Voted

hii

desc1

    UP VOTEDOWN VOTE

          8

        Voted

hello

desc2

    UP VOTEDOWN VOTE


While upgrading from D6, update.php appears to expect the Drupal 7 version of the database array and it throws errors

Question: Leaving settings.php in place (but writeable), per instructions 13 + 14 of major upgrade section of https://api.drupal.org/api/drupal/UPGRADE.txt/7.x , with the new D7 codebase but the old D6 DB, i get the following errors:

Notice: Undefined offset: 0 in Database::parseConnectionInfo() (line 1529 of [...]includes/database/database.inc).
Notice: Undefined index: driver in Database::openConnection() (line 1681 of [...]includes/database/database.inc).
Notice: Undefined index: driver in Database::openConnection() (line 1681 of [...]/includes/database/database.inc).
DatabaseDriverNotSpecifiedException: Driver not specified for this database connection: default in Database::openConnection() (line 1682 of [...]includes/database/database.inc).
Notice: Undefined index: driver in Database::openConnection() (line 1681 of [...]includes/database/database.inc).
The website encountered an unexpected error. Please try again later.

Here is the core of the question -- according to the instructions, and normal upgrades, update.php should note that settings.php is D6-style, and change it to D7-style, including db-connection format.
It is not doing so. What could be going wrong? Reading through the script, it determines the DB schema... but it's not obvious to me where it determines the settings.php version and updates it. Help? Thanks!
The installed Drupal 6 release is 6.38, the latest release for Drupal 6.
I first tried to upgrade to Drupal 7.95; then I tried to upgrade to Drupal 7.34, and then again with Drupal 7.0, but I had the same issue.
[[Note: the below is not part of the core of this question, but responds to "why don't you just hardcode D7-style DB connection? I can hard-code the database settings using the Drupal 7 array structure, but that leads to other problems (expecting things that don't exist yet):
Error
Error message
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal_7_test.main_system' doesn't exist: SELECT name, schema_version FROM {system} WHERE type = :type; Array ( [:type] => module ) in drupal_get_installed_schema_version() (line 151 of [...]/includes/install.inc).
The website encountered an unexpected error. Please try again later.

Per this report, my assumption is that this means the code is expecting the new D7 codebase because the database connection was D7 style: https://www.drupal.org/node/1308308
]]
Comment: What instructions? With Drupal 6 being end of life for many years Drupal 7 moved on. In this case you must update the database connection settings to the current Drupal 7 standard, shown in the example settings file. It should take all of a minute to do.
Comment: Thanks so much for your reply! Really appreciate it. I agree that Drupal 6 is exotically out of date, and know that it is casting back into the dim recesses of memory. These are the instructions I am following: the canonical UPGRADE.txt in every codebase of D7: https://api.drupal.org/api/drupal/UPGRADE.txt/7.x -- specifically items 13 and 14 of the "major version upgrade" section. As originally noted, the first thing I tried was to handcode the db connection, and then I get different error, indicating what appears to be a missing DB, which I assume is because the upgrade didn't happen.
Comment: Drupal Answers is a "one question at a time" site rather than a support forum. And those instructions say this, even for minor updates: "Copy the custom and site-specific entries from the backup you made into the new settings.php file. You will definitely need the lines giving the database information, and you will also want to copy in any other customizations you have added." This question is likely to be closed as lacking focus. Tables like `main_something` being missing suggests you have a table prefix configured.
Comment: Point #14 says: *Make your settings.php file writeable, so that the update process can
   convert it to the format of Drupal 7.x*. It is the update process that converts it to the Drupal 7 format, as long as the file is writable from the server.
Comment: As a side note, there is not a *minor version upgrade* and a *major version upgrade*. In Drupal terminology, passing from Drupal 6 to Drupal 7 is an upgrade. *Major version upgrade* just puts the emphasis on the fact that the major version number (the *7* in ***7**.95*) changes (for example, passing from ***6**.38* to ***7**.95*). If it is the minor version number that changes (for example, passing from _7.**34**_ to _7.**95**_), that is an update, not an *minor version upgrade*.
Comment: to @cilefen -- thanks for the input on the format of this forum. i edited the above to include a more detail regarding why simply hardcoding the database connection in the D7 format doesn't work. i can remove it again to focus on the specific question -- why is the update.php script unable to parse the D6-style url-based database connection that remains in the D6 settings.php?
Comment: to @apaderno you are absolutely correct about point #14, and the expected behavior. this is the kernel of the question -- why might this not be happening in my case? it should happen, but for some reason update.php is not reading the url-style database connection (which has all required detail and worked fine in D6), and is not changing it to D7 format.
Answer: The script update.php ascertains whether settings.php is D6 or D7 based on whether the $databases array is set. If that array is set in any form, it will skip all code designed to work with Drupal 6 settings file, and will skip upgrading the database to Drupal 7.
In my case, integration with CiviCRM required a bit of a kludgy addition to the settings.php creating aliases for databases, and used the $databases variable to do it. This confused update.php.


Saber quais div contem uma class especifica em jquery/javascript

Question: Estou precisando saber a quantidade de divs que contem uma class especifica, pensei em buscar todos os css que tenho nas divs, assim ir eliminando até achar as divs com "has-error", só que não estou conseguindo achar quem exatamente tem a class "has-error"
Como fazer?
$(document).on('click', "#btnSalvar", function () {

    var erros = 0;
    $("div").find('*').each(function () {
        var classe = $(this).attr("class");
        if (classe !== undefined) {
            if ($("" + classe + ":contains(has-error)")) {

            }

        }
   });
});

O que fiz até agora.
Edit:
Como que marca solucionado para duas pessoas ao mesmo tempo? hhaha
Valeu a todos
Comment: var numItems = $('.item').length;
Comment: Não sei se eu entendi muito bem, mas não seria mais simples utilizar o [Class Selector](https://api.jquery.com/class-selector/)?  Ficaria algo parecido com isso: `$('div.has-error')...` Você também poderia remover a 'div' e deixar somente a classe.
Comment: Acredito que sim, mas não estou sabendo implementar, como ficaria no meu código?
Comment: valeu cara, obrigado
Answer: Você pode usar a propriedade jquery  .length

var numItems = $('.has-error').length;

console.log (numItems);

Comment: +1 pelo exemplo funssional. :D
Comment: @dvd grafia errada é fumssional com M, o n só precede ç
Comment: Aquele lance de `$("#div1", "#div2")` significa: buscar #div1 dentro de #div2... agora `$("#div1, #div2")` significa selecionar as duas ids.
Comment: Beleza, vou buscar uma aplicação de `#div1 dentro de #div2` que nunca vi
Answer: Você pode fazer de uma forma simples com jQuery:
$("div.has-error").length

No caso acima irá encontrar apenas divs com a classe. Para contar qualquer, use:
$(".has-error").length

No seu código, ficaria:
$(document).on('click', "#btnSalvar", function () {
    var erros = $("div.has-error").length;
});

Com JavaScript puro:
var erros = document.body.querySelectorAll("div.has-error").length;

Comment: kkkk, iguais né
Comment: @LeoCaracciolo a minha tá canônica rs


Create commerce product through web services

Question: I want to create products using commerce services resource module. At this moment, I can create a product calling the resource .../product with POST, but It seems that It only creates a product variations, because If I navigate to "manage products" option, I can't see the new product but if I call a GET over resource .../product I can see the new one.
Then, I'd tried to create a product using .../node resource, but I always get an error:
"field_product][und][form][commerce_price][und][0][amount": "Price field is required"

I don't know what is the right JSON structure to create a node with its product variations.
Could some one put here an example of the right JSON structure for creating node products?
Thanks.
Answer: I've found the error. Firstable, my drupal commerce installation hasn't product_display content type. I have to add it manually. I don't know why, but It's missing after clean installation. Secondly, the right JSON structure for commerce price section is:
"field_product":{ "und" :
            {  "form": {
                   "commerce_price": {
                        "und": [ {
                           "amount": "1234.34",
                           "currency_code": "EUR",
                           "data": { "components": [] }
                            } ]
                      },
                   "sku":"eeaafe3231aa"
          }

After this change, I can create products display and I can see it on product manage page. Hope It could be useful for other who has the same problem.


Testing Relay [createFragmentContainer] with jest?

Question: I am tring to test my components but every component that exports createFragmentContainer shows me this issue:
console.error node_modules\react-native\Libraries\Core\ExceptionsManager.js:73
      Warning: Failed context type: Invalid prop/context `relay` supplied to `Relay(Product)`, expected `undefined` to be an object with an `environment` and `variables`.
          in Relay(Product)
    console.error node_modules\react-native\Libraries\Core\ExceptionsManager.js:73
      React caught an error thrown by Relay(Product). You should fix this error in your code. Consider adding an error boundary to your tree to customize error handling behavior.

      TypeError: Cannot read property 'environment' of undefined

      The error is located at:
          in Relay(Product)

so does jest support fragment containers or the problem is in my project ?
Comment: I've got the same problem! Did you ever make any progress on this issue @FrankenStein?
Comment: Check this out https://relay.dev/docs/en/testing-relay-components

you can use relay-test-utils
Answer: Add the below to __mocks__ folder. Then in the test add jest.mock('react-relay'); to the unit test that needs relay.

import React from 'react';
import PropTypes from 'prop-types';

const relayMock = jest.genMockFromModule('react-relay');

const relayChildContextTypes = {
  relay: PropTypes.object,
};

const relayEnvironment = {
  lookup: jest.fn(),
};

const relayContext = {
  relay: {
    environment: relayEnvironment,
    variables: {},
  },
};

const relayFragmentProps = {
  relay: {
    environment: relayEnvironment,
  },
};

const relayRefetchProps = {
  relay: {
    environment: relayEnvironment,
    refetch: jest.fn(),
  },
};

const relayPaginationProps = {
  relay: {
    environment: relayEnvironment,
    hasMore: jest.fn(),
    loadMore: jest.fn(),
    isLoading: jest.fn(),
  },
};

relayMock.__relayEnvironment = relayEnvironment;
relayMock.__relayFragmentProps = relayFragmentProps;
relayMock.__relayRefetchProps = relayRefetchProps;
relayMock.__relayPaginationProps = relayPaginationProps;

const makeRelayWrapper = (relayProps) => (
  (Comp) => {
    class HOC extends React.Component {
      getChildContext() {
        return relayContext;
      }

      render() {
        return <Comp {...this.props} {...relayProps}/>;
      }
    }

    HOC.childContextTypes = relayChildContextTypes;
    return HOC;
  }
);

relayMock.QueryRenderer = jest.fn(() => React.createElement('div', null, 'Test'));

relayMock.createFragmentContainer = makeRelayWrapper(relayFragmentProps);
relayMock.createRefetchContainer = makeRelayWrapper(relayRefetchProps);
relayMock.createPaginationContainer = makeRelayWrapper(relayPaginationProps);

module.exports = relayMock;
Comment: Please try not to link to external resources if snippets of code can be added to the answer (this makes the answer future-proof in case the URL's content is deleted).
Comment: Gotcha. Updated


Ferramenta FREE para Wireframe

Question: Dentre as várias ferramentas encontradas ao se pesquisar a respeito, alguém poderia dar indicação de uma boa ferramenta FREE para a criação de wireframe? O foco e desenvolvimento de sistema para web.
Observe que não busco a melhor, mas sim a indicação de quem já utilizou e pode recomendar.
O objetivo é de o cliente ver na folha de papel impressa e ter uma boa ideia de como a tela ficará depois de finalizada.
Agradeço pela atenção.
Comment: O mais simples. Apenas para o cliente ver na folha de papel impressa e ter uma boa ideia de como a tela ficará depois de finalizada.
Comment: Anderson, wireframe de alta fidelidade ou baixa? Para apresentação para cliente? Para testes de Experiência do usuário? Qual o motivo de fazer um wireframe?
Comment: Apresentação para cliente. O objetivo é que o cliente tenha conhecimento sobre o posicionamento dos dados, botões, layout, etc... Baixa fidelidade seria para o caso.
Comment: Seria Wireframe mesmo, ou um protótipo funcional? Ou seja, que tenha interação com o seu protótipo.
Answer: Seguem algumas opções:

http://iplotz.com/ (Free até $79)
http://pencil.evolus.vn/Default.html (Free)
https://www.gliffy.com/ (Free até $9,95 por mês)
http://www.mockflow.com/ (Free até $69 por ano)
http://framebox.org/ (Free)
http://iphonemockup.lkmc.ch/ (Free)

São considerados uns dos melhores.

Ferramenta FREE para Wireframe


Algebra books with challenging exercises

Question: I am taking my algebra quals this winter, and don't feel confident with my algebra abilities based on the class I'm taking. I feel comfortable with the content that's going to be in the quals (Galois correspondence, fields of fractions, PIDs, classifying groups) but don't have much practice with applying them to harder questions/exercises. Does anyone have books that focus on basic concepts, but apply them to more challenging exercises? Something like the algebra equivalent to baby Rudin in Analysis.
Thanks!
Comment: There are excellent exercises in Meyberg's book on abstract algebra, but even more conveniently you can solve the questions posed here under the tag "abstract-algebra" yourself. There are millions of questions.
Comment: Lang's Algebra has famously difficult exercises, and is broadly considered a "must read" for serious algebraists. I'll also second the advice of answering questions here, and looking back through old questions here to try and do them yourself. My algebra skills have improved dramatically since joining this website ^_^
Answer: I'm not sure I can gauge whether Dummit & Foote's (Abstract Algebra) exercises are challenging (it's been a few years) but I remember enjoying them. Also my school has a qual exam archive you could work through. What I did to prep for my qual was work 60ish problems from past quals and similar quals, and it did me fine. In our program these come right after the first year so they're not super intense exams. :) Link is here: Algebra Qual Archive
Comment: D&F is outstanding in its motivation, exposition, and exercises.
Answer: It seems like most of the books, and I haven't read that many, but whether Hungerford, Lang (basically a classic), Herstein, I'm actually partial to Fraliegh, which I learned from under Stallings, will have hard exercises.  Maybe baby Herstein, if I can call it that, because he has a harder book, Topics in Algebra, or some such, would have problems that are a little too easy.
I think Milne has a book, though it may just be on group theory.  There are, probably, alot of more specialized books.  If you are into combinatorial group theory, I heard Magnus is good.  Finite groups, Burnside.  Representations of finite groups, someone named Bob Steinberg.  Different than Robert Steinberg, the excellent UCLA professor, who discovered the Chevalley groups.  Speaking of whom, his notes, in the back of Lie Groups, Lie Algebras, and their Representations, by V.S. Varadarajan, are quite good, as is the book itself.
One title I like is Rings and their Modules.  I forget the author, but I would like to check it out.  Modules are an important topic in Algebra.  Among other things, the structure theorem for finitely generated abelian groups is a special case of the structure theorem for finitely generated modules.
Comment: Definitely should have thought of Lang, and I'll check out Hungerford/Herstein. Thanks! Fraleigh was actually the first book I learnt algebra under, and the exercises seemed a little basic.
Comment: Yes, Fraleigh is sort of introductory, but can I think still get you pretty far.
Answer: I don't see this book recommended often, and I honest don't know why.  But I really think Grillet's Abstract Algebra is an excellent place to learn graduate-level algebra and deserves to replace Dummit and Foote as the standard "it's not Lang" graduate algebra book.  To me, it sits somewhere between Hungerford and Lang in terms of sophistication, but it's highly readable.
It's hard to avoid Lang, and you should definitely work through some of his exercises (some of them are excellent, and some of them have.. typos).  Ken Ribet has a website with a lot of good material from courses he's taught from Lang, including some excellent problem sets.  But it's such a tome that I always felt like I learned the material better from other sources and later turned to Lang to deepen my understanding.
Grillet also has some pretty nice exercises at the end of each chapter.  Dummit and Foote has great coverage and some great exercises, but so many of them are just too mechanical, and I always walked away from it wondering if I really understood the material at the right level.  I really wish they would do some major updates to the text and cut out much of the fat.  Then again, when I was struggling to understand something from Grillet, I often found Dummit and Foote was nice for holding my hand a bit through it.  For whatever reason, I've always preferred textbooks that have a handful of well-chosen exercises at the end of each chapter, which you're expected to solve, to those with 50+ exercises which are a mix of good and bad.
That said, if Dummit & Foote made an updated edition with a lot of the chattiness cut out, better typesetting, and a nicer set of exercises, it would be fantastic.  Parts III and IV of D&F are particularly good.
Comment: Sorry to ask a question after long time. I am currently undergraduate student and spend half semester with group theory with reference book Dummit and foote. Is it good to use Grillet's book beside Dummit and foote?


mysqli execute returns false with large result set

Question: I have a MySQL query that works fine until the result set gets large (in this case large means about 13,000 rows) at which point execute returns false.  When I check the mysqli error, It gives me the following:
Duplicate entry '13054' for key 'group_key'
There is no group_key field in any of my tables, so this must be in the temp table mysql populates.  The error occurs across several different databases.  Any ideas?
Comment: Without any code, no, I have not ideas.
Answer: That's not a field, that's the name of a key. You'd need to look at show create table XXX to find the key names. MySQL requires each key have a name, but its auto-generated names are far uglier than this, so most likely this is a user-defined key name - look at the DDL for the tables involved in your query and look for a 'group' field.
Comment: I ran the show create table for all tables included in the query and there does not appear to be a group_key key in any of my tables.  When I use describe, mysql shows it is using a temporary table to generate the results.  I think the group_key is in that table and perhaps it is running out of room?  How would I look at that?
Comment: I doubt it's running out of room. That'd mean your server's out of disk space, and you'd see far more errors than just a duplicate key.
Comment: I guess I was thinking that because if I remove the biggest column from the query (a text description that was AES_ENCODEd), it does not fail.  Will post the query in a sec.


PNaCl & gtest—pnacl-ld: Incompatible object file (X8664 != X8632)

Question: I'm a newbie at this,Please help me ...T_T...
Recently I was building pthreadpool(required by NNPACK) with ninja on my Ubuntu 14.04 64bit.
It requires Google PNaCl(Portable Native Client) and Google Test,and I installed both.
After I run python ./configure.py in pthreadpool root dir,
it generated a file build.ninja:

pnacl_toolchain_dir = $nacl_sdk_dir/toolchain/linux_pnacl
pnacl_cc = $pnacl_toolchain_dir/bin/pnacl-clang
pnacl_cxx = $pnacl_toolchain_dir/bin/pnacl-clang++
pnacl_ar = $pnacl_toolchain_dir/bin/pnacl-ar
pnacl_finalize = $pnacl_toolchain_dir/bin/pnacl-finalize
pnacl_translate = $pnacl_toolchain_dir/bin/pnacl-translate
pnacl_sel_ldr = $nacl_sdk_dir/tools/sel_ldr.py
cflags = -std=gnu11
cxxflags = -std=gnu++11
optflags = -O3
rule cc
  command = $pnacl_cc -o $out -c $in -MMD -MF $out.d $optflags $cflags $
      $includes
  description = CC[PNaCl] $descpath
  depfile = $out.d
  deps = gcc
rule cxx
  command = $pnacl_cxx -o $out -c $in -MMD -MF $out.d $optflags $cxxflags $
      $includes
  description = CXX[PNaCl] $descpath
  depfile = $out.d
  deps = gcc
rule ccld
  command = $pnacl_cc -o $out $in $libs $libdirs $ldflags
  description = CCLD[PNaCl] $descpath
rule cxxld
  command = $pnacl_cxx -o $out $in $libs $libdirs $ldflags
  description = CXXLD[PNaCl] $descpath
rule ar
  command = $pnacl_ar rcs $out $in
  description = AR[PNaCl] $descpath
rule finalize
  command = $pnacl_finalize $finflags -o $out $in
  description = FINALIZE[PNaCl] $descpath
rule translate
  command = $pnacl_translate -arch $arch -o $out $in
  description = TRANSLATE[PNaCl] $descpath
rule run
  command = $pnacl_sel_ldr $in
  description = RUN[PNaCl] $descpath
  pool = console
rule install
  command = install -m $mode $in $out
  description = INSTALL $out
build /home/rokim/NNPACK/third-party/pthreadpool/build/pthreadpool.c.bc: cc $
    /home/rokim/NNPACK/third-party/pthreadpool/src/pthreadpool.c
  descpath = pthreadpool.c
  includes = -I$nacl_sdk_dir/include $
      -I/home/rokim/NNPACK/third-party/pthreadpool/include $
      -I/home/rokim/NNPACK/third-party/pthreadpool/src
build $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/libpthreadpool.a: $
    ar /home/rokim/NNPACK/third-party/pthreadpool/build/pthreadpool.c.bc
  descpath = libpthreadpool.a
build $
    /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.cc.bc: $
    cxx /home/rokim/NNPACK/third-party/pthreadpool/test/pthreadpool.cc
  descpath = pthreadpool.cc
  includes = -I$nacl_sdk_dir/include $
      -I/home/rokim/NNPACK/third-party/pthreadpool/include $
      -I/home/rokim/NNPACK/third-party/pthreadpool/src
build /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.bc: $
    cxxld /home/rokim/NNPACK/third-party/pthreadpool/build/pthreadpool.c.bc $
    /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.cc.bc
  libs = -lgtest
  libdirs = -L$nacl_sdk_dir/lib/pnacl/Release
  descpath = pthreadpool.bc
build $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/pthreadpool.pexe: $
    finalize $
    /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.bc
  descpath = pthreadpool.pexe
build $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/pthreadpool.nexe: $
    translate $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/pthreadpool.pexe
  arch = x86_64
  descpath = pthreadpool.pexe
build test: run $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/pthreadpool.nexe
  descpath = pthreadpool.nexe
default $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/libpthreadpool.a $
    /home/rokim/NNPACK/third-party/pthreadpool/artifacts/pthreadpool.nexe
build /usr/local/include/pthreadpool.h: install $
    /home/rokim/NNPACK/third-party/pthreadpool/include/pthreadpool.h
  mode = 0644
build /usr/local/lib/libpthreadpool.a: install $
    /home/rokim/NNPACK/third-party/pthreadpool/build/pthreadpool.c.bc
  mode = 0644
build install: phony /usr/local/include/pthreadpool.h $
    /usr/local/lib/libpthreadpool.a

But when I run the command ninja,there came the error:

[4/6] CXXLD[PNaCl] pthreadpool.bc
FAILED: /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.bc
/toolchain/linux_pnacl/bin/pnacl-clang++ -o /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.bc /home/rokim/NNPACK/third-party/pthreadpool/build/pthreadpool.c.bc /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.cc.bc -lgtest -L/lib/pnacl/Release
pnacl-ld: Cannot find '-lgtest'
ninja: build stopped: subcommand failed.

I thought it may be the path problem,so I put libgtest.a and libgtest_main.a (Generated from Google Test) in /usr/lib/gtest and modified the build.ninja:

libs = -L/usr/lib/gtest -lgtest_main -lgtest

It seems ninja found the lib files, but there came the error:

[1/3] CXXLD[PNaCl] pthreadpool.bc
FAILED: /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.bc
/toolchain/linux_pnacl/bin/pnacl-clang++ -o /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.bc /home/rokim/NNPACK/third-party/pthreadpool/build/pthreadpool.c.bc /home/rokim/NNPACK/third-party/pthreadpool/build/test/pthreadpool.cc.bc -L/usr/lib/gtest -lgtest_main -lgtest -L/lib/pnacl/Release
pnacl-ld: /usr/lib/gtest/libgtest_main.a: Incompatible object file (X8664 != X8632)
ninja: build stopped: subcommand failed.

I believe the lib files are good since I tried to use g++ to compile a test.cpp:
g++ test.cpp -lgtest_main -lgtest -lpthread
And it worked.
So I thought it might be something wrong about pnacl or the way I use it.I googled the 32bit 64bit incompatible problem about pnacl and gtest but I got nothing. Now I have totally no idea about what to do since I'm a newbie at this...
So please, any help, idea or suggestions would be greatly appriciate!
For Google PNaCl,I downloaded the nacl_sdk.zip and unziped it to /home/rokim/nacl_sdk and I got sdk_tools and pepper_49 up to date.
For Google Test,I run sudo apt-get install libgtest-dev . After cmake and make I got libgtest.a and libgtest_main.a then I put them into /usr/lib and /usr/local/lib.The gtest include file are put into /usr/include and usr/local/include.
Answer: You can't use libgtest from the host system with the NaCl compilers. Everything you link has to be built with the same (NaCl) compiler. So you want to build libgtest with pnacl-clang, and link that with your other PNaCl build.
Comment: Thaaank you!!! I modified cmakelist to compile gtest with pnacl-clang and it works now!Thank you veeery much!!! ^_^


Function not being called after drop-down selection

Question: I implemented a double drop-down and my function calling code, and after selecting something from the drop-down, the function is not being called.
The code is supposed to run a function relevant to the drop-down selection. This was tested on a normal drop-down and everything ran smoothly, but will not run on this double drop-down for some reason.
The code is outputting the selection, but I would like it to call the function.
Any help would be much appreciated.
Thanks!

    <select name="slist1" onchange="SList.getSelect('slist2', this.value);">
     <option>- - -</option>
     <option value="amazon">Amazon</option>
     <option value="apple">Apple</option>
     <option value="keurig">Keurig</option>
     <option value="nike">Nike</option>
    </select>

Comment: There is too much code here -- you'll need to trim this down into a *small* example that shows your problem.  Good chance you'll find the error on your own as you are.
Answer: Your slist2 select is dynamically generated content. In order to attach event handler to dynamic content, you should use $(document).on('change', 'select', function(){}) instead.
You were calling functions['Kindle Fire HD']() instead of functions['kindlefirehd']().
Replace
$( "select" )
  .change(function () {
    var selected = $( "select option:selected" );
    functions[selected.val()]();
  })
  .change();

with
$(document).on('change', 'select[name=slist2]', function(){
  var selected = $(this).val();
  var funcName = SList.scontent[selected];
  functions[funcName]();
});

See Demo
Answer: Your are right  at all but have mistake at
   $( "select" )
      .change(function () {
        var selected = $( "select option:selected" );
        functions[selected.val()]();
      })
      .change();

Remove above code
Try below Example
JS
    var SList = new Object();             // JS object that stores data for options
    var txtsl2 = '';

    SList.slist2 = {
     "amazon": ['Kindle Fire HD', 'Kindle Charger', 'Kindle Fire HDX'],
     "apple": ['MacBook', 'iMac', 'iPhone', 'iPad'],
     "keurig": ['Platinum', 'Vue'],
     "nike": ['Fuel Band']
    };

SList.scontent = {
 "Kindle Fire HD": 'kindlefirehd',
 "Kindle Charger": 'kindlecharg',
 "Kindle Fire HDX": 'kindlefirehdx',
 "MacBook": 'macbook',
 "iMac": 'imac',
 "iPhone": 'iphone',
 "iPad": 'ipad',
 "Platinum": 'platinum',
 "Vue": 'vue',
 "FuelBand": 'fuelband'
};

SList.getSelect = function(slist, option) {
      document.getElementById('scontent').innerHTML = '';           // empty option-content

if(SList[slist][option]) {
        // if option from the last Select, add text-content, else, set dropdown list
        if(slist == 'scontent'){ document.getElementById('scontent').innerHTML = SList[slist][option];
var selected = SList[slist][option];
functions[selected]();
}
        else if(slist == 'slist2') {
          var addata = '<option>- - -</option>';
          for(var i=0; i<SList[slist][option].length; i++) {
            addata += '<option value="'+SList[slist][option][i]+'">'+SList[slist][option][i]+'</option>';
          }

          document.getElementById('slist2').innerHTML = txtsl2+' <select name="slist2" onchange="SList.getSelect(\'scontent\', this.value);">'+addata+'</select>';
        }
      }
      else if(slist == 'slist2') {
        // empty the tag for 2nd select list
        document.getElementById('slist2').innerHTML = '';
      }
    }

    var functions = {
        kindlefirehd: function(){window.alert("func1 called")},
        kindlecharge: function(){window.alert("func1 called")},
        kindlefirehdx: function(){window.alert("func1 called")},
        macbook: function(){window.alert("func1 called")},
        imac: function(){window.alert("func1 called")},
        iphone: function(){window.alert("func1 called")},
        ipad: function(){window.alert("func1 called")},
        platinum: function(){window.alert("func1 called")},
        vue: function(){window.alert("func1 called")},
        fuelband: function(){window.alert("func1 called")}
    }

Change
Change is only at if condition
   if(SList[slist][option]) {
            if(slist == 'scontent'){ document.getElementById('scontent').innerHTML = SList[slist][option];
            var selected = SList[slist][option]; // Save Selected value to variable
            functions[selected]();               // call function with argument
    }

JSfiddle


Is the following function convex F(t;C) in C. Where $F(t;C) = {\exp({\sum_{k = 0}^p {{C_k}\cos (2\pi tk)} })}$

Question: Prove that the following function is convex F(t;C) in C.  Where $F(t;C) = \frac{1}{{{e^{\sum\limits_{k = 0}^p {{C_k}\cos (2\pi tk)} }}}}$ and $ - \frac{1}{2} \le t \le \frac{1}{2}$.   I tried the convexity definition assuming the domain set is a convex set.   I used the definition let ${C_1} \in D$ and ${C_1} \in D$ where $D$ is the convex domain then we need to prove    that $F(t;\lambda {C_1} + (1 - \lambda ){C_2}) \le \lambda F(t;{C_1}) + (1 - \lambda )(F(t;{C_2})$,   where $\lambda  \in [0,1]$ in matrix notation I let ${T_k} = [\begin{array}{*{20}{c}}
1&{\cos (2\pi t)}&{\cos (4\pi t)\begin{array}{*{20}{c}}
.&.&{\cos (2p\pi t){]^T}}
\end{array}}
\end{array}$  and ${C_1} = [\begin{array}{*{20}{c}}
{{c_0}}&{{c_1}}&{{c_2}\begin{array}{*{20}{c}}
.&.&{{c_p}]}
\end{array}}
\end{array}$ I need to prove $\frac{1}{{{e^{\lambda {C_1}^T.{T_k} + (1 - \lambda ){C_2}^T.{T_k}}}}} \le \frac{\lambda }{{{e^{{C_1}^T.{T_k}}}}} + \frac{{(1 - \lambda )}}{{{e^{{C_2}^T.{T_k}}}}}$.   Any help will be appreciated thank you all.
Comment: The rule of  of $F(t;C)$ is independent of $t$ besides restriction on the domain?
Comment: I'm not sure what you mean. Please if you can elaborate more so I can answer correctly rather than guessing.
But there are no restriction on the C's and t is between -0.5 and 0.5.
Comment: I don't see a $t$ in  $\frac{1}{{{e^{\sum\limits_{k = 0}^p {{C_k}\cos (2\pi fk)} }}}}$. There's $f$ and $p$ though.
Comment: Really sorry that was my mistake I put an f instead of a t. Thank you for pointing that out.
Answer: I did solve the problem and just in case somebody else run into the same problem this is how I solved it. We start
$$w(t;\textbf{C}) = \frac{1}{{\exp \left( {\sum\limits_{k = 0}^p {{c_k}\cos (2\pi kt)} } \right)}}$$
where $ - \frac{1}{2} \le t \le \frac{1}{2}$. Before we take the derivative we will do some abbreviation let
$$\textbf{C} = \left[ {\begin{array}{*{20}{l}}
{{c_0}}&{{c_1}}&{{c_2}}&.&.&{{c_p}}
\end{array}} \right]$$
$${\textbf{F}_k} = \left[ {\begin{array}{*{20}{l}}
1&{\cos (2\pi t)}&{\cos (4\pi t)}&.&.&{\cos (2p\pi t)}
\end{array}} \right]$$
then we can write the function as following
 $$w(t;\textbf{C}) = \frac{1}{{\exp \left( {\textbf{C} \cdot \textbf{F}_k^T} \right)}}$$
taking the first derivative (Gradient)
$$\frac{{\partial w}}{{\partial {C_m}}} = \frac{{ - \cos (2\pi mt)}}{{\exp \left( {\textbf{C} \cdot F_k^T} \right)}}$$ and taking the second derivative (Hessian) $$\frac{{\partial w}}{{\partial {C_m}\partial {C_n}}} = \frac{{\cos (2\pi mt)\cos (2\pi nt)}}{{\exp \left( {\textbf{C} \cdot F_k^T} \right)}}$$
To write the hessian matrix notice
$$\frac{{\partial w}}{{\partial {C_m}\partial {C_n}}} = \left\{ {\begin{array}{*{20}{l}}
{\frac{{\cos {{(2\pi mt)}^2}}}{{\exp \left( {C \cdot F_k^T} \right)}}}&{m = n}\\
{\frac{{\cos (2\pi mt)\cos (2\pi nt)}}{{\exp \left( {\textbf{C} \cdot F_k^T} \right)}}}&{m \ne n}
\end{array}} \right.$$
let
$$P = \exp \left( { - \textbf{C} \cdot \textbf{F}_k^T} \right)$$
writing the Hessian matrix we have
$$H = \frac{{\partial w}}{{\partial {C_m}\partial {C_n}}} = \left( {\begin{array}{*{20}{c}}
P& \ldots &{\cos (2\pi t)\cos (2p\pi t)P}\\
 \vdots & \ddots & \vdots \\
{\cos (2\pi t)\cos (2p\pi t)P}& \cdots &{\cos {{(2p\pi t)}^2}P}
\end{array}} \right)$$
where the diagonal of the matrix is the following
$$Dig = \left[ {\begin{array}{*{20}{l}}
P&{\cos {{(2\pi t)}^2}P}&.&.&{\cos {{(2p\pi t)}^2}P}
\end{array}} \right]$$
we can see that the diagonal is all positive, also notice that the matrix is real and symmetric. By using the pivots of the matrix for different order you will notice that all the pivots are non negative hence the Hessian is a positive semi definite matrix, which indicate that $w$ is a convex function which mean it satisfies the following, Let $C_1 \in D$, and $C_2 \in D$ where $D$ is assumed to be a convex set (Domain) then the following is true
$$w(t;\lambda {\textbf{C}_1} + (1 - \lambda ){\textbf{C}_2}) \le \lambda w(t;{\textbf{C}_1}) + (1 - \lambda )w(t;{\textbf{C}_2})$$
that is
$$\frac{1}{{\exp \left( {\left[ {\lambda {\textbf{C}_1} + (1 - \lambda ){\textbf{C}_2}} \right] \cdot F_k^T} \right)}} \le \frac{\lambda }{{\exp \left( {{\textbf{C}_1} \cdot F_k^T} \right)}} + \frac{{(1 - \lambda )}}{{\exp \left( {{\textbf{C}_2} \cdot F_k^T} \right)}}$$


exp(x) for imaginary numbers

Question: Well, I know how to get the $e^x$ function polynomial expansion, but how do I know that this is also valid for imaginary numbers, like $i\pi$?
I know that the Euler's Formula is:
$$e^{ix} = \cos(x) + i\sin(x)$$
It means that both the $\cos(x)$ and $\sin(x)$ expansions allow na imaginary number like $i\pi$ to be the input. How can I prove this? Is there some good PDF about this?
Comment: Are you asking why the Taylor expansion of $e^x$ is still valid when $x$ is complex?
Comment: @AntonioVargas I want to know why it is still valid
Comment: [Here are some proofs](http://www.proofwiki.org/wiki/Euler's_Formula) of Euler's formula that don't rely on the Taylor expansion (at least, not directly).  Perhaps you would prefer on of these.
Comment: Compare Euler's [infinite product](http://en.wikipedia.org/wiki/Infinite_product#Product_representations_of_functions) expression for the [sinc function](http://en.wikipedia.org/wiki/Sinc_function#Properties) $\displaystyle{\frac{\sin x}x=\prod_{n=1}^\infty\left(1-\left[\frac{x}{n\pi}\right]^2\right)}$ with that of the [exponential function](http://en.wikipedia.org/wiki/Exponential_function#Overview) $\displaystyle{e^x=\lim_{n\to\infty}\prod_{k=1}^n}\left(1+\frac xn\right)$.
Answer: Defining the complex exponential is straightforward.
What we want to do is find an analytic function $f(z)$ such that $$f(z_1+z_2) = f(z_1)f(z_2)$$ and $$f(x) = e^x$$
for all real $x$.
Therefore, we have $f(x+iy) = f(x)f(iy) = e^xf(iy)$, where the latter equality comes from the second condition.
Define $f(iy) \equiv M(y)+iN(y)$, which is just another way of saying "break $f$ into real and complex parts." Note that this means that $f(x+iy) = e^xM(y) + e^x iN(y)$. Since we want the function to be analytic, it must satisfy the Cauchy-Riemann equations:
$$\begin{align*}
M(y) &= N'(y), \\
M'(y) &= -N(y),
\end{align*}$$
hence, $$M''=-M.$$
Solving this differential equation gives us $M = a \cos y + b \sin y$ and so $N = -M' = a\sin y - b\cos y$.
Now, we use that $f(x) = e^x$ for all real $x$, which is true whenever $y = 0$. Since $M(0) = a$ and $N(0) = -b$, we use $$ e^x = f(x) = f(x+i\cdot 0) = e^xM(0)+e^x iN(0)$$
to conclude that $a=1$ and $b=0$.
Hence, $e^z = e^{x+iy} = e^x \cos y+ ie^x\sin y$.
This is why they Taylor series works.

exp(x) for imaginary numbers


Sharing Prism Viewmodels WPF and Xamarin Forms

Question: Does anyone know if it is possible to share viewmodels between a WPF and Xamarin Forms app? Below is a snippet of a Xamarin Forms viewmodel. There are some interfaces that are unique to the Forms app such as the IPageDialogService and also the way navigation is handled so it doesn't seem as though we can do this but wanted to check.
         using System;
         using System.Threading.Tasks;
         using Prism.Commands;
         using Prism.Mvvm;
         using Prism.Navigation;
         using Prism.Services;

         namespace PrismSample.ViewModels
         {
               public class MainPageViewModel : BindableBase, IInitialize, IConfirmNavigation,
                        INavigationAware
               {
                 private INavigationService _navigationService { get; }
                 private IPageDialogService _dialogs { get; }

                 public MainPageViewModel(INavigationService navigationService, IPageDialogService
                           dialogs)
                 {
                      _navigationService = navigationService;
                      _dialogs = dialogs;

                       NavigateCommand = new DelegateCommand<string>(OnNavigateCommandExecuted);
                  }
         }

Answer: If your code contains references to any type in Prism.Forms or Prism.Wpf you cannot share it between platforms.
Shared libraries should reference Prism.Core only. You could then create platform specific libraries that references your shared Prism.Core base library and adds the platform specific functionality for Xamarin.Forms and WPF respectively.


Coletar nome do arquivo utilizado

Question: Estou concluindo um código que utiliza muito a função copy de shutil. Como vou distribuir o arquivo em formato executável depois e provavelmente em algum momento vão mudar o nome dele, quero saber se tem como eu coletar o nome do arquivo onde o script está sendo rodado.
Algo como:
nome = os.getbasename()
print(nome)
-globancy.exe

Answer: Você tem diversas opções na verdade. Dessas apresento-lhe três:
import os
print(os.path.basename(__file__))

import sys
print (sys.argv[0])]

print (__file__)

Existe uma discussão interessante no SO a respeito dos prós e contras do uso de cada uma. Vale a pena consultar.
Onde:

__file__ é o arquivo atualmente em execução, conforme detalhado na documentação oficial:

__file__ é o nome do caminho do arquivo a partir do qual o módulo foi carregado, se foi carregado de um arquivo. O __file__atributo pode
  estar faltando para certos tipos de módulos, como módulos C que estão
  vinculados estaticamente ao interpretador; para módulos de extensão
  carregados dinamicamente a partir de uma biblioteca compartilhada, é o
  nome do caminho do arquivo de biblioteca compartilhada.

sys.argv[0](requer importação sys) é o nome do script que foi chamado
   a partir da linha de comando e pode ser um caminho absoluto, conforme
   detalhado na documentação oficial:

argv[0] é o nome do script (depende do sistema operacional se esse é um
  nome de caminho completo ou não). Se o comando foi executado usando a
  opção -c de linha de comando para o intérprete, argv[0] será definido para a string '-c'. Se nenhum nome de script foi passado para o
  interpretador Python, argv[0] é a string vazia.

As informações que compõe essa resposta foram retiradas daqui. Agradeço ao usuário Yoel.
Answer: Interpretando sua pergunta como "Descobrindo o nome do script corrente em Python".
Assim, seguem algumas soluções conforme questão em inglês:

O atributo __file__ em qualquer arquivo te dará o caminho para este.
  Então se quiser omitir o restante do caminho, use os.path.basename(__file__).2 3
Neste ínterim, você pode ainda importar __main__ e utilizar o mesmo atributo __file__.4
Ou ainda sys.argv[0], mas lembre-se de igualmente utilizar os.path.basename caso queira apenas o nome do arquivo.5

os e sys são módulos e devem ser importados para serem utilizados.

Coletar nome do arquivo utilizado


How to match different keys inside a union type

Question: I'm not sure how to ask this... but hopefuly the code example should clarify what I'm asking:

type A = {| +type: "A", +payload: "PA" |};
type B = {| +type: "B", +payload: "PB" |};

type Actions = A | B;

function dispatch<T: Actions>(type: $PropertyType<T, 'type'>, payload: $PropertyType<T, 'payload'>) {
}

dispatch("A", "PA"); // ok
dispatch("B", "PB"); // ok

dispatch("A", "PB"); // this doesn't error, but I'd like to
dispatch("B", "PA"); // this doesn't error, but I'd like to

dispatch("C", "PC"); // this errors properly

https://flow.org/try/#0C4TwDgpgBAglC8UDeAfKBqUkBcUBEMeANBmAIYgA2A9mQCa54AKhUKAvgNwBQW0AQgmRpM4CI37FSFGvUZNJbLt15jYAY2ABLagDsAzkLhp+PbgDMArrs07dUOlv3lg6gBYAeACq4YtvfoAfAAUfLgAJEwATtSQUaBeYt4kAOR8KYEk5FS0DFCRMXEJSV6p2bJ0GQCUyNzs3FDcjs5krm7BBFLMhFWcUAD0-VDUANZNTi7uHZIkzJK9A0OjKs2T7Z2zCngLg1AQUTFR4y1t010s2327+4crE61TeADC5y87QzfUUUA
Answer: You'll need a type that allows looking up the type based on the key, which I don't think tagged unions allow for unfortunately. For instance, you could change your function to be this:
type ActionsLookup = {
  A: A,
  B: B,
};
type Actions = $Values<ActionsLookup>;

function dispatch<K: $Keys<ActionsLookup>>(
  type: K,
  payload: $ElementType<$ElementType<ActionsLookup, K>, 'payload'>
) {}

Comment: We ended up changing the function's signature, similarly to this.
Thank you for your suggestion!


Is the product of two ideals in a number field order strictly contained in the two ideals?

Question: Let $\mathcal{O} \subseteq \mathcal{O}_K$ be an arbitrary order in a number field and let $\mathfrak{p}, \mathcal{I} \subsetneq \mathcal{O}$ be proper $\mathcal{O}$-ideals such that $\mathfrak{p}$ is prime. Is it true that $\mathfrak{p} \mathcal{I} \neq \mathcal{I}$?
Clearly this is true in $\mathcal{O} = \mathcal{O}_K$ by cancellation of ideals, but the cancellation of ideals does not hold in general in arbitrary sub-orders. This statement seems simple enough, but I cannot seem to find a convincing proof or counter-example.
Answer: If $PI=I\ne 0$ then $$(PO_K)(IO_K)=IO_K$$
which implies that $PO_K=O_K$ so that $P$ is contained in no maximal ideal of $O_K$ thus in no maximal ideal of $O$ ie. $1\in P$ and $P=O$.
Comment: This leaves out the case $I=0$ where the claim is in fact true
Comment: Perhaps you could expand on the statement "thus in no maximal ideal of $\mathcal{O}$"? Does that mean that all proper $\mathcal{O}$-ideals are contained in a maximal ideal of $\mathcal{O}_K$?
Comment: @ZacharyPepin If $P$ is a proper ideal of $O$ then it is contained in a maximal ideal of $O$ thus in a maximal ideal of $O_K$ thus $PO_K$ is a proper ideal of $O_K$
Comment: @reruns Hmm, I am afraid I don't see why this is true. It doesn't seem to be true of rings in general (i.e. $\mathbb{Z} \subseteq \mathbb{Q}$). Why is it true for orders in a number field?
Comment: @ZacharyPepin that fact is (I think) true. It definitely depends on the fact that the maximal order is integral over the smaller order. See Theorem 5.10 in Atiyah-Macdonald. There could be a more elementary approach to this fact.
Answer: Suppose $\mathfrak p I = I$. Localize at $\mathfrak p$, so then we can apply Nakayama's lemma which says that $I_{\mathfrak p} = 0$. Since $\mathcal O$ is an integral domain this is clearly not possible unless $I= 0$.


Interpretation of event study difference-in-difference coefficient

Question: I understand mathematically what a difference-in-differences model is estimating, but I want to confirm that I am 'translating' it into English/words properly.
Let's say I am running the following event study specification:
$y_{i,t} = \lambda_i +\tau_t + \sum\limits_{k \neq -1}Treat_i *\mathbb{1}\{t=k\}\beta_k + \eta_{i,t}$
where $i$ is the county, $t$ is time, $\lambda_i$ are county fixed effects, $\tau_t$ are time fixed effects, and $Treat_i$ is an indicator = $1$ if a county is in the treatment group, and $\mathbb{1}\{t=k\}$ as an indicator = $1$ if time = $k$. Thus, this is a difference-in-differences, where I replaced a 'post' dummy with a vector of year indicators. I am omitting the interaction $k = -1$, the year prior to the treatment being implemented, as the reference group. $\eta_{i,t}$ is the error term.
For the sake of this example, say $Y$ are mortality rates, deaths per 1000 population.
I want to put the coefficient $\beta_k$ in a sentence. say $k = 9$, and say $\beta_9 = 5$. Is it correct to say:
"Treatment counties experienced 5 more deaths per 1000 than control counties 9 years after treatment relative to the difference in the year before treatment."
Or, can one simply say:
"Treatment counties experienced 5 more deaths per 1000 than control counties 9 years after treatment relative to before."
I am curious if one of those is 'more correct', or are both incorrect?
Answer: I am partial to the former interpretation.
Here, $\beta_k$ is interpreted as the effect of treatment for different lengths of exposure to the treatment. As is the convention in most event study frameworks, $\beta_{-1}$ is normalized to be equal to 0. The estimate of $\beta_0$ is the instantaneous treatment effect; it's the average effect in the first year the treatment is implemented. Positive values for $k$ represent treatment lags, which is useful when we want to assess treatment effect dynamics. The estimate of $\beta_9$ is, in effect, the coefficient on the ninth lag. Put simply, it's the average effect of treatment 9 years after the first (immediate) adoption year.
As a general recommendation, don't concern yourself so much with interpreting each lead or lag. Instead, show their evolution over time by plotting the coefficients.
Comment: Thank you for this intuitive answer. I am taking your recommendation into account, but just for my own intuition to clarify something,  does that mean the effect for $\beta_9$ is the \textit{cumulative} effect 9 years afterwards? in other words, if we assume there is an underlying independent effect for each year, it would yield the sum of each of these effects up to 9 years?


Writing tests in Mocha/Chai with the namespace module paradigm

Question: Im writing a series of coffeescript files for doing math operations and I need to write some tests. I figure that mocha and chai are the way to go. At the moment, Im using the namespace method to group all my separate functions together in order to keep things tidy:
namespace = (target, name, block) ->
  [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
  top    = target
  target = target[item] or= {} for item in name.split '.'
  block target, top

exports? exports.namespace = namespace

The thing I'd like to test at the moment is my matrix class, which looks a little like this:
namespace "CoffeeMath", (exports) ->

  class exports.Matrix4
    for name in ['add', 'subtract', 'multiply', 'divide', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'translate']
        do (name) ->
          Matrix4[name] = (a,b) ->
          a.copy()[name](b)

    Matrix4.DIM = 4

    # Take a list in column major format
    constructor: (@a=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]) ->
      # etc etc ...

Now compiling all this up with the lovely coffeescript compiler is all well. I have a test like this:
chai = require 'chai'
chai.should()

{namespace} = require '../src/aname'
{Matrix4} = require '../src/math'

describe 'Matrix4 tests', ->
  m = null
  it 'should be the identity matrix', ->
    m  = new exports.Matrix4()
    m.a.should.equal '[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]'

The problem is, I get the following error:
node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
ReferenceError: namespace is not defined
    at Object.<anonymous> (/Users/oni/Projects/Saito.js/src/math.coffee:3:3)
    at Object.<anonymous> (/Users/oni/Projects/Saito.js/src/math.coffee:631:4)
    at Module._compile (module.js:441:26)

aname should be included I believe and that exports the namespace function so I cant see why namespace is not defined. Any thoughts?
Answer: From the fine manual:

To export an object, add to the special exports object.

And then, exports is returned by require:

module.exports is the object that's actually returned as the result of a require call.

So, when you say this:
namespace = require '../src/aname'

you have namespace.namespace available inside your test.
CoffeeScript wraps each file in a function wrapper to avoid polluting the global namespace:

all CoffeeScript output is wrapped in an anonymous function:  (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

This means that you have something like this in the compiled JavaScript:
(function() {
    exports.namespace = ...
})();
(function() {
    # Matrix4 definition which uses the 'namespace' function
})();
(function() {
    var namespace = ...
})();

The result is that namespace is not visible where you define Matrix4 since the test and Matrix4 exist in separate functions and thus separate scopes.
If you want to use namespace inside your math file, then you'll have to require it there rather in the code that requires your math file.
Comment: Thanks for that! Its a big help. Still attempting to merge a web based coffeescript application with a node based testing environment. this is one step closer. Cheers


Como mandar emails na versão de php 4.3.11?

Question: Como consigo enviar emails na versão de php 4.3.11? Tenho um site hospedado num servidor onde a versão do php é essa e a função mail() não funciona. Existe maneira de contornar o problema?
Comment: entre em contato com o suporte e peça a atualização do PHP, seria o melhor a fazer.
Comment: Explique não funciona. Dá algum erro? Você simplesmente não recebe o e-mail?
Comment: Upgrade meu amigo. PHP 4.3.11 não se usa mais. Já pede pra instalar o 7.
Comment: Simplesmente não manda email, não recebo nada. Penso não ser possível pedir a atualização de servidor
Answer: Normalmente os "hostings" permite a mudança do "engine" do php através do Painel de controle. Entre em contato com eles. Deve haver algum wiki deles que possa te ajudar.


foreach Loop Not Working With Object

Question: I have an object called entry. I want to access a MySQL database and pull the relevant information for the object entry. These are my pages:
objects.php
class main {
    function setValues( $rs = array() ){
        foreach( $rs as $key => $val ){
            $this->$key = $val ;
        }
    }

    var $created ;
    var $updated ;
}

class entry extends main {
    var $id ;
    var $channel ;

    var $title ;
    var $content ;
}
$table_names['entry'] = 'archive' ;

functions.php
$dbconn = mysqli_connect( DB_HOST , DB_USER , DB_PASS , DB_NAME ) ;
$table_names = array() ;

function getTableValues( $object ){
    global $table_names ;
    $table_name = $table_names[ get_class( $object ) ] ;

    $r = 'SELECT * FROM '.$table_name ;
    return $r ;
}

function query( $q ){
    global $dbconn ;
    $stmt = mysqli_query( $dbconn , $q ) ;

    return $stmt ;
}

function fetchRow( $stmt ){
    return mysqli_fetch_array( $stmt , MYSQLI_ASSOC ) ;
}

function find( $object , $other = '' , $orderBy = '' ){
    global $dbconn ;
    $list = array() ;
    $q = getTableValues( $object ) ;

    $q .= $other.' '.$orderBy ;
    $stmt = query( $q ) ;
    $objectClass = get_class( $object ) ;
    while( $rv = fetchRow( $stmt ) ){
        $obj = new $objectClass() ;
        $obj->setValues( $rv ) ;
        $list = $obj ;
    }

    return $list ;
}

Then, on the actual page I have
<?php
    require_once( '../lib/functions.php' ) ;
    require_once( '../lib/objects.php' ) ;

    $entries = find( new entry() ) ;
?>

<?php
    foreach($entries as $entry){
?>

        <?php echo $entry->id ?>
        <?php echo $entry->channel ?>
        <?php echo $entry->title ?>
        Edit View

<?php
    }
?>

I end up getting the error:
Trying to get property of a non-object

as a result of the foreach loop and it iterates this eight times even though right now there's only one entry for testing purposes. Using the foreach loop with only $entries, it properly pulled information but, again, iterated eight times. I'm pretty sure this is because there are eight columns in the SQL table, but I don't know why it would be doing this.
I also used used echo to make sure the SQL statements were correct, used count to make sure there was only one item in the arrays that were a result of the executed functions (there was) and used print_r() to print out the information stored in $entries (it was all correct). So, it seems to me that the reason this isn't working is because of the foreach loop. But I do not know why this is or how to fix it.
Any and all help is appreciated. Thank you!
Comment: `$table_names` is global variable?
Answer: Just change your find function to:
function find( $object , $other = '' , $orderBy = '' ){
    global $dbconn ;
    $list = array() ;
    $q = getTableValues( $object ) ;

    $q .= $other.' '.$orderBy ;
    $stmt = query( $q ) ;
    $objectClass = get_class( $object ) ;
    while( $rv = fetchRow( $stmt ) ){
        $obj = new $objectClass() ;
        $obj->setValues( $rv ) ;
        $list[] = $obj ;  // earlier you were looping through columns, now it will loop through rows
    }

    return $list ;
}

Comment: In your `foreach` loop you are iterating columns/fields. I corrected the code of `find` function to fix it.

foreach Loop Not Working With Object


Selecionar dados e exibir

Question: Estou com problemas para consultar o MySQL de uma forma simples.
Já tenho um arquivo no includes de conexão ao banco que funciona normalmente.
Porem na pagina de consulta não estou conseguindo exibi-los.
O código que achei no Google.
1 - Não estou entendo a parte do loop while. Ele cria uma variável dentro do próprio loop? ($clientes)
2 - O que é fetch_object()?
Queria um meio mais simples?
Comment: @RafaelAcioly você não precisa fazer isto, PDO não vai te ajudar em nada.Veja as respostas, e avise se ainda falta algo para entender melhor.
Comment: Já que está retornando aos estudos agora... aconselho a já estudar PDO. :)
Comment: Os passos para realizar uma consulta no banco são: 1 - transformar a string sql em uma consulta. 2 - Passar esse 'resultado' para a função/método que extrai as linhas do banco, geralmente é necessario utilizar um for/while para percorrer todas as linhas.
Comment: Onde posso encontrar esse material pra estudos PDO? você conhece algum lugar?

Poderia dar um exemplo de consulta em códigos para eu ver se entendo?
Comment: @RafaelAcioly não conselhei PDO por ajudar em sua dúvida, aconselhei pelo fato de ser mais limpo e suportar diversos bancos de dados; http://code.tutsplus.com/pt/tutorials/pdo-vs-mysqli-which-should-you-use--net-24059 | http://stackoverflow.com/questions/2190737/what-is-difference-between-mysql-mysqli-and-pdo
Comment: @RafaelAcioly Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Não tem forma mais simples que isso.
Sim, ele cria uma variável quando ele entra no while e reaproveita esta variável todas as vezes que ele passa pelo while atribuindo uma novo valor obtido do banco de dados. A função do fetch_object() é justamente trazer uma nova linha do banco de dados - associado a variável $resultado e o resultado no caso é um objeto que precisa ser atribuído a uma variável, no caso a $clientes. Se o não há mais dados para trabalhar o fetch_object() retorna false indicando que o laço deve encerrar.
Daí dentro do laço você pode usar esta variável para acessar seus membros que são justamente os campos que vieram do banco de dados se acordo com a query usada anteriormente.
<?php
require_once('includes/conexao.php'); //pegou dados da conexão

$sql = 'SELECT * FROM clientes'; //prepara a query a ser mandada para o banco de dados

$resultado = $con->query($sql); //executa a query e guarda o resultado em $resultado
//guarda uma linha do resultado em $clientes (este será um objeto cujos membros serão as
//colunas da tabela clientes, será false se não tiver novas linhas)
while ($clientes = $resultado->fetch_object()) { //cada passagem aqui pega uma linha nova
    echo $clientes->nome; //pega o membro nome da linha atual que o PHP está avaliando
    echo $clientes->telefone;
} //aqui termina o processamento de uma linha e vai tentar a próxima linha no while
?>

Coloquei no GitHub para referência futura.
Answer: Uma das vantagens das linguagens dinâmicas é que ela proporciona construções mais flexiveis que as linguagens de estaticas.
O while funciona em duas partes, primeira verifica-se fetch_object() é diferente de false, caso seja(existe um resultado do banco) vem a segunda parte a que é feita a atribuição do resultado a variável $clientes, isso ocorre devido as regras de precedências dos operadores do PHP.
O operador de atribuição é um dos que menos tem precendência, por isso é feita a verificação do valor do while(true ou false) e em caso positivo é feita a atribuição.
        2- passo          1 - passo
                     false/ou qualquer coisa
while ($clientes = $resultado->fetch_object()) {
  echo $clientes->nome;
  echo $clientes->telefone;
}

Que pode ser interpretado como:
while ($clientes = false) //Não entra no while

                           true
while ($clientes = $resultado->fetch_object())// Faz a atribuição

Answer:
O while está atribuindo o retorno da função "fetch_object" a variável "$clientes"
(dica: use "$cliente").
A função "fetch_object" retorna como objeto uma linha de resultado da query, por isso; somada ao while, ela faz com que você acesse cada linha do resultado da query.

Selecionar dados e exibir


Add a fading text with the fading images => JQuery

Question: I created this Crossfade effect on Jquery:

function doAnimationLoop(o, n, t, i, a) {
        fadeInOut(o, n, t, i, function() {
            setTimeout(function() {
                doAnimationLoop(o, n, t, i, a)
            }, a)
        })
    }

    function fadeInOut(o, n, t, i, a) {
        return $(o).animate({
            opacity: 1
        }, n).delay(t).animate({
            opacity: 0
        }, i, a)
    }
    var duration = 20,
        fadeAmount = .3;
    $(document).ready(function() {
        var o = $("#slideshow img"),
            n = o.size(),
            t = 3e3 * duration,
            i = t / n,
            a = i * fadeAmount,
            e = i - i * fadeAmount * 2,
            u = e * (n - 1) + a * (n - 2);
        o.each(function(o, n) {
            0 != o ? ($(n).css("opacity", "0"), setTimeout(function() {
                doAnimationLoop(n, a, e, a, u)
            }, e * o + a * (o - 1))) : setTimeout(function() {
                $(n).animate({
                    opacity: 0
                }, a, function() {
                    setTimeout(function() {
                        doAnimationLoop(n, a, e, a, u)
                    }, u)
                })
            }, e)
        })
    });
.home h1 {
    font-family: 'Open Sans';
    font-size: 5em;
}

.main {
    text-shadow: 0px 0px 10px #696969;
    position: absolute;
    top: 2em;
    color: #f6f6f6;
    font-weight: 900;
    z-index: 999;
}

.sub-main {
    font-weight: 100;
    position: absolute;
    top: 3em;
    color: white;
    text-shadow: 0px 0px 50px #696969 !important;
    z-index: 999;
}

#slideshow img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Title

Tagline

I am facing a problem I never have faced before which is...
I want to add Text on the top of these images, each image has it's title/tagline. I want the text to fade with the image though!!
How do I make a fading text with the fading images?
Thank you!
Answer: add this to your css:
.anim{
    animation: opac 2s infinite;
}
@keyframes opac{
    from {opacity:0}
    to {opacity:1}
}

then add the class anim to your title, tagline and tell if this is what you want or not?
Comment: Yes! this is what I'm looking for, Thank you, what's left is to set the correct timing of the animation.
Comment: you can mark my answer as the correct answer if this fit you and welcome anytime my friend :)


Rails 5: Submit form with jQuery

Question: I am trying to submit a form with jQuery if any of the element changes. For now I am not using remote: true.
Here is the code that renders the partial:
views/assets/index.html.erb
<%= render @assets %>

Code for partial:
views/assets/_asset.html.erb
<%= form_for [asset.project, asset] do |f| %>
  ...
<% end %>

Following is the javascript code for form submit:
$(document).on('turbolinks:load', function() {
  if (!($(".assets.index").length > 0)) return;

  $('.edit_asset').change(function() {
    alert("submitting..");
    $(this).submit();
  });
});

It's doing the alert but form is not getting submitted, please suggest..
Answer: Actually the issue was $(this) vs this. So it should be
this.submit(); # or
$(this)[0].submit();

But client side validations on form elements like required: true won't work as it's bound to the submit button of the form. So we have to trigger that event, here is how I am doing it:
views/assets/_asset.html.erb
<%= form_for [asset.project, asset] do |f| %>
  ...
  <%= f.submit "Update", style: "display: none;" %>
  ...
<% end %>

Javascript code will be:
$(document).on('turbolinks:load', function() {
  if (!($(".assets.index").length > 0)) return;

  jQuery.fn.submitOnChange = function() {
    $(this).change(function() {
      $(this).find("input[type=submit]").click();
    })
    return this;
  }
  $('.edit_asset').submitOnChange();
});

If we want to do this remotely, we have to add remote: true & authenticity_token: true to the form_for, so it will be:
<%= form_for([asset.project, asset], authenticity_token: true, remote: true) do |f| %>

Answer: Your issue is that $(this) in the .change for .edit_asset is targeting that element and trying to submit it. You need to find the form object and submit that instead:
$(document).on('turbolinks:load', function() {
  if (!($(".assets.index").length > 0)) return;

  $('.edit_asset').change(function() {
    alert("submitting..");
    $(this).parents('form').submit();
  });
});

This could also be a bit stressful on your install, I'd recommend having a bit of a timeout after the changes and then submitting rather than constantly hammering your rails install with submit requests.
Comment: ah, my apologies. Have you tried a `debugger;` statement in the change to try and manually run the `$(this).submit()` ? It may be worth doing that to see the exact issue you're having. Worth noting too that with `remote: true` off you'll trigger a page refresh.
Comment: Not working as in how? Is there any response from it? No errors? Nothing? Does the form ever submit? Can you see it in the console etc?
Comment: Found the issue it should be this not $(this)

Rails 5: Submit form with jQuery


number of different events in a random sequence

Question: I'm confronted with a probability problem that may have already been solved.
I'm considering random sequences of m events.
The number of possible events is n, and each type of event has the same fixed probability of occurrence 1/n.
I would like to know the probability distribution of the number of different events in the sequence (comprised between 1 and min(n,m))
Answer: Indeed, the problem was already solved. It's a generalization of Birthday paradox. The formula for probability mass function is

The probability of getting $k$ unique values from $[0, n)$ when choosing $m$ times is given by:
$$P(V = k) = \binom{n}{k}\displaystyle\sum_{i=0}^k (-1)^i \binom{k}{i} \left(\frac{k-i}{n}\right)^m $$
where $V$ is a random variable giving the number of unique outcomes and $\binom{\cdot}{\cdot}$ is the binomial coefficient.

as quoted by George V. Williams on math.stackexchange.com who refers to http://www.randomservices.org/random/urn/Birthday.html#General
<code>set.seed(123)

m <- 100
n <- 40

f <- function(x, m, n) {
  vapply(x, function(k) {
    choose(n, k) * sum( ((-1)^(0:k) * choose(k, (0:k)) * ((k - (0:k))/n)^m) )
  }, numeric(1))
}

out <- replicate(1e6, {
  length(unique(sample.int(n, m, replace = TRUE)))
})

plot(prop.table(table(out)), xlab = "k", ylab = "P(V=k)")
lines(1:m, f(1:m, m, n), col = "red")
</code>
Comment: +1 Is it possible that the use of $n$ and $m$ is swapped in the OP with respect to the answer?


Discussing $\frac{d}{d\theta}e^{i\theta}$ aka cis before complex derivatives and complex exponential

Question: A First Course in Complex Analysis by Matthias Beck, Gerald Marchesi, Dennis Pixton, and Lucas Sabalka
Definition of $e^{i \theta}$ (or cis in other texts)

About Prop 1.3f, how is it possible to discuss derivative of $e^{i \theta}$ before both defining derivatives of complex functions (Ch2) (including functions of a real variable I think!) and defining the complex exponential (Ch3)?
In particular, the proof of Prop 1.3f seems to assume linearity of the derivatives of complex functions.
There's even this exercise later on: Exer 1.6b

I know how to do this with Ch3's definition of the complex exponential. I don't believe this is possible to do with only Ch1 even if we write $e^{\phi + i\phi} = e^{(i+1)\phi}$.
Comment: For your Q1, this is the derivative of a complex valued function of a real variable. So you do not need complex derivatives.
Comment: I'm closing this as too broad as there are too many questions.
Comment: Your link does not work, it's behind a firewall, most likely.
Comment: There's still one too many questions. Keep it to one at a time, please.
Comment: @Shaun Nvm. There's only 1 question now. Thanks.
Comment: @LeeMosher http only seems to work. Thanks!
Comment: @Shaun Ok thanks. I took off De Moivre and made the question on derivatives only.
Comment: @LeeMosher Why did you delete your other comment?
Comment: @Kusma But still, how do we know complex constants can be treated the way real constants are? Oh wait, is it possible some universities or textbooks teach (or assume students were taught) derivatives of $f: \mathbb R \to \mathbb C$ ? I'm thinking perhaps the textbook assumes students know $$\frac{d}{dx} cf(x) = c\frac{d}{dx} f(x) \ \forall c \in \mathbb C$$?
Comment: @Shaun Q2 is further elaboration on Q1
Comment: I deleted my other comment because I though the comment of @Kusma was a much better explanation.
Comment: @LeeMosher do you disagree with mark viola?
Comment: @kusma do you disagree with mark viola?
Answer: As the author states, this is just a definition of a function of $\phi$ and could have been denoted $q(\phi)$.  This notation is chosen because it will accord with our definition of real and complex exponentiation.  It can be hard to look at $e^{i\phi}$ and remember (until chapter 3) that you don't know this is the complex exponential, you just know it is this function of $\phi$.
The properties in $1.3$ can all be verified directly from the definition and the usual trig identities.  In particular for $1.3f$ we have
$$\frac d{d\phi}e^{i\phi}=\frac d{d\phi}(\cos \phi +i\sin \phi)=-\sin \phi+i\cos \phi=ie^{i\phi}$$
Note that the rule for differentiating an exponential was not used.
The challenge I see for $1.6b$ comes from mixing the real and imaginary numbers in the exponential.  Even if you have already defined the exponential function for real arguments, we need to define $e^{a+bi}=e^ae^{bi}$ and I don't see a definition of that unless you have defined the sine and cosine of imaginary numbers.  If you are given that definition and have the derivative of the real exponential you can prove what is desired.
Comment: The first equality in my 1.3f is just the definition.  Then for the second you need to take off the multiplicative $i$ and apply the usual rule for the trig functions.  I don't know what you have covered at this point.  I would have thought you would have $(ax)'=ax'$ for constant $a$ even if it is complex.  If you don't then the middle inequality is not justified.  That is one of the hazards of defining such a suggestive notation.  You tend to forget what you are not allowed to do with it.
Comment: @rossmillikan Hi Ross.  If I understand the main concern of the OP, it is that the author has yet to prove that $$\frac{d}{d\phi}\left(\cos(\phi)+i\sin(\phi)\right)=\frac{d\cos(\phi)}{d\phi}+\frac{d i\sin(\phi)}{d\phi}$$and then ALSO that $$\frac{d i\sin(\phi)}{d\phi}=i\frac{d \sin(\phi)}{d\phi}$$That is, no rules for differentiating complex-valued functions of a real variable have been established.
Comment: @BCLC Ross didn't mention the first equality in my comment.
Comment: Indeed you need to establish the identities @MarkViola mentioned, but that is easy to do once you know what convergence means for sequences / functions involving complex numbers.
Comment: Yes, I meant the authors can get sloppy about what has been justified and what not.  Please do not edit comments into the answer.
Comment: Alternatively you can just *define* the real derivative of a complex valued function as derivative of real part plus i times derivative of imaginary part. Then you can easily differentiate $e^{i\phi}$.
Comment: Ross Millikan, thanks. I know what cis(theta) is. I had to take out because of Shaun. Anyhoo, for 1.3f, why can you take out i in the derivative? Sure you can take out REAL constants but DOES THIS APPLY TO COMPLEX CONSTANTS? Of course yeah in Ch2, but this is still Ch1. What's the justification for treating complex constants the way we would real ones? For exer 1.6b, you agree that it cannot be done with Ch1 only?
Comment: @MarkViola that's right and thanks! Although Ross Millikan posted a comment about a minute before you did in case you didn't see.
Comment: @MarkViola right thanks. I meant to ask about that too but sleepy and using phone.
Comment: @Kusma ONCE YOU KNOW. But when you're in Ch1, how to do?!?!? Convergence isn't even until Ch7 soooo.... (I already finished the book and am now revising, so I kinda know what you're getting at for the post-Ch1 approach/es)
Comment: @RossMillikan wait the 'you' in 'you tend' refers to the authors?
Comment: @Kusma I was thinking that. Kind of like integrals at the beginning of Ch4. Thanks! But that solves prop1.3f and not exer1.6b?
Comment: @MarkViola post an answer? It seems other answerer disagrees with you/us/me
Answer: When we define $e^{i\phi} = \cos \phi +i\sin \phi$ the only information from complex numbers is that $i$ is a constant whose square is $-1$
You can use the algebra of the complex field without using  differentiation theorems of complex variables.
When we prove $\frac {d}{dz}z^2=2z$ using the definition of derivative we are using complex variables, but when we use $\frac {d}{d\phi }(cos \phi + i\sin \phi)= -\sin \phi + i \cos \phi $ we are just using differentiation rules of real vlued functions, $\sin x$ and $\cos x$ with the algebra of complex numbers.
Comment: Do you disagree with Mark Viola? Quote: the author has yet to prove that $$\frac{d}{d\phi}\left(\cos(\phi)+i\sin(\phi)\right)=\frac{d\cos(\phi)}{d\phi}+\frac{d i\sin(\phi)}{d\phi}$$and then ALSO that $$\frac{d i\sin(\phi)}{d\phi}=i\frac{d \sin(\phi)}{d\phi}$$That is, no rules for differentiating complex-valued functions of a real variable have been established.
Comment: @BCLC Yes, I think there is no need for further rules to differentiate$$ \frac{d}{d\phi}\left(\cos(\phi)+i\sin(\phi)\right)=\frac{d\cos(\phi)}{d\phi}+\frac{id\sin(\phi)}{d\phi}$$
Comment: but how do we know that the imaginary number works the way all the real numbers do AT THIS POINT in the text?
Comment: $i$ is a constant and we treat it like a constant. The rest is all real.
Comment: sure that works for constants on the real line but what about constants elsewhere in the complex plane? :|
Comment: Also what's your answer to Exer1.6b?
Comment: @BCLC I think a  more general definition for $e^{a+ib}$  instead of just $e^{ib}$would have been more appropriate.
Comment: so you agree that Exer1.6b cannot be answered with Ch1 alone?
Comment: I agree that a hint or a definition would have helped.
Comment: @BCLC Thanks for your attention.
Comment: What's your answer to 'sure that works for constants on the real line but what about constants elsewhere in the complex plane? :|' ?
Answer: I believe it's a mistake in the way that Mark Viola describes.
The correction to the mistake is I think as follows:

I suspect a definition (*) such as
$$\frac{d}{d\theta}x(\theta)+iy(\theta) := \frac{d}{d\theta}x(\theta)+i\frac{d}{d\theta}y(\theta) \tag{1}$$
instead of something like 'we can treat $i$ as constant.
I think $(1)$ can be viewed as natural if you consider $z(\theta):=x(\theta)+iy(\theta) \in \mathbb C$ as a vector $\in \mathbb R^2$ s.t.
$$z(\theta) = [x(\theta),y(\theta)] \in \mathbb R^2$$
Then
$$z'(\theta)= [x'(\theta),y'(\theta)]$$

(*) Definition is in Ch2.3. see the 2 red boxes below.


How to run the same JS script in one HTML file?

Question: I have a JS script that opens a modal dialog window when you click on a certain HTML element.
My problem is that the script only works for one element. When I call the same class name .trigger on another element, the entire script fails to work.
HTML

Contact Me Form

              x

Contact form details goes here

About Me

              x

About Me details goes here

JS
          var modal = document.querySelector(".modal");
          var trigger = document.querySelector(".trigger");
          var closeButton = document.querySelector(".close-button");

          function toggleModal() {
              modal.classList.toggle("show-modal");
          }

          function windowOnClick(event) {
              if (event.target === modal) {
                  toggleModal();
              }
              else if (event.target === closeButton) {
                toggleModal();
              }
          }

          trigger.addEventListener("click", toggleModal);
          closeButton.addEventListener("click", toggleModal);
          window.addEventListener("click", windowOnClick);

edit:
I tried to change my JS code and it still doesn't work:
          var modals = document.querySelectorAll(".modal");
          const triggers = document.querySelectorAll('.trigger');
          var closeButtons = document.querySelectorAll(".close-button");

        for (const trigger of triggers) {
             trigger.addEventListener('click', toggleModal);
          }

          function toggleModal(event)
            event.target.querySelector('.modal').classList.toggle("show-modal");
          }

          function windowOnClick(event) {
              if (event.target === modal) {
                  toggleModal();
              }
              else if (event.target === closeButton) {
                toggleModal();
              }
          }

          closeButton.addEventListener("click", toggleModal);
          window.addEventListener("click", windowOnClick);
    ```

Comment: `var modal = document.querySelector(".modal");` selects **only the first** `.modal` in the document. Use `const modals = document.querySelectorAll('.modal');` and then iterate over the list that gets you.
Comment: @connexo I tried changing it to querySelectorAll and it doesn't work
Comment: Your `function toggleModal(event)
            event.target.querySelector('.modal').classList.toggle("show-modal");
          }
` is missing an opening `{`.
Answer: var modal = document.querySelector(".modal"); selects only the first .modal in the document. Use const modals = document.querySelectorAll('.modal'); and then iterate over the NodeList you get from that.
Like this:
const triggers = document.querySelectorAll('.trigger');

for (const trigger of triggers) {
  trigger.addEventListener('click', toggleModal);
}

function toggleModal(event) {
  event.target.closest('.trigger').querySelector('.modal').classList.toggle("show-modal");
}

This would be the window click listener:
// get the modals and make an array from the NodeList
// so we can use array methods on the list
const modals = Array.from(document.querySelectorAll('.modal'));
function windowOnClick(event) {
  // check if the clicked element is a modal, or in a modal
  if (modals.some((modal) => modal.contains(event.target))) {
    toggleModal();
  }
}

Comment: Ok please bare with me as I'm sorta new with JS.
I added your revisions to my code and it still doesn't work! Am I doing anything wrong?
Please see my edit above and what I tried to change
Comment: That was just one part of your code re-written. Use this as a starting point and try to deeply inhale what's going on in this. When you've grabbed that, you can easily re-write the rest by yourself.
Comment: Hmm I still can't figure it out. Here is my fiddle. I added my thought process in comments http://jsfiddle.net/r4906skh/1/
Comment: `function toggleModal(event) {
  event.target.closest('.trigger').querySelector('.modal').classList.toggle("show-modal");
}`
Answer: JavaScript always runs on the entire HTML page. The reason why this is not working is that document.querySelector(".class-name") only selects the first element of that class.
Edit: I just saw your comment on your question. Sorry I cannot make comments because I don't have 50 reputations yet. querySelectorAll selects all elements and returns an array. You have to iterate through the array and perform whatever you want to do to each element in the array with a for loop.
Answer: Within the function windowOnClick(event) you could add more conditional statements within the if.
For example:
if(event.target == modal || event.target == trigger) {

   //do stuff
}

Then for the toggleModal() function, you could pass an argument along side with it, to add the class to the right element.
function toggleModal(element) {
    element.classList.toggle("show-modal");

}

Another way to approach this is using a switch statement, if the above doesn't help.
Answer: Can you use select by Id?

Or in Jquery:
$( ".trigger" ).first().

Answer: Trying to use this setup in shopify https://shopify.dev/tutorials/customize-theme-add-size-chart
But we also already utilize the same modal and want to have 2 guides on the page.
But when adding 2 the last pop up content shows for the first trigger.
Any insights on how to use this setup and have multiple pop ups and triggers on the page


Only half of jQuery animation working. I can seem to get all of it to work

Question: So I've gotten half of this code to work, but I can't seem to get the rest of it going.
I can get the div to fade in, but not the image to move.
var mouse_is_inside = false;

$(document).ready(function() {
$(".how_btn").click(function() {
    var howWorks = $("#jhow_works");
    if (howWorks.is(":visible"))
        howWorks.fadeOut("fast");
    else
        howWorks.fadeIn("fast");
    return false;

    $("#spot-1").animate({
    marginLeft: "+=40px",
}, 2000 );

});

$("#jhow_works").hover(function(){
    mouse_is_inside=true;
}, function(){
    mouse_is_inside=false;
});

$("body").click(function(){
    if(! mouse_is_inside) $("#jhow_works").fadeOut("fast");
});
});

the css
#jhow_works {
display:none;
position:absolute;
width:440px;
margin:310px 150px 0 360px;
}

img#spot-1 {
position: absolute;
margin-left: 55px;
margin-top: 20px;
}

The html

How it Works

I must be doing something stupid here. I appreciate any help
Thanks!
Answer: Move your return statement to the end of the click function.
$(".how_btn").click(function() {
  var howWorks = $("#jhow_works");
  if (howWorks.is(":visible"))
    howWorks.fadeOut("fast");
  else
    howWorks.fadeIn("fast");

  $("#spot-1").animate({
  marginLeft: "+=40px"}, 2000 );

  return false;
});

Answer: I was going to answer with the same code as Heather has provided above so instead I will just post a link to some useful information regarding return false;. This info was provided by another Stack Overflow user in another question What does "return false;" do?
Hope this helps someone.
Comment: It certainly helped me. Thanks!


Sum of residues.

Question: Let $q$ be a polynomial of degree $n$ with distinct zeroes $z_1,\ldots,z_n$. Let $p$ be a polynomial of degree $n-2$ or less. Show that:
$\displaystyle\sum_{K=1}^{n} \operatorname{Res}\left(\frac{p}{q};z_k\right)=0$
I'm trying to think of ways to use the residue theorem, but I'm not sure how to proceed...any input would be appreciated!!
Answer: Hint integrate over a really large circle.
Comment: I was going to ask a similar question. I still don't understand how to proceed. How do we proceed?
Comment: @User69127 Use the "ML-inequality" to show that $$\lim_{R\to\infty} \int_{|z|=R} \frac{p(z)}{q(z)}\, dz = 0.$$

Sum of residues.


OpenLDAP allow editing only from ldapi interface?

Question: I am working on securing LDAP server. We have a few scripts that help us to manage records in it, and the access (from outside) to the slapd is done over ldap(s) ports (389/636). Management scripts are executed from localhost on the server where slapd is running and use ldapi for access (as in -Y EXTERNAL -H ldapi:///). Access to ldapi only open from localhost (using firewall).
I would like to make sure (if that at all is possible) that any changes attempted via ldap(s) would fail, while changes via ldapi are allowed.
Is there any way to configure that in slapd config itself?
PS: This setup uses new config model (/etc/openldap/slapd.d/...) and not a file config.
Answer: It appears hat on a default configuration adding following ACL does the trick:
olcAccess: to *
  by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage

The fact that peercred authentication works only over ldapi interface is not obvious and not mentioned anywhere in the documentation.
The line was found in here and also confirmed by developers on IRC
Comment: The fact that peercred authentication works only over ldapi interface is completely obvious because you can get uid or gid of a client only with unix domain socket.