Views and layout elements displayed conditionally

Question: I am semi-new to android development. I am getting ready to design a project that has a button that has 2 different methods when clicked (effectively a toggle). I know I can do this by implementing OnClickListener myself, but I was wondering if there was a way to make 2 different buttons in the layout xml and then conditionally show one or the other appropriately. Also if this is possible, is it generally a good practice, or is there a better way to have a button perform two different methods? Is it easier overall to just go ahead and implement OnClickListener?
Thanks
(I currently don't have any code to show at the moment, but if my question is vague I'll be happy to elaborate more if necessary)
Answer: Yes it very easy. Put both buttons in your layout XML, and add the attribute android:visibility=GONE to one of them. In your Java code you can change the visibility of your buttons with button.setView(View.VISIBLE) and button.setView(View.GONE). (Don't use button.setView(View.INVISIBLE) because the button will be invisible but still take up space in the View).
Comment: Would I be able to have them sit on top of each other in the layout? I was unaware of the visibility attribute, thanks for that.
Comment: What do you mean by sit on top of each other? Just insert the  tags consecutively in the XML file, with the same layout attributes and you should be ok as long as you make sure only one is visible at a time. BTW I've been thinking about your problem as I'm posting another answer below...
Answer: I've been thinking about it and if the only difference between the buttons is what they do when clicked, you should use only one button and either:

Use an if/else in the onClick() method or click listener to control the behavior, OR
Use button.setOnClickListener() to change the listener when you want to change the behavior

However if the buttons are significantly different (e.g. different location ...etc), use my other answer.
Comment: I think this is more of what I'm looking for because my overall goal is to have a single button (or effectively a single button) that does 2 different things alternatively on each click.


How big of a problem is it to punch a hole in the DMZ to one web server?

Question: We currently have our web server in a DMZ. The web server cannot see anything within the internal network, but the internal network can see the web server. How safe would it be to punch a hole in the firewall between the DMZ and the internal network to only one web server in the intranet? We are working on something that will be interfacing with several of our back-office applications (which are all on one server) and it would be so much easier to do this project if we could communicate directly with the IBM i server holding this data (via web services).
From my understanding (and I don't know brands), we have one firewall for the DMZ with a different external IP from our primary IP with another firewall. Another firewall is between the web server and the intranet.
So something like:
<code>Web Server  <==== Firewall ===== Intranet
     |                              |
     |                              |
  Firewall                      Firewall
     |                              |
     |                              |
 Internet IP1                  Internet IP2
</code>
Comment: How about some details such as what kind of firewall is providing this DMZ?
Comment: @SpacemanSpiff I tried from the minimal knowledge I have of the network. I am a developer planning this next project and coming up with options.
Answer: There's nothing wrong with creating access mechanisms for hosts in the DMZ to access hosts in the protected network when this is necessary to accomplish your intended result. It's, perhaps, not preferable to do so, but sometimes it's the only way to get the job done.
The key things to consider are:

Limit the access to the most specific firewall rule you can. If possible, name the specific hosts involved in the rule along with the specific protocols (TCP and/or UDP ports) that will be used. Basically, open only as small a hole as you need.
Be sure that you're logging access from the DMZ host to the host on the protected network and, if possible, analyze those logs in an automated fashion for anomalies. You want to know when something out of the ordinary happens.
Recognize that you're exposing an internal host, even if it's in an indirect manner, to the Internet. Stay on top of patches and updates for the software you're exposing and the host's operating system software itself.
Consider mutual authentication between the DMZ host and the internal host, if that's feasible with your application architecture. It would be nice to know that the requests coming to the internal host are actually coming from the DMZ host. Whether you can do this or not is going to be highly dependent on your application architecture. Also, bear in mind that someone who "owns" the DMZ host will be able to make requests to the internal host even if authentication is occurring (since they'll, effectively, be the DMZ host).
If there's concern about DoS attacks consider using rate-limiting to prevent the DMZ host from exhausting the resources of the internal host.
You may want to consider using a layer 7 "firewall" approach, where the requests from the DMZ host are passed first to a special-purpose internal host that can "sanitize" the requests, sanity-check them, and then pass them on to the "real" back-end host. Since you're talking about interfacing to your back-office applications on your IBM iSeries I'm guessing that you have limited capability for performing sanity-checks against incoming requests on the iSeries itself.

If you approach this in a methodical fashion and keep some common sense about it there's no reason you can't do what you're describing while keeping risk minimized at the same time.
Frankly, that you've got a DMZ that doesn't have unfettered access to the protected network puts you leaps and bounds beyond a lot of networks I've seen. For some people, it seems, DMZ just means "another interface on the firewall, possibly with some different RFC 1918 addresses, and basically unfettered access to the Internet and the protected network". Try and keep your DMZ as locked-down as you can while still accomplishing business goals and you'll do well.
Comment: Waaaay more thorough answer than mine :) +1
Comment: I love this information. Before I asked, I understood some of the things you talked about. But a lot of it I didn't fully grasp. Thanks!
Comment: That depends on what you mean by sanity checks. In a case like this, we would avoid as much SQL as possible (since RPG can "read" databases) and validate the data coming in before processing it. Also, most of the data being entered into back-office software would probably be added to an "inbox" for the employees to deal with manually.
Answer: There are obviously some dangers, but you can do it. Basically you're opening a pinhole that someone could get in through, so make it tiny. Limit it to only the servers on either end, and allow only data on the chosen ports. Its not a bad idea to use port address translation to just use bizarre ports. Still, security by obscurity is no security at all. Make sure that whatever the server on the other side is has some sort of way to check that information going through that connection is truly what it appears to be... or at least have some sort of context aware firewall in place. Also, there are certain firewalls made for this sort of thing... I know microsoft ISA does this same thing for OWA and Exchange servers.


What does the AdvAgg bundler do?

Question: The description for the AdvAgg bundler says:

If not checked, the bundler will not split up aggregates.

I know that aggregation is merging files together and I take that splitting isn't the opposite of aggregation. What is it, then?
Answer: The short answer is to take advantage of the browser cache. It can also be used to take advantage of the number of parallel connections that the browser can make.
Example:
Front page has a.css and b.css; node 1 has a.css, b.css and c.css. If using one aggregate then the user going from the front page to node 1 would have to download all of the CSS again. By splitting up the aggregate in a smart manner the user will only need to download c.css
Answer: Aggregated bundles can be aggregated in groups. For example, let's say there was some CSS you wanted included in the head tag and other CSS that should be included towards the bottom of your page. In this case there might be two aggregate groups.
In AdvAgg I believe the use-case you really want to look at is for JS more so than CSS. In JS you may have a "site-wide" group and a "theme" group and...
You can also have AdvAgg break up the groups by filesize or number of files being aggregated. There are some old browsers (read <= IE6) that have some issues with number of included CSS and number of CSS definitions in a single CSS file... these settings can be used to help with that.
Also, there are some HTTP2 improvements that make file aggregation less necessary for the typical use case (fewer TCP connection === better), but sometimes you would still want to aggregate in order to keep certain files together since they are functionally similar.

What does the AdvAgg bundler do?


Ingest several types of CSV's with Databricks Auto Loader

Question: I'm trying to load several types of csv files using Autoloader, it currently merge all csv that I drop into a big parquet table, what I want is to create parquet tables for each type of schema/csv_file
Current code does:

<code>#Streaming files/ waiting a file to be dropped
spark.readStream.format("cloudFiles") \
  .option("cloudFiles.format", "csv") \
  .option("delimiter", "~|~") \
  .option("cloudFiles.inferColumnTypes","true") \
  .option("cloudFiles.schemaLocation", pathCheckpoint) \
  .load(sourcePath) \
  .writeStream \
  .format("delta") \
  .option("mergeSchema", "true") \
  .option("checkpointLocation", pathCheckpoint) \
  .start(pathResult)
</code>
What I want
Answer: You can create different autoloader streams for each file from the same source directory and filter the filenames to consume by using the pathGlobFilter option on Autoloader (databricks documentation). By doing that you will end up having different checkpoints for each table and you can have the different schemas working.
This solution is similar to the one pointed here How to filter files in Databricks Autoloader stream.


Google Sheets: change the value of a specific cell automatically if a change is made on another sheet being called

Question: Is it possible to change the value of a specific cell automatically if a change is made on another sheet being called? I just want to make a "change log" and have the cell display YES or NO depending on the changes made on the called sheet in the past 24 hours.

YES - there's changes made in the past 24hrs on the called sheet
NO - no changes made in the past 24hrs on the called sheet
Comment: Please add a brief description of your search/research efforts as is suggested in [ask]. Also edit the question to make clear why the included tags are relevant to this question.
Answer: Take a look at simple triggers In particular look at the onEdit.  Here's the link to the event object
Here's a potential solution:
This function will track the changes made in the Sheets in the shts array.  I usedd an install onedit trigger.
function onMyEdit(e) {
  e.source.toast('Entry');
  const name=e.range.getSheet().getName();
  const shts=['Sheet1','Sheet2','Sheet3'];
  const idx=shts.indexOf(name);
  if(idx!=-1) {
    const ts=Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"ddMMyy HH:mm:ss")
    const sh=e.source.getSheetByName('Changes');
    if(e.range.columnStart==e.range.columnEnd && e.range.rowStart==e.range.rowEnd) {
      sh.getRange(sh.getLastRow()+1,1,1,5).setValues([[e.value,e.oldValue,ts,name,e.range.getA1Notation()]]);
    }else{
      const s=e.range.getValues().flat().join(',');
      sh.getRange(sh.getLastRow()+1,1,1,5).setValues([[undefined,s,ts,name,e.range.getA1Notation()]]);
    }
    sh.getRange(2,2).offset(0,idx).setValue('YES');
  }
}

This function will reset the changes sheet where all changes are recording as shown in the image below:
function resetChanges() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Changes');
  sh.getRange(2,2,1,sh.getLastColumn()).clearContent();
  sh.getRange(5,1,sh.getLastRow()-4,sh.getLastColumn()).clearContent();
}

