How do I create a Cognito Identity with Facebook token

Question: I have followed through all the steps in the documentation, user pool for registration through an email/pwd combo (working), configured FB identity provider in both the identity pool and user pool section for identity providers, and implemented the following code example found here http://docs.aws.amazon.com/cognito/latest/developerguide/facebook.html and modified below using my identity pool.
{code}
<code>function facebookLogin(){
    FB.login(function (response) {

        // Check if the user logged in successfully.
        if (response.authResponse) {

        console.log('You are now logged in.' + response.authResponse.accessToken);

        // Add the Facebook access token to the Cognito credentials login map.
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: 'us-east-1:eb997110-50b3-4e40-97ff-fbaf796da9ef',
            Logins: {
                'graph.facebook.com': response.authResponse.accessToken // cognitouser.idToken
            }
        });
        console.log('Added FB access token to Cognito.');

        // Obtain AWS credentials
        AWS.config.credentials.get(function(){
            //getCurrentUser();
            console.log('Got the aws creds.');
        });

        } else {
        console.log('There was a problem logging you in.');
        }
    });
}
</code>
{code}
I can step through and see the FB token being passed into CognitoIdentityCredentials and there are no errors but a user never gets registered in either my Identity Pool or User Pool.
Am I missing something?
Comment: I am having the same issue at the moment. Anyone has A solution? Thanks.
Comment: I never did get it and ended up doing a custom solution for FB and Google.
Answer: Here is a sample of the code I use for creating Federated Identities in AWS
<code>    function loadCredentials(identityPool, provider, accessToken) {

        var params = {
            /*AccountId: window.appInfo.accountId,*/
            //RoleArn: window.ap
            IdentityPoolId: identityPool,
            Logins: {}
        };
        params.Logins[provider] = accessToken;
        AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);
        AWS.config.credentials.get(function (err) {
            if (err) {
                console.log(err.message);
                console.log(err.stack);
            }
            else
            {
                console.log("Cognito Identity Id: " + AWS.config.credentials.identityId);
                console.log("Worked");
            }

        });
    }
</code>
Comment: This is the same code posted as example, how is this helping to get users registered in cognito using fb?


Remembering the last selected month in jQuery UI datepicker across multiple fields

Question: I have a page with multiple datepicker textfields using the standard jQuery UI.  I would like to set the default datepicker date to the last selected day or month for all blank fields, so the user doesn't have to manually change the month for each datepicker they select.
I have tried storing the date value in a variable via the onSelect function of the datepicker, but am unsure how to bind the defaultDate property so it updates all datepickers with whatever the last selected date was.
Below is the basic code. Again, if a user sets one of the date textfields to 10/20/2011, when he or she opens another datepicker through any of the blank textfields the datepicker should display the month of October by default (not today's current date).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/blitzer/jquery-ui.css" />

    <input type="text" class="datepicker" />

    <input type="text" class="datepicker" />

    <input type="text" class="datepicker" />

    <input type="text" class="datepicker" />

    <input type="text" class="datepicker" />

Answer: How about:
$(".datepicker").datepicker({
    changeMonth: true,
    changeYear: true,
    onSelect: function(dateText, inst) {
        $(".datepicker").datepicker("option", "defaultDate", dateText);
    }
});

Using the defaultDate option and the onSelect event.
Here's a working example: http://jsfiddle.net/MXHdj/


Returning data back to 1st Activity when setResult is called from 3rd Activity

Question: I have 3 Activities. When in the 1st Activity, the onClick method is called with startActivityForResult inside it that takes you to Activity 2. Then from Activity 2, you can click another button that takes you to Activity 3.
In Activity 3, I would like to call the setResult method, and after that, it will finish the Activity and take you back to Activity one with the data from Activity 3.
But, for some reason, the data is null and Activity.RESULT_OK is never called.
How can I handle this? thanks.
In Activity one:
<code>    @Override
public void onClick(View view) {

    IVID = view.getId();

    Intent i = new Intent(this, PhotoSelectActivityMultiple.class);
    startActivityForResult(i, 1);

}
</code>
In Activity 2:
<code>     Intent returnIntent = new Intent(getApplicationContext(), CollageGrid.class);
                returnIntent.putStringArrayListExtra("imageurls", mDownloadURL);
                startActivity(returnIntent);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
</code>
In Activity 3:
<code>            Intent intent=new Intent();
            intent.putExtra("part",byteArray);
            setResult(1, intent);
            finish();
</code>
In onActivity
<code>  @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK) {
            updateThis = (ImageView) findViewById(IVID);

            byte[] byteArray = data.getByteArrayExtra("part");
            Bitmap current_bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            updateThis.setImageBitmap(current_bmp);
        }
        if (resultCode == Activity.RESULT_CANCELED) {

        }
    }

}
</code>
Comment: So you call activities in this order `activity1->activity2->activity3` then you do `setResult()` in `activity3` and expect `activity1` to get the result in `onActivityResult` ? is that right?
Comment: @Bhargav Yes, that is what I would like to achieve.
Comment: Do you understand how `setResult` works? when you call activities in certain order, `setResult` travels back in the reverse order activites are launched, so what you need to do is make `onActivityResult()` in `activity2` and pass along the result your recieved (data) in the `setResult()`
Comment: I was just about to suggest that, but, I was thinking it would be a bad idea because I am passing down relatively big byte arrays and maybe that would slow down my application by a lot.
Comment: well I cant think of any other way, except you break the activity2 and 3 into fragments and attach it to activity1
Comment: hmm, yes. That could also be a viable solution.
Answer: Instead of starting Activity 3 by simply calling StartActivity we need to call activity 3 also by StartActivityForResult. So, Activity3 will return the value to Activity2 OnActivityResult, from where you can pass the value to Activity1.


Netbeans would not find compatible jdk while installation

Question: Netbeans would not find compatible jdk while installation while JDKs are located at C:Java and the files are:

jdk-8u73-windows-i586
jdk-8u73-windows-x64
jdk-8u141-windows-i586
Comment: Please, consider edit your question adding some details (what NetBeans version are you using, the exact error message you get, ...)

You probably won't receive any answer otherwise
Answer: From NetBeans Installation Instructions

The default location in Windows is C:\Program Files\Java\jdk1.7.0_10 or similar.

If your JDK is at C:\Java you just have to:

re-install the JDK under the default Netbeans location, or
specify your custom location during the installation wizard
Comment: thanks specified the location for sdks while installation also changed path to C:\Program Files\Java\ now the error is "An unknown error occured while validating the path" added sdks to C:\Program Files\Java\jdk1.8.0_73 still error
Comment: Please, just copy-paste your error message on a search engine before posting here. For instance, you could take a look here: https://forums.netbeans.org/post-162599.html#162599
Answer: Since I've run into this problem and this Q/A came up in my search, here is the solution that I found worked for me on the Windows platform.
I had to set up an system environmental variable named JAVA_HOME that pointed to the JDK directory.
JAVA_HOME=D:\Program Files\Java\jdk1.8.0_144

Even after this change, I still ran into the "An unknown error occured while validating path."
Right-click on the NetBeans install software and select "Run as Administrator...".  It looks like running the installer under your normal account, even though it may have admin rights, is not enough to scan the "\Program Files" folder and find the JDK.
Answer: *Delete your old java files.
*Download jdk file from.
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
*install new jdk version.
*Then install NetBeans //Now it will automatically identify your jdk and no need for manual selection...


Where do I include css file?

Question: As a total newbie in Drupal I asked myself where do I include a css file? (Using Drupal 6)
I wrote a web application with javascript, php and mysql and now I'm trying my first steps in migrating this application to Drupal. I already found out on Stackoverflow How to include css and javascript files.
Since i know now which function to use to include my css file, I don't know where.
Do I have to simply create a new module (named "mymodule" like in the example from stackoverflow)?
Or is the css file only applied to the module "mymodule"? If so, how can I apply it to a page filled with plain HTML?
Comment: Just as a matter of interest, if you're just starting out with Drupal - why Drupal 6?  IMHO Drupal 6 is on the verge of not being maintained by many module maintainers, since they've moved on to Drupal 7 themselves.
Comment: because my company uses drupal 6 with lots of modules that are not available for drupal 7. So first we will migrate the web application to drupal 6 and maybe later we will upgrade to drupal 7, but this will be lot of work, since we have to rewrite some modules by ourselves or search for alternatives.
Answer: To include your custom css say demo_global.css in your theme write following line in theme_name.info file of your theme folder-
      stylesheets[all][] = css/demo_global.css

Note: You must clear the cache to see the changes.
For more information please refer https://drupal.org/node/171209
Answer: As with anything, there's a few different ways to do it.
If you have a custom module (which IMO, you should, since you're porting a custom app), you can add any CSS required for your module in your module's page callback functions. CSS added this way only applies to that particular path. Just FYI if you want to have css apply to the entire site, you should put it in a theme.
So your module would look something like this:
function mymodule_menu() {
  $items['mymodule/blah'] = array(
    'page callback' => 'mymodule_page_blah',
  );
  return $items;
}

function mymodule_page_blah(){
  drupal_add_css(drupal_get_path('module', 'mymodule') . '/file.css', 'module', 'all', TRUE);
  ...
  return "<your blah page's html>";
}

Answer: This is for a custom module, you put this in your .module file
In Drupal 6:
/**
 * Implements of hook_preprocess_page()
 */
function <YOURMODULE>_preprocess_page(&$variables) {
  $module_path = drupal_get_path('module', '<YOURMODULE>');
  drupal_add_css($module_path . '/css/file.css');
  $variables['styles'] = drupal_get_css();
}

In Drupal 7:
/**
 * Implements hook_preprocess_page().
 */
function <YOURMODULE>_preprocess_page(&$variables) {
   $module_path = drupal_get_path('module', '<YOURMODULE>');
   drupal_add_css($module_path . '/css/file.css');
}

Comment: I searched far and wide for this. My stylesheet did not get added in D6 until I used the line: `$variables['styles'] = drupal_get_css();`
Answer: For creating a custom module please refer to following links:

Creating modules - a tutorial: Drupal 6.x
Writing .info files (Drupal 6.x)
Quick and Smart Drupal Module Configuration
Telling Drupal about your module

To include a CSS file for all the pages of site you can do either of the following:

Include it in the theme's info file as: stylesheets[all][] = FILENAME.css
Include it in the module's info file as: stylesheets[all][] = FILENAME.css

Don't forget to clear the cache after adding the CSS file in the .info file.
However if you are including it in the module file than remember than it will get loaded only if the module is enabled.
To load the CSS file for particular node you can do the following in the module file:
/**
 * Implements hook_preprocess_node().
 */
function MODULE_NAME_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Check if the node is the one on which you want to include the CSS file.
  if ((!empty($node)) && ($node->nid === $NODE_ID_ON_WHICH_YOU_WANT_TO_LOAD_CSS)) {
    drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . "/FILENAME.js", "module");
    drupal_add_css(drupal_get_path('module', 'MODULE_NAME') . "/FILENAME.css", "module");
  }
}

