text:
Q: Jquery: cálculos com máscara de moeda real e soma de datas Estou com uma tela pronta.
Mas há alguns ajustes que não estou conseguindo resolver.
Um deles é o calculo de valores com a máscara de Real.
Sem ela, funciona perfeitamente. Com ela o resultado fica Nan (o campo "Valor" recebe o mesmo e calcula para "Provisão royalties franchising", "Provisão fundo propaganda" e "Provisão royalties franchising").
A data está somando, mas com resultados malucos (a "Data da emissão" calcula para "1º vencimento", "2º vencimento" e "3º vencimento").
Estou mexendo o dia todo nisso e tentei adicionar o links dos scripts, mas não consegui.
Essa é a máscara para o Real (* maskMoney plugin for jQuery * http://plentz.github.com/jquery-maskmoney/) e esta é a mascara para data (jQuery Mask Plugin v1.14.10 // github.com/igorescobar/jQuery-Mask-Plugin).
Segue o que consegui fazer até o momento.

$(document).ready(function() {
  /****** Função percentual ******/
  function funcao_percentual(valor_1, destino, percentual) {
    $(valor_1).on("click", function() {
      $(destino).val('');
    });

    function arredondar(valor, casas) {
      var novo = Math.round(valor * Math.pow(10, casas)) / Math.pow(10, casas);
      return (novo);
    }

    $(valor_1).blur(function() {
      valor = $(this).val();
      porcentagem = percentual; // PORCENTAGEM A SER ADICIONADA
      total = (parseFloat((valor * porcentagem) / 100));
      $(destino).val(arredondar(total, 2));
    });
  }

  /****** Função subtrair ******/
  function funcao_subtrair(valor_1, valor_2, inicio, destino) {
    $(inicio).on("click", function() {
      $(destino).val('');
    });

    function arredondar(valor, casas) {
      var novo = Math.round(valor * Math.pow(10, casas)) / Math.pow(10, casas);
      return (novo);
    }

    $(inicio).blur(function() {
      valor_1_v = $(valor_1).val();
      valor_2_v = $(valor_2).val();
      total = (parseFloat((valor_1_v - valor_2_v)));
      $(destino).val(arredondar(total, 2));
    });
  }

  /****** Função calcular a data ******/
  function funcao_calcular_data(data_inicial, data_final, dias) {
    $(data_inicial).blur(function() {
      $(data_inicial).on("click", function() {
        $(data_final).val('');
      });

      var data_ini = $(data_inicial).val();

      var date = new Date(data_ini);
      date.setDate(date.getDate() + dias);
      var futDate = date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear();

      $(data_final).val(futDate);
    });
  }

  /****** Percentual de Provisão - Royalties (franchising) ******/
  funcao_percentual("#valor", "#provisao_royalties_franchising", 39.85)

  /****** Percentual de Provisão Fundo Propaganda ******/
  funcao_percentual("#valor", "#provisao_fundo_propaganda", 3)

  /****** Subtração de Provisão - Royalties ( franchising) ******/
  funcao_subtrair("#provisao_royalties_franchising", "#provisao_fundo_propaganda", "#valor", "#provisao_royalties_franchising_2")

  /****** 1º vencimento ******/
  funcao_calcular_data("#data_emissao", "#1_venc", 28)

  /****** 2º vencimento ******/
  funcao_calcular_data("#data_emissao", "#2_venc", 42)

  /****** 3º vencimento ******/
  funcao_calcular_data("#data_emissao", "#3_venc", 56)

});

$(document).ready(function() {
  $('#data_emissao').mask('00/00/0000');
  $('#vencimento').mask('00/00/0000');
  $('#1_venc').mask('00/00/0000');
  $('#2_venc').mask('00/00/0000');
  $('#3_venc').mask('00/00/0000');
  $('#data_emissao_2').mask('00/00/0000');
  $('#vencimento_2').mask('00/00/0000');
  $('#data_emissao_3').mask('00/00/0000');
  $('#vencimento_3').mask('00/00/0000');
});

$(function() {
  $(".valor").maskMoney({
    symbol: 'R$ ',
    showSymbol: true,
    thousands: '.',
    decimal: ',',
    symbolStay: true
  });
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      Data da emissão

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="data_emissao" id="data_emissao">

        Tipo
        <input type="text" placeholder="Tipo" name="tipo" id="tipo" value="" class="form-control" />

        Nº nota fiscal
        <input type="text" placeholder="Nº nota fiscal" name="num_nf" id="num_nf" value="" class="form-control" />

        Razão social
        <input type="text" placeholder="Razão social" name="razao_social" id="razao_social" value="" class="form-control" />

        Valor
        <input type="text" placeholder="Valor" name="valor" id="valor" value="" class="form-control valor" />

        Vencimento

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="vencimento" id="vencimento">

        Forma de pagamento
        <input type="text" placeholder="Forma de pagamento" name="forma_pgto" id="forma_pgto" value="" class="form-control" />

        Descrição
        <input type="text" placeholder="Descrição" name="descricao" id="descricao" value="" class="form-control" />

        1º vencimento

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="1_venc" id="1_venc" readonly>

        2º vencimento

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="2_venc" id="2_venc" readonly>

        3º vencimento

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="3_venc" id="3_venc" readonly>

        Data da emissao

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="data_emissao_2" id="data_emissao_2">

        Provisão royalties franchising
        <input type="text" placeholder="Provisão royalties franchising" name="provisao_royalties_franchising" id="provisao_royalties_franchising" value="" class="form-control valor" readonly />

        Provisão fundo propaganda
        <input type="text" placeholder="Provisão fundo propaganda" name="provisao_fundo_propaganda" id="provisao_fundo_propaganda" value="" class="form-control valor" readonly />

        Nº documento
        <input type="text" placeholder="Nº documento" name="num_doc" id="num_doc" value="" class="form-control" />

        Valor
        <input type="text" placeholder="Valor" name="valor_2" id="valor_2" value="" class="form-control valor" />

        Vencimento

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="vencimento_2" id="vencimento_2">

        Provisão royalties franchising
        <input type="text" placeholder="Provisão royalties franchising" name="provisao_royalties_franchising_2" id="provisao_royalties_franchising_2" value="" class="form-control valor" readonly />

        Nº nota fiscal
        <input type="text" placeholder="Nº nota fiscal" name="num_nf_2" id="num_nf_2" value="" class="form-control" />

        Data de emissão

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="data_emissao_3" id="data_emissao_3">

        Valor
        <input type="text" placeholder="Valor" name="valor_3" id="valor_3" value="" class="form-control valor" />

        Vencimento

                   <button class="btn default" type="button">

                   </button>

          <input type="text" class="form-control" name="vencimento_3" id="vencimento_3">

        Xml
        <input type="text" placeholder="Xml" name="xml" id="xml" value="" class="form-control" />

        Visto arquivo
        <input type="text" placeholder="Visto arquivo" name="visto_arquivo" id="visto_arquivo" value="" class="form-control" />


text:
Q: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView I am working on an app that contain drawer layout and navigation view in it.
When i try to launch app without NavigationView it works fine.
But when i include NavigationView to DrawerLayout it is throwing below error in logcat
error showed in logcat
java class
layout xml image
buil.gradle:app
thanks in advance.

A: FIRST YOU SHOULD DO THIS
!! As you are going for a drawer layout why not to try a project with the built in boiler plate navigation drawer activity and compare the code with your project code?
you are putting the navigation view above the menu bar! and add it below! first comment the code of navigation view and run the code! if it works fine then go for navigation view by putting it under the menu bar and try to use it again.
your styles.xml should look like this
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
          <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>

    </style>

for the app bar (aka tool bar)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    android:id="@+id/toolbar"
    android:elevation="4dp">

</android.support.v7.widget.Toolbar>

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Find and Append/Prepend to existing javascript I have read many of the articles on using jquery to find and append. I have been successful at doing this on other projects, but mostly appending to a div element. I need to append to javascript on the page that unfortunately I don't have core access to.
Existing JS:

Before the RenderWidget, I need to add
 widgetVideoCanvas37.SetVariable("isAutoStart", "true");

I've tried something like this:
$( "widgetVideoCanvasDS37.RenderWidget()" ).prepend( "
Test
" );

but it does appear to be working. Maybe prepend isn't the best way to do this. Thanks in advance for the help!

A: The element would be selected like $('script').appened('blah');
But i feel that that probably won't or shouldn't work.  That be a very large security flaw if i was able to run my own script locally to append JavaScript to the script element of another page that i don't have core access to.


text:
Q: How to keep the spawnchunks loaded without generating the nether or end I'm on a creative server and I have the ability to use cheats, commandblocks, etc. I want to keep the spawn chunks loaded entity processing when no player is online. All solutions I know of work by transferring entities to the nether, the most common one used in iron farms spits poppies through a nether portal every 15 seconds. I'm searching for a solution that doesn't require generating the nether or end in my world.

A: Aha! A video that shows a redstone contraption to keep chunks loaded.

Doesn't even need spawn chunks; the video demonstrates the difference between entity-active chunks and redstone-only active chunks.
UPDATE:
Ok, I've now watched a bunch of videos on chunkloading, and one on chunk unloading.
Turns out that chunk unloading is not "all-at-once", but rather "Unload 100 now, go back and unload more next tick".

Here is the key observation: If a chunk is loaded, and all 24 chunks in a 5x5 around it are also loaded, then that chunk will process both redstone and entities.
Have a 5x5 area? The 1x1 in the middle does both.
Have a 7x7 area? The 3x3 in the middle does both.
Etc.
For chunk unload protection, see this:

Basically, minecraft takes the X and Z chunk location, does an xor hash map, and that becomes the bucket it goes into. If it goes into a late enough bucket, and there are enough chunks loaded, the chunk will live long enough for hoppers to activate adjacent chunks, and force them to load, even if the game was trying to unload them.
So the trick becomes:
1. Have more than 100 chunks that want to be loaded,
2. Find out which chunks are "last" on that unload list hash order,
3. Have those chunks use hoppers to activate other chunks, which then reloads all your chunks.
4. Have a 2-chunk border around any chunk you want entity processing on.

A: What the OP requested is impossible to achieve.
I decompiled the minecraft 1.10 code using MCP and I can confirm what Skylinerw said. The only way to have entities processed in a dimension without players in it is by having an entity travel between that dimension and another dimension at least every 15 seconds.

A: In 1.14 and abobe this game mechanic had changed. You can`t load chuncks with reddstone or hoppers anymore. You have to fire items trough the nether or force an skeleton to shot arrows to a snow golem. You have to fire items every 15 seconds, if you do so you will charge a 5x5 area.
Is better explained in this Ilmango's video:

A: If you are using modded version and can add a mod to the mod list, Mystcraft mod could be used: an island world, with no seas, will look very "empty" (like The End).


text:
Q: complexity of a recursive function inside another recursive function I can't figure out the solution of this excercise:
Calculate the complexity of f(g(n))+g(f(n)) with g and f defined as follows:
int f(int x) {
 if (x<=1) return 2;
 int a = g(x) + 2*f(x/2);
 return 1+ x + 2*a;
}

int g(int x) {
int b=0;
 if (x<=1) return 5;
     for (int i=1, i<=x*x;i++)
         b+=i;
 return b + g(x-1);
}

could anyone explain me how to get to the solution?

A: There are two separate steps to solving this problem. Firstly we must look at the time complexity of each function, and then the output complexity.

Time complexity
Since g is self-contained, let's look at it first.
The work done in g consists of:

*

*x^2 executions of a loop

*A recursive call with parameter x - 1
Hence one might write the time complexity recurrence relation as (using upper-case to distinguish it from the original function)

To solve it, repeatedly self-substitute to give a summation. This is the sum of the squares of natural numbers from 6 to x:

Where in the last step we used a standard result. And thus, since a is a constant:

Next, f:

*

*One call to g(x)

*One recursive call with parameter x / 2

*Some constant amount of work

Using a similar method:

Applying the stopping condition:

Thus:

Since the exponential term 2^(-x^3) vanishes:

Output complexity
This is basically the same process as above, with slightly different recursion relations. I'll skip the details and just state the results (using lower case for output functions):

Thus the final time complexity of f(g(n)) + g(f(n)) is:

Which matches the result given by your source.


text:
Q: Encoding problem in Java while reading data from site/page: During writing automated test i have one problem.
While I reading data from database or from page i have problem with polish diacritics chars.
For example

30-09-2019 15:43:51 INFO [Log]: Wnioskodawca AutoNawa wysłał/-a wniosek.
  30-09-2019 15:43:51 INFO [Log]: {{#pl}}{{loggedUser.fullName}} utworzył/-a szkic wniosku.{{/pl}}> {{#en}}{{loggedUser.fullName}} created application draft.{{/en}}

It should be Wnioskodawca AutoNawa wysłał/-a wniosek etc.
Do You know how to this this issue?
I tried to add suffix useUnicode=true&characterEncoding=utf8 on db connection line, but it not works for me


text:
Q: SOQL for loop returning a list or list I get the concept that SOQL has two flavors of for loops and it advises us to use SOQL query in for loop.
However, I am not clear on which version we should use when we expect a high number of records from SOQL query. The knowledge available on web leads to some confusion.
The two versions of soql for loop can be found in Apex dev guide here and it says that

SOQL for loops retrieve all sObjects, using efficient chunking with calls to the query and queryMore methods of the SOAP API. Developers should always use a SOQL for loop to process query results that return many records, to avoid the limit on heap size.

Then under "SOQL For Loop Formats" heading on the above documentation link it says that "if you intend to use DML inside for loop then use for loop which iterates on a list".

*

*It has also given a code block for both formats (under SOQL For Loop Formats heading on above doc) where it does not process each record with second format. If we want to do so then it will cause inner for loop which is my concern. If we use the second format then won't we end up with for loop inside a for loop because we need to read/process each and every record.

*Does the first (and usual format of for loop) retrieves records in batches of 200? I read Why can I loop over the result of a SOQL query as if it is a list of lists? and I am confused if second format is now a hold over, and first format (which is a usual for loop) is good enough to be used in all cases, and it will save you with heap problem.

*When the doc says that "SOQL for loops retrieve all sObjects, using efficient chunking" then which SOQL format it is talking about. Which SOQL for loop format uses chunking?

A:
If we use the second format then won't we end up with for loop inside a for loop because we need to read/process each and every record.

Yes, but nested for loops aren't inherently evil and don't always need to be avoided at all costs. If you have a list of data that contains another list of data (easiest example is probably the result of a SOQL query that contains a parent-child subquery), the natural way to process those results is with a nested loop.
The metric you should be looking at here is the total number of times you're looping.
If you have something like this
// myListA and myListB defined and populated elsewhere
// Just for safety, don't do this at home (or work)
// The following example is purposefully bad and should not be used
//   in actual code
for(ObjA aRec :myListA){
    for(ObjB bRec :myListB){
        if(aRec.Field__c == bRec.Field__c){
            // do work
        }
    }
}

That would loop a total of A * B times (where A and B are the sizes of their respective lists). Even with modest values of A and B, the number of times we loop is large. This is what we want to avoid.
The "chunked list of lists" approach adds a few extra loop iterations into the mix, but it's pretty tame.
for(List<MyObj> objList :[SELECT Id FROM MyObj]){
    for(MyObj objRec :objList){
        // do work
    }
}

The outer loop runs a single new iteration per 200 records, and then the inner loop iterates over each chunk of 200 records. If this query returns X records, the number of times we loop with that construction is X + X/200. If X is 10,000 that means we loop a total of 10,050 times.

Does the first (and usual format of for loop) retrieves records in batches of 200?

I think that would take someone from Salesforce to confirm or deny. In the end though, the answer to that question doesn't really matter to us developers. We can't tweak that number or do anything directly with the queryLocator.

When the doc says that "SOQL for loops retrieve all sObjects, using efficient chunking" then which SOQL format it is talking about. Which SOQL for loop format uses chunking?

They both use chunking. The difference is that the second approach (chunked list of lists) allows you to see the individual chunks as they're retrieved.


text:
Q: listbox selection not retaining on postback (yes i check for postback) I have a listbox in an asp.net webpage.
I select item 2. if i have autopostback on, this reloads the page and selects item1.
I only databind the page on first load (!IsPostback), have stepped through and verified this. It's not rebinding or repopulating the list, it just selects the first item again, removing the second item selection.
Furthermore, the onselectedindexchanged event only fires AFTER postback so i cannot retain the selected index in a session variable to set on postback...
page is set to viewstateenabled, controls set to viewstateenabled, viewstatemode is enabled.
How do I set it up so that the 2nd item is still selected on postback? My code is very straightforward but I'll post it...
<asp:ListBox ID="AvailableRepairSelection" runat="server" AutoPostBack="True"
            onselectedindexchanged="AvailableRepairSelection_SelectedIndexChanged"
            ViewStateMode="Enabled"></asp:ListBox>

Again, I select item 2, page posts back, item1 is highlighted.
relevant parts of codebehind:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int selectedmodel = Convert.ToInt32(Session["selectedModel"]);
            List<AvailableRepair> Repairs = (from r in Database.instance().AvailableRepairs
                                             where r.modelid == selectedmodel
                                             select r).ToList<AvailableRepair>();
            foreach (AvailableRepair repair in Repairs)
            {
                AvailableRepairSelection.Items.Add(new ListItem(repair.repair + ": " + repair.description + "- " + repair.cost, repair.cost));
            }
        }
    }

PLEASE NOTE that there is more to this page but I have isolated the only issues to be with these snippets. So dont advise me how to change my page or why i am posting back a selection when theres nothing but a listbox in the page.


text:
Q: LinearSeqOptimized#find Reference Copy Looking at the Scala 2.10.0's implementation of LinearSeqOptimized#find in LinearSeqOptimized.scala, why is it necessary to call var these = this?
Why couldn't this simply be used?
  override /*IterableLike*/
  def find(p: A => Boolean): Option[A] = {
    var these = this
    while (!these.isEmpty) {
      if (p(these.head)) return Some(these.head)
      these = these.tail
    }
    None
  }

A: Because you would have to have the same condition and operation out of the loop for this and then start using these.
It's much simpler to just put everyone in the same basket and do it all in the loop itself. Example:
def find(p: A => Boolean): Option[A] = {

  if (!this.isEmpty && p(this.head)) {
    return Some(this.head)
  }

  var these = this.tail

  while (!these.isEmpty) {
    if (p(these.head)) return Some(these.head)
    these = these.tail
  }

  None
}

Not very smart, as you can see.
You could also easily implement this as a @tailrec operation:
@tailrec final def find[A](p : A => Boolean) : Option[A] = {
  if ( this.isEmpty ) {
    None
  } else {
    if ( p(this.head) ) {
      Some(this.head)
    } else {
      this.tail.find(p)
    }
  }
}

And it isn't done like this in Scala because tailrec calls have to be final or private.


text: Q: How to fix the alignment of the slider text with logo? I am working on a rev slider on word press. I align text with logo in 1300px resolution screen but when it comes to 1500px or larger, text and logo alignment change. How to fix this problem?


text:
Q: how to disable "missing xml comment..." warning? I add swagger to my asp.net project. there are a lot of warnings
the warning code is blank. so I cannot disable it through 1591. please help me

A: Disable "XML documentation file"


text:
Q: Check AD for same passwords We have an issue at work where too many people have the same password and end up logging into other user's accounts. This is not helped by the group leaders who insist all work passwords should be similar.
I know it is a different issue, but is there a way to check the AD and say these users have the same password?

A: No way since the passwords are separately hashed. However, I would just go on and push the button enforcing everyone to change their password, as well as put policies on how the password shall look like and forcing passwords to be changed every 30-60-120 days. Highly unlikely that people will actually change their password to the same one.

A: If you have the password, you could know who have the same password using PrincipalContext from System.Security.Principal class, using something like that:
/// <summary>
/// Return true if user is authenticated
/// </summary>
/// <param name="strUsername_">User name</param>
/// <param name="strPassword_">User password</param>
/// <returns>True if authenticated</returns>
public static bool IsAuthenticated(string strUsername_, string strPassword_)
{
    using (var pc = new PrincipalContext(ContextType.Domain, DomainManager.DomainName))
        return pc.ValidateCredentials(strUsername_, strPassword_);
}

In this code, DomainManager.DomainName is Domain.GetCurrentDomain().Name from System.DirectoryServices.ActiveDirectory library.
The user has the specified password verified, the method will return true.
But in any case, you will never get a password from the user, you can only try to verify it.


text:
Q: Showing that something is a maximal ideal. Let $R$ and $R'$ be commutative rings with unity $1$ and $1'$. Let $\phi: R\to R'$ be a surjective ring homomorphism with $\phi(1) = 1'$. I'm to show that when $M$ is a maximal ideal in $R$ such that ker $\phi \subseteq M$, then $\phi[M]$ will be a maximal ideal in $R'$.
Now I was thinking that since $R$ is a commutative ring with unity and $M$ is a maximal ideal, then $R/M$ is a field. Then $\psi: R/M \to R'/\phi[M]$ given by $\psi(a+M) = \phi(a)+\phi[M]$ is an isomorphism.
But I think I have to show that every non-zero element in $R'/\phi[M]$ is a unit, in order to say that it is a field. And I'm not sure how to do that.
Once that is done I can say that $R'/\phi[M]$ is a field and so $\phi[M]$ is a maximal ideal in $R'$, right?

A: You've already shown that $\psi:R/M \to R'/\phi[M]$ is an isomorphism.  Since $R/M$ is a field and $R'/\phi[M]$ is isomorphic to $R/M$, $R'/\phi[M]$ is also a field.
Note: when you state that $\psi$ is an isomorphism, it bears mentioning (as justification) that $\psi$ is a surjective ring homomorphism from a field.

A: Suppose $\varphi(M)$ is not a maximal ideal, suppose $N'$ is an ideal containing $\varphi(M)$ and consider $\varphi^{-1}(N')$.
Hopefully we already know that the preimage of ideals is an ideal. To show that is is bigger than $\varphi(M)$ you should use that $\varphi^{-1}(m')$ is already contained in $M$ for all $m'\in \varphi(M)$  (to do this use that $\ker\varphi$ is contained in $M$).
You could also just use the correspondence theorem.


text:
Q: Can we have a simple root of real polynomials with coefficients as linear functions such that the curve of the root is tangent to imaginary axis? Let us consider a parametrized polynomial
\begin{align*}
f(x, r) = x^n + ra_{n-1} x^{n-1} + \dots + ra_0,
\end{align*}
where $r \in \mathbb R$ is the parameter and $a = (a_{n-1}, \dots, a_0)$ is fixed. Alternatively, we can consider $f(x) \in \mathbb R[x]$ with coefficients as linear functions over $\mathbb R$
\begin{align*}
f(x, r) = x^n + a_{n-1}(r) x^{n-1} + \dots + a_0(r).
\end{align*}
Since $r \in \mathbb R$, there exists $n$ continuous functions $b_1(r), \dots, b_n(r)$ such that for each $r$, $\{b_1(r), \dots, b_n(r)\}$ is the set of roots for $f(x,r)$ counting multiplicity. Now suppose for $r_0 \in \mathbb R$ and some $b \in \mathbb R$, $f(bi, r_0) = 0$ where $i$ denotes imaginary symbol. Further assume at $r_0$, $bi$ is a simple root. So at least locally around $r_0$ (if I am not mistaken), we should have a smooth function that tracks this root. Let us call this function $\gamma(r)$.
My question is: is it possible that the curve $\gamma(r)$ is tangent to the imaginary axis at $r_0$? Here is a plot to demonstrate what I have in mind. Note the plot is a parabola, but the shape is really not important. I only need the very local behavior about $r_0$.

This is related to a question I asked here Can roots of a polynomial stay on one side of the complex plane as the coefficients vary?

A: Yes, it is possible. Try
$$
p_r (x) = x^5+r(2x^4+5x^3+4x^2+4x+2).
$$Let $\epsilon = r-1$ and write $p_r(x) = 0$ as
$$
x^5+2x^4+5x^3+4x^2+4x+2 = -\epsilon (2x^4+5x^3+4x^2+4x+2)\quad\cdots (*).
$$ At $\epsilon = 0$, we see that $x= i$ is a root of $(*)$. And a numerical plot shows that $\gamma(1+\epsilon)$ has a positive real part for all $\epsilon$ with sufficiently small absolute value. You can check this easily on the web using https://www.wolframalpha.com/.
$\textbf{EDIT:}$ Here's how I got this example. First, we can without loss of generality, assume that $r_0 = 1$ (through rescaling) and thus any such example is of the form of $(*)$:
$$
x^n + b_{n-1}x^{n-1} + \cdots + b_1x + b_0 = -\epsilon (b_{n-1}x^{n-1} + \cdots + b_1x + b_0)=-\epsilon Q(x)\quad\cdots(**).
$$ We can further assume that $x=i $ is a root of $(**)$ when $\epsilon=0$. That is, $i^n + Q(i)=0$. Secondly, we have
$$
\gamma(1+\epsilon) = i -\epsilon \frac{Q(i)}{ni^{n-1}+ Q'(i)}+\mathcal{o}(\epsilon),
$$ and hence $\gamma'(1) = -\frac{Q(i)}{ni^{n-1}+ Q'(i)} =i\beta$ for some real $\beta$. It is recommended to choose a high $n$ to produce such a plot in your figure. On the other hand, choosing a high $n$ produces too many coefficients to be determined. My choice was $n=5$. So, let $Q(x) = ax^4 + bx^3 + cx^2 +dx +e$ and do the calculation using $i + Q(i)=0$ and $-\frac{Q(i)}{5+ Q'(i)} = \frac{i}{5+ Q'(i)}=i\beta.$ This yields:
$$
(a-c+e) +i(-b+d+1) =0,
$$
$$
(-3b +d+5)+i(-4a+2c) =\frac{1}{\beta}=\beta'.
$$ This gives restrictions on the coefficients:
$$
c=2a, e=a, d=b-1,
$$ and $a,b$ are free variables. Finally, choose arbitrary $(a,b)$ and execute the test whether it produces such a plot. You may be able to find many other examples using this method.


text:
Q: I try to connect in my databases Atlas MongoDB with flutter but it's does'nt work import 'dart:collection';

import 'package:flutter/foundation.dart';
//import '../datas/data.dart' as data;
import '../models/city_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class CityProvider with ChangeNotifier {
  final List<City> _cities = [];
  UnmodifiableListView<City> get cities => UnmodifiableListView(_cities);

  City getCityByName(String cityName) =>
      cities.firstWhere((city) => city.name == cityName);

  fetchData() async {
    try {
      http.Response response = await http.get('http://10.0.2.2:80/api/cities');
      print(json.decode(response.body));
    } catch (e) {
      rethrow;
    }
  }
}

An Observatory debugger and profiler on TECNO KA7 is available at: http://127.0.0.1:56141/qSlaCfRC08A=/
E/flutter (19000): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: SocketException: OS Error: Connection timed out, errno = 110, address = 10.0.2.2, port = 45965

A: I think this is a problem with android debug bridge.
You can try
adb reverse tcp:<Port on your phone> tcp:<Port on your computer>


text:
Q: Audio File in RAM and play back - Bash 4.3.42 I am working here on a MacBook with El Capitan on it. OS X has an integrated text to speech program, that you can use via the command say.
The problem I have with this command is that my MacBook is kind of old and runs out of RAM quickly. So, I can use this command, but the first two sentences will sound really off, while the next sentences sound perfect.
I use the say command at the end of my alarm and egg-timer script, giving out a message. Right now I use bsay which is a little script written by me:
#!/bin/bash

path="/Users/joe/.joe_script/resources/bsay/"
name=".$(date "+%s").ogg"
say -o ${path}$name "$*"
afplay ${path}$name
rm $path$name

This works quite fine so far. Yet, I think it should even be better. I wanted to hold it in RAM and play it in RAM instead of writting it down on my drive. I have just no clue how to archieve that. At first, I imagined a single string would do it. I tried to simply do it by using the following line:
audio=$(say "Whatever I want to say")

It spoke it aloud instead. Than I thought, I just add prove of concept and tried this:
say -o output.ogg "Whatever I want to say"
audio="$(cat output.ogg)"
afplay $audio

That just gave me an explanation how afplay works... okay, bummer.. afplay doesn't support variables. But as a prove of concept, I tried this:
say -o output.ogg "Whatever I want to say"
audio="$(cat output.ogg)"
echo $audio >> output2.ogg
afplay output2.ogg

Which in turn did only give me back an error message:
Error: AudioFileOpen failed ('typ?')

So, I assume I am far off with my attempts. Can someone give me any hints or directions in which I could archieve something like that?

A: Your attempts are very logical and only fails because bash variables can't contain NUL bytes:
var=$'\0foobar'
[[ -z $var ]] && echo "Bash thinks the string is empty :( "

There are multiple options:

*

*Just stick with a temp file. Because it's so short lived, it might never reach the disk anyways

*Create a ram disk and store the file there.

*Use base64 or similar to convert binary data to text and back, so you can keep it in a variable.

*Pipe to a tool like sponge that can soak up input and then output it all at once.
Getting say to pipe audio data instead of writing to a file is another matter, and may require workarounds like named pipes.


text:
Q: Create a fifth column as list with PowerShell I have to make a fifth column in my array but when I run the script it gives me that :

Column1 :
Column2 :
Column3 :
Column4 :
Column5 :

I would like to get this:

Column1  Column2   Column3   Column4  Column5
-------  -------   -------   -------  -------

The code I'm using allows to display four columns and remove the matching cells in the array.
$csv = Import-Csv .\test1.csv -Delimiter ';'

$ref = [ordered]@{}
$columns = foreach ($i in 0..7) { ,[Collections.ArrayList]@() }

foreach ($row in $csv) {
    $value = $row.Column1
    $ref[$value] = $true
    $columns[0].add($value) >$null
}

foreach ($row in $csv) {
    $i = 1
    foreach ($col in 'Column2', 'Column3', 'Column4') {
        $value = $row.$col
        if (!$ref[$value]) {
            $columns[$i].add($value) >$null
        }
        $i++
    }
}

$maxLine = ($columns | select -expand Count | measure -Maximum).Maximum - 1
$csv = foreach ($i in 0..$maxLine) {
    [PSCustomObject]@{
        Column1 = $columns[0][$i]
        Column2 = $columns[1][$i]
        Column3 = $columns[2][$i]
        Column4 = $columns[3][$i]

    }
}

$csv

The lists have been build separately then joined in this context.

A: You are probably looking for the Format-Table cmdlet:
$csv | Format-Table


text:
Q: Fixed footer is cropped by Mobile Safari UI footer Trying to get my icon footer with social links to move above the Safari UI footer without adding padding or margin that breaks the style of the fixed bar on chrome or other browsers. Not sure why it's happening or if there's even an answer. This issue is when you click my hamburger menu and reveal my personal info it gets cropped at the bottom a bit and doesn't allow for the full size of the footer.
Hope you guys can help.
https://www.alexcoven.com
Bug is only in Mobile Safari.

Mobile Chrome:

A: I found that I was using vh as my variable for height and it was not getting read well on mobile devices. I than changed the height of my containers to be
height: calc (100% - 60px);

60px being the height of my footer. This worked famously!


text:
Q: What's the verb in this sentence? What is the verb in this sentence?

The friends had to get the door open soon.

I think it is open, but I am not sure.

A: Yes, "had to" is considered the verb here. The verb "had" typically indicates possession, but in this case it is actually a phrase that's used instead of the modal verb "must." It is actually the past tense of "have to." So the sentence could be rewritten as, "The friends must get the door open soon."
"get" is also a verb, but it is a bare infinitive. The main verb "had to" (or "must") takes the infinitive "to get" as its complement.
Note: the sentence can be simplified by just saying, "The friends must open the door soon." (In this case, "friends" is the noun, "must" is the (modal) verb, "open" is the bare infinitive (i.e. "to open" without the "to"), "the door" is the direct object, and "soon" is an adverb.)

A: Had (past tense of 'to have').
Compare "The friends must eat" and "The friends eat". The action in the first case is clearly not eating.

A: It is even easier to come to the answer if the sentence is shortened to "Friends had to"....... HAD is the verb."
"Open" I think would be an adjective as used in your question.


text:
Q: Filtering rows with junk characters using SQL Server regex In my table, certain rows have junk characters like Ё㺞稹㾸䐶ꖆ㩜癈ῤ in certain columns. I am trying to filter out such rows like below:
SELECT Col1, Col2, Col3 FROM MyTable WHERE Col2 NOT LIKE '%[REGEX]%'

*

*Is there any better approach?

*If no, how can I generate a proper regex? I don't want any records where Col2 has anything but alphanumeric characters, punctuations, and a space.

A: SQL Server doesn't support proper RegExs in the LIKE.
The pattern syntax does support negation (^) and ranges or sets of characters though so you could use something like..
WHERE Col2  LIKE N'%[^0-9A-Za-z .,;:]%' collate Latin1_General_BIN


text:
Q: No mic permission for CTI softphone after Chrome 63 deprecates cross origin iframe permissions We have a phone system integrated with Salesforce using OpenCTI and I'm looking for a solution to this: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes
Once Chrome 63 is rolled out it will no longer by default give permission for certain privileges such as microphone access to cross origin iframes. My understanding is this will prevent the mic from working in our softphone. I don't have much experience with CTI implementation and wasn't involved in the setup of this system so I'm flying a bit blind here. The phone system dev has suggested we need to update the Salesforce iframe tag or add an http header to include an allow attribute for microphone - the link above presents the example:
<iframe src="https://example.com" allow="geolocation; microphone; camera"></iframe>

I've looked around and from what I can see there's nowhere in Salesforce to configure the CTI iframe at this level. We are not using a softphone layout in Salesforce, just an external one hosted by the phone system. We have custom classes and a custom visualforce screen pop on call connection but I don't think they're of any use to this issue.
Is this something we can solve in Salesforce, or does it require changes in the CTI adapter?

A: Interesting thread here https://partners.salesforce.com/_ui/core/chatter/groups/GroupProfilePage?g=0F9300000001tcz&fId=0D53A00003OVvvs&s1oid=00D300000000iTz&OpenCommentForEdit=1&s1nid=0DB3000000007Uh&emkind=chatterPostNotification&s1uid=00530000009pmVs&emtm=1516049309647&fromEmail=1&s1ext=0
Open CTI product manager says:
"we're aware of the issue and are testing the fix. We'll be patching it soon so customers aren't inconvenienced. Exact dates are tbd at the moment."


text:
Q: How can I repeat an animation after changing the text inside the element? I have an text element (HTML) that plays an animation when the page loads and I'm trying to create a script to change the original text to a different one and then play the same animation. Here is part of my code:

setTimeout(function typewriter() {
    let txt;
    let themes = document.getElementById("themes");
    txt = "Games";
    themes.innerText = txt;
    themes.classList.add("changer");
}, 4000);
.typewriter h1 {
    color: #ffffff;
    background-color: #000000a8;
    border-radius: 5px;
    padding: 10px;
    font-family: monospace;
    font-size: 35px;
    overflow: hidden; /* Ensures the content is not revealed until the animation */
    border-right: .15em solid #333333; /* The typwriter cursor */
    white-space: nowrap; /* Keeps the content on a single line */
    margin: 0 auto; /* Gives that scrolling effect as the typing happens */
    animation:
      typing 2s steps(30, end),
      blink-caret .5s step-end infinite;
}
.changer {
    animation: typing 2 s steps(30, end),blink - caret .5 s step - end infinite;
}
/* The typing effect */
@keyframes typing {
    from { width: 0 }
    to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
    from, to { border-color: transparent }
    50% { border-color: #333333 }
}

Science

The problem is that after 4 seconds when the text changes I can't play the animation again. Can anyone help me, please? Thank you.

A: First, you are using setTimeout (This is wrong)
If you want it to repeat the function, you should use setInterval.
Second, you are changing the same "Text" every time you call the function, which is "Games". If you want it to change to a certain text, you need to store it first in an array,
var texts = [];

//Add a counter
var curr = 0;

//Store in array
texts.push("Games");
texts.push("Science");

setInterval(function() {
    let txt;
    //Change the texts array value with curr variable (the Counter)
    txt = texts[curr];
    let themes = document.getElementById("themes");
    themes.innerText = txt;
    themes.classList.add("changer");

    //Change the counter variable
    curr += 1;

    //Change the counter to the start of the array
    if(curr >= texts.length) curr = 0;
}, 4000);

In my case, the animation doesn't work. But if you want to change the text for every 4s, this code will help you.
You can add any number of text that you want.

A: I found a solution using JavaScript to increase the width of the element from 1% to 100%!
Here is my JavaScript code:
var texts = [];

//Add a counter
var curr = 0;

//Store in array
texts.push("Games");
texts.push("Science");

setInterval(function() {
    let txt;
    //Change the texts array value with curr variable (the Counter)
    txt = texts[curr];
    let themes = document.getElementById("themes");
    themes.innerText = txt;

    var width = 0;
    var id = setInterval(frame,10);
    function frame(){
        if(width >= 100){
            clearInterval(id);
        } else {
            width++;
            themes.style.width = width + "%";
        }
    }

    //Change the counter variable
    curr += 1;

    //Change the counter to the start of the array
    if(curr >= texts.length) curr = 0;
}, 4000);

Thank you for the help!


text:
Q: Is it worth to pool SocketAsyncEventArgs for reuse in this scenario? In my scenario, there are many clients' tcp sockets connected to the server.The server  ReceiveAsync() from all sockets and when the callback is called without error, parse the received data. If one socket's received data is an certain type of message , the receive callback will SendAsync() to all other sockets by a loop,and then start to ReceiveAsync() again. So for one socket, it has chance to call SendAsync() by many other Receivers'callback
in a very short time. I tried to synchronize the Sendings by waitone semaphore and release one semaphore after the sending IO completed so I can use only one SAEA obj for each socket, but this may cause the receiver's callback block in the sending loop . So I canceled the semaphore  and pooled some SAEA objs for each socket's sending method. However I found that some mobile-phone clients have big chance to lost there IP connection and there socket SendAsync() methods   ' error callbacks will not be called promptly.Perhaps in several minutes,  no SAEA will be recycled to the pool.
Another question is, if I pool the reusable SAEA, will the SAES.Buffer make memory fragments? Can I avoid the memory problem by calling SAEA.SetBuffer(null,0,0) method before pooling the SAEA?

A: To avoid memory fragmentation we use one giant buffer and assign a certain region of this buffer to each SAEA. So memory usage stays the same during the whole time and memory is allocated continuously.
Right now we use pooled SAEAs which can be a PITA, but it seems to be the most advocated solution (if you use SAEAs at all that is)


text:
Q: Jmeter Create JDBC Connection Configuration instance in java code I Would like to ask if there is a way to create instance of JDBC Connection Configuration for JMeter by code and not via GUI .
i have The following threadGroup :
SetupThreadGroup threadGroup = new SetupThreadGroup();
        threadGroup.setNumThreads(jMeterParam.getNumOfConnections());
        threadGroup.setRampUp(0);
        threadGroup.setDuration(7200);

    JDBCSampler sampler = new JDBCSampler();
    sampler.setQuery("select top 1 * from Production.ProductPhoto;");
    sampler.setVariableNames("firstPrfile");
    sampler.setQueryType("Select Statement");
    ConstantTimer timer = new ConstantTimer();
    timer.setDelay("300");

I need to create instance of JDBCConnectionConfiguration in order to set JMeter variable name , max number of connections , pool timeout , and all avilable parameters in JDBC Connection Configuration JMeter GUI .

The issue that i need to write java code in order configure Test Plan and run it via JMeter .
i have tried your suggestion to create JDBC connection as bellow :
SetupThreadGroup threadGroup = new SetupThreadGroup();
        threadGroup.setNumThreads(jMeterParam.getNumOfConnections());
        threadGroup.setRampUp(0);
        threadGroup.setDuration(7200);
        DefaultPoolController defaultPoolController = new DefaultPoolController();

        JdbcConnectionFactory jdbcFactory = new JdbcConnectionFactory("jdbc:sqlserver://10.10.10.171:1401;databaseName=AdventureWorks","sa","1q@W3e4r",true,"True","com.microsoft.sqlserver.jdbc.SQLServerDriver");
        JdbcConnectionPool jdbcConnPool= new JdbcConnectionPool(jdbcFactory,defaultPoolController,0,10,true);

        JDBCSampler sampler = new JDBCSampler();
        sampler.setQuery("select top 1 * from Production.ProductPhoto;");
        sampler.setVariableNames("firstPrfile");
        sampler.setQueryType("Select Statement");
        ConstantTimer timer = new ConstantTimer();
        timer.setDelay("300");

        sampler.addTestElement(timer);

        // Test plan
        TestPlan testPlan = new TestPlan("MY TEST PLAN");
        hashTree.add("testPlan", testPlan);
        hashTree.add("threadGroup", threadGroup);
        hashTree.add("JDBC Connection Configuration", jdbcConnPool);
        hashTree.add("sampler", sampler);

        jm.configure(hashTree);

        jm.run();

When running WARN MSG shown :
1) "Something bad happened when loading bean info for bean class org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler"
2) Did not find ".....ApacheJMeter.jar/commons-io-2.2.jar/etc ....
Do You know How to Solve it ?
Thanks A lot,
Khilo

A: I personally create my test via JMeter GUI and don't use JMeter API directly. But considering your question I think you can create JDBC connection and perform needed query without instantiating JDBC sampler. Or you can create BSF Sampler and setup connection and query in its body. I did the second way (although I used GUI): created BSF Sampler, connect to DB and perform query, then manipulate data using Groovy.


text:
Q: Extract unique elements from each row of a matrix (Matlab) I would like to apply the function unique to each row of a given matrix, without involving any for loop. Suppose I have the following 4-by-5 matrix
full(A) = [0    1     0     0    1
           2    1     0     3    0
           1    2     0     0    2
           0    3     1     0    0]

where A is the corresponding sparse matrix. As an example using a for loop, I can do
uniq = cell(4,1);
for i = 1:4
    uniq{i} = unique(A(i,:));
end

and I would obtain the cell structure uniq given by
uniq{1} = {1}
uniq{2} = {[1 2 3]}
uniq{3} = {[1 2]}
uniq{4} = {[1 3]}

Is there a quicker way to vectorize this and avoid for loops?
I need to apply this to matrices M-by-5 with M large.
Note that I'm not interested in the number of unique elements per row (I know there are around answers for such a problem).

A: You can use accumarray with a custom function:
A = sparse([0 1 0 0 1; 2 1 0 3 0; 1 2 0 0 2; 0 3 1 0 0]); % data
[ii, ~, vv] = find(A);
uniq = accumarray(ii(:), vv(:), [], @(x){unique(x.')});

This gives:
>> celldisp(uniq)
uniq{1} =
     1
uniq{2} =
     1     2     3
uniq{3} =
     1     2
uniq{4} =
     1     3

A: you can use num2cell(A,2) to convert each row into cell and then cellfun with unique to get cell array of unique values from each row:
% generate large nX5 matrix
n = 5000;
A = randi(5,n,5);
% convert each row into cell
C = num2cell(A,2);
% take unique values from each cell
U = cellfun(@unique,C,'UniformOutput',0);


text:
Q: Horizontal scrollview in XAML I have a list of MyClass:
 public class MyClass
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Type { get; set; }
        }

I would like to display this list in a Horizontal scrollview. Im doing it in XAML and having a hard time finding examples. I got this now:
<ScrollView Orientation="Horizontal">
      <ListView x:Name="MyClassList"
                  ItemsSource="{Binding MyClassList}"
                    RowHeight="210">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          <Grid Padding="5">
            <Grid.RowDefinitions>
              <RowDefinition Height="20"></RowDefinition>
              <RowDefinition Height="20"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1*"></ColumnDefinition>
              <ColumnDefinition Width="1*"></ColumnDefinition>
            </Grid.ColumnDefinitions>

          </Grid>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
    </ScrollView>

But this presents the list in a vertical manner. Any tips on how to scroll this list horizontally?

A: Not entirely sure if I understand the issue. My interpretation is that you want the ListView itself to add elements horizontally instead of vertically.
This can be achieved by settings the ListViews ItemsPanel to a horizontal StackPanel.
Try this:
<ScrollView Orientation="Horizontal">
    <ListView x:Name="MyClassList"
                  ItemsSource="{Binding MyClassList}"
                  RowHeight="210">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"></StackPanel>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid Padding="5">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="20"></RowDefinition>
                            <RowDefinition Height="20"></RowDefinition>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="1*"></ColumnDefinition>
                            <ColumnDefinition Width="1*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>

                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ScrollView>

A: This has been solved with a custom class called ItemsView (not to be confused with Xamarin's ItemsView for data templating in a ListView) which implements a ScrollView/StackPanel pattern.  Please see the code: https://gist.github.com/fonix232/b88412a976f67315f915


text:
Q: What is happening behind .setAttribute vs .attribute=? Description:
I am using simple javascript to set a the value of an input. I am using multiple methods that appear to be the same but with different results. Here is an example:
HTML:
<input name="testinput" value="" type="text" />

Javascript:
var input = document.getElementByTagName('input')[0];
input.value = "5"

console.log(input.value) // returns "5"
console.log(input.getAttribute("value")) // returns ""

Of course the functionality is reversed when using the setAttribute() function. Yet, when on form submit they both give a input=5 result.
Question:
What is the point of separating the two properties? is the .value stored differently than the .getAttribute("value")?
Disclaimer:
I have read:

*

*When to use setAttribute vs .attribute= in JavaScript?

*Setting a property via property or setAttribute
Both of those question/answers left me confused and unsatisfied.

A: input.value is dot notation, it sets the value property of the input object.
It does in no way update any attributes, so trying to get an attribute with the same name will not return the updated value.
If for some reason you have to update the attribute, you would do
input.setAttribute('value', 'new_value');

but you shouldn't have to use that, as you generally should be working with the properties, not the attributes, and you'd set and get the value property, not the attribute.

An attribute in HTML is a key / value pair inside the opening and closing brackets, as in

In many cases such attributes will set the initial value of the underlying property, and the property is a named key with a value, that is attached to the internal model of an element, which is what we access with javascript, the object holding the model and data for the element.
Changing any of that objects keys or values does not change the HTML, only the internal representation of the element, the object. However, changing the HTML attributes will in some cases change the object representation of the element.
getAttribute gets the actual attributes from the HTML, not the properties, while element.value clearly accesses a named property in the object representing that element.

A: It's important to take note of the differences between attributes and properties.
The value attribute
The value attribute of an <input>, visible in the HTML representation of the element, is mapped to the defaultValue property. For example:
var i = document.createElement('input');
i.setAttribute('value', 'foo');
console.log(i.defaultValue, i.getAttribute('value')); // "foo foo"

i.defaultValue = 'bar';
console.log(i.defaultValue, i.getAttribute('value')); // "bar bar"

The value property
The value property mirrors the defaultValue property (and value attribute) until it's explicitly been given a value, so:
var i = document.createElement('input');
i.defaultValue = 'foo';
console.log(i.value); // "foo"

i.value = 'bar';
i.defaultValue = 'foo';
console.log(i.value); // "bar"

This is another way of looking at it:
<input value="foo">
       ↑↓
input.defaultValue = "foo";
        ↓
input.value
  get(): value === undefined ? input.defaultValue : value
  set(newValue): value := newValue

Anchors
When using anchors, the href attribute and href property update each other, but in a different way, e.g.:
var a = document.createElement('a');
a.setAttribute('href', '/test');
console.log(a.href); // "http://stackoverflow.com/test"

a.href = '/test';
console.log(a.getAttribute('href')); // "/test"

Other elements
Here's a (partial) list of attributes and their corresponding properties:
element  | attribute | property
---------+-----------+----------------
option   | selected  | defaultSelected (bool)
label    | for       | htmlFor
input    | checked   | defaultChecked (bool)
select   | multiple  | multiple (bool)
li       | value     | value (int)

As you can see, whereas the attributes are always strings, the corresponding properties may be of other types.


text:
Q: How to make a PXE boot, if the client PC has no network card driver? As I have researched, we can do a clean installation of an OS through network booting (PXE boot). I have also tried to do it to a virtual machine via windows Deployment Services (WDS). It was OK. Because, virtual machine contains its virtual drivers. But when it comes to a physical machine, doesn't it need to have network card drivers installed, before starting a network boot? How the PC gets an IP address through DHCP, if it doesn't have correct drivers? How we can install drivers before the Network boot?

A: There was a great article in the TechNet Magazine column 'The Desktop Files' a few years ago called 'Network-Booting Windows' explaining PXE booting in great detail. This quote from the article is specific to your question:

Step 2: If the boot order puts PXE ahead of hard disks, or flash drives, or CD-ROMs, or if none of those devices are present, the Universal Network Driver Interface (UNDI) is loaded from NIC. The NIC features an extremely small network device driver and a Trivial File Transfer Protocol (TFTP) implementation.

So, at this point, no drivers are needed, as they are included on the NIC itself.
However, once you start loading an OS, that OS will need drivers. For example, If you are using Windows Deployment Services (WDS), you will use PXE booting to load the Windows PE image so that you can deploy a Windows image to the computer. You will need drivers for the Windows PE image, and for the Windows image that you deploy.
More information about deploying Windows can be found on the Deploy Windows 7 page of the Springboard Series on TechNet.
Hope this helps,


text:
Q: Create complex file name from user input I'm trying to adapt a script that currently contains the following segment:
#  Initialize the output files
working_dir = os.getcwd()
output_path = "{}/{}".format(working_dir, "output_Prelim")
if not os.path.exists(output_path):
    os.mkdir(output_path)
data_file = "{0}/RWA_2010_BUFFER_by_1.csv".format(output_path)
error_file = "{0}/failed_queries.txt".format(output_path)

In the statement that begins "data_file," the parts of the file name "RWA" and "2010" refer to the country and year in which a particular survey was conducted.
I'm trying to adapt that segment so that the file name preserves the same general format, but allows the user to enter a different country code and year.
I can generate a string called "file_name" that looks right, using the following code:
print('Enter the country code')
cCode =input()
print('The country code is '+cCode)
print('Enter the survey year')
srvyYear =input()
print('The survey year is '+srvyYear)

file_name = r'"{0}/'+cCode+'_'+srvyYear+'_'+'BUFFER300_by_1.csv"'\

When I print "file_name," I get
"{0}/BDI_2009_BUFFER300_by_1.csv"

That looks right, but am not sure what to do with it - in particular, how to get it understood as a file name rather than as a string.  When I try to concatenate that string with the remainder of the statement that begins "data_file," I get a syntax error.
Obviously I need to do a tutorial, but am not sure what to look for.
Many thanks, and apologies for the newbie question.

A: Not sure what your problem is exactly, but if you want to replace the {0} part with something else (e.g. the value in data_file), you can just do file_name.format(data_file).

A: Why not use join() method for string and os.path.join() for paht? e.g.
file_name = os.path.join(out_path, '_'.join([cCode, srvyYear, 'BUFFER300_by_1.csv']))

You can see its doc here, I believe that is what you needed, you'd better not concatenate string by yourself to construct path or filename. By the way, os.path.join() can construct filename without platform dependence, it will be a smart choice (especially for Windows).


text:
Q: How to optimize extracting data from nested hashes in ruby? Background
I have a collection of nested hashes which present a set of parameters to define application behavior:
custom_demo_options: {
    verticals: {
        fashion: true,
        automotive: false,
        fsi: false
    },
    channels: {
        b2b: true,
        b2c: true
    }
}

website_data: {
    verticals: {
        fashion: {
            b2b: {
                code: 'luma_b2b',
                url: 'b2b.luma.com'
            },
            b2c: {
                code: 'base',
                url: 'luma.com'
            }
        }
    }
}

The choices made in the custom_demo_options hash relate to data stored in the website_data hash and serve to return values from it:
data = []
collection = {}
custom_demo_options[:verticlas].each do |vertical_name, vertical_choice|
    # Get each vertical selection
    if vertical_choice == true
        # Loop through the channels for each selected vertical
        custom_demo_options[:channels].each do |channel_name, channel_choice|
            # Get each channel selection for each vertical selection
            if channel_choice == true
                # Loop through the website data for each vertical/channel selection
                website_data[:verticals].each do |site_vertical, vertical_data|
                    # Look at the keys of the [:website_data][:verticals] hash
                    # If we have a vertical selection that matches a website_data vertical...
                    if site_vertical == vertical_name
                        # For each website_data vertical collection...
                        vertical_data.each do |vertical_channel, channel_value|
                            # If we have a matching channel in the collection...
                            if vertical_channel == channel_name
                                # Add the channel's url and code to the collection hash
                                collection[:url] = channel_value[:url]
                                collection[:code] = channel_value[:code]
                                # Push the collection hash(es) onto the data array
                                data.push(collection)
                            }
                        }
                    }
                }
            }
        }
    }
}

The data pushed to the data array is ultimately used to create the following nginx map definition:
map $http_host $MAGE_RUN_CODE {
    luma.com base;
    b2b.luma.com luma_b2b;
}

As an example of the relationship between the hashes, if a user sets custom_demo_options[:channels][:b2b] tofalse, the b2b code/url pair stored in thewebsite_data` hash would be removed from the nginx block:
map $http_host $MAGE_RUN_CODE {
    luma.com base;
}

Question
The above code works, but I know it's horribly inefficient.  I'm relatively new to ruby, but I think this is most likely a logical challenge rather than a language-specific one.
My question is, what is the proper way to connect these hashes rather than using loops as I've done?  I've done some reading on hash.select and it seems like this might be the best route, but I'd like to know: are there are other approaches I should consider that would optimize this operation?
UPDATE
I've been able to implement the first suggestion (thanks again to the poster); however, I think the second solution will be a better approach. Everything works as described; however, my data structure has changed slightly, and although I understand what the solution is doing, I'm having trouble adapting accordingly.  Here's the new structure:
custom_demo_options = {
    verticals: {
        fashion: true,
        automotive: false,
        fsi: false
    },
    channels: {
        b2b: true,
        b2c: true
    },
    geos: [
        'us_en'
    ]
}
website_data = {
    verticals: {
        fashion: {
            us_en: {
                b2b: {
                    code: 'luma_b2b',
                    url: 'b2b.luma.com'
                },
                b2c: {
                    code: 'base',
                    url: 'luma.com'
                }
            }
        }
    }
}

So, I add another level to the hashes, :geo.
I've tried to adapt the second solution has follows:
class CustomOptionsMap
    attr_accessor :custom_options, :website_data

    def initialize(custom_options, website_data)
        @custom_options = custom_options
        @website_data = website_data[:verticals]
    end

    def data
        verticals = selected_verticals
        channels = selected_channels
        geos = selected_geos

        # I know this is the piece I'm not understanding.  How to map channels and geos accordingly.
        verticals.map{ |vertical| @website_data.fetch(vertical).slice(*channels) }
    end

    private
    def selected_geos
        @custom_options[:geos].select{|_,v| v } # I think this is correct, as it extracts the geo from the array and we don't have additional keys
    end
    def selected_verticals
        @custom_options[:verticals].select{|_,v| v }.keys
    end
    def selected_channels
        @custom_options[:channels].select{|_,v| v }.keys
    end
end

demo_configuration = CustomOptionsMap.new(custom_demo_options, website_data)
print demo_configuration.data

Any guidance on what I'm missing regarding the map statement would be very much appreciated.

A: Say you have key = :foo and hash = { foo: 1, bar: 2 } - you want to know the hash's value for that key.
The approach you're using here is essentially
result = nil
hsh.each { |k,v| result = v if k == :foo }

But why do that when you can simply say
result = hsh[:foo]

It seems like you understand how hashes can be iterable structures, and you can traverse them like arrays. But you're overdoing it, and forgetting that hashes are indexed structures. In terms of your code I would refactor it like so:
# fixed typo here: verticlas => verticals
custom_demo_options[:verticals].each do |vertical_name, vertical_choice|
  # == true is almost always unnecessary, just use a truthiness check
  next unless vertical_choice
  custom_demo_options[:channels].each do |channel_name, channel_choice|
    next unless channel_choice
    vertical_data = website_data[:verticals][site_vertical]
    channel_value = vertical_data[channel_name]
    # This must be initialized here:
    collection = {}
    collection[:url] = channel_value[:url]
    collection[:code] = channel_value[:code]
    data.push(collection)
  end
end

You can see that a lot of the nesting and complexity is removed. Note that I am initializing collection at the time it has attributes added to it. This is a little too much to go into here but I highly advise reading up on mutability in Ruby. You're current code will probably not do what you expect it to because you're pushing the same collection hash into the array multiple times.
At this point, you could refactor it into a more functional-programming style, with some chained methods, but I'd leave that exercise for you

A: Object Oriented approach.
Using OOP might be more readable and consistent in this context, as Ruby is Object Oriented language.
Introducing simple Ruby class and using activesupport module, which is extending Hash with some useful methods, same result can be achieved in the following way:
class WebsiteConifg
  attr_accessor :custom_options, :website_data

  def initialize(custom_options, website_data)
    @custom_options = custom_options
    @website_data   = website_data[:verticals]
  end

  def data
    verticals = selected_verticals
    channels = selected_channels

    verticals.map{ |vertical| @website_data.fetch(vertical).slice(*channels) }
  end

  private
  def selected_verticals
    @custom_options[:verticals].select{|_,v| v }.keys
  end

  def selected_channels
    @custom_options[:channels].select{|_,v| v }.keys
  end

Based on passed custom_demo_options we can select verticals and channels of only those keys, which values are set as true.
For your configuration will return
selected_verticals #  [:fashion]
selected_channels  #  [:b2b, :b2c]

+data()
Simple public interface is iterating through all selected verticals based on the passed options and return Array of hashes for the given channels by using slice(keys).
fetch(key)
return value for the given key it is an equivalent of h[:key]
h = {a: 2, b: 3}
h.fetch(:a)  # 2
h.fetch(:b)  # 3

slice(key1, key2) does require activesupport
returns hash which contains passed as an arguments, keys. Method is accepting multiple arguments, as in our example we are getting an Array of those keys, we can use * splat operator to comply with this interface.
h = {a: 2, b: 3}
h.slice(:a)         # {:a=>2}
h.slice(:a, :b)     # {:a=>2, :b=>3}
h.slice(*[:a, :b])  # {:a=>2, :b=>3}

Usage
  website_config = WebsiteConifg.new(custom_demo_options, website_data)
  website_config.data

  # returns
  # [{:b2b=>{:code=>"luma_b2b", :url=>"b2b.luma.com"}, :b2c=>{:code=>"base", :url=>"luma.com"}}]

UPDATE
Changed relevant parts:
def data
    verticals = selected_verticals
    channels = selected_channels
    geos = selected_geos

    verticals.map do |vertical|
      verticals_data = @website_data.fetch(vertical)

      # in case of multiple geolocations
      # collecting relevant entries of all of them
      geos_data = geos.map{|geo| verticals_data.fetch(geo) }

      # for each geo-location getting selected channels
      geos_data.map {|geo_data| geo_data.slice(*channels)  }
    end.flatten
  end

  private
  # as `website_data' hash is using symbols, we need to covert string->sym
  def selected_geos
    @custom_options[:geos].map(&:to_sym)
  end

  def selected_verticals
    selected_for(:verticals).keys
  end

  def selected_channels
    selected_for(:channels).keys
  end

  def selected_for(key)
    @custom_options[key].select{|_,v| v }
  end

Easiest way to understand what kind of output(data) you have on each of the steps in the each(map) iterator, would be to place there debugger
like: pry, byebug.


text:
Q: Why is Handler trait not implemented for simple async fn returning status? I thought Handler should be implemented for an async function returning a StatusCode:
use axum::{
    headers,
    http::StatusCode,
    routing::{delete, get, post, put},
    Router,
};

pub fn create_routes() -> Router {
    Router::new().route("/webhook", post(webhook_handler()))
}

#[debug_handler]
async fn webhook_handler() -> StatusCode {
    StatusCode::OK
}

error[E0277]: the trait bound `impl futures::Future<Output = StatusCode>: Handler<_, _>` is not satisfied
   --> src/webhook.rs:16:39
    |
16  |     Router::new().route("/webhook", post(webhook_handler()))
    |                                     ---- ^^^^^^^^^^^^^^^^^ the trait `Handler<_, _>` is not implemented for `impl futures::Future<Output = StatusCode>`
    |                                     |
    |                                     required by a bound introduced by this call
    |
    = help: the trait `Handler<T, ReqBody>` is implemented for `Layered<S, T>`
note: required by a bound in `axum::routing::post`
   --> /home/andrew/.cargo/registry/src/github.com-1ecc6299db9ec823/axum-0.5.11/src/routing/method_routing.rs:400:1
    |
400 | top_level_handler_fn!(post, POST);
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `axum::routing::post`
    = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info)

This seems nearly identical to an example provided in the documentation:
// `StatusCode` gives an empty response with that status code
async fn status() -> StatusCode {
    StatusCode::NOT_FOUND
}

A: The function itself needs to be passed as an argument to post, not a function call. Removed the parenthesis like so: .route("webhook", post(webhook_handler))


text:
Q: Script for a for moving a large database in Rackspace - Perl I have no experience in Perl. We are trying to move our 250MB database into MySQL with a Perl script that is scheduled as a Cron Job The Rackspace cloud has recommend this script:

#!/bin/sh
mysql -h DB_HOST -u DB_USER -p'DB_PASSWORD' DB_NAME < /path/to/file/db_import.sql

I have filled in the variables as so (user and pass have changed for this post):

!/bin/sh mysql -h mysql51-032.wc1:3306 -u 806637_Admin -p
  '*******' 806637_Vs_Hl <
  /mnt/stor09-wc1-ord1/762283/806637/www.vs-hl.com/Vs-hlDB/Vs-DB.sql

Doing some research I found that the '#' starts a comment in Perl so I removed it and this is what I received as an error report:

Bareword found where operator expected at main.pl line 1, near
  "/bin/sh"     (Missing operator before h?)
Bareword found where operator expected at main.pl line 1, near
  "806637_VMHAdmin"     (Missing operator before VMHAdmin?)
Number found where operator expected at main.pl line 1, near
  "'Admin1234' 806637_"     (Missing operator before  806637_?)
Bareword found where operator expected at main.pl line 1, near
  "806637_Vets_Hall"    (Missing operator before Vets_Hall?)
syntax error at main.pl line 1, near "/bin/sh mysql "
Execution of main.pl aborted due to compilation errors.

My question is what am I doing wrong syntax wise?
Thanks for reading!

A: That's not a Perl script, that's a Bourne Shell script. Just move it onto two separate lines.
#!/bin/sh
mysql ...

Note that the #! has to be the very first two characters of the file. No blank lines may proceed it.

A: A Perl "script" and shell script are not the same things. So when dealing with programmers, I call it a "Perl program" since Perl is a fully functional programming language. This is a shell script which uses 2 separate lines:
#!/bin/sh
mysql ...

That has nothing to do with Perl. If you want to execute a command in Perl you can do this inside a Perl program. I'll call it doit.pl:
# Note I'm using backticks, and any error msgs are in $msg.
$msg=`mysql -h DB_HOST -u DB_USER -p'DB_PASSWORD' DB_NAME < /path/to/file/db_import.sql`;
print "Messages are: $msg\n";

And you don't need Perl if nothing in the command line changes. You could use Perl if you are looping through and copying many database names though.


text:
Q: Custom Paragraph Number For Questions List I am trying to do a question and answer application. I have a problem on the screen that appears below. I'm trying to find a right way about how to add the question number. I researched paragraph style on android. but I couldn't find anything. while researching I found something like this in swift language. I looked for a method similar to that done here.
  var attributes = [NSAttributedString.Key: Any]()
  let paragraphStyle = NSMutableParagraphStyle()
  paragraphStyle.headIndent = 15
  attributes[.paragraphStyle] = paragraphStyle

I planned to solve with linear layouts, but I was not successful. Can you guide me on what to do


text:
Q: Appending matching column onto each result row I'm not a SQL veteran so please excuse me if this is obvious; I'm learning.
I have two tables in a database for a wedding invite system; guests and invites. One invite (invitation) can contain many guests.
For purposes of creating a mail merge for the invites, I'm trying to select the firstname and lastname from the guest table, where the guest's inviteID is the same as the others; effectively returning on row of data containing the inviteID's data and a column each for the names of the guests.
My problem is I can return the data, but across multiple rows which won't work for the mail-merge. I can create a PHP script to do a work-around, but I would like to learn how this could be achieved in pure SQL.
Can anybody shed some light? Can this be done? Is this sheer madness?
Hoping to achieve:
***************************  1. row ***************************
       inviteID: 39
  inviteURLSlug: thewinnetts
                ....
guestFirstName1: Sid
  guestSurname1: Winnett
guestFirstName2: Claire
  guestSurname2: Winnett

'invite' table:
+---------------------+--------------+
| Field               | Type         |
+---------------------+--------------+
| inviteID            | int(11)      |
| inviteURLSlug       | varchar(64)  |
| inviteQRValue       | varchar(255) |
| inviteQRImageURL    | varchar(255) |
| inviteAddress1      | varchar(32)  |
| inviteAddress2      | varchar(32)  |
| inviteAddress3      | varchar(32)  |
| inviteCity          | varchar(32)  |
| inviteCounty        | varchar(32)  |
| inviteCountry       | varchar(32)  |
| invitePostcode      | varchar(16)  |
| inviteDateSend      | datetime     |
| inviteDateResponded | datetime     |
| inviteCreated       | datetime     |
| inviteUpdated       | timestamp    |
+---------------------+--------------+

'guest' table:
+-------------------+--------------+
| Field             | Type         |
+-------------------+--------------+
| guestID           | int(11)      |
| inviteID          | int(11)      |
| guestFirstName    | varchar(32)  |
| guestSurname      | varchar(32)  |
| guestSide         | varchar(8)   |
| guestAttending    | tinyint(1)   |
| guestEmail        | varchar(255) |
| guestPhone        | varchar(32)  |
| guestMobile       | varchar(16)  |
| guestAddress1     | varchar(32)  |
| guestAddress2     | varchar(32)  |
| guestAddress3     | varchar(32)  |
| guestCity         | varchar(32)  |
| guestCounty       | varchar(32)  |
| guestCountry      | varchar(32)  |
| guestPostCode     | varchar(16)  |
| guestProfilePhoto | varchar(64)  |
| guestFoodVeg      | tinyint(1)   |
| guestFoodReq      | varchar(255) |
| guestTwitter      | varchar(15)  |
| guestFacebook     | varchar(32)  |
| guestPlusone      | int(1)       |
| guestCreated      | datetime     |
| guestUpdated      | timestamp    |
+-------------------+--------------+

Failed Join attempt and cropped results sample:
SELECT * FROM guest INNER JOIN invite on guest.inviteID = invite.inviteID \G

*************************** 64. row ***************************
            guestID: 72
           inviteID: 39
     guestFirstName: Claire
       guestSurname: Winnett
                    .......
*************************** 65. row ***************************
            guestID: 73
           inviteID: 39
     guestFirstName: Sid
       guestSurname: Winnett
                    .......

A: To achieve those results will require additional processing in PHP.
To do so, modify your query to this:
SELECT i.*,
  g.guestFirstName,
  g.guestSurname
  GROUP_CONCAT(DISTINCT g.guestFirstName, '|', g.guestSurname ORDER BY g.guestSurname DESC) AS names
FROM invite i
INNER JOIN guest g ON i.inviteID = g.inviteID;

making sure to return your results as an array.  From there, convert the concatenated results into an array then iterate through them to set the custom key name and corresponding value (assumes your query results are in array format with the variable name $queryresults):
$names = explode(',' $queryresults['names']);
unset($queryresults['names']);

$i = 1;
foreach ($names as $name) {
  $split_name = str_split("|", $name);
  $queryresults['guestFirstName' . $i] = $split_name[0];
  $queryresults['guestSurname' . $i] = $split_name[1];
  $i++;
}

This should give you your desired results.

A: SQL is not good at this sort of thing. It wants to work in sets, where all the items in the set are the same. You are asking for two items within the set to be smooshed together. Here is a possible solution:
SELECT
  t1.inviteID,
  t1.guestID,
  t1.guestFirstName,
  t1.guestSurname,
  t2.guestFirstName AS guestFirstName2,
  t2.guestSurname AS guestSurname2
FROM
  guests as t1
LEFT OUTER JOIN
  guests as t2
ON t1.inviteID = t2.inviteID
AND t1.guestID <> t2.guestID
WHERE
 t1.guestID = (select min(t3.guestID) from guests as t3 where t3.inviteID = t1.inviteID)
;

The guests table is used twice, once to provide the first guest on each invite, and a second time, using a LEFT OUTER JOIN to provide the second. The LEFT OUTER ensures you still get the first even if there isn't a second. The other criteria are there to ensure you don't join a row to itself, and you only output the firsts, with the seconds attached (and not the other way around).
Here is a sample fiddle (in MySQL)

A: Is something like this what you are looking for?
Updated after your comment.
SELECT GROUP_CONCAT( DISTINCT `guest`.`guestFirstName`,`guest`.`guestSurname`, `invite`.`inviteURLSlug` ) FROM `guest`
LEFT JOIN `invite` ON `invite`.`inviteID` = `guest`.`inviteID`
WHERE `invite`.`inviteID` = 5

I just made two simple tables with minimal information for testing, but is easily expandable to whatever you have/want.
You are going to have some fields repeated since the number of rows is going to be related to the number of guests.


text:
Q: EmberJS - record with hasMany relation fails to load I am using EmberJS 1.0.0 with Ember Data 1.0.0 beta and the latest version of the LocalStorage Adapter. When I try to load a record with a hasMany relationship from the store I get the follwing error:
ember-1.0.0.js (Line 394)

Assertion failed: You looked up the 'items' relationship on
  'App.List:ember236:1' but some of the associated records were not
  loaded. Either make sure they are all loaded together with the parent
  record, or specify that the relationship is async (DS.attr({ async:
  true }))

and ember-data.js (Line 2530)

TypeError: resolver is undefined
  }).then(resolver.resolve, resolver.reject);

Quick demo app: http://jsbin.com/oKuPev/49 (watch the console)
<script type="text/x-handlebars">
    List: {{name}}
    <div>
        {{#each items}}
            {{id}} - {{name}}<br/>
        {{/each}}
    </div>
</script>

<script type="text/javascript">

    window.App = Ember.Application.create({});
    App.ApplicationAdapter = DS.LSAdapter.extend({});

    var FIXTURES = {
      'App.List': {
        records: {
          '1': { id: '1', name: 'The List', items: ['1','2'] }
        }
      },
      'App.Item': {
        records: {
          '1': { id: '1', name: 'item 1', list: '1' },
          '2': { id: '2', name: 'item 2', list: '1' }
        }
      }
    }

    // Store fixtures in localStorage
    localStorage.setItem('DS.LSAdapter', JSON.stringify(FIXTURES));

    // Models
    App.List = DS.Model.extend({
        name: DS.attr('string'),
        items: DS.hasMany('item')
    });

    App.Item = DS.Model.extend({
        name: DS.attr('string') ,
        list: DS.belongsTo('list')
    });

    // Route
    App.ApplicationRoute = Ember.Route.extend({
        model: function() {
          // Fails!!!
          return this.store.find('list', 1);
        }
    });

  </script>

I'm not sure if the problem is ember.js, ember-data.js or the LocalStorage adapter.

A: This works if you define items as an asynchronous relationship.
item: DS.hasMany('item',{async:true})
Here's a working jsbin : http://jsbin.com/oKuPev/53/edit

A: You need to define "items" on your model as being async in nature as ember makes separate requests for those models and then joins them together asynchronously.
App.List = DS.Model.extend({
  name: DS.attr('string'),
  items: DS.hasMany('item',{async:true})
});

A: Anyone else that stumbles on this thread b/c associations aren't loading (but w/o an error) notice the items: [1, 2] which associates the parent to child records.


text:
Q: How to compare 2 JSON structures using VB.NET? I am new to JSON.NET. I am trying to compare 2 JSON structures using VB.NET like
{
 "attrs":[
    {
    "name":"_DB_ATTR_OSD_PARENT_",
    "column":"OsDeployerParent",
    "type":"Integer",
    "enumName":null
    },
    {
    "name":"_DB_ATTR_SMALLICON_",
    "column":"CurrentSmallIcon",
    "type":"Enum"
    }
]
}
Please can someone help me.
Thanks.

A:
classes to be used

public class testObjects
{
    public List<testObject> attrs;
}
public class testObject
{
    public string name;
    public string column;
    public string type;
    public string enumName;

}

Comparison preparing for class

class ObjectComparer : EqualityComparer<testObject>
{
    public override bool Equals(testObject c1, testObject c2)
    {
        if (c1.name == c2.name &&
            c1.column == c2.column &&
            c1.enumName == c2.enumName &&
            c1.type == c2.type)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override int GetHashCode(testObject c)
    {
        int hash = 23;
        if (c.name != null) hash = hash * 37 + c.name.GetHashCode();
        if (c.column != null) hash = hash * 37 + c.column.GetHashCode();
        if (c.enumName != null) hash = hash * 37 + c.enumName.GetHashCode();
        if (c.type != null) hash = hash * 37 + c.type.GetHashCode();
        return hash;
    }
}

operations starts right here

string jsonObjects = @"{ 'attrs':[ { 'name':'_DB_ATTR_OSD_PARENT_', 'column':'OsDeployerParent', 'type':'Integer', 'enumName':null }, { 'name':'_DB_ATTR_SMALLICON_', 'column':'CurrentSmallIcon', 'type':'Enum' } ] }";
        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        var objects = js.Deserialize(jsonObjects, typeof(testObjects));

        ObjectComparer cmp = new ObjectComparer();

        testObjects deserializedObject = ((testObjects)objects);

        // this allows you to remove double entries
        var distinctObjects = deserializedObject.attrs.Distinct(cmp).ToList();
        Console.WriteLine(string.Format("duplicate objects count : {0}", (deserializedObject.attrs.Count - distinctObjects.Count).ToString()));

        //If you want to compare if the following code can be used individually
        testObject obj1 = ((testObjects)objects).attrs.First();
        testObject obj2 = ((testObjects)objects).attrs.Skip(1).First();
        bool isObjectEquals = cmp.Equals(obj1, obj2);

        Console.WriteLine(string.Format("Objects are {0}", isObjectEquals ? "Equals" : "Not Equals"));

A: this is vb code

classes to be used

Public Class testObjects
    Public attrs As List(Of testObject)
End Class
Public Class testObject
    Public name As String
    Public column As String
    Public type As String
    Public enumName As String

End Class

Comparison preparing for class

Class ObjectComparer
    Inherits EqualityComparer(Of testObject)
    Public Overrides Function Equals(c1 As testObject, c2 As testObject) As Boolean
        If c1.name = c2.name AndAlso c1.column = c2.column AndAlso c1.enumName = c2.enumName AndAlso c1.type = c2.type Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Overrides Function GetHashCode(c As testObject) As Integer
        Dim hash As Integer = 23
        If c.name IsNot Nothing Then
            hash = hash * 37 + c.name.GetHashCode()
        End If
        If c.column IsNot Nothing Then
            hash = hash * 37 + c.column.GetHashCode()
        End If
        If c.enumName IsNot Nothing Then
            hash = hash * 37 + c.enumName.GetHashCode()
        End If
        If c.type IsNot Nothing Then
            hash = hash * 37 + c.type.GetHashCode()
        End If
        Return hash
    End Function
End Class

operations starts right here

Dim jsonObjects As String = "{ 'attrs':[ { 'name':'_DB_ATTR_OSD_PARENT_', 'column':'OsDeployerParent', 'type':'Integer', 'enumName':null }, { 'name':'_DB_ATTR_SMALLICON_', 'column':'CurrentSmallIcon', 'type':'Enum' } ] }"
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim objects = js.Deserialize(jsonObjects, GetType(testObjects))

Dim cmp As New ObjectComparer()

Dim deserializedObject As testObjects = DirectCast(objects, testObjects)

' this allows you to remove double entries
Dim distinctObjects = deserializedObject.attrs.Distinct(cmp).ToList()
Console.WriteLine(String.Format("duplicate objects count : {0}", (deserializedObject.attrs.Count - distinctObjects.Count).ToString()))

'If you want to compare if the following code can be used individually
Dim obj1 As testObject = DirectCast(objects, testObjects).attrs.First()
Dim obj2 As testObject = DirectCast(objects, testObjects).attrs.Skip(1).First()
Dim isObjectEquals As Boolean = cmp.Equals(obj1, obj2)

Console.WriteLine(String.Format("Objects are {0}", If(isObjectEquals, "Equals", "Not Equals")))

A: New Codes
string jsonObjects = @"{ 'attrs':[ { 'name':'_DB_ATTR_OSD_PARENT_', 'column':'OsDeployerParent', 'type':'Integer', 'enumName':null }, { 'name':'_DB_ATTR_SMALLICON_', 'column':'CurrentSmallIcon', 'type':'Enum' } ] }";
    string jsonObjects2 = @"{ 'attrs':[ { 'name':'_DB_ATTR_OSD_PARENT_', 'column':'OsDeployerParent1', 'type':'Integer', 'enumName':null }, { 'name':'_DB_ATTR_SMALLICON_', 'column':'CurrentSmallIcon', 'type':'Enum' } ] }";
    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
    var objects = js.Deserialize(jsonObjects, typeof(testObjects));
    var objects2 = js.Deserialize(jsonObjects2, typeof(testObjects));

    ObjectComparer2 cmp = new ObjectComparer2();

    testObjects deserializedObject = ((testObjects)objects);
    testObjects deserializedObject2 = ((testObjects)objects2);
    bool isObjectEquals = cmp.Equals(deserializedObject, deserializedObject2);
    Console.WriteLine(string.Format("Objects are {0}", isObjectEquals ? "Equals" : "Not Equals"));

Class ObjectComparer
Inherits EqualityComparer(Of testObject)
Public Overrides Function Equals(c1 As testObject, c2 As testObject) As Boolean
    If c1.name = c2.name AndAlso c1.column = c2.column AndAlso c1.enumName = c2.enumName AndAlso c1.type = c2.type Then
        Return True
    Else
        Return False
    End If
End Function

Public Overrides Function GetHashCode(c As testObject) As Integer
    Dim hash As Integer = 23
    If c.name IsNot Nothing Then
        hash = hash * 37 + c.name.GetHashCode()
    End If
    If c.column IsNot Nothing Then
        hash = hash * 37 + c.column.GetHashCode()
    End If
    If c.enumName IsNot Nothing Then
        hash = hash * 37 + c.enumName.GetHashCode()
    End If
    If c.type IsNot Nothing Then
        hash = hash * 37 + c.type.GetHashCode()
    End If
    Return hash
End Function

End Class
Class ObjectComparer2
    Inherits EqualityComparer(Of testObjects)
    Public Overrides Function Equals(c1 As testObjects, c2 As testObjects) As Boolean
        Dim cmp As New ObjectComparer()
    For Each obj1 As testObject In c1.attrs
        If Not c2.attrs.Any(Function(x) cmp.Equals(x, obj1)) Then
            Return False
        End If
    Next
    Return True
End Function

Public Overrides Function GetHashCode(c As testObjects) As Integer
    Dim hash As Integer = 23
    For Each obj As testObject In c.attrs
        hash += obj.GetHashCode()
    Next
    Return hash
End Function

End Class


text:
Q: Weird spacing in aligned environment Here's my code:
$$\begin{aligned}
h_t     &= ca_t + &2c^2a_{t+1} + 3c^3&a_{t+2}+\ldots \\
h_{t+1} &=        &ca_{t+1}    + 2c^2&a_{t+2} + 3c^3a_{t+3}+\ldots \\
h_{t+2} &=        &                 c&a_{t+2} + 2c^2a_{t+3} + 3c^3a_{t+4}+\ldots
\end{aligned}$$

and the picture:

*

*What's with the weird space between ca_t + and 2c^2a_{t+1}? How can I get rid of it?

*Although it looks correct, I don't understand why the picture has the a_{t+1} terms aligned when in the code I write that the 2c^2 and c should be aligned. Again, it looks right (and I should fix my code), but I'm just confused about why the picture looks the way it does.

A: Is this what you want?
You have to remember that n alignment points require 2 n – 1 &. Also, using alignat* gives you full control on the spacing of the alignment columns.
Unrelated: don't use  the TeX construct $$ ... $$, use the LaTeX construct \[ ... \] (unnecessary here – use the starred version of the amsmath environments):
\documentclass[11pt]{article}
\usepackage{amsmath}

\begin{document}

\begin{alignat*}{3}
h_t &= ca_t &{}+2c^2 & a_{t+1} & {}+ 3c^3&a_{t+2}+\dotsb \\
h_{t+1} &= & c \,& a_{t+1} &{} + 2c^2&a_{t+2} + 3c^3a_{t+3}+\dotsb \\
h_{t+2} &= & & & c&a_{t+2} + 2c^2a_{t+3} + 3c^3a_{t+4}+\dotsb
\end{alignat*}

\end{document}

A: A variant of Mico's answer, with more alignment points, but with easier input, taking advantage of the repetitive structure.
\documentclass{article}
\usepackage{amsmath}
\usepackage{array}

\begin{document}
\[
\setlength{\arraycolsep}{0pt}
\newcommand{\row}[1]{%
  &
  c^{\hphantom{1}} &
  a_{t\ifnum#1=0 \else+#1\fi} &
  + &
  2 &
  c^2 &
  a_{t+\number\numexpr#1+1} &
  + &
  3 &
  c^3 &
  a_{t+\number\numexpr#1+2} &
  + &
  \multicolumn{3}{l}{\dotsb}
}
\begin{array}{
  l % the left hand sides
  >{{}}c<{{}} % the equals sign
  *{5}{
    l % numeric coefficient
    l % power of c
    c % 'a' term
    >{{}}c<{{}} % plus
  }
  lll % final dots
}
h_t     &=& \row{0} \\[\jot]
h_{t+1} &=& &&&& \row{1} \\[\jot]
h_{t+2} &=& &&&&&&&& \row{2}
\end{array}
\]
\end{document}

A: I'd use an array environment, which is highly customizable.

\documentclass{article}
\usepackage{array} % for "\newcolumntype" directive
\newcolumntype{C}{>{{}}c<{{}}}
\newcommand\mydots{\multicolumn{1}{l}{\cdots}}

\begin{document}
\[
\setlength\arraycolsep{0pt}
\begin{array}{l*{6}{Cr}}
h_t     &=&ca_t&+&2c^2a_{t+1}&+&3c^3a_{t+2}&+&\mydots \\
h_{t+1} &=&    & &ca_{t+1}   &+&2c^2a_{t+2}&+&3c^3a_{t+3}&+&\mydots \\
h_{t+2} &=&    & &           & &   ca_{t+2}&+&2c^2a_{t+3}&+&3c^3a_{t+4}&+&\mydots
\end{array}
\]
or, if lining up the ``$c$'' coefficients matters too,
\[
\setlength\arraycolsep{0pt}
\begin{array}{l*{6}{Cr}}
h_t     &=&c\,a_t&+&2c^2a_{t+1}&+&3c^3a_{t+2}&+&\mydots \\
h_{t+1} &=&    & &c^{\phantom{1}}a_{t+1}   &+&2c^2a_{t+2}&+&3c^3a_{t+3}&+&\mydots \\
h_{t+2} &=&    & &           & &   c^{\phantom{1}}a_{t+2}&+&2c^2a_{t+3}&+&3c^3a_{t+4}&+&\mydots
\end{array}
\]
\end{document}


text:
Q: You may need an appropriate loader to handle this file type. Typescript I'm trying to make use of Typescript typings for you Youtube Data API here: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3
I am using Ionic framework and I receive the error below after I do Ionic Serve with the following line in code:
  gapi.client.load("client", "v3");

Module parse failed: /Users/yoko/Desktop/myApp/node_modules/gapi/lib/gapi.coffee Unexpected token (1:17)
You may need an appropriate loader to handle this file type.
| config = require './config'
|
| module.exports =

This is how the api.coffee looks like
config = require './config'

module.exports =
  server:
    setApiKey: (apiKey) ->
      config.api.key = apiKey
    load: (apiName, apiVersion, callback) ->
      @[apiName] = require "./#{apiName}/#{apiVersion}"
      callback()

What does that mean?

A: Assuming you are using Gulp, install CoffeeScript via npm, then add it to your package.json via:
npm install gulp-coffee --save-dev #devDependencies

or
npm install gulp-coffee --save #dependencies

Then add the following to your Gulpfile.js:
var coffee = require('gulp-coffee');
var paths =  { coffee: ['/Users/yoko/Desktop/myApp/node_modules/gapi/lib/*.coffee'] };

function coffeePipe(done)
  {
  gulp.src(paths.coffee)
    .pipe(coffee({bare: true})
    .on('error', gutil.log.bind(gutil, 'Coffee Error')))
    .pipe(concat('application.js'))
    .pipe(gulp.dest('./www/js'))
    .on('end', done)
  }

gulp.task('coffee', coffeePipe);

References

*

*CoffeeScript-Ionic-Starter/gulpfile.js at master · StephenGrider/CoffeeScript-Ionic-Starter

*Introduction to Gulp.js with practical examples | Julien Renaux Blog

*gulp-coffee

*05 - Using a package.json | npm Documentation

*Quick tip: using gulp to customize the 'serve', 'run' and 'build' process for your Ionic framework apps by leob on CodePen

*Alter The Ionic 2 Gulp Script To Include Browser JavaScript Files

*10 Minutes with Ionic 2: Hello World | The Official Ionic Blog

*Why You Should Not Use Ionic Serve For Hybrid Apps


text:
Q: Can't Retrieve Data from MongoDB in django application I am trying to develop a website in Django. I am using MongoDB as a database for the first time. I used Djongo to develop the connection between django and MongoDB. I have created a  database  in the Robo3T and the connection is also developed between django and MongoDB. The data is saving fine in the database I have seen in the robo3T. But when I am trying to retrieve the data back from the MongoDB to dispay on the Django Template, its not shoiwng the data and show the template tag like this {{post.tile}} {{post.content}}.
Here is my code:
Setting.py
DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test',
        'HOST':'localhost',
        'PORT':27017
    }
}

view.py
from django.shortcuts import render
from django.views.generic import View,TemplateView
from .forms import FormName
from .models import Post
# Create your views here.

class MainPageView(TemplateView):
    template_name='main.html'

class LoginView(TemplateView):
    template_name='login.html'

def RegistrationView(request):
    form=FormName()
    if request.method == 'POST':
        print("In Post")
        print(request.POST)
        form=FormName(request.POST)

        if form.is_valid():
            form.save(commit=True)

    else:
        form=FormName()

    return render(request,'registration.html',{'form':form})

    # template_name='registration.html'

def main(request):
    post=Post.objects.all()
    return render(request,'main_temp.html',{'Post':post})

models.py
from django.db import models
# from OnlineJobPortal.settings import DBNAME

# # Create your models here.

# # connect(DBNAME)
class Post(models.Model):
    title=models.CharField(max_length=250)
    content=models.CharField(max_length=250)

forms.py
from django import forms
from .models import Post
class FormName(forms.ModelForm):
    class Meta():
        model=Post
        fields='__all__'

A: Change your template tags to
{{ post.tile }} etc.
The spaces make the difference since the template tags won't be interpreted correctly without.
official docu

A: You have made a spelling mistake while accessing the field (post.title instead of post.tile) in your template. Your template coding structure should be somewhat similar to as follows.
{% for post in Post %}
    {{ post.title }}
    {{ post.content }}
{% endfor %}


text:
Q: right mouse button not working I am using Lubuntu 14.04 for over a year and suddenly my right click button does not work and I am unable to right click anywhere
I tried the following commands:
sudo su
echo options pmouse proto=exps > etc/modprobe.d/pmouse.conf

Specifications:

*

*HCL Desktop

*Frontech motherboard

*2GB Ram

*Microsoft Usb Mouse

A: I know this sucks, but checking the obvious, did you verify that this is not hardware failure?  Does the mouse work on another system?

A: I had the same issue with my mouse. It turned out that if the battery gets weak the right mouse button stops working. It's always good to look for a simple solution first.