image:
Comment: Hi! Thanks for this. But I'm not a programmer :(
Comment: This is the actual answer, your requirements need the use of triggers in the sheets. If you are not a programmer I don't see this being made with just UI and sheets functions. I would recommend you to try to learn [Apps Script](https://developers.google.com/apps-script) or hire someone to do it for you.


Step Definition detection only works when project is configured as cucumber project.- Virtual Machine

Question: feature file and stepdefiniton file could not be connected.  It happens only in eclipse installed in Win Server 2012R2 Virtual Machine.
Answer: This error will appear when you import any new cucumber project from git or directly from local system. Because you have not configured the project to cucumber and it is configured only to maven.
This error can appear for both Selenium and appium testing for web and mobile automation testing.
You can use below screenshot to convert to cucumber project.
Comment: After i have done this. , Still didn't work for me.
Comment: @Saikat Update the cucumber version and check again
Answer: This issue will be resolved if you convert the project as a cucumber project.
Right-click on your project from the Project Explorer > Configure > Convert as Cucumber Project.
Comment: While this is true, the question is why do this? Step definition detection used to work before without having to do this. In fact, in my team, there's a member who has a Java/Maven project and detection works fine. Mine used to work before and then stopped working out of the sudden.
Comment: this setting is required when you are using the latest version of eclipse and remembers this setting is required only when you import your project in eclipse. If you use any other tools like IntelliJ, Netbeans then this configurations will not be required.
Comment: I am using Eclipse 2018-12 and I didn't need that configuration until very recent. Something else might've changed. Again, a member of my team hasn't done this configuration and his workspace links glue code just fine. There's got to be another explanation.
Answer: After changing the project to Cucumber the issue resolved for me.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Validar campos com html 5 e mvc 5

Question: Como eu valido campos no próprio CSHTML, que quando eu clicar no botão, ele valide os campos e caso haja campos não preenchido ele permanece na página, exibindo uma mensagem. Veja os campos de exemplo e o botão para validar.

        Nome

        <input type="text" name="txtNome" class="grid_14 required" placeholder="Nome completo" required />

        Email

        <input type="email" name="txtEmail" class="grid_6  required" placeholder="Email válido" required />

        CPF

        <input type="number" name="txtCpf" class="grid_5  required" placeholder="99999999999" required />

//Botão

    <button value="novaPesquisa" class="btn-pular-passo pull-right">Continuar</button>

Answer: No asp.net-mvc, a validação é feita decorando as propriedades do seu Model com os atributos adequados.
Exemplos:

[Required]: Torna a propriedade de preenchimento obrigatório.
[StringLength(60)]: Faz a propriedade String ter no máximo 60 caracteres.

Para que as validações funcionem adequadamente, é preciso usar o seguinte código em Razor logo após o <input> da sua propriedade:
@Html.ValidationMessageFor(model => model.SuaProperty)

Comment: Tentei assim, mas no Helper do Razor não funciona. Preciso adicionar algum using? Só uma pergunta. O required não deveria travar se o campo estivesse vazio? Meu botão chamando outra página, por exemplo, caso tenha campo vazio não deveria travar? E se o botão apenas habilita uma div, que é meu caso, como eu faria para travar?
Answer: O que você esta querendo não é a bibliioteca Microsoft jQuery Unobtrusive Validation? Adicione ela via NuGet.
Habilite no web.config e teste.
No web.config é essa propriedade que precisa habilitar:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

Eu até tentei aqui também, mas na hora de instalar ela deu erro de incompatibilidade com jQuery. Mesmo desinstalando o jQuery e instalando ele, deixando então que ele resolva a dependência do jQuery, ainda assim deu problema.
Então, se der problema remova o jQuery, instale primeiro o jQuery Validation e ai então instale o Microoft jQuery Unobtrusive Validation.
Isso aqui pra mim resolveu a incompatibilidade.
EDIÇÃO
Não se esqueça de adicionar os plugins jQuery Validation na View.
Para seguir o padrão você precisa adicioná-los no BundleConfig.cs dentro da pasta App_Start.
bundles.Add(new ScriptBundle("~/js/jqueryval").Include(
    "~/Scripts/jquery.validate.*"));

E depois adicionar na view a chamada à esses scripts:
@Scripts.Render("~/js/jqueryval")

Feito isso tem que funcionar.
Comment: Já estão habilitadas.
Comment: Adicionou a biblioteca?

Validar campos com html 5 e mvc 5


tensorflow conv2d number of parameters

Question: Want to know why number of parameters in conv2d is more by 1 than what I expect...
import tensorflow as tf
import tensorflow.keras as keras
input_shape = (40, 512, 512, 1)
conv2d = keras.layers.Conv2D(input_shape=input_shape[1:],
                         filters=1,
                         kernel_size=3,
                         strides=(1, 1),
                         padding='same')

model = keras.Sequential(conv2d)
model.compile()
model.summary()

Output:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 512, 512, 1)       10
=================================================================
Total params: 10
Trainable params: 10
Non-trainable params: 0
_________________________________________________________________

As kernel size is 3, I was expecting it to be Param # as 9 but its 10.
Answer: By default, use_bias=True. There's a bias for each filter, so in this case you add 1 more parameter for the bias. This gives a total of 10 parameters.

tensorflow conv2d number of parameters


What is an advanced area in football (soccer) field?

Question: In this article Tactical Theory: Vertical Build-Up Passing  the author used the words advanced area for many times, for example

Every team utilises different build-up patterns in order to move into more advanced areas of the pitch

or

But midfielders, who have more license to move into advanced areas, can combine passing accuracy & aim with runs of their own.

Could you please explain for me what is an advanced area?
I wonder is there an official definition of advanced area or it is just the dangerous area in opponent's field?
Answer: To advance is to move forward; to be advanced is to have moved, or be in a position which is comparatively, forward of some other place.
In football the primary division of the field is the half, by the centreline. Thus, an advanced area is best understood to be one which is forward of the team's own half, i.e. a position in which that team is attacking.


Populating Dropdown in ASP.net Core

Question: Does anyone know how to deal with Dropdowns in Asp.net core. I think I made myself very complicated to understand the new Asp.net core concept. (I am new to Asp.net Core).
I have models called Driver, Vehicle. Basically one can create bunch of vehicles in the master then attach it to the Driver. So that the driver will be associated with a vehicle.
My problem is that I am also using viewmodel in some area to combine two different models.(understood little from default template)
My problem is I have no idea what is the next step since ASP.net Core is very latest, there are not a lot of tutorials and Q/As available.
Driver Model
public class Driver
{
    [Required]
    public int Id { get; set; }

    [Required]
    public string ApplicationUserId { get; set; }

    [Required]
    public int VehicleId { get; set; }

    [Required]
    public string Status { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }
    public virtual Vehicle Vehicle { get; set; }
}

Vehicle Model
public class Vehicle
{

    [Required]
    public int Id { get; set; }

    [Required]
    public string Make { get; set; }
    public string Model { get; set; }

    [Required]
    public string PlateNo { get; set; }
    public string InsuranceNo { get; set; }

}

ViewModel of Driver
    public class DriverViewModel
{
    [Required]
    [Display(Name = "ID")]
    public int ID { get; set; }

    [Required]
    [Display(Name = "User ID")]
    public string ApplicationUserId { get; set; }

    [Required]
    [Display(Name = "Vehicle ID")]
    public IEnumerable<Vehicle> VehicleId { get; set; }
    //public string VehicleId { get; set; }

    [Required]
    [Display(Name = "Status")]
    public string Status { get; set; }

}

Here is my View

   @*<input asp-for="VehicleId" class="form-control" />*@
   @Html.DropDownList("VehicleId", null, htmlAttributes: new { @class = "form-control"})

Answer: Looking at the documentation it appears that asp.net core may be moving away from HTML helpers and towards the use of tag helpers. The following link should help
https://docs.asp.net/en/latest/mvc/views/working-with-forms.html#the-select-tag-helper
specifically
@model CountryViewModel

<form asp-controller="Home" asp-action="Index" method="post">
<select asp-for="Country" asp-items="Model.Countries"></select>

<button type="submit">Register</button>
</form>

Note the use of "asp-for" which references the Model attribute to bind and the use of "asp-items" which references the model attribute source for the List of Select List items and how it is applied to the select tag
The sample model used in the documentation is referenced below for completeness
namespace FormsTagHelper.ViewModels
{
public class CountryViewModel
{
    public string Country { get; set; }

    public List<SelectListItem> Countries { get; } = new List<SelectListItem>
    {
        new SelectListItem { Value = "MX", Text = "Mexico" },
        new SelectListItem { Value = "CA", Text = "Canada" },
        new SelectListItem { Value = "US", Text = "USA"  },
    };
}
}