Also you may check this link:
Adding style sheets
drupal_add_css

Where do I include css file?


If $C$ is a $m \times n$ matrix such that $Cx=b$ is consistent for all $b \in \mathbb{R^m}$, which of the statements is/are definitely correct?

Question: (I) For each $b \in \mathbb{R^m}$, there is a unique solution $x$.
(II) The column space of $C$ has dimension $m$.
(III) It is possible that $Cx=0$ has non trivial solutions.
I have put (II) as my answer to be the only statement that is correct. However I'm unsure if (III) can also be correct or not, need some help here thanks.
Comment: The phrasing "it is possible that $Cx=0$ has nontrivial solutions" is strange. Either $Cx=0$ has nontrivial solutions or it does not.
Answer: Consider
\begin{align}
C =
\begin{pmatrix}
1 & 0 & 0\\
0 & 1 & 0
\end{pmatrix}
\end{align}
then clearly
\begin{align}
Cx = b
\end{align}
has solutions for any $b \in \mathbb{R}^2$. Moreover, $(0, 0, 1)^T$ belongs in the kernel of $C$.


Delete elements from iframe Jquery

Question: I have a built-in iframe from a pools app webservice.
To add the iframe of a pool I add this code:

The structure of the html when the iframe loaded is:

         (no id)
            <!DOCTYPE html>
                    ...

                         ...

                         ...

I want to hide or delete h1.
I have tried these with no success, even It doesn't allow me to add a id to iframe and of course I can't delete or hide h1:
a)

b)
$(document).ready(function(){
var f = $("iframe");
f.load(function(){
    f.find(' h1').css({'display' : 'none'});
    //f.find('h1').hide();
    //f.contents().find('h1').remove();
    });
});
</script>