Comment: Warning to all! At some point I ended up with the `select` element having a self-closed tag e.g. `` instead of `` (I think because I'd converted from `Input` which allows self-closing) - this caused total confusion for about 30 minutes, because it simply doesn't work, but I didn't see any warnings.
Comment: This might just be an ASP.NET Core / Razor Page thing, but this only worked once I added `[BindProperty]` to `Country`.
Comment: @jamheadart I did the exact same thing and then read this comment.... Thanks ha
Answer: Driver Controller
public class DriverController : Controller
{
    private readonly ApplicationDBContext _context;

    public DriverController(ApplicationDBContext context)
    {
        _context = context;
    }

    // GET: Driver/Create
    public IActionResult Create()
    {
        ViewData["VehicleId"] = new SelectList(_context.Vehicle, "Id", "PlateNo");
        return View();
    }
}

Driver View
@model DriverViewModel
<form asp-action="Create">

        <select asp-for="VehicleId" class ="form-control" asp-items="ViewBag.VehicleId"></select>

</form>

Answer:

@model EmployeeViewModel

<form asp-controller="Home" asp-action="SaveEmployee">
  Desirable Position
  <select asp-for="DesirablePosition" asp-items="Model.DesirablePositionItems"></select>
</form>

public class EmployeeViewModel {
public string DesirablePosition { get; set; }

public List<SelectListItem> DesirablePositionItems { get; } = new List<SelectListItem> {

        new SelectListItem { Value = "j", Text = "Junior" },

        new SelectListItem { Value = "m", Text = "Middle" },

        new SelectListItem { Value = "s", Text = "Senior" },
    };

}
public class HomeController : Controller {
public IActionResult SaveEmployee(){

    return View(new EmployeeViewModel());
}

}

Populating Dropdown in ASP.net Core


What is the name of this function? index?

Question:
Burton- Number theory p.163
Let $n\in\mathbb{Z}^+$.
Let $r$ be a primitive root mod $n$, so that $<r>=\mathbb{Z}_n^*$
Let $a\in \mathbb{Z}_n^*$
Let $k$ be the smallest positive integer such that $a=r^k$
Then, $k$ is called the index of $a$ relative to $r$ and denoted by $ind_r(a)$.

Well.. this definition can be extended to any cyclic group and since the term "index" is really ambiguous, if this tool is useful, I am sure that there is another terminology for "index" here.
Is there another name for "index" here?
This is not on wikipedia so I think this term is not standard..
Answer: Usually it's referred to as the discrete logarithm of $a$ with respect to $r$, denoted by
$$k = \log_r a \pmod{\varphi(n)}$$
Where $\varphi(n)$ is the euler totient function wich counts the elements of $\mathbb Z_n^\ast$.
Comment: if  $Z_n*$ is not cyclic then do we have $k=\log_ra(\bmod\lambda(n))$ which is Carmicheal function if order of $r$ is $\lambda(n)$?


Tomcat7: Error waiting for multi-thread deployment of WAR files to complete

Question: Tomcat 7.0.30 fails on startup (does not manage to start) with this exception:
SEVERE: Error waiting for multi-thread deployment of WAR files to complete

The following is the exception's full stack trace:
==> /usr/share/tomcat7/logs/catalina.out <==

Sep 17, 2012 2:43:22 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/share/tomcat7/webapps/cfwd.war
Sep 17, 2012 2:43:22 PM org.apache.catalina.startup.HostConfig deployWARs
SEVERE: Error waiting for multi-thread deployment of WAR files to complete
java.lang.InterruptedException
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1302)
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:248)
    at java.util.concurrent.FutureTask.get(FutureTask.java:111)
    at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:752)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:472)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1454)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:296)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1374)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
    at java.lang.Thread.run(Thread.java:679)

Note that cfwd.war is the only war file in the webapps directory (in addition to the usual default contents, as examples, manager, etc etc).
Any ideas about possible causes for this?
Comment: duplicate of http://stackoverflow.com/questions/12263684/infinite-loop-when-deploying-a-war-on-tomcat-7
Answer: This is usually caused by an issue with the applciation class hierarchy. One example I have seen is with out of date classes introducing circular inheritance.
If you upgrade to 7.0.47 you'll get a more informative error message as to what the problem is. Alternatively, a clean build of your applciation may be enough to clean things up.


How do I retrieve the private key for a certificate generated on AWS Certificate Manager?

Question: Someone purchased a wildcard certificate via AWS Certificate Manager for their domain name and I need to transfer it to Heroku for an app that uses a sub-domain of the domain name.
I can't figure out, either through the AWS Console or through their CLI, how I would get the private key used to generate the CSR for this certificate? Can anyone on here help me?
Comment: It is not possible to retrieve the cert key for usage in EC2, and you cannot use Elastic loadbalancing which is supported by ACM, but does not allow single targets. Thanks AWS for making a simple task very hard..
Comment: I have the same problem now, do you solve it? can you help me now or answer this question?
Comment: I don't know for sure, but I think after a lot of searching, I found that the private key cannot be exported. You can only get the CRT file itself, and the bundle. For example, see [this discussion on Reddit](https://www.reddit.com/r/aws/comments/1cystt/downloading_arn_ssl_certificates_after_they_have/)
Answer: You can't. That's one of the points of using AWS Certificate Manager: the private keys won't leave AWS infrastructure. You can't even use AWS Certificate Manager certs on EC2 today, only on specific services. More information here and here.
Edit: You can now use private certificates issued with ACM Private CA with EC2 instances, see more info here. However, that is only useful for private networks, as major browsers won't recognize ACM Private CA by default.
Comment: Is this answer still true? AWS docs says you can export private certificate and use with ec2 instance: https://aws.amazon.com/certificate-manager/faqs/.
Comment: Just wanted to highlight the edit says private certificates can be exported only for those issued by **ACM Private CA**. I missed that context the first time reading this.
Comment: @AndrewFeng good catch. I've edited my answer.


Why is any ring homomorphism from a ring of integers to an algebraically closed field (char=0) injective?

Question: Let $\mathcal{O}_L$ be the ring of integers in a number field $L$. Let $K$ be an algebraically closed field of characteristic zero, and let $f:\mathcal{O}_L \to K$ be a ring homomorphism. Why must $f$ be injective?
I know the following: if $\alpha \in \mathcal{O}_L$ has minimal monic irreducible polynomial $h_\alpha(x) \in \mathbb{Z}[x]$, then $f(\alpha)$ is also a root of $h_\alpha(x)$. That is, $f$ preserves Galois orbits of $\operatorname{Gal}(L/\mathbb{Q})$ acting on $\mathcal{O}_L$. That is, $f(\alpha) = \sigma(\alpha)$ for some $\sigma \in \operatorname{Gal}(L/\mathbb{Q})$. However, if $\alpha, \beta \in \mathcal{O}_L$ with $f(\alpha) = f(\beta)$, I don't know how to conclude that $f(\alpha) = \sigma(\alpha)$ and $f(\beta) = \sigma(\beta)$ for the same Galois automorphism $\sigma$. If I could do that, I could apply $\sigma^{-1}$ to both and conclude that $\alpha = \beta$, but I don't see how this works.
Comment: If the kernel $\mathfrak a$ of $\mathcal O_L$ is not trivial, then the quotient $\mathcal O_L/\mathfrak a$, which is a finite ring with finite characteristic, would inject into the field.
Answer: Every nonzero ideal of $\mathcal{O}_L$ contains an integer (if $a\in\mathcal{O}_L$ is nonzero, then its minimal polynomial has nonzero constant term and that constant term is in the ideal generated by $a$).  So, if the kernel of $f$ were nontrivial, it would contain a nonzero integer, but this is impossible since every nonzero integer remains nonzero in $K$ since $K$ has characteristic $0$.


How to sample transactions to estimate customer-level effects

Question: Let's say I am trying to estimate the treatment effect of rude waiters on how often customers frequent a restaurant. To simplify, let's assume that rudeness is binary, observable, and random. I consider the population of all transactions in October, and I see that some customers have eaten multiple meals and others only once. My outcome will be number of meals in November-Dec period.
I would like to construct a customer-level cross section out of my panel data since the estimation method I am using gets complicated with non-independent observations. I have three options available to me:

Grab a random transaction for each customer. Use the waiter from that transaction to determine if a diner was treated or not.
Aggregate the October data by calculating the # of rude waiters/# of meals for each customer
For each person, grab a random rude transactions if there was a rude one at any time in October. Otherwise, grab a random transaction.

Unfortunately (2) is off the table since there are other attributes of the meal that are hard to aggregate.
Method (1) has the problem that 2 people who both dined twice and had rude transactions half of the time might wind up in separate groups, which seems strange since they have the exact same history.
Method (3) seems the most sensible, but it is giving me an estimate that have the wrong sign, and seem fragile.
I have three related questions:

Is there anything wrong with (3) from a theoretical sampling perspective?
Can I rationalize using (1), since on average the mis-assignment bias might cancel out?
Can I get my cross section in some other way, perhaps by adding weights of some sort?
Answer: I think the problem you noted with method (1) is more subtle: I would expect that people would stop visiting a restaurant after they have been exposed to a rude waiter, so a sequence (0,0,1) is plausible, but (1,0,0) is arguably less plausible (1 is for the rude waiter). If that is the case, this would prevent the mis-alignment bias to cancel out, per your second question, as not all permutations and subsamples of the customer history should be considered as equally likely.
Method (3) is essentially a population-based case-control study, in which your sampling design depends on the outcome. I don't know how much sampling/survey statistics background you have, but try taking a look at Scott (2006) Waksberg lecture. It is certainly not terribly wrong from a theoretical perspective, but you need to know how to analyze this kind of stuff properly. Note that Alastair Scott talks about a logistic regression in which the dependent variable is the outcome you sampled upon; in your application, this would mean modeling the probability that in a given transaction, a waiter will be rude. Your research question is different, though, so most of what the case-control outcome-dependent sampling would do is to produce a substantial variability in pweights.
On your third question, there's been some work on inverse sampling (Rao, Scott and Benhin 2003) and balanced sampling (Tille 2011) as possible ways to reduce the complexity of the problem while retaining some other desirable properties.


Add a canvas form element

Question: I am developing a module and I have this HTML markup.
<canvas id="cnv" name="cnv" width="500" height="100"></canvas>

I want to add it in a form. Looking at the Form API reference documentation page, I don't see any canvas form element.
What should I instead use?
Answer: This document page might help you.
Here is a sample code that I wrote to create a canvas in my form in Drupal 8.
$form['canvas']=array(
      '#type' => 'html_tag',
      '#tag' => 'canvas',
      '#attributes' => array(
                    'style'=>'border: 1px solid #000000;
                              width: 200;
                              height: 100;'
                            ),
      );

Answer: The form api does not support every tag in HTML. For special cases use a form key of #markup to embed raw HTML. Scan the form APIs for that keyword for examples.

Add a canvas form element


Differentiating an Option Payoff

Question: Okay this is probably going to be an extremely easy/straightforward question but I thought I should post it here just to double check. Suppose I have a payoff $\Phi = (S_{T}-K)^{+}$. Now let's say I now have an equation: $u = s\partial_{s}\Phi - \Phi$, this means that given a payoff $\Phi$ as given above then, substituting this payoff into the equation and assuming $S_T = S_{0}\exp((r-1/2)T+\sigma\sqrt{T}Z_i))$ then I should get:
$u = max(S_{T},0) - max(S_{T}-K,0)$, right?
And from this equation, the possible solutions should be:
If $S_{T} > K$, $u = K$, if $S_{T} < K$ and $S_{T} > 0$, $u = S_{T}$, and if $S_{T} < K$ and $S_{T} < 0$ then $u = 0$.
Is all of this correct? I know this is really trivial but I just thought I should check...
Answer: I assume you mean $s\Phi'(s) - \Phi(s),$ to be evaluated at $s = S_T$. In that case, the specific stochastic nature of $S_T$ is irrelevant.
We have
$$\Phi(s) = \begin{cases} s - K, &\mbox{if } s > K \\   0, &\mbox{if } s \leqslant K\end{cases} \\ \Phi'(s) = \begin{cases} 1, &\mbox{if } s > K \\   0, &\mbox{if } s < K\end{cases}$$
Hence,
$$s\Phi'(s) - \Phi(s) = \begin{cases} K, &\mbox{if } s > K \\   0, &\mbox{if } s < K\end{cases} $$
Note that the derivative $\Phi'(K)$ does not exist, but the left-hand and right-hand derivatives are $\Phi_L'(K) = 0$ and $\Phi_R'(K) = 1$.
Thus,
$$S_T\Phi'(S_T) - \Phi(S_T) = \begin{cases} K, &\mbox{if } S_T > K \\   0, &\mbox{if } S_T < K\end{cases} $$
Comment: Thanks heaps for that, I knew it was something fairly trivial :/
Comment: @ThePlowKing: You're welcome.

Differentiating an Option Payoff


OAuth v2 no Django 1.4

Question: Amigos, estou estudando como implementar o protocolo OAuth v2 na minha aplicação. Já pesquisei muito aqui e não encontrei nada que pudesse resolver meu problema. Até o momento tenho um banco de dados no PostgreSQL e autenticação com uma middleware do Django.
Venho tentando seguir a documentação em http://django-oauth-toolkit.readthedocs.io/en/stable/, sem sucesso, porque o PyCharm não reconhece o algumas bibliotecas em INSTALLED_APPS e outras coisas fundamentais nesse tutorial que em teoria tem suporte ao Django 1.4.x.
Teriam como me ajudar, por favor?
Informações:

Ambiente: PyCharm 2016.2.3
Interpretador: Python 2.7.12
Framework: Django 1.4.22
Banco de dados: PostgreSQL 9.3.15
Sistema Operacional: Windows 7 - 32 bits
Comment: Só por curiosidade, você está usando django 1.4 por alguma imposição de um cliente ou simplesmente por que quer?
Comment: Na documentação que você citou, essa biblioteca não suporta a versão 1.4 do django.
Comment: É uma necessidade do cliente. Tem uma versão dessa documentação que diz que suporta: http://django-oauth-toolkit.readthedocs.io/en/stable/. Alterei na pergunta!
Answer: Se o pycharm não esta reconhecendo as bibliotecas, significa que o seu projeto pode estar apontando para um ambiente diferente de onde estão instaladas essas bibliotecas, veja na configuração:
File/setings/Project:seuprojeto/Project Interpreter
Veja a figura

OAuth v2 no Django 1.4


Accidental written twice

Question: The following piece is in key of Eb/Cm and I'm struggling to read it.
Firstly, the key is Eb so, the A is already Ab, does the accidental turn it into
 an Abb(G)?
Secondly, the Abb appears yet again in flat form, does it mean it will be an Abbb?(Gb)?
Source, Kent Hewit, My Funny Valentine
Comment: The key is most likely 3b, so Eb/Cm. If it was Bb, the Abm6 chord would be unusual. And while the first Ab *may* be courtesy, there's absolutely no need for the second. Unless, of course, the key sig is 2b (Bb) where the Ab would need signing. But then it's wrongly written.
Comment: Right I confused it.
Comment: It looks like a courtesy accidental to remind the player that that note is flat in that measure.  But that is usually not done in the same measure.  A courtesy is usually given in next measure to remind you that the accidental is inactive (this really bugs me).  I would be inclined to initially read it as a double flat, had I not known about the courtesy.
Answer: As others have written, those accidentals don't sum up.
To understand, why they are in this bar, I think it helps to look at the bars before the one in question. So, here we go:

Firstly, the key is Eb so, the A is already Ab, does the accidental turn it into an Abb(G)?

Right before this, in the previous bar, is an A natural. Hence, the flat you ask about is a reminder to play Ab again.

Secondly, the Abb appears yet again in flat form, does it mean it will be an Abbb?(Gb)?

This is also a reminder not to play A natural, but Ab. This time, it is meant for the second voice (which consists of the quarter notes/crotchets).
As Tim correctly commented, both reminders are not really necessary, since a bar line in general cancels all accidentals of the preceding bar. In this case, the bar line cancelled the A natural.
Answer: Actually the key is e flat; the accidentals do not add up to the key signature as already discussed in this question; if adding up was intended, a double flat would be required. Repetition of an accidental is also not changing something.
Courtesy accidentals (convention is to put them in parentheses) are quite untypical to appear for accidentals from the key signature (but since the a flat was natutalized in the bar before, it is a valid courtesy accidental); additionally the c flat is necessary.
Answer: No, and no.  This could be considered a courtesy accidental.  It belongs to the melody voice, which had an A-natural in the immediately preceding measure.  Sometimes courtesy accidentals are notated in parentheses to indicate the note is already modified.
Answer: Your question is rather muddled.  "The following piece is in key of Bb and I'm struggling to read it. Firstly, the key is Eb...".
Don't tell us about the key signature, SHOW it to us!
Assuming a 3-flats key signature, and assuming there was an A natural accidental in the preceding bar, a cautionary Ab (with or without parentheses) is normal and correct.   Where there are two 'voices' it is maybe a little pedantic to add it for each voice in piano music (it would be required in a vocal score where the different 'voices' actually WERE different voices.)
In any case, no, accidentals are not additive.  A flat in front of A means A flat, no matter how many previous times we've been told A's are flattened.

Accidental written twice


Use output of two greps with diff

Question: How do I make better the following method of comparing certain lines (lines that start with "@") of two files? I feel certain this could be done on one line and without embarrassing temporary files. I am pretty new to Linux so go easy on me! Thanks in advance.
grep "^@" myfile1 > temp1
grep "^@" myfile2 > temp2
diff temp1 temp2

Comment: Alternatively, it could be more practical to do: diff myfile1 myfile2 | grep "^@"
Answer: In Bash, you can use <(...), which will handle temporaries (usually implemented as named pipes under the hood) for you:
diff <(grep "^@" myfile1) <(grep "^@" myfile2)

Comment: They're not named pipes, they're named pipes :)
Comment: @MattJoiner So, Schrödinger's pipes?
Comment: They're not **temporary files** ಠ_ಠ
Comment: They may or may not be named pipes, depending on what the underlying OS supports (e.g. they could be `/dev/fd/...` file descriptors, which are distinct from named pipes), but the benefit is that `bash` manages them and any required setup/cleanup for you.

Use output of two greps with diff


Combine 2 dictionaries by key-value in python

Question: I have not found a solution to my question, yet I hope it's trivial.
I have two dictionaries:
dictA:
contains the order number of a word in a text as key: word as value
e.g.
{0:'Roses',1:'are',2:'red'...12:'blue'}

dictB:
contains counts of those words in the text
e.g.
{'Roses':2,'are':4,'blue':1}

I want to replace the values in dictA by values in dictB via keys in dictB, checking for nones, replacing by 0.
So output should look like:
{0:2,1:4,2:0...12:1}

Is there a way for doing it, preferentially without introducing own functions?
Comment: Please indicate what you tried.
Answer: Use a dictionary comprehension and apply the get method of dict B to return 0 for items that are  not found in B:
>>> A = {0:'Roses',1:'are',2:'red', 12:'blue'}
>>> B = {'Roses':2,'are':4,'blue':1}
>>> {k: B.get(v, 0) for k, v in A.items()}
{0: 2, 1: 4, 2: 0, 12: 1}

Comment: Cool, thanks. That was exactly what I was looking for.


Should I learn a new minor scale pattern, or "reframe" a major scale pattern?

Question: I'm confident with the major scale pattern in the image. Now I'm looking to learn a minor scale pattern to use for soloing or playing in minor keys. It seems in my mind that I could simply "reframe" the major scale pattern such that the root note (and third, and all others) are in another place. I'd call the G major pattern an E minor pattern and re-learn where the roots and thirds and fifths are.
Is this a good pedagogical idea? Or am I better off learning another minor scale pattern?
Answer: I think it's a good idea, because so many things in music are about relative relationships. You have a deeper understanding of scales overall if you think of the commonalities between major/minor scale and the small changes that make them different.
As an aside I would look for, or make, diagrams that label the scale degrees rather than the fingers. With that labeling your scale diagram looks like...

The major third ^3 and major sixth ^6 scale degrees are circled in yellow. Those are the two modal degrees that define the scale as major.
If you just shift those two degrees down one fret, the tones become the minor third and minor sixth scale degrees, and the scale is now the harmonic minor scale.

There are three types of minor scales, but we don't need to get into those details now. The point is all of them can be formed with relative changes to some other scale, like the major scale as a sort of default reference point.
You can expand that idea further and divide up scales into tonal degrees - the root, perfect fourth, and perfect fifth - and variable modal degrees - second, third, sixth, and seventh.
If we put the tonal degrees into the big dots and the modal degrees - natural and lowered forms - in plain numbers, the diagram looks like...