Any help, would be great and appreciated
Best
Jose
Comment: You cannot access elements inside an iFrame which gets its content from a different URL/ domain
Comment: Thanks @empiric There is no exception, right?
Comment: [This](http://madskristensen.net/post/iframe-cross-domain-javascript-calls) ressource might help you. But in general, when you don't have full access the the iFrames source/domain this is restricted due to security reasons.
Answer: Due to security reasons you cannot access the content of an iFrame with its source coming form another domain, called the same-origin policy
There are some excpetions which are explained here.
The most reliable way to access html inside an iframe is, when you have access to the iframes source and/or domain.
A dirty way around that would be scraping the html from the other side and include it under your domain, but I definitely would not recommend doing this.
You lose a lot of functionality and maybe miss crucial updates.

Delete elements from iframe Jquery


Runing a program in gdb with an option

Question: There is a program I usually run with -t as in ./program -t but when I do gdb ./program -t, it says
gdb: option '-t' is ambiguous; possibilities: '-tui' '-tty'
Use `gdb --help' for a complete list of options.

I've tried gdb --args ./program -t as well but it doesn't work either (returns no such file or directory). Is there a way I could run this program in gdb with -t?
Answer:
I've tried gdb --args ./program -t as well

That is the correct way to invoke your program.
You could also do this:
gdb ./program
(gdb) run -t

but it doesn't work either (returns no such file or directory)

This likely means that either ./program doesn't exist, or is not runnable on your system. Or you could have something non-standard in your ~/.gdbinit or in ./.gdbinit.

Runing a program in gdb with an option


Como criar um gráfico em ASP.Net

Question: Eu estou tentando criar um gráfico com o histórico de uso da rede na minha empresa.
Eu nunca criei um gráfico antes em Asp.Net, então eu realmente não sei como começar, e os exemplos que eu encontrei na internet, usando o Microsoft Chart Control,não eram exatamente claros para um novato e eles estavam bem desatualizados, porque só funcionam com o VS2008 e eu estou usando VS2013.
Eu tenho os dados que quero exibir, o DBA já garantiu que os dados existem e vai criar uma consulta para obter os dados e, em seguida, eu posso manipular essa informação em minhas variáveis.
A questão é a seguinte:
Como posso criar um gráfico no ASP.Net? Existe algum substituto para esse Chart Control? Ou então, existe o AddOn dele para o VS2013?
Answer: Eu utilizo em alguns projetos o MS Chart para alguns gráficos simples. Caso você queira conhecer outras opções Google Chart e Chart.js também são bastante utilizados.
Para usar o MS Chart Control você vai precisar das classes:
using System.Web.UI.DataVisualization;
using System.Web.UI.DataVisualization.Charting;

Para usar o MS Chart adicione ao seu projeto a referencia:

System.Web.DataVisualization

Segue abaixo um exemplo completo:
Clique aqui para baixar o projeto no Git.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using System.Globalization;
using Exemplo_grafico.Models;

namespace Exemplo_grafico.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult MostrarGraficoPersonalizado()
        {

            List<LogsViewModels> MeusLogs = new List<LogsViewModels>();
            //Preenchendo qualquer dado para exibir no gráfico
            //Substitua por seu método para buscar as informações e preenchar a model
            Random rand = new Random();
            for(int i = 0; i < 20; i++)
            {
                LogsViewModels auxLog = new LogsViewModels();
                auxLog.CodigoLog = i;
                auxLog.Dia = DateTime.Now.AddMonths(rand.Next(5)).AddDays(i).AddSeconds(rand.Next(1000)).AddMinutes(rand.Next(60));
                auxLog.QtdeAcessos = i + rand.Next(200);
                MeusLogs.Add(auxLog);
            }

            Chart chart = MostrarGrafico(MeusLogs);

            MemoryStream ms = new MemoryStream();
            chart.SaveImage(ms);

            return File(ms.GetBuffer(), @"image/png");
        }

        private Chart MostrarGrafico(List<LogsViewModels> DadosLogsErros)
        {
            var chart = new Chart();
            chart.Width = 930;
            chart.Height = 600;
            chart.BackColor = Color.FromArgb(211, 223, 240);
            chart.BorderlineDashStyle = ChartDashStyle.Solid;
            chart.BackSecondaryColor = Color.White;
            chart.BackGradientStyle = GradientStyle.TopBottom;
            chart.BorderlineWidth = 1;
            chart.Palette = ChartColorPalette.BrightPastel;
            chart.BorderlineColor = Color.FromArgb(26, 59, 105);
            chart.RenderType = RenderType.BinaryStreaming;
            chart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
            chart.AntiAliasing = AntiAliasingStyles.All;
            chart.TextAntiAliasingQuality = TextAntiAliasingQuality.Normal;
            chart.Titles.Add(CreateTitle("Quantidade de acessos por dia"));
            chart.Series.Add(CreateSeries(SeriesChartType.Bar, DadosLogsErros));
            chart.ChartAreas.Add(CreateChartArea());

            return chart;
        }

        public Title CreateTitle(String titulo)
        {
            Title title = new Title
            {
                Text = titulo,
                ShadowColor = Color.FromArgb(32, 0, 0, 0),
                Font = new Font("Trebuchet MS", 14F, FontStyle.Bold),
                ShadowOffset = 3,
                ForeColor = Color.FromArgb(26, 59, 105)
            };

            return title;
        }

        public Series CreateSeries(SeriesChartType chartType, ICollection<LogsViewModels> list)
        {
            var series = new Series
            {
                Name = "Gráfico de histórico de acessos",
                IsValueShownAsLabel = true,
                Color = Color.FromArgb(198, 99, 99),
                ChartType = chartType,
                BorderWidth = 2
            };

            List<Color> Cores = ColorList();
            int i = 0;
            foreach (var item in list)
            {
                var point = new DataPoint
                {
                    AxisLabel = item.Dia.ToString(),
                    YValues = new double[] { Convert.ToDouble(item.QtdeAcessos) }
                };

                series.Points.Add(point);
            }

            foreach (var element in series.Points)
            {
                element.Color = Cores[i];
                i++;
            }

            return series;
        }

        public ChartArea CreateChartArea()
        {
            var chartArea = new ChartArea();
            chartArea.Name = "Gráfico de histórico de acessos";
            chartArea.BackColor = Color.Transparent;
            chartArea.AxisX.IsLabelAutoFit = false;
            chartArea.AxisY.IsLabelAutoFit = false;
            chartArea.AxisX.LabelStyle.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 8F, FontStyle.Regular);
            chartArea.AxisY.LabelStyle.Font = new Font("Verdana,Arial,Helvetica,sans-serif", 8F, FontStyle.Regular);
            chartArea.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisY.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.MajorGrid.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea.AxisX.Interval = 1;

            return chartArea;
        }

        public Legend CreateLegend()
        {
            var legend = new Legend
            {
                Name = "Gráfico de histórico de acessos",
                Docking = Docking.Bottom,
                Alignment = StringAlignment.Center,
                BackColor = Color.Transparent,
                Font = new Font(new FontFamily("Trebuchet MS"), 9),
                LegendStyle = LegendStyle.Row
            };

            return legend;
        }

        public List<Color> ColorList()
        {
            List<Color> listaCores = new List<Color>();
            listaCores.Add(Color.FromArgb(200, 0, 0, 205));
            listaCores.Add(Color.FromArgb(200, 139, 0, 0));
            listaCores.Add(Color.FromArgb(200, 0, 100, 0));
            listaCores.Add(Color.FromArgb(200, 148, 0, 211));
            listaCores.Add(Color.FromArgb(200, 105, 105, 105));
            listaCores.Add(Color.FromArgb(200, 255, 0, 0));
            listaCores.Add(Color.FromArgb(200, 210, 105, 30));
            listaCores.Add(Color.FromArgb(200, 178, 34, 34));
            listaCores.Add(Color.FromArgb(200, 70, 130, 180));
            listaCores.Add(Color.FromArgb(200, 240, 230, 140));
            listaCores.Add(Color.FromArgb(200, 65, 105, 225));
            listaCores.Add(Color.FromArgb(200, 154, 205, 50));
            listaCores.Add(Color.FromArgb(200, 184, 134, 11));
            listaCores.Add(Color.FromArgb(200, 255, 105, 180));
            listaCores.Add(Color.FromArgb(200, 255, 140, 0));
            listaCores.Add(Color.FromArgb(200, 47, 79, 79));
            listaCores.Add(Color.FromArgb(200, 128, 128, 0));
            listaCores.Add(Color.FromArgb(200, 139, 69, 19));
            listaCores.Add(Color.FromArgb(200, 147, 112, 219));
            listaCores.Add(Color.FromArgb(200, 0, 191, 255));
            listaCores.Add(Color.FromArgb(200, 198, 99, 99));
            //repetir cores (crie outra lógica se seu gráfico pode possuir muitas colunas)
            listaCores.Add(Color.FromArgb(200, 0, 0, 205));
            listaCores.Add(Color.FromArgb(200, 139, 0, 0));
            listaCores.Add(Color.FromArgb(200, 0, 100, 0));
            listaCores.Add(Color.FromArgb(200, 148, 0, 211));
            listaCores.Add(Color.FromArgb(200, 105, 105, 105));
            listaCores.Add(Color.FromArgb(200, 255, 0, 0));
            listaCores.Add(Color.FromArgb(200, 210, 105, 30));
            listaCores.Add(Color.FromArgb(200, 178, 34, 34));
            listaCores.Add(Color.FromArgb(200, 70, 130, 180));
            listaCores.Add(Color.FromArgb(200, 240, 230, 140));
            listaCores.Add(Color.FromArgb(200, 65, 105, 225));
            listaCores.Add(Color.FromArgb(200, 154, 205, 50));
            listaCores.Add(Color.FromArgb(200, 184, 134, 11));
            listaCores.Add(Color.FromArgb(200, 255, 105, 180));
            listaCores.Add(Color.FromArgb(200, 255, 140, 0));
            listaCores.Add(Color.FromArgb(200, 47, 79, 79));
            listaCores.Add(Color.FromArgb(200, 128, 128, 0));
            listaCores.Add(Color.FromArgb(200, 139, 69, 19));
            listaCores.Add(Color.FromArgb(200, 147, 112, 219));
            listaCores.Add(Color.FromArgb(200, 0, 191, 255));
            listaCores.Add(Color.FromArgb(200, 198, 99, 99));
            return listaCores;
        }
    }
}

Na model coloquei apenas isso:
namespace Exemplo_grafico.Models
{
    public class LogsViewModels
    {
        public long CodigoLog { get; set; }
        public int? QtdeAcessos { get; set; }
        public DateTime Dia { get; set; }
    }
}

O ActionResult MostrarGraficoPersonalizado retorna uma imagem, então você pode chama-lo assim em seu cshtml:

Ou se quiser mostrar apenas a imagem, chame ele diretamente em um ActionLink:
@Html.ActionLink("Mostrar Grafico 2", "MostrarGraficoPersonalizado", "Home")

No exemplo que está no GitHub chamei das duas formas. Uma está no Mostrar Grafico 1 e a outra no Mostrar Grafico 2, respectivamente.

Como criar um gráfico em ASP.Net


Views global text area replacement patterns for multiple values

Question: I have a views block that is listing the similar nodes (based on taxonomy terms).
I want to show some custom text and the taxonomy term field's value(s) on the footer of the block.
I added Global: Text area to footer of the views and selected the Use replacement tokens from the first row option.
What I want to show is that My Term's other nodes and I'm using that for what I wanted:

[field_my_taxonomy_term]'s other nodes.

It works correctly if the field_my_taxonomy_term field has only one value but if it has multiple values (multiple terms) it only shows the first taxonomy term value.

How can I show multiple values on Global: Text area?

This is the replacement patterns part of the Global: Text area:

[title] == Content: Title
[field_my_taxonomy_term] == Content: My Term
%1 == Content: Nid title
!1 == Content: Nid input
%2 == Content: Has taxonomy term ID title
!2 == Content: Has taxonomy term ID input
Comment: Any solution or opinion about that? I've been searching to find any solution but couldn't find yet.
Comment: The problem is solved by that way: http://drupal.stackexchange.com/questions/138682/other-related-nodes-with-the-same-taxonomy-block-grouping-problem - It's not the method I asked here but a better usage. If you have the same problem you can use it.
Answer: You need to either display as a table, or change the settings to force fields to be included in the View.
When you add a field to Views, you can alter how it is represented, including Rewrite, Style and if it contains multiples, how to display those values.
Adjust the field settings for the field you want and then that should be represented in the replacement pattern further down the chain
Comment: the field should still be included in the fields section, and then 'filtered' by the contextual filter to only show specific values. Then you would use the field as the replacement token, not the contextual filter itself
Comment: The replacement tokens I used come from Contextual Filters, not from the fields area. So, there is no option as you said _(When you add a field to Views, you can alter how it is represented, including Rewrite, Style and if it contains multiples, how to display those values.)_


Terminate WebAssembly from JavaScript

Question: Is it possible to terminate running WebAssembly code and cleanup any remaining resources from JavaScript?
In general the scenario is this. JS initializes a WASM module and calls an exported function. At a later point in time WASM code calls an imported function f transferring control back to JS. f does some stuff and based on the result decides whether to keep WASM running or not.
Two cases:

WASM should be kept running. f simply returns.
f decides to terminate the WASM function and possibly cleanup any WASM related resources. Can it? How?

If it would make it easier to analyze a more concrete example think how execve works. If the call fails it simply returns indicating failure. However if it succeeds it does not return - a broad oversimplification would be to say it terminates the caller and starts a new one in it's place (keeping some of the environment unchanged).
Comment: Couldnt you simply use a kill flag? Afaik you can write to wasm memory, so the js program could set the flag which the wasm program checks regularily
Comment: @JonasW. Ideally I'd like to avoid that. I'd rather the WASM module not be required to know or have anything specially crafted for this to work.
Answer: The only way to possibly terminate a caller -- no matter whether the caller is Wasm or JavaScript -- is to throw an exception. That leaves it up to the caller to react adequately. In particular, if it needs to do cleanup then it should be written such that it catches possible exceptions, performs the cleanup, and rethrows (or, equivalently, use a try-finally construct when available).
Wasm does not currently support exception handling directly, but that can be emulated by thunking out to JavaScript. Future versions of Wasm will have proper exception handling support.
Comment: Oh, throwing will terminate wasm but not the js side. So simple. Thank you!

Terminate WebAssembly from JavaScript


Set a breakpoint in another package's R function

Question: When I'm working on code in my own package, it's easy to set a breakpoint just by clicking in the margin of the editor window.
But suppose I want to know what's going on in somebody else's code, say in stats::predict.lm(). I'm concerned with a particular place way down in the code, say at line 75 of that function. I can do debug(predict.lm), then the next time I run the predict function, it will bring up the browser at the very beginning of this function, and I have to step through one code line at a time until I finally get to the line in question. Is there a way (perhaps using the condition argument of debug() that will instead effectively set a breakpoint at line 75 of that function, and save me from having to step through?
Answer: Functions in the stats package are hard, because it's a base package, so you would have to rebuild R with debug information.  Otherwise, it's pretty easy.  Just reinstall the package with debug information (--with-keep.source is the option to use), then set the breakpoint using setBreakpoint().
For stats::predict.lm with a standard install of R, it's harder because "line 75" of that function is not known to R.  You can set a breakpoint at the 5th statement in the function using
trace(stats::predict.lm, at = 5, tracer=quote(browser()))

which will result in R breaking around the line
type <- match.arg(type)

in stats::predict.lm.  As @Roland pointed out in a comment, it may be easier to use
trace(stats::predict.lm, edit = TRUE)

which will let you edit the source of that function to insert a call to browser() or any other tracing action.
One oddity:  if you set the tracer using the line above, you will need to call predict.lm(fit) directly, rather than calling predict(fit) and relying on S3 dispatch to find it.  However, if you use
trace(stats:::predict.lm, edit = TRUE)

(notice the 3 colons), then you will edit the version in the methods table, and predict(fit) will see the tracing, but predict.lm(fit) will not.
Comment: `trace(stats::predict.lm, edit = TRUE)` and then add a `browser()` call at (before) the desired line. (Note that you have to call `predict.lm` directly and not via method dispatch.)
Comment: @Roland:  I hadn't noticed that limitation, but the same appears to be true for using `at = 5` or similar.  `trace()` appears to be doing some weird replacements:  if you trace a function, it becomes an S4 object.  Also, `debug()` no longer works on it unless you make the direct call.
Comment: @Roland:  I think the fact that you need the direct call is a bug in `trace()`.  It tries to update the S3 methods table, but it looks in the wrong place and doesn't find it.
Comment: Depending on your confidence in this finding and after ensuring the documentation doesn't say anything about this, you could bring this to the r-devel mailing list.
Comment: I'm not so sure it's a bug now, it might just be a weird design decision.  Using the `:::` version of retrieving the function does allow it to find the S3 table.
Comment: Thanks so much. It's a little disorienting because the line position shown in the window is off by 1 or two ahead of the next line actually run. But it definitely beats stepping through from the beginning.
Comment: @user2554330 Barging in on your exchange, the `:::` thing makes perfect sense to me because `trace(fcn, edit = TRUE)` creates a new copy of `fcn` that is run instead. With the three dots, that definitely refers to a function within the namespace of the package, and so the substitute version steps in whenever that function in that namespace is called. With just `::`, that's something in some export structure somewhere.
Answer: You can use vscode and create breakpoints. It has an advanced debugger.
Comment: This doesn't answer the question
Comment: I don't even know what vscode is.


How to get Block Plugin Id? when block created using block type entity?

Question: I have created the Block type entity using Drupal 8 UI. Now I have to Place that block entity programatically in theme region. The related question discussed.
Here
As solution given by @Shawn Conn is fine when we define our own block plugin class. As in my case I don't. I created Block type using UI
Answer: You use the custom block uuid:
<code>'plugin' => 'block_content:' . $custom_block->uuid(),
</code>
Comment: I'm not sure that's right. I have a block with a UUID of `667863b8-b052-4a3a-8a4e-02e1b0eedea3` and a Plugin ID of `block_content:d199e31a-ff75-4500-b8e0-3de1085a519e`.
Comment: @Beau, the UUID of a block and the plugin id are two different things.


Checkboxes Defaulting to Selected When Not Desired

Question: This is going to be sound like a real stupid question, but for the life of me I don't know how to fix it. I have inherited some code that I need to maintain, and the issue I am experiencing is that a form containing checkboxes is displayed, and they are always all selected. The code for the checkboxes is as follows:
<code>$license_result = db_select('licenses')
  ->fields('licenses', array('code', 'name'))
  ->execute();

foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $selected_licenses,
  ),
);
</code>
I though that by having an empty array for #default_value would deselect all checkboxes. Am I reading the form API wrong in this regard? Eventually I would like to set the default values but right now I want to make sure they start off as unselected.
Thanks.
Comment: You're not using the [Multistep module](http://drupal.org/project/multistep) by any chance, are you? There's a [known bug](http://drupal.org/node/1419120) in that which affects checkboxes specifically.
Answer: I think you have to set the value in each checkbox, so probably this would be it :
<code>foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
  $licensevalues[$license->code] = 0;
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $licensevalues,
  ),
);
</code>
Comment: That was a good idea and I tried it but they still come out selected. I suspect that somewhere else in the code is modifying the selection but I can't seem to find where.
Comment: try to create a form_alter hook in which you would just `dpm($form)` so you could see whether something else is set there


Views Filter Content Type Drop down option sorting

Question: I have a view to with the Filter of Content Type in drop down and based on selection it is displaying the nodes.
Now I need to alphabetically order the Content Type options into Filter Drop down.
Currently the content type listed into drop down as

Press Release
News
Event

and I need to display it as

Event
News
Press Release

There is no such way I found into views configuration. Do any one have idea how to do so ?
Answer: One solution here is to use the Grouped filters option the Filter type to expose setting. In each grouped filter you can use the Is one of... operator and select the type. Grouped filters have weights that you can drag around to any arbitrary ordering.
As an example, here's a reverse ordering of content types:


mousemove focus is lost when DOM modification is initiated on FF5

Question: Demo:
http://anuary.com/dev/hp/pad3/
Scenario:
On arrival to the page, you will notice finger following your cursor. Click on any of the videos, click on the video again. (don't click anything anymore; this should close the video) mousemove is no longer responding unless clicked anywhere on the document.
This is caused by the following lines (200):
$.hp.ul.find('img').show();
$.hp.ul.find('li object, li div').remove();

Commenting them out makes everything work again.
Bug found on OSX, FireFox 5. Please report if this bug does not appear on your OS/browser.
What's the problem? How to fix this?
An update:
This appears to be a much more serious thing and probably OS/Browser bug. The thing is that when the cursor disappears and you are trying to go outside of the browser window, the cursor is still invisible. (unless you click somewhere)
Any workaround solutions are appreciated.
Answer: You can try:
$(document).live('mousemove', function(e){
        cursor.css({
            left:  e.clientX-tab.offset().left-60,
            top:   e.clientY-tab.offset().top+15
        });
    });

Although I'm not able to reproduce this on FF5/Chrome (Win XP). Video doesn't stop (even though the image is shown, it plays in background).
Also, your implementation interferes with addons like Flashblock, something you might want to consider.
Comment: Yeah, your site works fine on Chrome/FF5 on my end (even with the old one). Maybe be bug on OSX/FF5...
Comment: Mrchief, there is no interference with Flash, because all user clicks on is HTML.
Comment: Yes, but flash cannot load if you have flashblock. It will show a placeholder icon which needs to be clicked for flashblock to allow that flash. Only workaround now is to go to `Addons | Flashblock | Options | Add to whitelist manually`
Comment: I am not sure what this has to do with the issue I am having.
Comment: Its a usability suggestion, sorry if it was not clear from my post.


Does online learning theory have any real world applications?

Question: This is a question regarding the specific application of online learning theory in the sense of http://www.mit.edu/~9.520/spring08/Classes/online_learning_2008.pdf
I went through ICML papers for 2017 on online learning, and I can say with confidence that 90% of these papers are theoretical papers and should have most appropriately belonged to a statistics or optimization journal (if weren't for the glorious title of being a Machine Learning researcher).
This field is a mathematician's heaven, but as an engineer, it is hard for me to see how I could use these algorithms in practice. The "applications" that people have came up in this field so far are purely academic and does not clearly show practical real world applications as compared to supervised learning/neural nets for things like optical character recognition, or reinforcement learning for robotics applications. I know the latter works, because there has been much written about them, but I am not convinced that the same is true for online learning algorithms.
For example, all from 2017:
http://proceedings.mlr.press/v70/shamir17a/shamir17a.pdf
http://proceedings.mlr.press/v70/vaswani17a/vaswani17a.pdf
http://proceedings.mlr.press/v70/barmann17a/barmann17a.pdf
http://proceedings.mlr.press/v70/mukkamala17a/mukkamala17a.pdf
All these papers deal with finding some theoretical bound on the "goodness" of their algorithms, but does not clearly show how it relates to practical real world applications.
I am self studying online learning at the moment, using: http://ocobook.cs.princeton.edu/OCObook.pdf
However, I am quickly becoming disillusioned at the lack of serious utility of this mathematical framework. The examples given in the online convex optimization book are very academic. It is difficult to relate them to real life. Even courses on online learning does not provide examples as to how it can be used. I also have tried to dig up some successful applications based on online algorithms, so far I have failed.
Can someone point to some successful real-life applications/implementations of online learning algorithms?
Comment: Maybe search for examples of "Bandit algorithms" and "Contextual bandits" and other algorithms that are listed as topics in the course you linked by name. Perhaps they are not categorised in use in industry as "online learning" as per the course, but they are used heavily in web site advertising and content placement for instance. The goals of the bandit algorithms are interesting in their own right - how to make exploratory actions when mistakes made *whilst learning* have a cost.
Comment: @DetectiveMooch please define exactly what do you consider as "online learning" so people do not have to go to external resources to understand your question. Otherwise you are likely to receive answers that are not relevant to what you wanted to ask.
Comment: @DetectiveMooch so please define what exactly your question is about. In many sources reinforced learning would be considered as a kind of online learning.
Comment: Google, Amazon, Netflix...
Comment: I can definitely agree that Contextual bandits are useful, but this is a typical topic in reinforcement learning, which is already useful by itself. I am more referring to things like FTRL, online gradient descent, online mirror descent, regret minimization. These topics constitute 99% of all online learning algorithms. For example, almost the entire OCO book devote itself to these topics.
Answer: The UWash page you list gives a few examples right at the top:

Weather forecasting, predicting stock market trends, and deciding which ads to present on a web page are examples of sequential prediction problems

Weather forecasting is, for example, a classic usage of online learning.  Any time you want to track a moving object whose location you measure with some error is another canonical example, eg. airplane traffic control.  Really any kind of forecasting where information arrives sequentially and your underlying state is changing or developing is a potential application: epidemiology, forest fire tracking, etc. are all areas where online learning is useful.
Comment: "Any time you want to track a moving object whose location you measure with some error is another canonical example" - that's way too broad of a definition. that way you'd say any missile targeting is online learning, that's not true. if your "coefficients" are not updated in real time it's not online. for instance, $y_t=c+\phi y_{t-1}+e_t$  would fall into your definition, and it's clearly not a learning at all, as well as a whole field of error correction models. they "correct" for errors online, aren't they? but they're not learning
Comment: @CliffAB, OP's asking a reasonable question. There's a lot of learning apps, and usually they're offline, in that they're estimated/tuned by developers, then when deployed they don't learn anything, they apply the knowledge that was learned during development. so it's not that often when online learning is used in practice
Comment: The OP's question is a bit odd, because it seems very difficult to doubt the *utility* of online learning. But I think they were very specifically asking for concrete examples of applications of the many new "online algorithms" being used in practice. This answer seems to be saying "they naturally apply to this problem"...but as far as I know those cases really solve the optimization problem offline!
Comment: @Aksakal: my point is that I don't think online learning is a topic that is purely an academic topic with no real applications. Rather, it seems quite the opposite: lots of people in applied situations really want this, but it's a valid question if in practice we can get something much better than, say, batch updates.


Inverse of partitioned matrices

Question: A matrix of the form
$$A=\begin{bmatrix} A_{11} & A_{12}\\ 0 & A_{22} \end{bmatrix}$$
is said to be block upper triangular. Assume that $A_{11}$ is $p \times p$, $A_{22}$ is $q \times q$ and $A$ is invertible. Find a formula for $A^{-1}$.
Could anyone help on this?
Comment: @S.Panja-1729 Apparently, $A_{12}$ is a $p \times q $ matrix.
Comment: What is $A_{12}$ ?
Comment: It's an interesting question even though it is asked poorly. This type of matrix inverse arises in all sorts of modern numerical methods.
Answer: An easy one to remember is the following surprising result:
$$\begin{bmatrix}I & X \\ & I\end{bmatrix}^{-1} = \begin{bmatrix}I & -X \\ & I\end{bmatrix}$$
which is straightforward to verify by multiplying it out, or understand by just thinking about it.
You can get your desired inverse by factoring out the diagonal blocks,
$$\begin{bmatrix}A_{11} & A_{12} \\ & A_{22}\end{bmatrix} = \begin{bmatrix}A_{11} \\ & I\end{bmatrix}\begin{bmatrix}I & A_{11}^{-1}A_{12}A_{22}^{-1} \\ & I\end{bmatrix}\begin{bmatrix}I \\ & A_{22}\end{bmatrix},$$
then applying the identity above. Doing so yields the following explicit formula for the inverse:
\begin{align}
\begin{bmatrix}A_{11} & A_{12} \\ & A_{22}\end{bmatrix}^{-1} &= \begin{bmatrix}I \\ & A_{22}^{-1}\end{bmatrix}\begin{bmatrix}I & -A_{11}^{-1}A_{12}A_{22}^{-1} \\ & I\end{bmatrix}\begin{bmatrix}A_{11}^{-1} \\ & I\end{bmatrix} \\
&= \begin{bmatrix}A_{11}^{-1} & -A_{11}^{-1}A_{12}A_{22}^{-1} \\ & A_{22}^{-1}\end{bmatrix}.
\end{align}
In some numerical methods, it is prefferable to keep it in the factored form rather than multiplying the matrices together at the end.
Comment: Could you show how could you find the inverse of A12?
Comment: If you look at the formula, $A_{12}$ does not need to be inverted. It can even be rectangular.
Answer: Since $A$ is nonsingular, $A_{11}$ and $A_{22}$ have to be nonsingular. (You can convince yourself of this fact by say, reducing $A_{11}$ and $A_{22}$ to RREF. If either is singular, then its RREF has to have zero rows and zero columns. This means, $A$ has to have zero rows or zero columns, contradicting nonsingularity of $A$. The easier argument is by determinants: $|A|=| A_{11}|\cdot| A_{22}|$. Left hand side is nonzero if and only if both factor on the right hand side are nonzero.)
Thus, consider the matrix $B=\begin{bmatrix}A_{11}^{-1}& -A_{11}^{-1}A_{12}A_{22}^{-1}\\0& A_{22}^{-1}\end{bmatrix}$.
Multiplying:
$AB=\begin{bmatrix}A_{11}& A_{12}\\0&A_{22}\end{bmatrix}\cdot\begin{bmatrix}A_{11}^{-1}& -A_{11}^{-1}A_{12}A_{22}^{-1}\\0& A_{22}^{-1}\end{bmatrix}\\
=\begin{bmatrix}I_{p}& -A_{11}\cdot A_{11}^{-1}A_{12}A_{22}^{-1}+A_{12}A_{22}^{-1}\\0&I_q\end{bmatrix}=I.$
Hence, $B$ is the inverse of $A$.
Answer: Hint:
You may consider the matrix $$B = \begin{bmatrix} B_{11} & B_{12} \\ B_{21} & B_{22} \end{bmatrix},$$
such that:
$$\begin{bmatrix} A_{11} & A_{12}\\ 0 & A_{22} \end{bmatrix} \cdot \begin{bmatrix} B_{11} & B_{12} \\ B_{21} & B_{22} \end{bmatrix} = \begin{bmatrix} I_{p\times p} & 0 \\ 0 & I_{q\times q} \end{bmatrix},$$
where $B_{11}$ is a $p\times p$ matrix, $B_{12}$ is a $p\times q$ matrix, $B_{21}$ is a $q \times p$ matrix and $B_{22}$ is a $q \times q$ matrix.

Inverse of partitioned matrices


Java iterate through 1D array and 2D array

Question: I have a 1d array of questions and a 2d array of answers. I'm trying to print off one question and the multiple choice answers for that question and get user input then go back and get the second question and print off the multiple choice answers from the 2d array. Sorry if confusing.
Code:
private String[] questions =
{"Favourite Sweet", "Favourite subject at Hogwarts", "Dream Vacation"};

private String [][] selection =

{{"1.Acid Pops","2.Sherbert Lemons","3.Bertie Bott's Every Flavour Beans",
"4.Cake","5.Hagrid's Rock Cakes","6.Chocolate Frogs","7.Ginger Newt",
"8.I hate sweets\n"},

{"1.Care of Magical Creatures","2.Charms","3.Defense Against the Dark Arts",
"4.Divination","5.Herbology","6.History of Magic","7.Muggle
Studies","8.Potions", "9.Study of Ancient Runes","10.Transfiguration\n"},

{"1.Anywhere with friends","2.Egypt","3.Hogwarts","4.Museum","5.India","6.Forest",
"7.Can't be bothered with a vacation\n"}

};

I want to print off "Favourite Sweet" and then 1-8 sweets then print "Favourite subject at Hogwarts" then 1-10 subjects then "Dream Vacation" and print 1-7 vacations.
Code I have is garbage but here it is:
public void printQuestion(){

    for (rowQ = 0; rowQ <= questions.length; rowQ++){
        System.out.println(questions[rowQ]);
        for(int rowS = rowQ; rowS <= rowS; rowS++){
            for(int colS = rowS; colS <= selection[rowS].length; colS++){
            System.out.println(selection[rowS][colS]);

        }
    }
}

This is what happening with my code now when I run it:
Favourite sweet
1.Acid Pops
2.Sherbert Lemons
3.Bertie Bott's Every Flavour Beans
4.Cake
5.Hagrid's Rock Cakes
6.Chocolate Frogs
7.Ginger Newt
8.I hate sweets
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
Comment: What's happening currently? What specific issue are you having? What steps have you taken to debug/reason about the problem? What *is* the problem?
Comment: Your iterations stop at `rowQ == question.length` and you are getting out-of-bounds exception. All your iterations. Change iteration check from `<=` to `<` at it should work. And of course fix that infinite loop at `rowS <= rowS`
Comment: you are confusing how rows and column indicies work on line 3 and 4.
Comment: Valid array indices are `0` to `array.length - 1` - lose the `=` in `rowQ <= questions.length` and `rowS <= rowS` is an infinite loop. And lose the `=` in all of those tests.
Answer: Since you said that your code is not good I took the privilege of rewriting it completely and it works for me:
for (int i = 0 ; i < questions.length ; i++){
    System.out.println(questions[i]);
    for(int j = 0 ; j  < selection[i].length ; j++){
        System.out.println(selection[i][j]);
    }
}

The Idea behind this is for every question print out all the answers in the selection array that has the same index as the question array up to the end of that array
Comment: Thanks so much that works perfect!!!!   So selection[i].length is how it prints to the end of that index corresponding to the question? if that makes sense.
Comment: Yep selection[I].length corresponse with the question and the length of all the answer/selections
Comment: By the way if the answer answers your question it will be good for the community to sign my answer as a solution. (Also it will be great for me :-) since it highers my rating)


How do I access the view block name?

Question: How do I access the view block name?
function <theme_name>_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {

 // print_r(array_keys($variables));
  if (isset($variables['view'])) {
    $view_id = $variables['view']->id();
    $view_block = 'testing';
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $view_block);
  }
}

Answer: I'm not really sure this is correct, but I guess you are looking for the id for the block:
function THEMENAME_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  if (isset($variables['view'])) {
    $view_id = $variables['view'];
    $id = $view->id();
    $block_id = $view->getDisplay()->display['id'];
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $block_id);
  }
}

You can also print out the contents of the $view->getDisplay()->display array to check for other values that you might use.
Comment: Thanks for the $view->getDisplay()->display tip that really helped

How do I access the view block name?


AdMobs/ AdView - Anuncio na parte inferior

Question: adicionei o anúncio conforme abaixo. Porém esta centralizado no meio da tela, gostaria de adicionar na parte de baixo. Já adicionei o         android:layout_alignParentBottom="true" mas nada:
<?xml version="1.0" encoding="utf-8"?>

<include
    layout="@layout/app_bar"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/header_main"
    app:menu="@menu/activity_main_drawer"
    android:background="@color/colorBlue"
    app:itemTextColor="@drawable/drawer_item"
    app:itemBackground="@drawable/selector_menu"
    app:itemTextAppearance="@style/MenuItem"
    app:paddingStart="@dimen/space8"/>
<com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="681dp"
    ads:adSize="BANNER"
    ads:adUnitId="xxxxxx"></com.google.android.gms.ads.AdView>

Comment: E está sua activity está em que? Relative Layout, Linear Layout...?
Comment: está somente deste jeito mesmo...coloquei aqui o xml todo
Comment: até tentei colcoar dentro de um  mas nem apareceu mais
Answer: Opção 1 - Linear Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <include
        layout="@layout/app_bar"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/header_main"
            app:menu="@menu/activity_main_drawer"
            android:background="@color/colorBlue"
            app:itemTextColor="@drawable/drawer_item"
            app:itemBackground="@drawable/selector_menu"
            app:itemTextAppearance="@style/MenuItem"
            app:paddingStart="@dimen/space8"/>
    </LinearLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="xxxxxx" />
</LinearLayout>

Opção 2 - ConstraintLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/app_bar" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/colorBlue"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/header_main"
        app:itemBackground="@drawable/selector_menu"
        app:itemTextAppearance="@style/MenuItem"
        app:itemTextColor="@drawable/drawer_item"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar"
        app:menu="@menu/activity_main_drawer"
        app:paddingStart="@dimen/space8" />

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="xxxxxx"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>


Why does the Hendrix E7#9 chord sound good?

Question: The Hendrix chord contains both a major third and a sharp 9th (or flat 10th if you prefer), which are a half step (plus an octave) apart.  From a classical harmony standpoint, those two notes in the same chord should clash, but the chord as a whole works somehow.
Why is that?  It feels like somehow the 7th is the the glue that holds it together, since the 7th and #9th are a perfect fourth apart, enharmonically speaking.
Comment: BTW, voicing is important for the Hendrix chord. If you actually play the flat 10 and the third right next to each other, they sound much more clearly in conflict, as opposed to an octave apart as in the Hendrix chord.
Comment: @Tim I only know enough about jazz to know I have very little interest in knowing more about jazz, so if it's a jazz thing to never talk about a flat 10, then that's why I don't know not to do that. There is such an interval as a 10th and just like any interval it could be flattened, although maybe I should have written "minor 10th" instead of "flat 10". Oh, now I see. I was **speaking the asker's language**. THEY used the phrase "flat 10th", so I used it also to make sure they understood what I was writing.
Comment: @ToddWilcox - so that's that then. It isn't jazz, it's tertiary chords. There's 1,3,5,7,9. I'm sure the OP appreciated you using his language, although a 'flat ten' or 'm10' chord isn't the usual moniker it gets, although among guitarists it could well be so. (I'm also a guitarist,,,) But on a serious note, OP says it contains *both* a #9 *and* a b10, which isn't true at all !
Comment: @ToddWilcox - which is why the two common voicings use #9 an octave away from the maj3.
Comment: @ToddWilcox - can't believe you referred to it as 'flat 10' ! What? See Elf Raad'sanswer.
Comment: @Tim, OP says flat10/#9! He surely means either and not both! and  each of them  would clash with the major 3rd.
Comment: It is common to play the major and minor third of the tonic chord together in blues. Sounds best if the minor third is played above the major. Try playing an E chord and add a G natural over it. Sounds great. We hear the G natural as an embellishment, decoration or passing note, a dissonance that creates a sense of yearning.  . .
Comment: @Tim Adam Neely had some interesting things to say about [♯9/♭10](https://youtu.be/2IEN65JQW1E?t=484). Check it out! Reminds me of how I used to get into arguments with Laurence Payne... Good times...
Answer: There are a lot of chords that have notes that clash that we use all the time. The 7th of a Major 7th chord is a half step away from the root of the chord.
Notes in chords clashing and dissonance in general doesn't mean a chord sounds bad or that it shouldn't be used and in fact the dissonance/clashing nature of the dominant  7th chord  with  the tritone which in classical music theory is a very dissonant interval and needed to be approached and resolved correctly  is very big driving force in a lot of today's  music.
Voicing also plays a very big role in general in how chords sound. There are always good voicings and bad voicings of chords. The typical voicing of a 7#9 chord on a guitar is very effective with two distinct groupings of notes being utilize in the voicing. The lower grouping  consists of the root and the 3rd and the upper grouping  consists of the 7th and the #9. These two distinct  groupings are separated by tritone both stand out individually meld and create interesting resulting sound. How good or bad it sounds is in the ears of the beholder.
Comment: @AlbrechtHügli the question as I interpret it is mostly about the clashing #9 and 3rd which I go over in an objective way which makes up almost all the body of the question.  As I say in the last sentence "How good or bad it sounds is in the ears of the beholder." which I still stand behind and is the real answer to what they want. It may sound good, it may not sound good it's up to the listener. Why it sounds good to the listener is impossible, but we can talk about the objective aspects of it and what got us here.
Comment: You are not answering OP question at all
Comment: I bet if I had asked this question you would have on hold it as opinion based ... my new question is quite different and has nothing to do with why does it sound good and is not discussing whether there's a clash or not.
Comment: @AlbrechtHügli which is why the more objective path was taken on this question. This question was also not a duplicate of yours. That was the questions that go over the #9/b10 which have been discussed in length on this site.
Answer: To add to Dom's great answer - there are other chords, the notes of which should clash. b9 is one, where the root and b9 are also a semitone apart. 11th is another, where 4th and maj3rd are a semitone apart. Playing them an octave apart blends their sound. Yes, I also think the 7th acts as a sort of catalyst. There's also the blues conundrum to consider - often a m3 is played over a major/dom7 chord. This gives exactly the same effect as the Hendrix/7#9 sound. Something Classical and Baroque music frowned upon. Centuries later, having heard the effect many, many times, it's become acceptable to modern ears - in the Western world at least.
Answer: I can't add anything to the basic question of why the chord sounds "good" as that is above my paygrade! (LOL) In other words, why does any chord sound "good" or "bad"? This is a question of tradition, context, and personal aesthetics, so I try not to use these two words to describe any chord or tone cluster.
The part where I do want to add my two cents actually has to do with a couple of other things:

I know that ever since Jimi Hendrix wrote and performed "Purple Haze" and "Foxy Lady," people have called the 7th/#9th chord the "Hendrix chord." It's a nice tribute, but in truth, the chord has a long history in jazz and blues before Hendrix. Eric Clapton used it when he played with John Mayall's Bluesbreakers, and I can pretty much guarantee he didn't hear it from Jimi! :-)
It may be a lost point on some heads, but we need to be careful about treating the #9th (augmented ninth) in this chord as if it were a b3 (flat third or minor third). Here's why: When you first learn how to build chords on a chordal instrument, you usually learn first where to put your fingers, then either the names of the notes or their intervals. If we look at the 7th/#9 chord (in music theory context, I prefer the term Dominant Augmented 9th) in "Purple Haze," the song is mostly in a blues E tonality, and the famous chord has an E root. So, the intervals in the chord (ignoring voicing) are: Root, Major Third, Perfect Fifth, Minor Seventh, and Augmented Ninth. This resolves to the note names: E, G#, B, D, and Fx (F double sharp).

"F DOUBLE SHARP? Are you sh**ting me?" Wouldn't it be simpler to just call that last note a G natural, since that's what you see when you play it on a guitar or keyboard? Nope. Here's why: Any ninth above a root is going to have the same generic note name as a second. If Jimi had played a "regular" 9th chord instead of this more interesting version, we wouldn't have an issue, right? Root (E), Major Third (G#), Perfect Fifth (B), Minor Seventh (D), and Major Ninth (F#). Guitar players can play that one all day, barred at the fifth fret, yes? But what if you want to play an E7/b9 (Dominant Diminished 9th), as in John Lennon's song on the Beatles' Abbey Road album, "She's So Heavy"? That would be E, G#, B, D, F. Again, no problem, and this is another chord even more familiar in the jazz harmonic lexicon, but it sure sounded weird to our rock ears when that album came out, especially with those percussive rhythms!
The point is, all of these versions of a 9th stacked up on an E Dominant 7th chord have some flavor of F, because any 9th interval above a root of E has to be some form of F: NEVER a G! Please let me know if this doesn't make sense.
Elf Raad
P.S. I recognize that, especially for more modern composers from the Impressionists onward, who often write linearly, and don't care so much about the names of whatever chord temporarily falls out of the woodwork, there might not be a problem with having a G# and a G natural occurring at the same time over an E root! That's a totally different topic for another day, but think of it this way: In a piece with an A minor tonality, adhering to the rules for the A minor melodic scale in a contrapuntal piece might find you using G# in one instrument playing the ascending version of A minor melodic (A, B, C, D, E, F#, G#, A) while another instrument simultaneously plays a passage using the descending version of A minor melodic (A, B, C, D, E, F, G, A, or more likely going down: A, G, F, E, D, C, B, A). The collision between G# on the way up and G on the way down will make some people cringe like it was a wrong note, and other people sigh, thinking: Ohh, sounds like Hendrix! Isn't music just the most wonderful, mind-blowing thing sometimes?
In the words of Joe Pike: Stay Groovy!


Problema ao ler palavras do banco de dados com acento ou cedilha

Question: Estou a ler a minha tabela categorias do banco de dados  e quando tenho palavras com cedilha ou acentos, aparecem no meu projecto com caracteres estranhos.
Por exemplo, nas categorias tenho um titulo Avaliações, no meu projecto este título aparece como: AVALIA��ES.
Estive a pesquisar acerca deste problema e percebi que tinha de ter no meu banco de dados o Agrupamento (Collation) como utf8_general_ci, e também que no topo da minha página deveria conter esta meta: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Contudo, mesmo com estes 2 métodos para solucionar o problema, continuo a ter o meu título como AVALIA��ES.
Alguem sabe o que pode estar a acontecer e como poderei resolver isto?
Answer: Eu proponho que você faça o seguinte:
1 - Insira estas linhas de código no seu arquivo de conexão ao banco:
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');

2 - Tenha certeza que o banco de dados esteja em formato UTF-8. Para isso acesse seu banco de dados e vá em Operações (phpmyadmin) e certifique-se de que seu banco está guardando as informações com a codificação certa.
Posta depois se resolver.
Comment: Obrigado marcosvinicius. A solução era mesmo essa, mas no meu caso que estou a utilizar pdo, tem de ser assim: array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
Comment: Ok fiz o procedimento acima e deu certo. parabéns!
Comment: Camarada, muitoobrigado. Estava com este problema aqui e você me ajudou muito.


How do I set up a Drupal view with two relationships?

Question: I have "Event," "Session," and "Download" content types. Events can have many sessions, and each session can have many downloads. I have used node references to link the downloads to the sessions, and sessions to the events. Can I create a view of the downloads which will show session information and also the event information? I know I can use a relationship to link two node types in a view, but can I do it for three node types?
I'm using Drupal 7, and Views 3.
Answer: I found my answer at Multiple Node Relationships?

The answer is to go to the Relationships section and add two relationships, each for your node references. You'll find them under the 'Content' group. When adding the second relationship, select it to use the first relationship so that they chain. That will get you "base" node being the lowest level child, the first relationship is that node's parent, and the second relationship is the grandparent.
Then, add the Node: title field 3 times. Set 1 to use no relationship, 1 to use the first relationship, and 1 to use the second. Preview your view. That should get you the basis for what you want. Add sorts, filters and other fields to taste.


Find three numbers that are divisors of given number and their sum is minimal.

Question: I'm trying to work this problem for over a day and i can't come with reasonable solution. We have one given number $N$ ($1< N<10^9$) and we have to find three numbers $M,P,Q$ so they satisfy $M \times P \times Q=N$ and their sum is minimal (the smallest possible). Thank you in advance! Have a great day!
Comment: It helps, thank you so much! Have a nice day!
Comment: If the question was posed for *two* numbers, the answer would be the two divisors approximating the square root as much as possible i.e. $M$ is the largest divisor smaller or equal than $\sqrt{N}$ and $P$ is the smallest divisor greater or equal than $\sqrt{N}$. This might help in solving your problem.
Comment: Take $M=P=Q=N^{1/3}$.
Comment: @GerryMyerson, I think OP is looking for integers.
Comment: Yes, only positive integers.
Comment: Then it should say so in the body of the question.
Answer: Let $N={p_1}^{e_1}{p_2}^{e_2}\cdots{p_r}^{e_r}$ be the prime factorization,
and let $\Omega(N) = e_1+e_2+\cdots +e_r$.
You can choose $X,Y,Z$ in two for loops as follows.
$X={p_1}^{x_1}{p_2}^{x_2}\cdots{p_r}^{x_r}$
$Y={p_1}^{y_1}{p_2}^{y_2}\cdots{p_r}^{y_r}$
$Z={p_1}^{z_1}{p_2}^{z_2}\cdots{p_r}^{z_r}$
where $x_i+y_i+z_i = e_i$.
This is  $\mathcal{O}(n^2)$ because the number of ways to write $N$ as product  $XYZ$ is:
$$\dbinom{\Omega(N)+2}{2}$$
Comment: It's sort of a bin-packing problem. You have $e_1$ objects of wieght $\log p_1$, $e_2$ objects of wieght $\log p_2$, and so on, and three bins to put them in, and you want to fill the three bins as equally as possible. Bin-packing problems are notoriously resistant to efficient strategies, it doesn't take much to make a bin-packing problem NP-complete.
Comment: And what if you don't know the factorization of $N$?
Comment: Hmm.. $10^9$ is a relatively small number for a computer to handle. He could write a small method like [this](https://jsfiddle.net/JamesOR/RC7SY/) to generate the prime factorization of all the numbers $\lt 10^9$ at the start of his program. I think the OP has it worked out already.. @GerryMyerson
Comment: @GerryMyerson but I'm not too happy with my method. It is really a bruteforce. Would love to see some other clever method that avoids checking every combination..
Comment: I received this problem for homework but I am not allowed to use arrays, so I can't store the factorization of N. Meanwhile, finding the closest divisor possible to the cubic root of N gives me a wrong result. For example, if I have the number 1400352, it gives me 116, 24 and 503, instead of 58, 48 and 503 as answers.


I need to find the name of this interpolation method.

Question: I have found a really interesting solution for interpolating cosh.
First, the solver chooses the number of nodes, then, calculates Chebyshev polynomial roots on the desired interval, then finds the approximation using Lagrange construction of the polynomial. And then follows this method.
Let $\phi_1$ be the Lagrange polynomial the solver found before.
The solver began to calculate other $\phi$'s according to this recursive formula:
$$\phi_{i+1}(t) = 2\cdot\phi_i\bigg(\frac{t}{2}\bigg)^2-1$$
After he reached $\phi_7$, he stopped, I think because he reached the desired precision. And then he wrote the resulting interpolation as follows:
$$
\phi(t) =
\begin{cases}
\phi_7(-t), \space t<0 \\
\phi_7(t), \space t ≥0
\end{cases}
$$
Of course this could be done because cosh is y-axis symmetrical and continuos in 0.
So my question is : what is the name of this method, and is it possible to apply it to other symmetrical functions except cosh.
Answer: I would not call it interpolation; it is a kind of range reduction. Essentially you are using the half-angle formula (see e.g. http://dlmf.nist.gov/4.35.E21)
$$
\cosh \frac{t}{2} = \left(\frac{\cosh t + 1}{2}\right)^{\frac{1}{2}}
$$
to reduce the argument to a smaller range where you use an approximation for $\cosh$. You do not need interpolation, you can use e.g. the first terms of the Taylor expansion
$$
\cosh t \approx 1 + \frac{1}{2}t^2 + \frac{1}{24}t^4
$$
With this method and  7 reduction steps you get
$\cosh 1 = 1.543080634809$ with a relative error of about $-3.9\times 10^{-12}.\; $ With more steps or more Taylor terms it would be smaller ($1.4\times 10^{-16}$ with 4 terms), but the error increases for larger argument.
Comment: It's not about what I use. It's about what the solver did.


Using php(?) to increase number value every server day by random amount

Question: Looking for breadcrumbs/hints on a project I've found in my lap. I typically work in pure HTML/CSS with sprinkles of basic PHP/Javascript. Usually if someone sends me in the right direction I can piece things together.
My client wants a ticker that updates every SERVER DAY.
For Example:
1. Value X is set to 100
2. check if 24 hours (SERVER time, not client time) has passed
3. Run number generator between 5-10. Store in value Y
4. Update value X to X+Y. Re-store as value X
5. Return to step 2
I have searched this problem a couple different places but haven't quite found the direction I'm looking for. This question was close: javascript, increase number day by day
and led me to believe PHP might be my language of choice...but I'm finding more information geared towards this question written in javascript and stored client-side in cookies, which wasn't really what we were going for.
Does anyone have any ideas to get me started in the right direction? Doesn't seem to hard logically, just need to figure out the semantics. Any help is super appreciated....
UPDATE:
I've decided to use wordpress cron and found the handy wordpress crontrol plugin. This fixes the TIME issue, and thanks to 'Misunderstood's help I think I've got that file opening/random number thing down. Now what I am curious about is how to make a line of text on the site itself (could be div, h1, whatever) display the contents of the txt file 24/7. I used to know how to do this but it's escaping me. Do I need to use AJAX or javascript?
Comment: cron job, db, some math
Answer: Run a cron job that calls a php script every 24 hours at what ever time you want that to be.
<code>$fp = fopen('x.txt','r+');
$x = intval(fread($fp));
$y = mt_rand (1,5);
fwrite($fp,$y + $x);
fclose($fp);
</code>
Comment: Curious - just did some research into cron, which I admit I know nothing about. I'm not sure at this point if my client's server allows the use of cron but I did read that wordpress has a psuedo-cron system. The client's site is built with wordpress- does that add any options to my challenge?
Comment: If the server has cPanel, there is an icon in the "Advanced" group labeled "corn jobs".  The command would be something like: php /home/use/public_html/script.php, where script.php is the name of the script to run.
Comment: Thanks so much I really appreciate both your thoughtful responses. I did some research and found a plugin for wordpress that allows me to set up cron jobs easily. The only piece I'm missing is calling the contents of the .txt file into a section of the website....do I need AJAX or...?
Comment: If your page is generated by PHP, the easiest way to bring in a local txt via PHP is `readfile(filename);` where filename is something like /home/user/textfiles/file.txt.  From any web site `echo file_get_contents('http://www.exasmple.com/file.txt');` If it's an HTML page then AJAX if it is dynamic.
Answer: If you don't have access to do a cronjob, you can do the following:
When the script, that has to display this value is called, open a file (or read from a DB) the last time it was updated. For example, if the script was called today (2015.01.18), and the last call was on 2015.01.13 then you have to update X 5 times. So add 5 random values to X then store it with the new (today's) date.


Guitar chords high on the neck

Question: Apologies, this is an incredibly vague question, but any help would be appreciated.
When watching skilled acoustic guitar players, I regularly see them playing chords high on the guitar neck (ie around the 5-8th frets). I'm still pretty new, and looking at various chord charts I haven't found any fingerings in that range.
For clarity's sake, these aren't bar chords (at least not any that I recognize) and they're not using a capo. Does anyone have any ideas on where I can find out how to play chords like this?
Comment: Welcome to Musical Practice and Performance.
Comment: I often play chords up at the 18th fret on an electric, and even 15th fret on acoustic guitars. I think 5th fret is fairly low :-)
Comment: Welcome. I'm confused by your commenting that the fifth-to-eighth frets are pretty high on the neck. Traditionally, get counting starts at the nut (and some guitars have a zero feet next to the nut) so the eighth feet isn't that far up to me. Are you counting from the sound hole?
Comment: @VarLogRant For me, anything higher than 4 is pretty high. So, probably no confusion there.
Comment: ^ My reaction exactly. "High" starts past the 12th fret.
Comment: Sounds like he is a beginner.. "high" is probably anything above first position. Makes sense to me. To the OP: I might have an idea what you are talking about, I call them "jazz chords," though they work in many genres: http://guitarlessonsbybrian.com/jazz_chords_2/index.html
Comment: High is relative, and as one progresses as a guitarist, "high positions" get higher up on the fretboard, just like "hard songs" get harder and harder.
Answer: There are three kinds of chord you can play high on the neck.
Barre chords: You mention these in your question, but I mention it for completeness.
<code>  %5/1.5/1.7/3.7/4.6/2.5/1
</code>
In this example you barre across the 5th fret, and use fingers 2,3,4 to form the rest of the chord shape.
Chords containing both high fretted notes, and open strings
<code>  %0/1.7/2.7/3.6/1.0/2.0/1
</code>
In this example you play open E, B, E strings, while fretting notes on the others, on the 6th and 7th frets. It can result in some full, complex chords.
Chords in which some strings are not played
<code> %X/X.X/X.7/2.7/3.6/1.X/X
</code>
In this example, the E,A,E strings are not played, and a triad is played on the remaining three strings. Of course, if you finger a 6-note chord, you can strum wildly, but when you play a chord like this one, you need more precision. You can either suppress the unwanted strings with various muting techniques, or you can just make sure you don't pluck/pick those strings.
Most guitar parts more sophisticated than strum-the-chords, involve playing chords of fewer than 6 notes, most of the time.

There are lots of ways you can construct 2-3 note chords.
One way is to shift shapes you already know, up the neck. For example, a "D major shape"
<code>%X/X.0/0.0/0.2/1.3/3.2/2
</code>
Don't play the open strings, and move this up 2 frets, it's an E. 1 more fret, it's an F. 2 more frets, it's a G:
<code>%X/X.X/X.X/X.7/1.8/3.7/2
</code>
Try playing that shape, then the G chord you already know, to see how they sound harmonically alike.
This means that you could play chords for any song, using just the D major and D minor shapes, at various positions on the neck. Try it!
You can do this with all the shapes you know.
Another way is to imagine a barre shape for the chord you want to play, choose the strings you want to play, and make a simpler fingering that only frets those strings.
Yet another way is to get familiar with intervals. For any root note, you can work out (and, with experience, instinctively know) where the fifths and the thirds are, on the nearby strings. Then you can construct a chord out of any combination of those.
Or, you can simply learn the note name of every position on the fretboard, and the note names that make up every chord, and use that knowledge to construct chords. For example, C minor is made up of C, Eb, G. If you know where all of those are on a fretboard, you can make up the chord.
Different people prefer different ways of thinking. I prefer thinking in terms of intervals (F minor is "F, 3 semitones up from F, 7 semitones up from F"), whereas some people prefer thinking in terms of absolute notes ("F minor is F, Ab, C"). Find your own preference.
Finally, don't be afraid of just trying shapes to see how they sound. If it sounds good, it is good.
Comment: The second and third categories (or a combination of the two) are definitely what I'm looking for. Thanks for putting it so clearly. Any suggestions on where I should start for learning these kinds of chords?
Comment: Added something about "finding" these chords.
Comment: And a good understanding of music theory and chord construction will take this information and expand on it exponentially so you can "learn all the chords on the guitar".
Answer: They are chords like any others, but they aren't the two bar chords you have learned. Don't get intimidated though... There are not very many chords to learn at all.
I think this exercise will appropriately blow your mind given your level:
Take a C major chord (C, E, G) and draw every single C, E, and G on the fretboard. Now circle anything that is close together and can be played with your fretting hand at the same time. There's your chord.
See if you can find the two barre chords you have learned.
This picture should give you the right idea - http://vincelauriamusic.com/blog/assets_c/2012/12/C%20major%20Pentatonic%20Scale-thumb-500x224-113.png
Comment: +1 Welcome to the site. I think this is a very good approach, based on chord building. You might also note that open strings are still available when fretting *higher* chords.
Comment: That does sound like an interesting exercise. It looks like I will have to spend some quality time with my fret board. I can see there will be a ton of fingerings for each chord. Are there any "common" ones that you know of, just like there are common fingers for the standard chords near the top of the neck?
Answer: It would be helpful for you to start learning the names of the notes and their positions on the fingerboard, and think less about chord shapes from a chord chart. For instance, you know the F chord? It starts with the note F on the third fret of the fourth string, and then goes up a major third, then the fifth, then the octave. If you move the entire fingering two frets higher, the lowest note, on the fifth fret of the fourth string, is G, and then up a third, then the fifth, then the octave. That's not in your chord charts in your book, but it's another way to play a G chord. Now move the same fingering up two more frets, and that's an A chord. Are you getting the hang of it? Move the same fingering up two more frets, and that's a B chord.
In other words, don't concentrate on memorizing shapes from fingering diagrams. When you do that, you aren't really learning how the music works. Rather, learn how to spell the notes in the chords. Find the root note and figure out how to play the chord you want from spelling out the intervals between the pitches, and the fingering and the shape will come from that. Learn how to recognize and play intervals above your root note; major and minor third, fourth and fifth, seventh and octave. This way you'll learn how to make chords anywhere on the neck without having to resort to a book with chord fingering diagrams, which is a crutch. These guitar-chord-shape-diagram books are very popular, but I believe using that approach is counterproductive.
Answer: First thing to know is that a chord shape in one place is the same chord 12 frets up. Second thing is, you don't have to play all six strings when you play a chord. You just need three notes, and you can often get away with two. (Strictly speaking, that's an interval, not a chord, but if it sounds good, that's fine.)
There's more fun stuff, like inversions, but if you start playing around with those two points, you'll open up your playing.
Comment: Freddie Green chords are one note, two ghost notes and a bunch of thump, and it works well in context. "Power chords" are root-fifth or root-fifth-octave, to get rid of the third, so the soloist can decide whether it's major or minor, or just so the combination of distortion and the major third doesn't sound bad.

"A chord in music is any harmonic set of three or more notes that is heard as if sounding simultaneously." http://en.wikipedia.org/wiki/Chord_(music)

I've been playing for nearly 30 years. I have an idea how much is 2 notes, not 3.
Comment: No, in music theory a diatonic chord is at least **three** notes: a root, a third, and a fifth. That gives you the major, minor, diminished and augmented chords, by choosing a major or minor third, and a diminished, perfect, or augmented fifth. Beyond that you have the seventh chords and then the "jazz" chords. As for how many notes to use in a chord on a guitar, Joe Pass said, "Guitarists use too many notes in their chords. Never play a three-note chord when a two-note chord will do."
Comment: "Strictly speaking" a chord is two or more notes played together. So a two-note chord is definitely a chord. You'd be surprised how much of what great guitarists play is two or three notes.
Comment: The 1st reference in that Wikipedia article says "three or more notes". The 2nd references says "two or more". Chambers dictionary says "combination of notes of a different pitch". I'm going with two or more.
Comment: btw - the "you" in "you'd be surprised" isn't necessarily you, VarLogRant :)
Comment: So, we're in violent agreement. Cool.
Comment: Wheat, you are talking about TRIADS, o.k. they are still chords, but specific ones.Would you call a sus 4 or sus 2 a chord ? Of course, but where's the 3rd ? I love this site: it makes me 'do my homework'! In my big music book it states that ANY notes sounding together constitute a chord, so reluctantly I'll agree that 2 notes = chord. Having said that, in lots of situations I bet you'll find the "missing" notes to that chord being played simultaneously by another instrument.......
Comment: Added to above comment - If one played a C note and an octave C at the same time does this make a chord ? Why? Why not? Thought for the day !
Answer: One common thing I've seen (and do myself) is that if you play an A shape on the 7th fret, it's an E (frets = 07999x) . Leave the lowest open E string open, and play all 5 strings bar the highest one (normally it's too tricky to leave un-muted). You get a great, huge sound.
Because you're playing an A shape, a lot of familiar patterns emerge as well and there are a lot of nice licks etc to be played around that area while letting the E string ring.  Also, around the 7th/9th fret you have the advantage that there is a kind of "sweet spot" of resonance in the string while still easy to play (frets haven't got so small up the neck yet). Or at least there is on my guitars (electeic & acoustic), so I assume all/most others behave similarly.
Comment: Thanks, I'll try that. A friend of mine recently suggested I play around with an E shape around the 7th fret and that has been pretty interesting as well.
Comment: yep, I guess you're playing in that "sweet spot" still just on an E shape.
Comment: I'm guessing you mean playing 07999x, the way you described it could be ambiguous and read by a beginner as 00777x, which would be a muddy sounding D/E
Comment: @DaveHalsall  Yes that's right- it didn't seem ambiguous to me but i'll update the answer, thanks .  Might even fix the typos too ;-)
Answer: Try the book "Joe Pass Guitar Chords" by jazz guitarist Joe Pass.  A teacher recomended it to me and it has a wealth of chord shapes all over the neck - well worth exploring.  A quick search on google should find it and it's not expensive.  Good luck!
Answer: I'd definitely recommend MaxRunFast's suggestion:

I think this exercise will appropriately blow your mind given your level: Take a C major chord (C, E, G) and draw every single C, E, and G on the fretboard. Now circle anything that is close together and can be played with your fretting hand at the same time. There's your chord.

To specifically answer the part of your question:

Does anyone have any ideas on where I can find out how to play chords like this?

There are several chord dictionaries online where you can find out how to play any standard chord higher up on the fretboard.
For instance, if we wanted to find all the places to play a Gmaj chord between frets 5 and 8, we could do something like this:
http://songwritingtheory.com/bazzle/Gmaj/tab-using-frets-5-to-8/guitar
Then of course we could expand it to show us all the Gmaj tab from frets 3 to 14, for example:
http://songwritingtheory.com/bazzle/Gmaj/tab-using-frets-3-to-14/guitar
I hope that helps!
(Full disclosure: I created the linked tool).

Guitar chords high on the neck


How to perform Normalization on Call Details Record to perform k-Mean Clustering

Question: I'm new to data mining and currently doing mining project on telecom customer segmentation (based on profile and call details record). I have gender, age, call time and call duration and have to perform k-mean clustering. My question is:- How to normalize data to perform clustering. Any reference or suggestion are welcomed.
Answer: K-means is inherently distance based, so any normalization implicitly includes assumptions about the relationship between the different variables. Also I notice that your dataset only have 3 continuous variables (and one binary), so you can actually visualize the data relatively easily. Any clusters that are so robust to be meaningful to your client should be visible to your highly evolved pattern recognition system (your brain). I imagine that your dataset is large, so you might have to subsample or estimate a density function from the original data.
You also have the problem that one of your variables is circular (clock time), so you can't use that one directly in a k-mean algorithm because it's metric distance based, so you should convert it into a space in which the 'distance' between 11:59 pm and 12:01 am is the same as between 12:01 and 12;03. I think it might work to map into rectangular coordinates (but that adds a dimension to your data).
For more information visit this link http://www.youtube.com/watch?v=22bqfmiZAKU


How to linearize the following constraint? (a summation of a product of a integer with a bounded continuous variable)

Question: I need to linearize the following function. Variable $0\leq y_{b,n,j} \leq1$ and variable $z_{nj}$ is a non-negative integer that I can specify an upper-bound such as 20 if it is needed.
$$y_{b,n,j} =\frac{{a_{bnj}z_{nj}}}{\displaystyle\sum_{j \in J}\sum_{n \in N^{'}}{b_{bnj}}+{\sum_{n \in N}}{a_{bnj}z_{nj}}}. \quad \forall b \in B, n \in N^{'},j \in J$$
It is worth to mention that $\sum\limits_{n \in N}{z_{nj}}\leq k_{j} x_{j}$ $(\forall j \in J)$, which $ x_{j}$ is a binary variable. All the other notations are parametrs.
Would you please help me with that?
Answer: Recipe:

Multiply both sides by denominator
On the left you have now multiplication of a continuous variable $y$ times an integer variable $z$.
Expand $z$ to a sum of binary variables.
Now we have multiplications of a continuous variable times a binary variable.
This can be linearized easily.
Comment: Thank you very much, Erwin, but I don't want to introduce some binary variables, I think it is possible to define a continuous variable and linearize it.
Comment: Good luck with that.


No R, como calcular a média de uma coluna baseado em outra?

Question: Tenho a seguinte tabela XLSX:

Preciso calcular a média da coluna SP500 para cada ano. Fiz com 'mean(nomedatabela$SP500)' e encontrei a média total. Agora eu preciso da média por cada ano. Alguém sabe como posso fazer?
Obrigado!
Answer: Há várias maneiras de fazer o que quer.
Mas primeiro os dados.
set.seed(941)    # Torna os resultados reprodutíveis

Data <- c("3/1/2005", "4/1/2005", "5/1/2005", "6/1/2005",
          "14/2/2006", "15/2/2006", "16/2/2006", "17/2/2006",
          "6/3/2007", "7/3/2007", "8/3/2007", "9/3/2007",
          "13/2/2008", "14/2/2008", "15/2/2008", "16/2/2008")
SP500 <- round(runif(length(Data), 900, 1400), 2)

nomedatabela <- data.frame(Data, SP500)

Como vamos precisar do ano, transforma-se a coluna Data num vetor de class Date, com a função base as.Date. Depois, para obter o ano, vou usar o pacote lubridate.
nomedatabela$Data <- as.Date(nomedatabela$Data, "%d/%m/%Y")
ano <- lubridate::year(nomedatabela$Data)

Agora as médias.
A função tapply agrupa o primeiro argumento por um fator e calcula um valor da função FUN para cada grupo. O resultado é um vetor.
tapply(nomedatabela$SP500, ano, FUN = mean, na.rm = TRUE)
#    2005     2006     2007     2008
#1213.207 1092.210 1174.513 1124.352

A função aggregate também agrupa e calcula um valor da função FUN para cada grupo mas o resultado é um objeto de classe data.frame. Para definir os grupos, vou usar a interface de fórmulas de aggregate.
aggregate(SP500 ~ ano, nomedatabela, FUN = mean, na.rm = TRUE)
#   ano    SP500
#1 2005 1213.207
#2 2006 1092.210
#3 2007 1174.513
#4 2008 1124.352

Comment: Funcionou perfeitamente, muito obrigado! Apenas por curiosidade, supondo que minha tabela possua mais entradas que essas, exemplo: 800 linhas de data. Existe alguma forma mais rápida para definir 'Data' ou eu teria que entrar com as 800 linhas na mão, como no seu código?
Comment: @VictorOliveira Não percebo, entrar com as 800 linhas como? Isso não está nalgum ficheiro? Se não está, bom, entre com elas só uma vez e grave em disco! Se as datas são consecutivas, pode usar `seq.Date`.
Answer: Estou criando uma tabela para explicar oq estou fazendo
Data <- c("3/1/2005", "4/1/2005", "5/1/2005", "6/1/2005",
      "14/2/2006", "15/2/2006", "16/2/2006", "17/2/2006",
      "6/3/2007", "7/3/2007", "8/3/2007", "9/3/2007",
      "13/2/2008", "14/2/2008", "15/2/2008", "16/2/2008")
SP500 <- runif(length(Data), 900, 1400)

Ao inves de fazer t <- data.frame(Data, SP500) leia a base dada usando read.alguma(dependendo da extenso q vc esta usando).
Daqui para baixo estou usando pacote dplyr
library(dplyr)
 t <- tibble(Data, SP500)

Estou acresentando o ano
a<- as.Date(t$Data, "%d/%m/%Y")
ano <- tibble(ano=lubridate::year(a))

Achando a media pedida
base <- cbind(t,ano)
base2 <- base %>% group_by(ano) %>% summarise(media=mean(SP500))

A unica diferenca entra a minha solucao e a solucao de cima e que estou usando o pacote dplyr para calular a media e criar tibbles


Translate routing and menu titles

Question: I've made two yml files, for both routing and menu item:
Route:
tester_helper.products_controller_overview:
  path: '/assortment'
  defaults:
    _controller: '\Drupal\tester_helper\Controller\ProductsController::overview'
    _title: 'Assortment'
  requirements:
    _permission: 'access content'

Menu item:
tester_helper.products_controller_overview_link:
  title: Assortment
  parent: main
  route_name: tester_helper.products_controller_overview
  menu_name: main
  weight: 3

Is it possible to translate both the path and the menu item title?
For example:
EN (english):
"Assortment" => /assortment
DE (german):
"Sortiment" => /sortiment
Answer: _title in *.routing.yml and title in *.links.menu.yml are translatable by default. Go to user translation (/admin/config/regional/translate) and search there for 'Assortment' and translate it.
The path is not translatable. See this similar question:
Translating paths in routing.yml
In the answer you find some ideas.
Comment: Thanks for your answer! I'll try my luck translating the paths with aliases.

Translate routing and menu titles