At first glance that looks like a big mess of numbers. But the idea is to learn what modal degrees define each scale and then fill them in between the tonal degrees or shifting from some base scale.
Natural minor will use ♭3 ♭6 ♭7, fill in those between tonal degrees or drop them down from natural 3 6 7 of major. Then, when that scale is familiar to you, you can make further changes. For example, dorian mode will take that natural minor scale and raise ♭6 up to natural 6. Or, you can get the phrygian mode from natural minor by dropping the natural 2 to ♭2.
The type of box your have is very popular, and you see it a lot for the "CAGED" teaching system for guitar. But, you can also think of scales as combining two tetrachords, and comparing relative relationships. There are four main tetrachords - major, minor, phrygian, and harmonic. Just those four patterns can be combined to make all the major and minor scales, diatonic modes, and several important "exotic" scales. The idea is not as popular as "CAGED", but then again "CAGED" will keep you stuck in diatonic scales only. You can find tutorials online about the tetrachord method for scales.
You also might look up "three notes per string." That uses boxes similar to what you have, but differs on the B string, giving three rather than two notes. You can get fingering patterns more consistent across the strings that way.
Answer: There are 5 of these types of patterns. Within each pattern is the major scale AND the relative minor scale (and all the modes for that matter). Assuming this is a G major scale, it is also an E minor scale as well. E minor, the relative minor of G, starts on the 6th degree, or D string, 1st finger. Here is the minor scale version of that same pattern with roots in red:

This is great but having a minor scale with the root on the 4th string is not ideal so…
If you go all the way to pattern 5 and change the major roots to the relative minor roots (in this counting backward, 1-7-6) it gives you a minor scale with the roots on the 6th, 4th and 1st strings, just like the major scale you are using:

This pattern is good for minor keys because it allows you to play the roots in 3 different octaves, just like the major scale you are comfortable with. In the end you don't really have to re-frame it, it already exists in another pattern.
Like I said earlier though, the natural minor scales are available to you within all 5 of the major scale patterns. All you have to do is go either backward or forward from the major tonic to the 6th degree to find them.
Answer: Using the natural minor notes, you'll really only need to re-jig the pattern you know for its relative major scale. Pretty straightforward.
The only real problem that occurs with minor pieces is that the leading note is missing. The seventh note from a natural minor scale will need, in a lot of cases, to be raised, so it's one semitone under the root, not one tone like it will be in the natural minor. So, if you bear that in mind, and compensate accordingly, you'll have a slightly different pattern from the relative major, with its fifth note sharpened (up a fret). Wouldn't worry for now about melodic minor notes - they'll come later.
If you decide to learn a 'new' pattern, you'll probably be pleasantly surprised that some of the notes are in the same place as what I've just described anyway!


How to customize exporting query result (PHP mysql) to excel file?

Question: I have some questions about customizing export result(excel) with php. The idea is i want to export my query of my raw data (mysql table) to excel file but with some customization in the result.
for example i want to have result which is summary of the table like below table:

The 3rd column until 7th column is named based on the last 5 days of my report date.
My idea is:
1. create temporary table using format as the result table i want to generate
2. Insert the table with my raw data.
3. Delete those table.
Is that efective?or is there any better idea?
Answer: You can always use a view. Which is essentially a select statement with your data in there, and which will be updated whenever your tables are updated. Then you can just do a 'select * from view_name' and export that into your excel.
Answer: Depending on the size of the data, there is no need to think about performance.
Edit the data before
You can have a temp table. Depending on the data, this is very fast if you can select and insert the data based on indexes. Then you make a SELECT * from tmp_table; and you have all your data
Edit the data after
You can just join over the different tables, get the data and then loop (read as foreach) over the result array and change the data and export it afterwards


How to handle a post request from an external application in Drupal?

Question: I am integrating with the Stripe payment gateway and I need to be able to handle a post from their server to authenticate a standalone account. I am trying to follow the instructions at https://stripe.com/docs/connect/standalone-accounts
Namely, I need to provide a callback URL which will receive the data I need through request parameters.
https://mydrupalsite.com/callback?scope=read_write&code=AUTHORIZATION_CODE
I need to be able to get the scope and the code value.
Once I have that, I will need to then redirect based on their values to certain pages.
I tried creating a MENU_CALLBACK type menu item with a page callback to handle the parameters, but what I tried didn't work.
Below is the code I tried.
function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['bh_commerce_stripe_oauth/callback/%'] = array(
        'title' => 'bh_commerce_stripe_oauth_callback',
        'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
        'page arguments' => array(2),
        'type' => MENU_CALLBACK
  );
  return $items;
}

function _bh_commerce_stripe_oauth_handle_callback($post_parm_args) {
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}

Comment: How about looking at how Drupal Commerce handles it? https://www.drupal.org/project/commerce_stripe
Answer: Your path is wrong I think. You should be able to access that callback here.
https://mydrupalsite.com/bh_commerce_stripe_oauth/callback/randomstring
So actually your hook_menu should look like this.
/* Implements hook_menu */
function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['callback'] = array(
    'title' => 'bh_commerce_stripe_oauth_callback',
    'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

Note: You don't have any path wildcards (represented by % in your array key) in the callback you are getting that are useful. Therefore you don't need any page arguments. The interesting things are in the $_GET (or $_REQUEST).
And then to access the results something like:
function _bh_commerce_stripe_oauth_handle_callback() {
  $scope = $_GET['scope'];
  $code = $_GET['code'];
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}


Dúvida MySql - Resultado da consulta

Question: Galera me ajudem com uma situação por gentileza, preciso pegar todos os registros da tabela "comprador" e seus atributos e caso eu tenha na registros de um cliente na tabela pedido vinculado a algum comprador listado ele me mostre por comprador:
comprador.nomeCompr,
comprador.descCatComprador,
COALESCE(sum(mercadoria.precoMercadoria*pedido.quantMercPedido),'0') as 'valorTotal',
COALESCE(sum(pedido.quantMercPedido),'0') as 'volumeTotal'

from comprador
join fornecedor on fornecedor.codComprFornecedor = comprador.codCompr
left join pedido on pedido.codFornPedido = fornecedor.codForn
left join mercadoria on mercadoria.codMercadoria = pedido.codMercPedido
where comprador.codCompr in (select codCompr from comprador)
and pedido.codAssocPedido = '4102'
group by comprador.codCompr order by valorTotal desc

Mas nesse caso ele retorna somente os compradores que tem pedido e não os que estão zerados, eu gostaria que ele retornasse também os compradores que estão com valores zerados, caso eu não utilize a condição where pedido.codAssocPedido = '4102' ele retorna todos os valores inclusive os zerados, mas trás também clientes que eu não quero listar, segue abaixo os prints.
Comment: Se você já está trabalhando com a tabela comprador no SELECT mais externo qual o motivo de `where comprador.codCompr in (select codCompr from comprador)`? Isto não será sempre verdadeiro? Como você não tem nenhuma restrição para clientes por qual motivo diz que trás clientes que você não quer listar?
Comment: Na verdade eu criei essa ambiguidade propositalmente, mas por exemplo estou dizendo na linha '''and pedido.codAssocPedido = '4102'''' que ele deve puxar somente o "cliente" que associado na verdade da tabela de pedidos
Answer: Você pode tentar a seguinte alteração no seu SELECT-->
Ao invés de você utilizar essa cláusula JOIN:
`join fornecedor on fornecedor.codComprFornecedor = comprador.codCompr`

Utlizar como um LEFT JOIN para retornar os compradores sem um fornecedor vinculado:
left join fornecedor on fornecedor.codComprFornecedor = comprador.codCompr

Dúvida MySql - Resultado da consulta


Could a group of musicians play a new piece by sight-reading on first attempt?

Question: Is it possible, without any rehearsal, relying solely on sight-reading?
Are there any experiments of this kind with octets, nonets, maytbe entire orchestras?
Answer: Yes. High-paid studio musicians are all expected to sight read perfectly on the first read. There are even programs to illustrate and develop the skill for younger musicians. Many movie soundtracks are recordings of first-time sight reading.
Comment: However hourly rate can be around the $1000/hr mark, so cheaper is relative.
Comment: Possible, but in reality how many composers and conductors are happy with the first read? It takes a number of rehearsals to get the nuances perfect. In movies, you may have other considerations that have to work with other sound elements (Foley, dialogue). A first read by competent musicians is certainly possible, but getting what the composer or director or conductor wants in a first read is rare.
Comment: Singers are another business--I doubt Sinatra was reading from music at all in making that recording. It's a standard tune, so he probably reviewed the arrangement they had written for the orchestra with his producer beforehand and took many liberties with the actual line and words. That's what makes different singers distinctive.
Comment: It's cheaper also. You don't have to pay musicians as much for time.
Comment: Anecdote I was told by my band director: over half of the recordings for the Star Wars Ep. 1 soundtrack were first reads. I think these musicians are some of the world's best, and can actually perform at that level.
Comment: Anecdote: Listen to Frank Sinatra's recording of "One For My Baby (And One More For The Road)". He sings it once through, but it's written with a first ending back to the beginning, with the pickup note and the word "it's" ("It's quarter to three...") The song ends "the road, that long, long road." Frankie sings "the road, that long, long, it's long." Was he seeing the music for the very first time as he sang it for the recording? Yes, musicians can play or sing it on sight, no rehearsal, one take, and get a hit record.
Comment: Sinatra must have liked "that long, long, it's long" because he did it in live performances too. I can't say whether he DID sight-read the first recording, but he had the ability. And it's not unprofessional to do that. In fact it's VERY professional to do it when necessary.
Comment: i think there might be some confusion between a first *read* and a first *take*. great performances can be got from a first read but the likelihood of a (film) score being recording on a first read is zero. music is usually received ahead of time (not always) and then rehearsed before it's recorded.
Comment: Second link is dead
Answer: I doubt, a full symphonic orchestra will achieve a breath-taking recording on the first attempt. Of course anybody knows its Beethoven, so it is not exactly sight-reading, but these points make it difficult:

the conductors individual interpretation
increased complexity of voice interaction
sheer area of a late-romantic orchestra make it challenge to hear
soloists from remote groups
Answer: Yes.  And all too often they have to.  Meticulous scoring, music preparation and playing skills are taken for granted in the professional music world.  But it's also great to hear a performance that has benefited from sufficient rehearsal and a few previous outings.


Kalman filter to smooth accelerometer signals using rotation matrix

Question: I have 3D accelerometer signals which are obviously noisy. I am trying to use Kalman filter to remove bias and drift from these signals. As an extra input I have rotation matrix.
I can also use a moving average filter and it will be fine but how can I use Kalaman filter to smooth these signals using rotation matrix?
Best Regards
Chintan
Comment: I am interested in this problem too. Did you find a solution?
Answer: Please have a look the documentation how to use scalar Kamlan Filter:
http://www.swarthmore.edu/NatSci/echeeve1/Ref/Kalman/ScalarKalman.html
If you can run the code in Matlab and see how the scalar Kalman Filter works:
http://www.swarthmore.edu/NatSci/echeeve1/Ref/Kalman/scalarkalman.m
Once you are familiar with the basic and use of scalar kalman filter then you can follow the practical implementation guide:
http://robotsforroboticists.com/kalman-filtering/
Rotation is included and the linear model is replaced by a general one. Next two filters are combined and finally the federated Kalman Filter is included:
http://campar.in.tum.de/Chair/KalmanFilter
Comment: I understood Kalman filter for Scalar case using the first two links. In fact the best description I have found so far. The 3rd link is confusing so left it. It looks like the material in the 4th link could be helpful but I need more information. In that the author uses position data along with quaternion. However, how can I apply that technique it to filter accelerometer data using rotation matrix. Thanks.
Comment: Thank you for giving these links. I will study them and come back :)


How to access the variable to which OS copies

Question: An interesting feature, I have seen in jDownloader software is any links I copy in the browser window (i.e., Ctrl+c), the copied content links automatically appears ( i.e., with out me actually pasting it) in their UI and starts downloading the content from the links, if they are valid.
I would like to program the same but am puzzled as how to access the variable to which OS copies. Please share your ideas.
Thanks.
Answer: Adam Robinson's answer is on the right track, but is not entirely correct. I'm going to try and provide the "long" version (in contrast to his "short" version), and explain along the way where/why I think the solution that he proposes falls short of achieving your ultimate goal.
As the documentation he links to explains, there are three different ways of monitoring changes to the Windows clipboard, each with their own caveats:

Creating a clipboard viewer window that hooks into the clipboard viewer chain and receives notification messages when the contents of the clipboard have been changed by the user. (Available on all versions of Windows, but generally more difficult to code and thus discouraged for newer applications that don't have a specific need for its features.)
Querying the clipboard sequence number, which is a 32-bit value that changes each time the clipboard's contents are changed. Your program calls the Windows API function GetClipboardSequenceNumber once and caches its value, then each time you want to check if the clipboard's contents have changed, you call that same function again and compare its return value to the value you've cached. There are two important caveats here:

This function is only available in Windows 2000 and newer. This is not likely to be a problem if you're writing .NET apps, as versions of the Framework as early as 3.0 dropped W2K support.
This is not a notification method, and you should not call this function repeatedly in a polling loop. That means that you have to manually call the appropriate function and compare the clipboard sequence number. You cannot use this method if you want to "listen in" and be immediately notified whenever the clipboard's contents change, as you describe in your question. The documentation is very explicit here:

This method is more suitable to programs which cache results based on the current clipboard contents and need to know whether the calculations are still valid before using the results from that cache. Note that this is a not a notification method and should not be used in a polling loop. To be notified when clipboard contents change, use a clipboard format listener or a clipboard viewer.

Creating a clipboard format listener, which registers to be notified whenever the clipboard's contents change. This is the ideal solution in your case, because it avoids the complexities of creating a clipboard viewer window (option 1), but also allows you listen in and be notified each time the clipboard's contents are changed (in contrast to option 2).
The problem is that this is only available under Windows Vista and later. If you still have any need to target Windows XP (as most of us do), this is really not an option for you.

Therefore, from the example you provide in the question, it sounds to me like the only option available to you is option 1, creating a clipboard viewer window. The documentation goes into the gory details of how you'd set this up using the SetClipboardViewer function and listening for the WM_DRAWCLIPBOARD and WM_CHANGECBCHAIN messages. Getting this to work right can be a difficult task to do on your own, but fortunately for us .NET developers, others have already done the hard work for us. ("Others", I say, despite having been one of those others myself.)
This article on CodeProject is a good example. It implements three different types of hooks: a mouse hook, a keyboard hook, and a clipboard hook. The only thing you're interested in is the clipboard hook, but you can just add a reference to the DLL in your project to start using its functionality immediately.
If you are interested in the internals of how this works and want to try coding it up yourself, this article appears to be a fantastic description of the specific steps involved.
Answer: Use the My.Computer.Clipboard.GetText() function
Also see the msdn page
Comment: But how would I know something is copied by the user to the running application ?
Comment: To be able to call that function, at first I should be able to know a copy event is generated by OS( i., right click and copy ). But how to know that is generated, to the current running application ?
Answer: Check out this MSDN link regarding the clipboard. In particular, this link's anchor should take you to the section of the document about monitoring the clipboard contents.
The short version is that you can monitor either by polling for the sequence number and checking to see if it has changed, or you can register to listen for changes for specific clipboard contents formats. Note that the latter is only available on Vista and above, so you depending on your target platform you may have to stick with polling.
In order to use these functions, you'll have to declare a P/Invoke to the unmanaged function. Here's the PInvoke.net page on the GetClipboardSequenceNumber function, though the declaration here is C#, not VB.NET. The VB.NET syntax should be (I don't have VS in front of me to check):
<DllImport("user32.dll")>
Public Shared Function GetClipboardSequenceNumber() as UInt32
End Function

Comment: I agree with most what you suggest, but as you say yourself, "Note that the latter is only available on Vista and above, so you depending on your target platform you may have to stick with polling." If the asker has a need to run on older versions of Windows and therefore needs to "stick with polling", the `GetClipboardSequenceNumber` function is not an option. You're going to have to do it the old school way with hooking into the clipboard viewer chain. I describe this more thoroughly in my answer.


adding attribute using knockout js with dynamic string value

Question: I am working on dynamically creating the tiles like UI for showing the metrics. i want to show some color dynamically based on the id. i need to append  "_flag" with the dynamic value(symptom.symId = S1). my code is given below.

Please help me
Comment: Your question is quite unclear. Where do you want to append this `_flag`?
Answer: If I understand your question correctly, then you want to do:
attr: { id: sympton.symId + '_flag' }

or if symId is observable, then:
attr: { id: sympton.symId() + '_flag' }


Open Graph Built-in Like vs. Like Social Plug-in for mobile web apps

Question: I have a mobile app created using the javascript sdk, I would my user to be able to like posts, on the news feed. does anyone know how to achieve this?
Answer: There is nothing that prevents you from inserting multiple Like buttons on the same page.
Provided the first post leads to https://github.com/ and the second one to https://stackoverflow.com/ the Like buttons look like this:

When the user clicks the like button, it appears on their Facebook page.
Note that the Likes should have links to pages that can be accessed by Facebook. Of course you can use your own pages.
More info: https://developers.facebook.com/docs/reference/plugins/like/


Find the $r^{th}$ term from the beginning and the $r^{th}$ term from the end of $(a+2x)^n$

Question:
Find the $r^{th}$ term from the beginning and the $r^{th}$ term from the end of $(a+2x)^n$

$(a+2x)^n=[a(1+\dfrac{2x}{a})]^n=a^n(1+\dfrac{2x}{a})^n$
$(1+\dfrac{2x}{a})^n=1+^nC_1(\dfrac{2x}{a})+^nC_2(\dfrac{2x}{a})^2...+^nC_r(\dfrac{2x}{a})^r...$
So the $r^{th}$ term from the beginning is $a^n(^nC_r)(\dfrac{2x}{a})^r$. But the answer is given as $\dfrac{n(n-1)...(n-r+2)}{(r-1)!}a^{n-r+1}(2x)^{r-1}$.
As to the $r^{th}$ term from the end, I suppose I have to find a way to transform it so I can count it from the beginning? How would I go about doing that? Thanks.
Comment: Since the first term is 1, the $r^{th}$ term is $a^n(^nC_{r-1})\left(\frac {2x}{a}\right)^{r-1}$ which simplifies to the given answer.
Answer: We can expand $(a+2x)^n$ to get $${}^nC_0a^n(2x)^0+{}^nC_1a^{n-1}(2x)^1+{}^nC_2a^{n-2}(2x)^2+\ldots+{}^nC_na^0(2x)^n$$
As you can see the $r^\mathrm{th}$ term will be $${}^nC_{r-1}a^{n-(r-1)}(2x)^{r-1}={}^nC_{r-1}a^{n-r+1}(2x)^{r-1}$$
Note that the mistake you made is that you took the ${}^nC_0a^n(2x)^0$ term to be the $0^\mathrm{th}$ term rather than the $1^\mathrm{st}$, which gave you the $r^\mathrm{th}$ term as $${}^nC_ra^{n-r}(2x)^r={}^nC_ra^n\left(\frac{2n}a\right)^r$$
Since ${}^nC_r=\frac{n!}{r!(n-r)!}$, this can be rewritten as $$\begin{align}\frac{n!}{(r-1)!(n-r+1)!}a^{n-r+1}(2x)^{r-1}&=\frac{n(n-1)\ldots(n-r+2)(n-r+1)!}{(r-1)!(n-r+1)!}a^{n-r+1}(2x)^{r-1}\\&=\boxed{\frac{n(n-1)\ldots(n-r+2)}{(r-1)!}a^{n-r+1}(2x)^{r-1}}\end{align}$$
as required.


Phoenix: How to store state shared across sockets in a channel?

Question: I have an app where 2 people chat. But before they chat, BOTH parties have to press "accept"
on the front end I have a button that calls this function:
function acceptMatch() {
  channel.push("accept_match", {
    "matched_client_email": matchedClientEmail,
  });
}

in my phoenix channel I have this (which is incomplete because I'm not sure what to do):
  def handle_in("accept_match", %{ "matched_client_email" => matched_client_email }, socket) do
    Logger.info "accept_match"
    ...
    ############################### here ####################################
    match_accepted = true # <-- I want to be able to find out if the other person has pressed "accept" as well
    case match_accepted do
      true ->
        ...
        {:noreply, socket}
      _ ->
        {:noreply, socket}
    end
  end

I looked into Agent, but that seems to be tied to a PID, which I wouldn't be able to easily pass around to different sockets. I'm trying to look for a common storage (other than a database) between all connections that I can save to / query. This way if party A presses accept, I can ask the storage "did party B accept?"
=== UPDATE ===
When I try using a named Agent I get this:
iex(11)> myfunc = fn -> %{} end
#Function<20.52032458/0 in :erl_eval.expr/5>
iex(12)> Agent.start_link(myfunc, name: "Cool")
** (CaseClauseError) no case clause matching: {"Cool", []}
    (elixir) lib/gen_server.ex:544: GenServer.do_start/4
iex(12)>

Answer: Actually it seems that you might pass to each new connection in connect in your user_socket this particular PID or name of the Agent and it should solve this case. You only need one Agent, so you can name it, eg.
Agent.start_link(your_func, name: :myagent)

and later get from it
Agent.get(:myagent, your_get_func)

Also you can consider to use Registry, which is from Elixir 1.4 in standard library.
This agent can be in lib and you can just add it in the <app_name>.ex file as a single worker and supervise it with dedicated Supervisor if needed.
Comment: ooo cool! when I tried doing it I get an error... updated my question with the error
Comment: Yes, sorry. I updated my answer. Name must meet requirements in https://hexdocs.pm/elixir/GenServer.html#module-name-registration


Using array contents as reference to object name

Question: So I'm trying to run a for loop to update several objects variables and using an array of their names but the reference doesn't work and instead appears undefined. I presume this is because the array is a string and not an object and was wondering what the easiest way around this would be.
I've attached some simple code to give you an idea what i'm attempting, cheers.
    <!DOCTYPE html>

Comment: Is there a particular reason you have an array of simple strings rather than actual references to the objects?
Answer: Your array is not containing references to your objects, but simple strings. Try declaring it like that :
var people = [person1, person2];

Comment: Oh of course, sometimes it's the simplest of things you overlook. Thank you.


Mostrar um EditText ao clicar no FloatingActionButton

Question: Vejam se pode me ajudar estou começando a trabalhar com FloatingButton gostaria de quando o usuário clicar no botão aparece um EditText para digitação e um botão ao final para apagar o texto, conforme imagem abaixo:

Criei esse FrameLayout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="9dp"
    android:visibility="gone"
    android:padding="5dp">

    <EditText
        android:id="@+id/calc_txt_Prise"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:textColor="@color/barDarkColor"
        android:textStyle="bold"
        android:hint="@string/app_name"
        android:singleLine="true" />

    <Button
        android:id="@+id/calc_clear_txt_Prise"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_gravity="right|center_vertical"
        android:background="@drawable/com_facebook_close" />

</FrameLayout>

Mas agora como poderia chamar para exibir?
Answer:  FrameLayout frameLayout = findViewbyId(frame_layout);

 FloatingActionButton fab = findViewById(R.id.fab)
 fab.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
                 frameLayout.setVisibility(View.VISIBLE);
            }
        }
    });

Desse jeito deve funcionar, só que eu acho melhor você usar um LinearLayout horizontal pois tem dois filhos diretos, e o FrameLayout(se não me engano) é utilizado quando tem apenas um
Answer: Você poderia fazer de dois jeitos:

Inflar esse FrameLayout/Inflar e usar na view de um AlertDialog
Colocar o edt e o botão na mesmo layout que o floatingbutton e trabalhar com a visibilidade
setVisibility(View.VISIBLE)
setVisibility(View.GONE)


solve the quintic non-linear system

Question: $x^5+y^5=33$ and $x+y=3$
I tried a variety of things here, all too ugly to post.  the most promising was doing long division $(x^5+y^5)/(x+y), $but it still looked kind of ugly and not easily factorable.  I am looking to solve this with simple high school level algebra techniques.  Can someone give me a hint?  Much appreciated.
Comment: Yes, the exercise was taken from a 9th grade algebra textbook in Eastern European curriculum
Comment: Any particular reason to expect a simple solution to this problem?
Comment: The first thing I will try is plug some random small integers to the equations. I already find two solutions this way: $(x,y) = (2,1), (1,2)$
Answer: The first thing I try is plug some random small integers to the equations and see
whether they work. I already get two "obvious" solutions $(x,y) = (2,1)$ and $(1,2)$.
To see this exhaust all solutions, introduce a parameter $u$ such that $x = \frac{3+u}{2}$ and $y = \frac{3-u}{2}$.
In terms of $u$, we have
$$\begin{align}
& x^5 + y^5 = 33\\
\iff & (3+u)^5 + (3-u)^5 = 33\cdot 2^5\\
\iff & 2(3^5 + 10\cdot 3^3 u^2 + 5\cdot 3 u^4) = 33\cdot 2^5\\
\iff & 10\cdot 3^2 u^2 + 5 u^4 = \frac13\left(\frac12\cdot 33\cdot 2^5 - 3^5\right)
= 11\cdot16 - 81 = 85\\
\iff & u^4 + 18u^2 -19 = 0\\
\iff & (u^2-1)(u^2+19) = 0\\
\implies & u = \pm 1\end{align}$$
This means the equations have two and only two real solutions: $(x,y) = (2,1)$ and $(1,2)$.
Answer: From the second $y=3-x$. Plug in the first equation and expand
$$x^5+y^5=x^5+(3-x)^5=15 x^4-90 x^3+270 x^2-405 x+243$$
making the equation to be
$$15 x^4-90 x^3+270 x^2-405 x+210=0$$ Divide all terms by $15$ to get
$$x^4-6 x^3+18 x^2-27 x+14=0$$ which, by inspection, shows two simple roots.
Just continue.
Comment: Thank you, Claude.  I was looking for a clever solution instead of trying the obvious. Thanks again.
Answer: Given $x+y=3$, raise to the fifth power:
$x^5+5x^4y+10x^3y^2+10x^2y^3+5xy^4+y^5=243$
Subtract $x^5+y^5=33$ from this and factor the remaining terms:
$5xy(x^3+2x^2y+2xy^2+y^3)=210$
$xy(x^3+2x^2y+2xy^2+y^3)=42$
We then have
$x^3+2x^2y+2xy^2+y^3=(x^3+3x^2y+3xy^2+y^3)-xy(x+y)=(x+y)^3-xy(x+y)=27-3xy,$
using the linear equation $x+y=3$. So
$xy(27-3xy)=42, xy(9-xy)=14$
$(xy)^2-9(xy)+14=0$
Thus $x+y=3$ and $xy\in\{2,7\}$. For each possible product we form a quadratic equation whose roots will give a pair of $x,y$ values. With $xy=2$ we have
$w^2-3w+2=0, w=x\text{ or }y\implies \{x,y\}=\{1,2\}$
With $xy=7$:
$w^2-3w+7=0, w=x\text{ or }y\implies \{x,y\}=\{(3/2)+\sqrt{19/4}i,(3/2)-\sqrt{19/4}i\}$
The quadratic equations are factors of the quartic found in Claude Lebovici's answer.

solve the quintic non-linear system


Why is explicitly returning 0 from main() considered good practice?

Question:
Possible Duplicate:
return statement vs exit() in main()

I've just read the first chapter of Accelerated C++ (seems like an awesome book), and at the end the author says

However, explicitly including a return from main is good practice.`

Why is this considered good practice? In C99, I always omitted the return 0, using exit() to signal abnormal program termination, and never missed the explicit return.
Comment: http://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main
Answer: A couple of reasons,
firstly, main is declared to return int, and so it should
secondly, and maybe more importantly for C++ an exit() from main will skip calling destructors for local object instances in main.
Answer: In C99 and in C++ if execution of the program reaches the closing brace of the main() function then an implicit return 0; is executed.  That wasn't the case in C90 - reaching the end of main() without an explicit return would result in an indeterminate value being returned (strictly speaking, the behavior is undefined).
I can only guess that the authors of "Accelerated C++" feel that the explicit return is good practice simply because it makes your intent explicit.  The only other reason I can think of is that it makes code compatible with C90, but I find it difficult to believe that that would hold much weight as a reason.
Comment: Correct me if I'm wrong, but I thought that prior to C99, a function with a declared return type could *legally* return without specifying a value if it could be sure (based e.g. upon parameters) that the caller would never try to use the return value.  Not to say that anyone *should* ever write code like that, but I think prior to C99 such code was legal and did not invoke UB.
Answer: The calling program (usually a OS shell) can gather the return code and know if the program failed or not.
Having a single exit point from a program makes a good place to put a breakpoint.
Having a single execution flow makes it easier to follow a program if you're unfamiliar with it.
Comment: #1 doesn't matter. Leaving main without explicitly returning anything is to implicitly return `0`.
Comment: As to the other two, you can't use `return 0;` if you also want to have a single exit point as well as indicate abnormal termination.
Comment: @visitor, you can have a variable that tracks the program status and return that.
Answer: I think this rule of thumb not so much applies to callling exit() instead, but to fall off main() without returning anything, relying on the implicit return 0 the run-time system has to do in that case.
I guess that main() is the only function returning a value where you can omit explicitly returning a value. IMO that's a very good reason to not to rely on that rule.
Answer: By C++ standard main() should return int. This is an error code application returns on its termination and in practice this is useful when calling process wants to know whether this application terminated with success (usually error code is 0 in this case) or it failed.
I'll give a Microsoft specific example, but it shows general need for returning error code:
ProcessA needs to create ProcessB and wait for it to terminate, after which it wants to check whether ProcessB executed successfully. ProcessA will use CreateProcess function to create ProcessB, then will use ProcessB's handle to wait for its termination and then will use GetExitCodeProcess function to get ProcessB termination code - which is int value returned from main().


Is it possible to define a global (header + footer) wrapper on react-native using react-navigation and nativebase

Question: I am very new to React-Native, React navigation and nativebase. Roughly, I am trying to find a way to set the same header and footer on each screen of my application. The header contains the title + a login icon. The footer contains the navigation. What is the proper way to have a global header and a global footer to the application ?
I have tried defining a wrapper component (MainStructure) and add {this.props.children} in the content  but I get an error on this.props.navigation whenever I click the footer. For this error, I have tried adding navigation props manually to MainStructure it did not work. I have tried adding HOC withNavigation, no result neither.
I have tried defining a header component and a footer component and adding them everywhere in the component, but that's ugly + it does not work for some reason I don't get.
Finally, I have tried defining header in navigationOptions and defaultNavigationOptions it did not work neither.
this is the App code
const AppNavigator=createSwitchNavigator(
    {
        Home:Home,
        Search: Search,
        Account:Account,
        Login:Login
    },
    {
        initialRouteName:"Home",
    }
);
const AppContainer= createAppContainer(AppNavigator);

class App extends Component{

  render() {
    return (
        <MainStructure>
            <AppContainer/>
        </MainStructure>
    );
  }
}

export default App;

AppRegistry.registerComponent('Kioozi', ()=> App);

Here is the MainStructure code
class MainStructure extends React.Component {
    constructor(props){
        super(props);
        Text.defaultProps.uppercase=false
    }
    render() {

        return (

        );
    }
}

export default MainStructure;

I used createSwitchNavigator as I want to use the bottomTab from nativebase and not from react-navigation.
Expected Result : whenever I press a tab, I get the related screen with the header and footer.
Answer: Wrap the <AppContainer /> like below with importing Header and Footer from nativebase
<MainStructure>
  <View style={{flex:1}}>
    .....
    <AppContainer />

  .....
 </View>
</MainStructure>;


Como carregar um array e dividir as posições do mesmo por caracter especial

Question: Tenho uma tabela onde existem filtros para a mesma:

Como podem ver na imagem, para cada coluna tenho um filtro onde utilizador pode digitar o que entender para fazer a pesquisa que entender. Agora estou a permitir que o utilizador faça download da listagem em formato PDF com os filtros aplicados. Então, estou a criar um array com os filtros onde depois envio o mesmo array para uma função num controller da aplicação. Até ai tudo bem!
Problema:
Caso o utilizador num filtro escreva por exemplo Belém, Lda, e como existe uma virgula neste filtro, vou criar mais uma posição no array e não criar uma string completa numa posição do array.
O que estou a pensar fazer é: dividir cada posição no array com um carácter que o utilizador não utilize, como por exemplo um ☺ (smile)
Dúvida:
Para ir buscar os dados dos filtros estou a usar (uso componente do DevExpress onde disponibilizam funções javascript para poder manipular dados, neste caso o filterEditorState para ir buscar os dados dos filtros):
var myArray = gvSortingListagemGARs.filterEditorState; //Devolve um array com todos os filtros
Eu sei que posso construir o array da seguinte forma:
var pos1 = gvSortingListagemGARs.filterEditorState[1];
var pos2 = gvSortingListagemGARs.filterEditorState[2];
var pos3 = gvSortingListagemGARs.filterEditorState[3];
...

E depois junto todos os dados num array, colocando sempre com um ☺ no inicio e no fim de cada string.
É possível construir logo um array e alterar o divisor de posição (virgula)? Assim evitava de fazer N linhas e simplificar o meu código.
Comment: Em relação ao "smile" acho melhor ter uma string tipo password. Ainda não compreendi bem o problema. Quer mudar a array que recebe em `var myArray = gvSortingListagemGARs.filterEditorState;` ou encontrar uma alternativa para gerar a array?
Comment: Queria encontrar uma alternativa ao gerar o array. Onde pudesse contornar a questão da virgula na string de um filtro. A solução que pensei foi ir buscar filtro a filtro a string respetiva, mas ai me questionei se existe outra solução para resolver isto
Comment: Mas mesmo com sub-arrays e caso use o split, uma string de pesquisa pode ficar comprometida (por exemplo `Belém, Lda`)
Answer: Uma possibilidade é ir ao DOM buscar esses valores e criar uma array com eles. Usando o JSON.stringify dá para passar para o lado do servidor em formato JSON e aí as virgulas dentro de cada string são mantidas.
var array = $('table tr:first td').map(function () {
    return $(this).text();
}).get();
var JSONarray = JSON.stringify(array);

Exemplo: http://jsfiddle.net/XT4N6/
Notas:

talvez queiras usar return $(this).find('input').val(); se esses campos forem inputs
uso o .get() para obter uma array nativa, e não um objeto "array-like" do jQuery


How to save many to many field?

Question: I want to count tags . I have Post model and tags model and post model has manytomany field to tags. When I want to add new post meanwhile I add tags for post , it has to increase tag count number.
My Post and Tags model:
class Post(models.Model):

    tags = models.ManyToManyField(Tag,blank=True,null=True,verbose_name=_('tags'))

    def save(self)
       super(Post, self).save()
       for i in self.tags.all():
       i.save()

class Tag(models.Model):

    name=models.CharField(max_length=30,verbose_name=_('name'))
    count = models.IntegerField(blank=True,null=True,default=0)
    slug = models.SlugField(blank=True,null=True)

    def save(self):
       self.slug = slugify(self.name.upper())
       self.count = Post.objects.filter(tags__name=self.name).count()
       super(Tag, self).save()

When I added new post , I look up the tag model and see count number does not change but when I press the save button in Tags Admin then I see the real count. But I want to see real count when I look up the tag admin without pressing the save button in tag.
Also I want that when I edit the post it should not increase the tags count again.
Comment: You seem to be dealing with [this](http://stackoverflow.com/questions/1925383/issue-with-manytomany-relationships-not-updating-inmediatly-after-save) issue.
Answer: I would use m2m_changed signal for this problem.
Answer: You could do the following:
class Post(models.Model):

    tags = models.ManyToManyField(Tag,blank=True,null=True,verbose_name=_('tags'))

    def save(self)
        super(Post, self).save()
        for tag in self.tags :
            tag.count = tag.post_set.count()
            tag.save()

OR, instead of saving the count value into a field, just do the lookup when needed:
tag.post_set.count()

you could add a function to Tag to get this on the easy:
def count(self) :
    return self.post_set.count()

Comment: post your admin forms and screencaps so i can see what you are talking about. Also, which solution did you go with?
Comment: actualy I dont do anything special in tag admin or post admin. What can i do ?

How to save many to many field?


Guitar book to complement my guitar lessons

Question: I have recently started guitar lessons. I really love them, but I feel there is something missing. My teacher's approach is "every class, let's learn a new song" but I feel I need some theory, like how to build chords, what note I make if I pulse this or that string, or playing techniques, etc.
That is why I thought I could complement my lessons with a "theory guitar book" where how to play the guitar is explained and with progression of exercises.
Is there such a thing? Or my teacher's approach is the way to learn to play an instrument (It is the first time I ever attempt to learn to play a musical instrument).
Any advice will be welcomed!!
Answer: The type of book you're talking about is called a method book and it contains exercises and home work for a student. Method books are meant to be used with an instructor. I personally favor Hal Leonard's method books but there are other good options, too.
However, before you pick one up: If you need more structure, you might start by asking your teacher. A good teacher will be flexible enough to give you what you need. Your teacher's approach isn't right or wrong, many students do better when they learn through songs, but it sounds like you're craving more of the fundamentals. While it is possible that your teacher isn't capable of doing this, it's also possible you simply need to ask.
There are books about theory that you could profit from, but music theory and guitar fundamentals (generally, chords and sight reading) aren't the same thing, quite. Theory is more about describing how music does what it does. You may have picked up some concepts without knowing it.
Working through a method book will give you discipline and a grasp of fundamentals. If you've already learned a lot, you can always skip through some exercises, but the guidance of a teacher will help you here.
Answer: Learning a little theory will definitely make you a better musician.  Learning to read is also a great skill to have under your belt.  Both of these take a little more commitment and take a little longer to bear fruit than simply working out the chords to a tune.  Especially learning to read.  I had been playing for years when I first started to try to read sheet music.  It was a huge step backwards and a humbling experience to say the least but it has been the best thing I have ever done with respect to being a musician.  The guitar teacher that pointed me down this road used the "Your in the Band" series to teach reading.  They were great!  They start simply and progress through a series of small incremental steps that get you reading very quickly.  They also have play along tracks that make it really fun and keep you honest.
https://www.halleonard.com/product/viewproduct.action?itemid=406393&subsiteid=7
Answer: Personally, I thought that piano-related books tend to present chord construction more clearly, since pianos don't have any ambiguity about where to find a particular note. Then the process of mapping those chord tones and extended voices to the guitar will strengthen your learning. The book that I borrowed decades ago from my local University library was Modern Jazz Piano (subtitled A Study in Harmony) by Brian Waite. It served me very well; your mileage may vary.
Guitarists certainly have it easier than pianists when transposing keys.