Javascript - Exportar para csv

Question: Como faço uma exportação de uma tabela html para um arquivo CSV?
No meu código abaixo estou salvando o arquivo csv, porém ao abrir no excel não apresenta as divisões de colunas.
Gostaria de exportar diretamente para CSV. Mas não consigo achar nenhuma forma que faça isso para o chrome e o IE.
Segue meu código:
`<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Export table to Excel in 10 lines</title>`

`<script>`

`function Exportar(){
    var textRange; var j=0;
    var tab = document.getElementById("Tabela"); // id da tabela
    if(document.getElementById("Tabela").rows.length < 2){
        alert("Por favor, realizar uma pesquisa antes de exportar.");
    }
    else{
        var a=[], csv='', LF='\r\n', r, c, rs, cs, row, cell, i, j, v;
        for (r=0; r<tab.rows.length; r++){
            row = tab.rows[r];`

            for (c=0; c<row.cells.length; c++){
                cell = row.cells[c];
                rs = cell.rowSpan+r;
                cs = cell.colSpan+c;

                for (i=r; i<rs; i++){
                    if (!a[i]){
                        a[i]=[];
                    }

                    for (j=c; j<cs; j++){
                        a[i].push(i>r || j>c ? '' : cell.innerHTML);
                    }
                }
            }
        }

        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // Se for Internet Explorer
        {
            for (r=0; r<a.length; r++){
                v = '';
                for (c=0; c<a[r].length; c++){
                    csv += (v + a[r][c]);
                    v = ';';
                }
                csv += '\r\n';
            }

            txtArea1.document.open("txt/html","replace");
            txtArea1.document.write(csv);
            txtArea1.document.close();
            txtArea1.focus();
            sa = txtArea1.document.execCommand("SaveAs",true,"Socilitações.csv");

        }
        else
            for (r=0; r<a.length; r++){
                v = '';
                for (c=0; c<a[r].length; c++){
                    csv += (v + a[r][c]);
                    v = ';';
                }
                csv += "%0A";
            }

            var a         = document.createElement('a');
            a.href        = 'data:attachment/csv,' + csv;
            a.target      = '_blank';
            a.download    = 'Solicitações.csv';

            document.body.appendChild(a);
            a.click();
            //sa = window.open('data:attachment/csv,' + encodeURIComponent(csv));

        return (sa);
    }}

`</script>`
`</head>`

`
    <button onclick="Exportar()">Exportar</button>

            1
            2

            3
            4

            5
            6

`

Podem me ajudar?
Obrigado.
Comment: Excel abre sim corretamente as colunas de um CSV desde que você selecione as opções corretas de abertura e que o arquivo seja válido. Você já verificou estas duas situações?
Comment: você quer uma solução que utilize EXCLUSIVAMENTE javascript? uma solução em que o JavaScript faça uma requisição para um componente server side de modo que este gere seu arquivo CSV e o disponibilize para download resolveria o seu problema?
Comment: Marcelo, estou aberto para qualquer tipo de solução que faça a exportação da minha tabela html para um arquivo csv.
Anteriormente eu havia feito em java uma função que gera o arquivo csv, porém não consegui fazer o download.
Comment: Vinícius, quando salvo o arquivo o IE da apenas opções para salvar em HTML ou TXT. Eu estou salvando o arquivo com a extensão CSV do tipo TXT ou HTML. Na hora que vou abrir o arquivo o excel não separa as colunas nas células.
Comment: Estou postando novamente um código que funcionou para o Chrome. No Chrome quandoo faço o download do CVS abre corretamente no excel. Mas no IE quando faço o download ele não divide as colunas pelo ";". O arquivo no excel fica desconfigurado.
Answer: Salve o código abaixo com este nome jquery.battatech.excelexport.js
/*
 * jQuery Client Side Excel Export Plugin Library
 * http://www.battatech.com/
 *
 * Copyright (c) 2013 Batta Tech Private Limited
 * Licensed under https://github.com/battatech/battatech_excelexport/blob/master/LICENSE.txt
 */

(function ($) {
    var $defaults = {
        containerid: null
        , datatype: 'table'
        , dataset: null
        , columns: null
        , returnUri: false
        , worksheetName: "My Worksheet"
        , encoding: "utf-8"
    };

    var $settings = $defaults;

    $.fn.battatech_excelexport = function (options) {
        $settings = $.extend({}, $defaults, options);

        var gridData = [];
        var excelData;

        return Initialize();

        function Initialize() {
            var type = $settings.datatype.toLowerCase();

            BuildDataStructure(type);

            switch (type) {
                case 'table':
                    excelData = Export(ConvertFromTable());
                    break;
                case 'json':
                    excelData = Export(ConvertDataStructureToTable());
                    break;
                case 'xml':
                    excelData = Export(ConvertDataStructureToTable());
                    break;
                case 'jqgrid':
                    excelData = Export(ConvertDataStructureToTable());
                    break;
            }

            if ($settings.returnUri) {
                return excelData;
            }
            else {
                window.open(excelData);
            }
        }

        function BuildDataStructure(type) {
            switch (type) {
                case 'table':
                    break;
                case 'json':
                    gridData = $settings.dataset;
                    break;
                case 'xml':
                    $($settings.dataset).find("row").each(function (key, value) {
                        var item = {};

                        if (this.attributes != null && this.attributes.length > 0) {
                            $(this.attributes).each(function () {
                                item[this.name] = this.value;
                            });

                            gridData.push(item);
                        }
                    });
                    break;
                case 'jqgrid':
                    $($settings.dataset).find("rows > row").each(function (key, value) {
                        var item = {};

                        if (this.children != null && this.children.length > 0) {
                            $(this.children).each(function () {
                                item[this.tagName] = $(this).text();
                            });

                            gridData.push(item);
                        }
                    });
                    break;
            }
        }

        function ConvertFromTable() {
            var result = $('
').append($('#' + $settings.containerid).clone()).html();
            return result;
        }

        function ConvertDataStructureToTable() {
            var result = "
";

            result += "

";
            $($settings.columns).each(function (key, value) {
                if (this.ishidden != true) {
                    result += "";
                    result += this.headertext;
                    result += "	";
                }
            });
            result += "

";

            result += "
";
            $(gridData).each(function (key, value) {
                result += "
";
                $($settings.columns).each(function (k, v) {
                    if (value.hasOwnProperty(this.datafield)) {
                        if (this.ishidden != true) {
                            result += "";
                            result += value[this.datafield];
                            result += "	";
                        }
                    }
                });
                result += "
";
            });
            result += "
";

            result += "
";
            return result;
        }

        function Export(htmltable) {
            var excelFile = "";
            excelFile += "";
            excelFile += '<meta http-equiv="Content-type" content="text/html;charset=' + $defaults.encoding + '" />';
            excelFile += "";
            excelFile += "";
            excelFile += "";
            excelFile += htmltable.replace(/"/g, '\'');
            excelFile += "";
            excelFile += "";

            var uri = "data:application/vnd.ms-excel;base64,";
            var ctx = { worksheet: $settings.worksheetName, table: htmltable };

            return (uri + base64(format(excelFile, ctx)));
        }

        function base64(s) {
            return window.btoa(unescape(encodeURIComponent(s)));
        }

        function format(s, c) {
            return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; });
        }
    };
})(jQuery);

Exemplo completo e funcional:
<!DOCTYPE html>

    <title></title>

                    #
                    First Name
                    Last Name
                    Username

                    1
                    Mark
                    Otto
                    @mdo

                    2
                    Jacob
                    Thornton
                    @fat

                    3
                    Larry
                    the Bird
                    @twitter

        <button id="btnExport">Export</button>

Comment: Olha, funcionou quase que perfeitamente aqui, porém ele da uma piscada na tela, tem como corrigir isso? ou é do plugin mesmo?
Comment: Sem fala que no chrome baixa html da tabela e nao o csv

Javascript - Exportar para csv


Amazon S3 as measure of server's throughput?

Question: My server uses a 100Mbps shared port with 10Mbps nominal guaranteed BW. The highest speed of upload to Amazon S3 that I've seen from the server is 2.5MB/s. What does this indicate with respect to the server's actual bandwidth capacity?
Answer: It means absolutely nothing.  Your provider can only guarantee a certain bandwidth to the edge of their network -- it's entirely possible that network congestion is going to cause problems beyond their bounday.  Also, an upload to Amazon is likely to be using a single TCP connection, and the bandwidth-delay product could very well be biting you in the butt.


Laravel 5 - insert multiple users

Question: I have a simple User - Department relationship.  My User Model has the following
public function department() {
    return $this->belongsTo('App\Department', 'departmentId');
}

And my Department Model has
public function user() {
    return $this->hasMany('App\User');
}

At the moment I am working with the departments side of things.  My index function looks like the following
public function index() {
    $departments = Helper::returnDepartmentsFromLdap();

    return view('departments.index', compact('departments'));
}

What it basically does it gets all the departments from LDap (Active Directory) and displays them.  On the index page for departments, I have
{!! link_to_route('departments.updateDepartments', 'Update Database', null, array('class' => 'btn btn-info')) !!}

So the database can be updated if new departments are added to our server.  I do not have a create function as it is not needed.
Anyways, at the moment, my routes are like so
Route::model('departments', 'Department');
Route::bind('departments', function($value, $route) {
    return App\Department::whereId($value)->first();
});
Route::resource('departments', 'DepartmentsController', ['except' => ['show', 'edit', 'create', 'delete', 'update', 'destroy']]);
Route::post('departments/updateDepartments', array('as' => 'departments.updateDepartments', 'uses' => 'DepartmentsController@updateDepartments'));

And in my updateDepartments function I am simply doing the following for now
public function updateDepartments()
{
   dd("TEST");
}

If I click on the button on my index page to update the database, which should trigger the above, I am seeing a MethodNotAllowedHttpException.
Am I missing something obvious here?
Answer: Route::post('departments/updateDepartments', ...) means you only allow POST requests on that route. Make sure the form method is POST instead of GET (default) on your index page
Comment: The problem is that I am not using a form, because the departments are obtained from LDAP, therefore I never need to enter information about a department
Answer: try to use get:
because you can only pass data using get method with link link_to_route
Route::get('departments/updateDepartments', array('as' => 'departments.updateDepartments', 'uses' => 'DepartmentsController@updateDepartments'));

Comment: Will get allow me to still add data to the database?  I am not using a form because data is obtained from LDAP, so within the updateDepartments function, I will get all departments from LDAP, and then save/update them in database

Laravel 5 - insert multiple users


debugging high load average due to slow io on ec2

Question: I am on amazon ec2 ubuntu 11.04 large instance with a 150GB volume mounted for the database (ext4).
The cpu usage is VERY low but the load average has been consistently at 2.0 for about a day now. I used to have the database partition on a 40GB volume and did not have this problem.
iostat tells me we are spending a lot of time waiting for io:

:~$ iostat 1 2
Linux 2.6.38-11-virtual (flashgroup)    04/05/2012      _x86_64_        (2 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           7.16    0.09    2.62    1.11    2.09   86.92

Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
xvdap1            3.45         0.88        18.59    9137065  192742888
xvdb              4.47         2.84        24.17   29479675  250638760
xvdh             10.62        19.95        88.05  206811124  912892410
xvdf              0.18         0.00         1.93       1378   19971464
xvdg              0.00         0.00         0.00        656          0

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           5.22    0.00    1.92   42.58    3.02   47.25

Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
xvdap1            0.00         0.00         0.00          0          0
xvdb             43.00         0.00       172.00          0        172
xvdh              0.00         0.00         0.00          0          0
xvdf             49.00         0.00       288.00          0        288
xvdg              0.00         0.00         0.00          0          0

The product is performing just fine and the database is not logging any slow queries...
How should I go about debugging this?
EDIT:
It turns out that none of the volumes are exhibiting high latency and all other aspects of the system seem to be healthy. Wikipedia tells me that linux includes processes in the un-interruptable state in the load average. ps tells me that there are two hung mount commands are in such state:

ps auxww | grep " D"
root     21557  0.0  0.0   9904   760 ?        D    Apr03   0:00 umount db /dev/xvdh
root     26428  0.0  0.0  16456   912 ?        D    Apr03   0:00 mount /dev/xvdh /mnt/db

I am afraid to kill these (probably would not even work if I tried) so I think that this instance is sick and needs a restart. Thanks for your help!
Comment: In theory, any volume could result in the high iowait, however, from the second output - there is a good chance it is xvdb or xvdf. Following traditional naming - xvdb is likely ephemeral storage, while xvdf should be EBS. Run `iostat -x` to get more details about each volume - and look at the await column to narrow down the problem. EBS volumes do sometimes exhibit strange latencies, and, if that is the case, the best solution is often to simply create a new EBS volume. Another solution may be to look at setting up multiple EBS volume as a RAID.
Comment: If restarting the node fixed the issue, and you think it was related to those two processes, you should probably answer your own question so it gets closed.
Comment: Thanks for the advice. Followed your advice and updated post.
Answer: It turns out that none of the volumes are exhibiting high latency and all other aspects of the system seem to be healthy. Wikipedia tells me that linux includes processes in the un-interruptable state in the load average. ps tells me that there are two hung mount commands are in such state:

ps auxww | grep " D"
root     21557  0.0  0.0   9904   760 ?        D    Apr03   0:00 umount db /dev/xvdh
root     26428  0.0  0.0  16456   912 ?        D    Apr03   0:00 mount /dev/xvdh /mnt/db

Restarting the instance got rid of these hung processed and the load average is back to normal.


What does it mean when a low number of quadrature points gives a very different GLMM fit?

Question: I am interested in a logistic regression model with 10 fixed-effects parameters and random intercepts, which I can fit using the lme4::glmer function in R. The value of the nAGQ parameter determines the number of quadrature points used in approximating the likelihood, with 1 corresponding to a Laplace approximation and 0 using "a faster but less exact form of parameter estimation for GLMMs by optimizing the random effects and the fixed-effects coefficients in the penalized iteratively reweighted least squares step" (glmer documentation).
The fixed-effects parameter estimates appear to stabilise once nAGQ gets above 8-10:

(The coloured horizontal lines show the estimates from the same model fitted using mgcv::gam (red), gamm4::gamm4 (blue) and SPSS's GENLINMIXED (green) command)
I appreciate that as we increase the number of quadrature points, we get a closer approximation to the log-likelihood, but I came across this message posted by Jim Lindsey to the r-help list in 2001:

When discussing GLMMs using Gauss-Hermite integration, the question of
  approximations is essentially a red herring. No matter the number of
  quadrature points, the likelihood is always exact (as exact as any
  likelihood can be on a digital computer). It is a finite mixture. The
  approximation question arises in the sense that this finite mixture is
  more or less close to a Gaussian mixing distribution, which is a
  completely artificial choice in the first place. It is quite possible
  for the model with very few quadrature points to fit better than one
  with sufficient for a very close approximation to the normal mixing
  distribution, indicating that normal mixing is not a good choice.
It is false to say that the properties of this approximation, in the
  latter sense are unknown. GLMMs using Gauss-Hermite go back at least
  to an unpublished tech report by Don Pierce in the mid 70s and the
  published paper by John Hinde in 1982. Since then, there is a vast
  literature on the subject of the approximation in the second sense
  above, especially for the model in question, mixed logistic
  regression, including work by Alan Agresti, Murray Aitkin, David
  Brillinger, Bruce Lindsay, etc.  (There is also another literature on
  approximations replacing Gauss-Hermite, such as Breslow and Clayton.)
  The most recent published reference that I am aware of is earlier this
  year, but I have refereed others that are not yet in print. 15 to 20
  quadrature points gives an extremely close numerical approximation to
  the normal mixing distribution for most data sets, for what that is
  worth.

My question has a few parts:
(1) Does this mean that if the results from using a PIRLS fit or Laplace approximation are very different to using a higher number of quadrature points, it suggests that the Gaussian assumption for the random effects is not well-supported by the data?
(2) If so, would it ever make sense to take the PIRLS / Laplace results as the fitted model? Or is a higher number of quadrature points always 'better' (convergence & computational time issues not withstanding)?
(3) In my example, the log-likelihood of the fitted model takes its maximum at nAGQ = 4 (see below). Does this mean that this is the optimal fit (I appreciate that it is only a tiny difference), or are these fitted log-likelihoods not comparable because they are different approximations?

(Background information: I am trying to help someone who is only comfortable using SPSS. I haven't been able to find any documentation of the GENLINMIXED fitting algorithm, but the parameter estimates that it gives are very close to those of glmer with nAGQ = 0)
Answer: A few points:

according to this page, SPSS GENLINMIXED uses (one of) pseudo-likelihood, marginal quasi-likelihood, or penalized quasi-likelihood to estimate GLMMs. I'm not sure about MQL/PL, but PQL (at least standard PQL: there are some "improved"/second-order variants out there) is pretty well known to behave badly in many of the same cases where Laplace approximation fails and Gauss-Hermite quadrature is necessary (Breslow 2004). In particular, GH is necessary where the sampling distributions of the conditional modes are far from Gaussian, which happens when there is little information per cluster - e.g., binary responses with few observations per group (Biswas, 2015). These are the cases where we expect a large number of quadrature points to be necessary, e.g. the (in)famous "toenail" (oncholysis) data set (Lesaffre and Spiessens 2001).
the failure of PIRLS/Laplace doesn't invalidate the assumption that the random effects have a Gaussian distribution; rather, it suggests that the sampling distributions of the conditional modes are not Gaussian. In particular, adaptive GHQ with order $n$ works perfectly if the sampling distributions are proportional to a Gaussian times an $n-1$st order polynomial; $n=1$ (Laplace) works if the sampling distributions are exactly Gaussian, $n=2$ works if the sampling distributions are $\propto (a+bx) G(x)$, $n=3$ works if the sampling distribution is quadratic $\times$ Gaussian, etc.
Lindsey's comments (that GHQ with a small number of quadrature points can be considered an estimate of a particular finite mixture model), and your comment (that PIRLS/Laplace might actually give the best answer), is interesting - I hadn't thought of it that way. I'd be a little uncomfortable since I know so little about the model that we're implicitly fitting in that case, though ...
I tend to think of different nAGQ values as being different approximations to the same model, but, again, Lindsey's point is a good one. AFAICT the models should be of the same complexity (there are the same number of parameters), so we shouldn't have to worry about whether they're nested or not. In this case I don't think I'd take that bump at nAGQ=4 very seriously though ...

Biswas, Keya. "Performances of Different Estimation Methods for Generalized Linear Mixed Models.," 2015. https://macsphere.mcmaster.ca/handle/11375/17272.
Breslow, N. E. "Whither PQL?" In Proceedings of the Second Seattle Symposium in Biostatistics: Analysis of Correlated Data, edited by Danyu Y. Lin and P. J. Heagerty, 1–22. Springer, 2004. http://www.bepress.com/uwbiostat/paper192/.
Lesaffre, Emmanuel, and Bart Spiessens. 2001. "On the Effect of the Number of Quadrature Points in a Logistic Random Effects Model: An Example." Journal of the Royal Statistical Society: Series C (Applied Statistics) 50 (3): 325–35. doi:10.1111/1467-9876.00237.
Comment: Yes, the general advise is to start increasing the number of quadrature points until the results are stabilized. Currently, `glmer()` only allows you to fit the adaptive Gaussian quadrature when you only have a random intercept for a single grouping factor. If you want to include a random slope, you can give a try in the **GLMMadaptive** package: https://drizopoulos.github.io/GLMMadaptive/
Comment: Thanks for this great answer, it's really cleared a few things up. My outcome is binary and I only have 1 or 2 observations per cluster, so it fits under the "little information per cluster" scenario. So in your opinion, I should trust the GHQ results with nAGQ high enough so that estimates have stabilised?


In Rational (Eclipse), CVS version and CVS url after Project Name

Question: I am using Rational (Eclipse) with CVS, the CVS version and URL use to show after the project name. But somehow they are now showing anymore.
In Project -> Properties -> CVS, I still need the correct setting for the project. What's the problem? How can make the CVS version and URL to show again?
Answer: These are called "Label Decorations". Go to Preferences -> Team, expand CVS, then focus on "Label Decorations".
Comment: Hi Isaac, thanks for the info. I am using the default settings and everything looks good in the Preview window. But somehow the File Decoration, Folder Decoration and Project Decoration still don't show in the Navigation view. Any idea?
Comment: RAD used to have a bug... it wouldn't show the decorations unless you go to one project, right click -> properties, focus on the CVS info, then click OK (without changing anything). You can try that.
Comment: Tried that, still no luck. Thanks anyway.


InvalidDataAccessApiUsageException: first-result value cannot be negative

Question: I have got a problem with spring data. I have two repositories, with each method on one repository:
Repository1
Page<Model> findAllByIdAndLibraryTypeAndIsActive(Long Id, LibraryType libraryType,
      boolean isActive, Pageable pageable);

Repository2
Page<Model2> findAllByIdAndBookTypeAndIsActive(Long id, BookType bookType,
      boolean isActive, Pageable pageable);

Then I have a common method in my service to get out data from one of repository, it depends of parametres:
  private Page<?> findAll(Long id, String type, boolean isActive, Pageable pageable) {
   if (EnumUtils.isValidEnum(LibraryType.class, type)) {
      return repository1
          .findAllByIdAndLibraryTypeAndIsActive(id, LibraryType.valueOf(type), isActive, pageable);
    } else if (EnumUtils.isValidEnum(BookType.class, type)) {
      return repository2
          .findAllByIdAndBookTypeAndIsActive(id, BookType.valueOf(type), isActive, pageable);
    }
  }

The call seems so:
Pageable pageRequest = PageRequest.of(0, 10000);
Page<?> all = findAll(id, type, true, pageRequest);

So, when I try to test this in my test method, I'm getting the error:
org.springframework.dao.InvalidDataAccessApiUsageException: first-result value cannot be negative : -2147477296; nested exception is java.lang.IllegalArgumentException: first-result value cannot be negative : -2147477296
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:367)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy208.findAllByInsurerIdAndDocumentTypeAndIsActive(Unknown Source)
    ***at findAll(Service.java:93) - Page<?> all = findAll(id, type, true, pageRequest);
    at method(Service.java:69) - repository1
      .findAllByIdAndLibraryTypeAndIsActive(id, LibraryType.valueOf(type), isActive, pageable);***
    at $$FastClassBySpringCGLIB$$9205311a.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
    at org.springframework.cloud.sleuth.instrument.async.TraceAsyncAspect.traceBackgroundThread(TraceAsyncAspect.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at $$EnhancerBySpringCGLIB$$c6a8ab2f.extract(<generated>)
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
Caused by: java.lang.IllegalArgumentException: first-result value cannot be negative : -2147477296
    at org.hibernate.query.internal.AbstractProducedQuery.setFirstResult(AbstractProducedQuery.java:925)
    at org.hibernate.query.internal.AbstractProducedQuery.setFirstResult(AbstractProducedQuery.java:106)
    at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.setFirstResult(CriteriaQueryTypeQueryAdapter.java:136)
    at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.setFirstResult(CriteriaQueryTypeQueryAdapter.java:59)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:102)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.invokeBinding(PartTreeJpaQuery.java:244)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.createQuery(PartTreeJpaQuery.java:171)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.doCreateQuery(PartTreeJpaQuery.java:92)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:210)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:192)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    ... 69 more

I found one thing, the value "-2147477296" is setting on the method
public QueryImplementor setFirstResult(int startPosition) {
        getProducer().checkOpen();
        if ( startPosition < 0 ) {
            throw new IllegalArgumentException( "first-result value cannot be negative : " + startPosition );
        }
        queryOptions.setFirstRow( startPosition );
        return this;
    }

then I'm getting thrown exception.
However I cant understand how is coming this number. Maybe, someone can help me how I can fix this problem on my side. I was googling too much and even can't find any useful information.
Comment: Facing the same issue, did you get any resolution to this? In my case the exception coming when the offset is in millions.
Answer: I know this is not the right answer for you, but this can help others that have the same error message.
The jpa is getting the offset (which is a long type) from the pageable object and then it's trying to convert it to an integer. Therefore, if the offset is bigger than the max value of int type the conversation will overflow.
(page number × page size) <= Integer.MAX_VALUE
Comment: I think you are right. Both page number and size shouldn't exceed the max Integer value.


CSS Animation - hide the text until the page loads

Question: I have the css animation working but the problem is when the page loads the text is visible and then it animates. I want it so that the text isn't visible until it animates onto the screen. My example is here, any help would be appreciated.

.text-reveal {
  margin: 0;
  text-align: center;
  font-size: 200px;
  overflow: hidden;
  line-height: 1;
}
    .oneReveal {
      display: block;
      animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 0.5s;
       }
    .twoReveal {
      display: block;
      animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 1.2s;
        }
    .threeReveal {
      display: block;
      animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 1.5s;

      }

@keyframes "reveal" {
  0% {
    transform: translate(0,100%);
    visibility: hidden;
    opacity: 0;
  }
  100% {
    transform: translate(0,0);
    visibility: visible;
    opacity: 1;
  }
}

            reveal

            reveal

            reveal

Comment: Why you don't set the visibility hidden to the .text-reveal > span ?
Answer: You can keep the % and just add the "forwards" and the visibility hidden.

    .text-reveal {
    margin: 0;
    text-align: center;
    font-size: 200px;
    overflow: hidden;
    line-height: 1;
}

.oneReveal {
    display: block;
    visibility: hidden;
    animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 0.5s forwards;
}

.twoReveal {
    display: block;
    visibility: hidden;
    animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 1.2s forwards;
}

.threeReveal {
    display: block;
    visibility: hidden;
    animation: reveal 1.5s cubic-bezier(0.77, 0, 0.175, 1) 1.5s forwards;
}

@keyframes reveal {
    from {
    transform: translate(0,100%);
    opacity: 0;}

    to {
        transform: translate(0,0);
        visibility: visible;
        opacity: 1;
    }
}`enter code here`

            reveal

            reveal

            reveal

Comment: Perfect, thank you! I'm new to css animation so your help is much appreciated!


In a video challenge in volleyball, does the challenging team have to specify the challenged fault?

Question: Assume the following situation: In a high-class (high enough for a video challenge system being in place) volleyball game an attack hit goes out of bounds and the referee assigns the point to the defending team. However, the attacking team thinks they have seen the block touching the ball and call a video challenge. When reviewing the video replay, the referee does not find a ball touch by the block, but it shows a touch of the net by one of the blocking players, so it would indeed be a point for the attacking team.
My question is now, what are the rules of such a challenge? Must the challenging team specify which type of fault they want to have reviewed (such as "block touched the ball") or is it enough to just challenge based on "during this action, we think that the situation was different from what the referee decided" and then just the whole situation is reviewed in the video material? And if the former is the case, is the referee obliged to give the challenge to the challenging team if they cannot confirm the reason for the challenge but finds a different fault that would change the original decision – such as the net violation in my example situation above?
Additional clarification:
Since the video challenge is obviously not part of the official FIVB rules, let's restrict this question to international tournaments directly organized by the FIVB, i.e. World Cups and World League/World Grand Prix competitions.
Comment: You're going to need to specify which tournament you're interested in; the general [rules of the game](http://www.fivb.org/EN/Refereeing-Rules/RulesOfTheGame_VB.asp) don't contain anything about video challenges.
Comment: Don't know! I'd have to start digging - I'm not even sure if the tournament regulations are made public...
Comment: @PhilipKendall Is restricting it to international tournaments directly organized by the FIVB (World Cups, and World League/World Grand Prix) enough or do the rules differ even within those competitions?
Comment: Sorry for the incomplete answer; I didn't find **any** credible resource to quote.
Answer: For FIVB-conformant matches:
The team has to specify the error to verify. If the error has not occured the team loses the challenge. This is also the case if another arbitrary error occurs, i.e., only the error specified by the team is checked.
This has already lead to such funny situations as you described.
There is a list of verifiable errors here, along with a more detailed description of the video challenge rules.
Unfortunately, it lacks information answering your actual question.
I haven't found any resource backing up my statement. Sorry.
Anyway, I am sure because I've eye-witnessed that all (including the "funny" situation) while watching a FIVB match, that is, on international level.
Comment: The December 2017 version of the challenge system rules allows eight seconds for indicating a challenge, then a further eight seconds to indicate the claimed fault. Failure to indicate is an automatic lost challenge, as you state, but the same version of rules mentions "the same set of images" and that the first fault observed by R1 will be taken as the result. That should mean the challenge is successful in the "funny situation" you mention.


Tizen Native: How to change the progressbar color

Question: I'm developing a Tizen Native Wearable App.
I want to change the color of my progressbar so I'm following this links:

https://developer.tizen.org/zh-hans/forums/native-application-development/color-progressbar-processsmall-style?langswitch=zh-hans
https://developer.tizen.org/zh-hans/development/ui-practices/native-application/efl/ui-component-infrastructure-modules/customizing-components?langredirect=1

I know that in order to change the color of any widget in Tizen I need to use "Themes" but I can't get it to work.
This is what I did:
In my app_main.c I have:
static bool _on_create_cb(void *user_data)
{
    uib_app_manager_get_instance()->initialize();

    char resource_path[PATH_MAX];
    app_get_resource("edje/progressbar_custom.edj", resource_path, (int)PATH_MAX);
    elm_theme_extension_add(NULL, resource_path);

    return true;
}

In the folder res I created a folder edje and then in res/edje I created a file progressbar_custom.edc
The content of progressbar_custom.edc is the one given as answer in the first link.
Then in my progress bar object I set the style:
...
Evas_Object* pb;
pb = elm_progressbar_add(parent);
elm_object_style_set(pb, "custom_progress");
...

When I launch the app the progressbar does not show.
I guess that the problem is the content of the progressbar_custom.edc because I think it comes from mobile, not wearable. Every tutorial says to copy the content of the "default style" but I have no idea where this "default style" is!
Any help is apreciated, thanks!
Answer: I think EDJE syntax or part name in your edc file is not vailable in current wearable tizen.
data.item means some data is supplied from outside of edje.
and blar_vg_blar means efl vector graphic API draw something in there.
but vector graphic API is not in version of tizen wearable (2.3.1).
Basically, EDJE theme for Elementary is super entangled with elementary widget code. elementary widget code use hard coded signals and part name in EDC file.
so elementary's theme is not means another themes like css.
it has logic for viewing and events and some controller and data for view.
if you want make new theme you implement everything again that implemented in default theme.
best easy way is copy original one and edit it. so you must check version of your target for copying right theme.
currently, every wearable tizen OS in samsung device is under 2.3.1.
so you should make theme match with tizen 2.3.1 wearable profile.
this is basic theme for tizen 2.3.1 wearable profile.
it's not same in real device because real device can has different theme then original profile. it is same relationship like google's android theme and other vendors themes.
Anyway you can refer this that is default progressbar theme in tizen 2.3.1 wearable.
I make some simple example with modifed default style in EDC's first group.
progressbartest.cpp

#include <app.h>
#include <Elementary.h>
#include <efl_extension.h>
#include <dlog.h>

#define LOG_TAG "progressbartest"

#include <string>
#include <cstdlib>

static void layout_back_cb(void *data, Evas_Object *obj, void *event_info)
{
    Evas_Object* win = static_cast<Evas_Object*>(data);
    elm_win_lower(win);
}

static bool create_base_gui()
{
    char *res_path_ptr = app_get_resource_path();
    std::string res_path(res_path_ptr);
    std::free (res_path_ptr);

    std::string edje_path = res_path + "edje/progressbartest.edj";
    elm_theme_extension_add(nullptr, edje_path.c_str());

    Evas_Object* win = elm_win_util_standard_add("test", "test");
    elm_win_conformant_set(win, EINA_TRUE);
    elm_win_autodel_set(win, EINA_TRUE);

    evas_object_smart_callback_add(win, "delete,request", [](void*, Evas_Object*, void*){ui_app_exit();}, NULL);
    eext_object_event_callback_add(win, EEXT_CALLBACK_BACK, layout_back_cb, win);

    Evas_Object* pb = elm_progressbar_add(win);

    bool ret = elm_object_style_set(pb, "custom_progress");

    elm_progressbar_value_set(pb, 0.5);
    evas_object_move(pb, 10, 150);
    evas_object_resize(pb, 340, 20);
    evas_object_show(pb);

    evas_object_show(win);

    return true;
}

int main(int argc, char *argv[])
{
    ui_app_lifecycle_callback_s event_callback = {};
    event_callback.create = [](void *data)->bool { return create_base_gui(); };
    return ui_app_main(argc, argv, &event_callback, nullptr) != APP_ERROR_NONE;
}

progressbartest.edc (modified group from default one)
#define PROGRESSBAR_HEIGHT 30

collections {
   group { name: "elm/progressbar/horizontal/custom_progress";
      parts {
         part { name: "access";
            type: RECT;
            description { state: "default" 0.0;
               fixed: 1 1;
               color: 0 0 0 0;
            }
         }
         part { name: "background";
            type: RECT;
            mouse_events: 0;
            scale: 1;
            description { state: "default" 0.0;
               rel1.to: "elm.swallow.bar";
               rel2.to: "elm.swallow.bar";
               color: 71 200 71 255;
            }
         }
         part { name: "elm.swallow.bar";
            mouse_events: 0;
            scale: 1;
            type: SWALLOW;
            description { state: "default" 0.0;
               min: 1 PROGRESSBAR_HEIGHT;
               max: -1 PROGRESSBAR_HEIGHT;
            }
         }
         part { name: "drag.background";
            mouse_events: 0;
            type: RECT;
            scale: 1;
            description {
               state: "default" 0.0;
               visible: 0;
               rel1.to: "elm.swallow.bar";
               rel2.to: "elm.swallow.bar";
            }
         }
         part { name: "elm.progress.progressbar";
            type: RECT;
            mouse_events: 0;
            scale: 1;
            description {
               state: "default" 0.0;
               min: 0 0;
               fixed: 1 1;
               rel1.to: "elm.swallow.bar";
               rel2 {
                  to_x: "elm.cur.progressbar";
                  to_y: "elm.swallow.bar";
                  offset: -1 -1;
                  relative: 0.5 1.0;
               }
               color: 255 110 0 255;
            }
            description {
               state: "invert" 0.0;
               inherit: "default" 0.0;
               rel1 {
                  to_y: "elm.swallow.bar";
                  to_x: "elm.cur.progressbar";
                  relative: 0.0 0.0;
               }
               rel2.to: "elm.swallow.bar";
               rel2.relative: 1.0 1.0;
            }
            description {
               state: "state_begin" 0.0;
               inherit: "default" 0.0;
               rel1 {
                  to: "elm.swallow.bar";
                  relative: 0.0 0.0;
               }
               rel2 {
                  to: "elm.swallow.bar";
                  relative: 0.1 1.0;
               }
            }
            description {
               state: "state_end" 0.0;
               inherit: "default" 0.0;
               rel1 {
                  to: "elm.swallow.bar";
                  relative: 0.0 0.0;
               }
               rel2 {
                  to: "elm.swallow.bar";
                  relative: 1.0 1.0;
               }
            }
            description { state: "disabled" 0.0;
               inherit: "default" 0.0;
               color: 0 110 255 38;
            }
         }
         part { name: "elm.cur.progressbar";
            mouse_events: 0;
            scale: 1;
            dragable {
               confine: "drag.background";
               x: 1 1 1;
               y: 0 0 0;
            }
            description { state: "default" 0.0;
               min: 0 10;
               fixed: 1 1;
               visible: 0;
               rel1.to: "drag.background";
               rel2.to: "drag.background";
            }
         }
         part { name: "progress-rect";
            type: RECT;
            mouse_events: 0;
            scale: 1;
            description {
               state: "default" 0.0;
               rel1.to: "elm.progress.progressbar";
               rel2.to: "elm.progress.progressbar";
               color: 0 0 0 0;
            }
         }
      }
      programs {
         program { name: "slide_to_end";
            action:  STATE_SET "state_end" 0.0;
            transition: LINEAR 0.5;
            target: "elm.progress.progressbar";
            after: "slide_to_begin";
         }
         program { name: "slide_to_begin";
            signal: "elm,state,slide,begin";
            action: STATE_SET "state_begin" 0.0;
            target: "elm.progress.progressbar";
            transition: LINEAR 0.5;
            after: "slide_to_end";
         }
         program { name: "start_pulse";
            signal: "elm,state,pulse,start";
            source: "elm";
         }
         program { name: "stop_pulse";
            signal: "elm,state,pulse,stop";
            source: "elm";
            action: ACTION_STOP;
            target: "slide_to_begin";
            target: "slide_to_end";
            target: "start_pulse";
         }
         program { name: "state_pulse";
            signal: "elm,state,pulse";
            source: "elm";
            action: STATE_SET "state_begin" 0.0;
            target: "elm.progress.progressbar";
         }
         program { name: "state_fraction";
            signal: "elm,state,fraction";
            source: "elm";
            action: ACTION_STOP;
            target: "slide_to_begin";
            target: "slide_to_end";
            target: "start_pulse";
            action: STATE_SET "default" 0.0;
            target: "elm.progress.progressbar";
         }
         program { name: "set_invert_on";
            signal: "elm,state,inverted,on";
            source: "elm";
            action:  STATE_SET "invert" 0.0;
            target: "elm.progress.progressbar";
         }
         program { name: "set_invert_off";
            signal: "elm,state,inverted,off";
            source: "elm";
            action:  STATE_SET "default" 0.0;
            target: "elm.progress.progressbar";
         }
         program { name: "progressbar_disable";
            signal: "elm,state,disabled";
            source: "elm";
            action:  STATE_SET "disabled" 0.0;
            target: "elm.progress.progressbar";
            target: "background";
         }
         program { name: "progressbar_enable";
            signal: "elm,state,enabled";
            source: "elm";
            action:  STATE_SET "default" 0.0;
            target: "elm.progress.progressbar";
            target: "background";
         }
      }
   }
}


How to rewrite this code using lambdas and streams?

Question:  public class Java_03 {
 public static void main(String[] args) {
    List<Integer> listOfEven = Stream.iterate(1, i -> i+1)
                                    .filter(i -> i % 2 == 0)
                                    .limit(10)
                                    .collect(Collectors.toList());
    List<Integer> listOf3 = Stream.iterate(1, i -> i+1)
                                    .filter(i -> i % 3 == 0)
                                    .limit(10)
                                    .collect(Collectors.toList());

    // how to rewrite this code using lambdas and streams ?
    Map<Integer, Integer> map = new TreeMap<>();
    int i = 0;
    for (int a : listOf3) {
        map.put(listOfEven.get(i), a);
        i++;
    }
    System.out.println(map);
 }
}

I want to write this code using lambdas and stream I've tried alot but failed. please help.
map should contain: key - multiplication table of 2 and value - multiplication table of 3
for eg - {2=3, 4=6, 6=9, 8=12, 10=15, 12=18, 14=21, 16=24, 18=27, 20=30}
Comment: Your code above already uses lambdas and streams. Does it not work? What else are you trying to achieve?
Comment: @KushalMaharana just edit your question
Comment: what did you try so far?
Comment: cannot paste my code in comment!
Comment: the code which is in comment should be done using lambda and streams.
Comment: @KushalMaharana oh man... your question is badly formatted I think this is how people missed your point
Comment: zipping 2 collections together is ugly, you should rather build your results from a single collection like http://ideone.com/pUiNcd
Comment: @zapl: that's going into the right direction, but `Stream.iterate(1, i -> i + 1).limit(10)` should be replaced with `IntStream.rangeClosed(1, 10).boxed()`…
Comment: Of course, if all that matters is the output, you can simply use `System.out.println(IntStream.rangeClosed(1, 10).mapToObj(i -> i*2+"="+i*3) .collect(Collectors.joining(", ", "{", "}")));`
Answer: The method Collectors.toMap can be used to do the requested.
Sample (count holds the counter):-
int[] count = {0};

listOf3.stream().collect(Collectors.toMap(x->listOfEven.get(count[0]++), x->x))

Running Example :-
public static void main(String[] args) {
        List<Integer> listOfEven = Stream.iterate(1, i -> i+1)
                                        .filter(i -> i % 2 == 0)
                                        .limit(10)
                                        .collect(Collectors.toList());
        List<Integer> listOf3 = Stream.iterate(1, i -> i+1)
                                        .filter(i -> i % 3 == 0)
                                        .limit(10)
                                        .collect(Collectors.toList());

         int[] count = {0};
         System.out.println(listOf3.stream().collect(Collectors.toMap(x->listOfEven.get(count[0]++), x->x)));
         }

Comment: This abuse of an array is a discouraged code style. Besides that, this code produces an unspecified type of map, not a `TreeMap`.
Answer: IntStream.range(0, listOf3.size()).forEach(i -> map.put(listOfEven.get(i), listOf3.get(i)));

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.


Understand Unicode and code pages in SQL Server collations

Question: Why all SQL Server 2008 R2 collations are associated to a code page. Are all collations unicode ?
How to choose a collation when our database is used by several languages using differents code pages ?
Thank you.
Comment: @frikozoid: OK - all textual columns have a collation assigned. For **non-Unicode** columns (`char/varchar`) that defines both the encoding (the possible characters you can store and get back) as well as the character order for sorting. With non-Unicode, you have to pick **one collation** and you're stuck with it. For **Unicode** datatypes (`nchar/nvarchar`), the collation assigned **only** defines the sorting order - the encoding (the possible characters) are always the UCS-2/UTF-16 character set - the collation doesn't influence that in any way, shape or form.
Comment: @marc_s
Unicode (nchar/nvarchar) fields have collations defined, too..
Comment: @marc_s: Agreed, but you said "non-Unicode encoding - these have collations defined", which may imply that unicode fields don't have/need collations, while things like case sensitivity comparison/sorting method is always specified, no matter encoding.
Answer: CHAR vs. NCHAR (ie. Non-Unicode vs. Unicode) defines the character storage encoding. Collations define... collation (ie. sort order and comparison rules). They are different concepts, although often confused.
The confusion stems from the fact that the client tools use the collation of non-Unicode data as hint to choose the code page of the data. See Code Page Architecture. This means that a client like ADO.Net SqlClient can properly encode the single-byte CHAR data received from the server as a multi-byte string .Net object. The column metadata will contain the collation used and so the client will know how to interpret the single-byte data according to a specific code page.
For Unicode (NCHAR) columns the client does not need to interpret the data according to a code page, the data itself is already multi-byte and the client will interpret it according to the UCS-2 encoding (the actual flavor of Unicode used by SQL Server).
However do not confuse this with what collations actually are: rules for comparing characters. As described in Working with Collations:

an English speaker would expect the character string 'Chiapas' to come before 'Colima' in ascending order. However, a Spanish speaker in Mexico might expect words beginning with 'Ch' to appear at the end of a list of words starting with 'C'. Collations dictate these kinds of sorting and comparison rules. The Latin_1 General collation will sort 'Chiapas' before 'Colima' in an ORDER BY ASC clause, whereas the Traditional_Spanish collation will sort 'Chiapas' after 'Colima'.

This sorting rule applies to any data type (CHAR non-Unicode or NCHAR Unicode).
Comment: @marc_s: you know you worked too close with collations when you see 'Chiapas' and think ['Turkish I'](http://www.i18nguy.com/unicode/turkish-i18n.html)...


Android GCM error authentication sender account

Question: It's been a while since I created a Android app with GCM integrated. Previously in the API console you would specify the server IP as a white list. However on my latest project this option is not there. Instead it asks for the SHA1 from the signing key which I have configured.
However when I try to send a notification to a registered device ID I get
"There was an error authenticating the sender account"
I am using the correct API key so I can't see what is wrong.
Comment: Have you resolved this?
Answer: Previously in the API console you would specify the server IP as a white list. However on my latest project this option is not there
This section is found when you generate a SERVER API key in your GDC.
"There was an error authenticating the sender account"
Found this on GCM Authentication guide. Make sure these are implemented.

A message request is made of 2 parts:  HTTP header and HTTP body.
The HTTP header must contain the following headers:
Authorization: key=YOUR_API_KEY Content-Type: application/json for
  JSON; application/x-www-form-urlencoded;charset=UTF-8 for plain text.
  If Content-Type is omitted, the format is assumed to be plain text.

For example:
<code>Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}
</code>
Additional Note:
Authentication Error 401 - The sender account used to send a message couldn't be authenticated.

Possible causes are:
-Authorization header missing or with invalid syntax in HTTP request.
-Invalid project number sent as key.
-Key valid but with GCM service disabled.
-Request originated from a server not whitelisted in the Server Key IPs. Check that the token you're sending inside the Authentication
  header is the correct API key associated with your project. See
  Checking the validity of an API
  Key
  for details.
Answer: Google Cloud Messaging defaults to Firebase Cloud Messaging (FCM) now. Use the Server Key provided in the Firebase Console.
Before that, you may also need to Import your Google Cloud Project into Firebase if you have one.
Import instructions (only follow the "Migrate your console project" section)


File transfer speed in LAN network

Question: I transfer from 1 linux host to another linux host around 15TB data.
The sender host have those network cards:

[44.206701] igb: eth0 NIC Link is Up 1000 Mbps Full Duplex, Flow
  Control: RX/TX
[44.274112] bonding: bond0: link status definitely up for interface
  eth0, 1000 Mbps full duplex.
[44.278534] igb: eth1 NIC Link is Up 1000 Mbps Full Duplex, Flow
  Control: RX/TX
[44.573636] bonding: bond0: link status definitely up for interface
  eth1, 1000 Mbps full duplex.

The receiver host have this network card:

[16.964486] e1000e: eth0 NIC Link is Up 100 Mbps Full Duplex, Flow
  Control: None

My max transfer speed right now is 11 MB/s.
I'm wondering, what do I need to do to increase the transfer speed?
upgrade the receiver network card?
Thanks!
Comment: `e1000e: eth0 NIC Link is Up 100 Mbps Full Duplex` - That is a 1Gbps nic, but it is linking at 100Megabits per second.  Figure out why it isn't linking at 1Gbps.  Oh, and 100Megabits/8=~12MB/s.  So right now you are getting the maximum speed.
Comment: 99% of the time a 1000BASE-T (1 Gbps) NIC connects at 100BASE-TX (100 Mbps) is because the cable is bad. 1000BASE-T requires all four pairs of wires be correctly configured in the cable. If even one wire doesn't work, the auto-negotiation will step down the connection to 100BASE-TX.
Answer: The receiver side is linking at only 100 Mb/s:

e1000e: eth0 NIC Link is Up 100 Mbps Full Duplex, Flow Control: None

which translate to about 12.5 MB/s of maximum raw bandwidth. After taking into account the IP/TCP overhead, at 11 MB/s you are basically maxing your receiver bandwidth.
Answer: it would better to have a 1gig network card on the receiving machine yes, also, i can see in the tags that you are using scp.
scp is usually very bad for important data transfers, i always had horrible performance with it
try ftp (but it's unencrypted), you will clearly notice an important difference with the transfer speed.
ftp (or another protocol/program but not scp) + at least a 1000mb NIC on receiving machine will clearly help you
Comment: Hi, I'm actually using rsync, I dunno why I tagged 'scp' :P
Comment: thanks for your answer, rsync uses ssh (which is the same protocol as scp), try using ftp just to compare, change your NIC on the receiving box, and be careful with disk I/Os too, as billthor said !
Answer: As others have suggested, the reason why you are only getting 11Mb/sec is because the receiving network card has a link speed of 100MBit, despite the card theoretically being able to handle 1GBit.
The only possible reasons I can think of is that either the NIC is connected to a 100MBit switch, or the card is configured to auto-negotiate speed and has negotiated the wrong speed. In that case you should be able to force the NIC to run at 1GBit.
At the current transfer rate it will take you about 15 days to transfer 15Tb (http://www.thecloudcalculator.com/calculators/file-transfer.html).
With a 1GBit connection on the receiver side it will only take about 1.5 days.
Comment: I wrote if you decide to disable autonegotiations then you need to disable it on both ports. I didn't say that disabling autonegotiations is a good idea. But sometimes it helps when equipments aren't compatible.
Comment: If autonegotiations doesn't work it must be disabled on both physical interfaces: switch and server. Speed must be configured the same on both interfaces.
Comment: @MikhailKhirgiy *Never* disable autonegotiation on 1GBit or higher-speed links. Doing so places the link outside the IEEE specifications.  [The standards for 1000BASE-T, 1000BASE-TX and 10GBASE-T require autonegotiation to be always present and enabled. Other than speed and duplex mode, autonegotiation is used to communicate the port type (single port or multiport) and the master-slave parameters (whether it is manually configured or not, whether the device is master or slave if this is the case, and the master-slave seed bit otherwise).](https://en.wikipedia.org/wiki/Autonegotiation#Overview)
Comment: Disabling autonegotiation to force gigabit speed when it otherwise doesn't work is like getting a flat on your car, removing the wheel, tossing it in the ditch, and continuing to drive.  When your car gets a flat tire, *you fix the flat tire*.
Answer: both sides should be at 1000full if you have a bad cable , forced/*hardcoded the speed on the switch side it will sync at 100 Full on the receiving end.
look at how the switch is configured if its auto auto put your interface hardcoded at 1000full if it does not go up at that speed check cabling. up to switch.
at 12MB you are at 100Full speed .  e1000e is a gig interface should sync up to that speed . your transfer should go from 300 to 800 Mbps (30MB to 80MB) depending on the host capabilities.
Answer: You are transferring data close to the limit of the receiving interface, although it not running at its maximum speed.  Can your switches handle the speed?
Your bottleneck may be the speed at which you can read from or write to disk or it may be bottleneck in the network.  A few questions:

How are you transferring the data?  (Disk images might be faster than individual files.)
What kinds of disk do you have on the systems? (Flash drives are generally faster than hard disks.  Raid systems can add write time overhead.  Interface speeds are often higher than read/write speeds.)
What is their transfer rates?  (It doesn't matter how fast the network is if you can't read or write the data at near the network transfer rate.)
How large are the files you are transferring? (Small files have more file system overhead.)
Does the target file system use a journal?  (This adds additional write overhead unless you disable the journal.)
Are you buffering data being transferred over the network?  (Buffering allows data that can not yet be written to be transferred over the network.)
Can you run multiple transfers in parallel? (If the transfers run on different disks, you may gain on overall transfer rate.  Too many parallel transfers will add additional overhead that can slow down file movement.)
Is the transfer stream encrypted/compressed?  (Either can add overhead. Compression can compensate for a network bottleneck.)
Are there any errors on any of the interfaces? (Duplex mismatches can cause issues.)
Are the network cards/switch ports running at full capacity/speed? (If any device on the network is running at full capacity, it becomes a bottleneck.  If they are not running at full speed, it lowers the available throughput.)

As noted in my comment, the receiving system's Ethernet card appears to be running at 1/10th is maximum speed.  The transfer rate you are achieving is close to the maximum achievable without compression at the current network card speed.
Running rsync in daemon mode on one side may provide better performance than tunneling using SSH.  There are security implications to running rsync as a daemon.
Comment: 1. I'm using rsync. 2. The systems have WD Blue 2TB disks - The sender host is with 20 disks Raid 10. 3. they are SATA 6.0Gb/s. 4. some files are 500 GB+ some are 100GB, I have total of 15 TB. 5. The root system is currently in 'Read-Only' mode because the os hard disk failed and have corrupted files which fsck cannot fix.
Comment: The WD Blue disk should be able to keep up with the network for such large files.  Your transfer rate is about 2 times the sender disk speed.  Rsync overhead could account for the difference between network capacity and transfer throughput.  I would look at why you are getting 100Mbps rather than 1000Mbps on the network card.  This is likely either the router/switch or a bad cable.  It may be possible to switch either without restarting the network.
Comment: @Billthor at only 11 MB/s, nor the filesystem nor the disks can be the bottleneck.
Comment: @shodanshok Disk and filesystem should not be an issue on a modern system at that rate,  But Iv occasionally work on older but still active systems where these speeds can be bottlenecks.  As noted in my comment, the network card on the receiving system is not running at full speed and may be the bottleneck.

File transfer speed in LAN network


Preciso quebrar a linha

Question: Ola estou com problema que não me deixa em paz, preciso que quando essas células da tabela cheguem em 4 em cada linha ela pular para a próxima, mas está ai o problema estou puxando essas células do banco de dados usando o $dado["descricao_map"]; não sei o que fazer.
<?php
include("ArquivoConexão.php");
$consulta = "SELECT * FROM materialapoio";
$con = $mysqli->query($consulta) or die($mysqli->error);
?>
<!doctype html>

    <link rel="shortcut icon" href="../IMAGENS/Favicon.png" />
    <link rel="icon" href="../IMAGENS/Favicon.png" type="../image/x-icon" />
    <meta content="IE=edge"http-equiv="X-UA-Compatible" charset="utf-8">
    <title>Kep</title>
    <link href=../CSS/Estilo_02.css rel=stylesheet>

            <input type="checkbox" id="navicon" onclick="Aumentar('MenuTotal') & Diminuir('Conteudo') & Aparecer('Menu') & Aparecer('Logo')"/>

                <input type=button class="BotaoMenu PositionRe FonteArial" value="MATERIAL DE APOIO" onclick="MaterialDeApoio()">
                <input type=button class="BotaoMenu BotaoMenu2 PositionRe FonteArial" value="CALENDÁRIO" onclick="Home()">
                <input type=button class="BotaoMenu BotaoMenu3 PositionRe FonteArial" value="LISTA DE TAREFAS" onclick="ListaDeTarefa()">

                    <input type=button class="PositionRe IconesCabeçalho iconeHome" onclick="Home()">
                    <input type=button class="PositionRe IconesCabeçalho Home" onclick="Sair()">

Material de apoio

                            <?php while($dado = $con->fetch_array()){ ?>
                                <?php echo $dado["descricao_map"];?>
                            <?php }?>

Comment: Olha se isso resolve https://pt.stackoverflow.com/questions/324963/como-colocar-um-limite-de-4-imagens-por-linha/324976#324976 Vc precisa estruturar o seu HTML para quebrar dessa forma, depois vc popula com o que vier do banco e ai vai quebrar corretamente de acordo como o CSS feito para receber o conteúdo
Comment: Desculpa falar uma coisa meio nada a ver, mas... porque não usa Bootstrap? Lá você já tem o grid pronto. É sempre 12. Daí você pode colocar `col-md-3`, que vão caber 4.
Comment: É uma boa pratica marcar uma resposta que lhe atendeu como aceita, veja como em https://i.stack.imgur.com/evLUR.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: Boa tarde,
Utilizando o padrão de percentual e não o de pixel, pois dessa forma isso vai se adequar independente do navegador.
Tenta algo desse tipo:

Answer: Aproveitando o seu código, daria resultado dessa forma.

    <?php
        $numerocolunas = 4;

        while($dado = $con->fetch_array()){

        echo "
";
            for ($x = 0; $x < $numerocolunas; $x++) {
                echo "".$dado["descricao_map"]."	";
            }
        echo "
";

        }
  ?>

É só um detalhe, mostrar como poderia ter sido feito levando em conta o código da pergunta e a pergunta em si é: preciso que quando essas células da tabela cheguem em 4 em cada linha ela pular para a próxima. Nesse caso a minha resposta aponta como isso pode ser feito, agora se a pergunta fosse outra existe uma forma melhor de fazer isso certamente a resposta seria outra. Isso só pra deixar aqui a minha indignação aos downsvote.

Essa situação se parece com alguém perguntando ao seu mecânico: qual a solução para o defeito do meu fusquinha, a resposta, então seria, olha compra um Mercedes zero quilometro que é melhor.
Answer: Você pode usar flexbox! Torna o layout responsivo e de fácil manutenção.
Por exemplo, você define um escopo inicial, com algumas div's. E a partir delas podemos definir um tamanho fixo utilizando px ou com porcentagem.
O exemplo abaixo foi feito com tamanho fixo, utilizando px's.
A partir disso demos um display: flex para a div pai, e adicionamos a propriedade flex-wrap: wrap que permitirá a div "ir para baixo sozinha", pois, por padrão, todos os itens vão tentar ficar em uma linha só.

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  display: flex;

  flex-wrap: wrap;
  flex-direction: row;
  justify-content: space-around;
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 200px;
  height: 150px;
  margin-top: 10px;

  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}

1

2

3

4

5

6

Para mais informações sobre flexbox confira esse guia.

Preciso quebrar a linha


What is a good solo to learn in the major scale?

Question: I am starting to play / improvise in the major scale and would like to learn some guitar solos that are good examples of this scale so that I see how other people use it. What are some famous solos in contemporary or classic rock that make use of this scale?
Update: I asked the question in this form because I thought it was more genericly useful, but some of the answers aren't quite getting at the question because they're assuming I'm a begininer (which is how I phrased the question) and giving other advise. I'm a teacher, and I find that my students learn scales, theory, and improvisation much better if they learn it in the context of a song they might know. I was looking for some new examples to change up my teaching a little.
Comment: I think it's a great idea to teach scales by including real music, like a solo, along with the regular playing of scale patterns on their own.
Comment: Check out: Lou reed, sweet jane https://www.youtube.com/watch?v=LrMLt9bMd_I;
Comment: I kinda went the other way, going through the major scale, first up and down so my fingers knew where to go, then skipping notes and such until I started recognizing things. "Oh, that's 'God Rest Ye, Merry Gentlemen'", and such.
Comment: Even though it's not rock (and that's why I comment instead of answering), moto perpetuo By Paganini (the violin part obviously) is a great exercice to learn the C scale and even to learn to sight read because of its very few alterations.
Comment: Brian May from Queen used the major scale notes in lots of his solos.
Answer: Sweet Child Of Mine always struck me as a decent solo that stays mostly in the major scale.
Comment: er.. does it ? I think it's mainly minor.. pretty sure, in fact (tell me if I'm wrong!)
Comment: Presumably JimR was thinking of the main riff, which is major. Yeah the solo is mostly harmonic minor I think.
Comment: There's a sort of mini-solo that comes after the chorus about 1:10 into the song that's major.  If you wanted to you could also teach the vocal melody on guitar since it outlines the major scale; it can be interesting for students to see how melody lines map to the neck.
Comment: But yeah, the extended solo section doesn't use the major scale, it goes from mainly harmonic minor and then into "blue minor" (or what a guitarist might call "pentatonic").
Answer: To me, you don't learn solos to learn scales, you learn scale patterns. While it's possible to learn scales from solos you'll never quite be able to understand them and it can take an awful long time (maybe for a few intelligent people it will work but for most it won't). If you want to learn scales learn scales, not solos, chords, etc... If you wanna learn to solo learn solos, etc...
If you want to teach improvisation you can have them learn specific solos so they can use them to get used to working the changes/playing in time/etc but if they ultimately want to be free to do their own thing they have to do it all. You shouldn't assign solos based on which scales they use but the complexity. Music isn't about scales and even if you knew the major scale perfectly doesn't mean your solos will sound any good.
If I were the "teacher" I would assign "solos" based on complexity, style, and specific issues it may solve for the student(if they student has issues with position changing I might try and find a solo for him that would help with it). I would also have the student work on scale patterns along side of everything else.
A student should be working on many things a little bit at a time and not one thing only. Scales, songs, chords, arps, solos, improvising, techniques, theory, etc... All these need to progress about the same although some are more important than others. This is assuming the student wants to do more than just play his favorite song.
Heres a list of the order of things that should be focused on by a beginner:

Basic Chords (standard open position chords),
Basic Scale pattern fragment(very simple 2 or 3 line box pattern),
Simple fun songs for chord practice and maybe even a little simple soloing,
Basic Theory (very basic as not to overwhelm the student),
Possible sight reading
Very simple techniques.

The lower stuff should be introduced subtly and without any requirement. Like if your teaching a pull-off you would do it very quickly but just mention a word about it when the context is right. e.g., if your teaching a simple box pattern you could say "You can pull off the note without picking if you want", etc...
Once they get more advanced you can then adapt the order for what they need. For instance if they pick up the chords very easy (which usually isn't the case but assuming) then you could focus more on scales and improvising and more complex chord forms.
Comment: Not agreeing with this answer.If I teach a solo, that's ALL I've done.It is difficult for a learner to grasp the connection between a given solo and improvisation.The opposite is apposite. When a pupil knows scale patterns he can visualise how Clapton, et al,uses the notes from the pattern to come up with a solo.Smoke on the Water - blues scale.Sunshine of your Love - blues scale.Etc.etc.When you learn a solo you learn the notes for it in a particular order.This does not help to produce a solo of your own.Teaching a riff is almost as bad for getting someone to improvise by themselves.
Comment: I don't think there are rules to learn improvisation. There are tools that can help you to get better, yes, but rules? There are plenty of great musicians that have learnt the hard way, simply listening and playing along with records.
Comment: I think it depends on the instrument.

For guitar (which I play), yeah, it's scale patterns, and as long as you can say "This note is A, this scale pattern is a harmonic minor scale, that's where the anchor should be, so this flurry of notes is in A harmonic minor."

But that scale pattern (except in the most abstract sense) is useless with the piano, and I'm sure it's all out the window with horns.
Comment: VarLogRant - 'that scale pattern' is not useless with the piano.Sadly it involves learning each and every scale pattern on each and every note - yes, thats 12 maj.,12 min., 12 pents etc.Each is a pattern in its own right, so there's a heck of a lot more to remember ! Guitar patterns are SO much easier, as there are fewer, and all transferable up and down the neck. I know - I play both.
Comment: @Tim Upvoted, but if you teach the material by ear this is less true. When teaching, I start very basic (1 or 2 notes), and have the student play back to me what I play them. By the time we're learning more complete solos or riffs, they're still learning by ear, and so I'll play the riff to them slowly until they get it (repeat bits where they make an error, and of course correct fingering if necessary). This habit of learning by ear not from tabs means students invariably digest some of the underpinnings of the solos. Of course it's still useful to look at shapes and scales afterwards too!
Comment: This answer begins, "To me, you don't learn solos to learn scales", and explains the reasoning behind this statement. That is not an answer to the question "What is a good solo to learn in the major scale?". Did you miss the "in" perhaps?
Answer: Have to say it's not all that common, but here are some guitar solos I can think of which I think are major:

I believe in a thing called love - The Darkness
Wish you were here - Pink Floyd
Purple Rain - Prince
I Want to Break Free - Queen
Maggie May - Faces
Right By Your Side - Eurythmics (kind of a solo)
Hammer to Fall - Queen (second solo)
Come up & see me - Steve Harley & the Cockney rebel

Although now I think about it, some of these possibly would use a minor 7th (thanks Tim), but are fundamentally major in that if you stray into a minor scale (flatten the 3rd), it sounds all wrong.
Comment: A diminished seventh is the same note sound as a major sixth. You probably mean *minor seventh*.
Comment: @user2808054 people often say "flat 7" too, just FYI (especially in pop, rock, jazz contexts).  Upvoting this answer because I think it's great to teach mixolydian alongside major, and having solos that occasionally pop in a flat 7 in a major context is a great way to teach students about "major solos" in a broader sense.  (It's not confusing to a student to see that sometimes the 7 is flat and other times not, if anything it's more confusing to insist on a wall of separation between mixolydian and major in guitar context)
Comment: @tim thanks, I googled dininished 7th and found it wasn't what Idthought it was. I'm not that good with the names of things like that, but can find it all ok on the guitar. Answer corrected.
Comment: @Some_Guy ta, aye I've heard 'flat 7' too whcih is where the confusion with diminished came from. Only been getting it wrong 30 years haha
Answer: I don't know if you would find many solos in Rock that is pure Major. Most would reference the Pentatonic, Lydian, or Mixolydian scales. I would say that Jessica or Melissa from Allman Brothers would be solos and licks to check out. I'm thinking Don't Stop Believing from Journey would be one to look at.
Answer: I once asked Jimmy Hendrix what scales he thought of when playing solo's - he then gave me the best advice I ever got : he said "I don't think of scales, I close my eyes and go for it'. However, as a start point you may find this interesting.....
http://www.dummies.com/how-to/content/how-to-use-the-pentatonic-scale-in-a-lead-guitar-s.html
Answer: I believe the first guitar solo on "Comfortably Numb" stays completely in the D major scale for the first half, then G major for the second half.  And it's something any "classic rock" listener will know very well.
(The second solo is bluesier.)
Answer: One of my favorite guitar solos/songs in major is "The Wheel" by Jerry Garcia. Two reasons it might not fit the parameters of your question: he is playing pedal steel, and he mostly avoids the 7th degree. But I'm pretty sure that throughout, the major 7th would sound better than the flat 7th. And this definitely isn't just a simple pentatonic--he uses all the rest of the notes of the major scale.
Answer: It seems to be difficult to get a straight answer to "how do I solo in major?".  I can play the blues blindfolded in my sleep, but soloing over a major progression has been troublesome, and dropping down to the actual "relative minor" position three frets down was disastrous.  None of the usual "tricks" seem to work there.  I tried reverting back to my modes or positions to come up with the perfect solution.  It's a combination of the Lydian and Mixolydian modes, starting on the IV or the fourth note of the major scale.  Be aware that the starting note isn't the root, of course, but in this position (Lydian) on the lower three strings, and then sliding up two frets and continuing in Mixolydian on the upper three strings, I found it extremely easy, using the "pentatonic mindset" that I'm accustomed to, to solo fairly effectively over major progressions.  I'm sure the musical "geniuses" will have no idea what I'm talking about, but for those of us working Joes who just want to play a passable solo over major, try this out and I think you'll be pleased.  Questions?  Just read what I wrote again, and keep trying.  There's no magic, if you're good on blues, you're halfway there, just keep plugging and you'll get it.  James Taylor's Fire and Rain is the song that helped me with the breakthrough.
Comment: Hey Mike I used to have a devil of a time on the majors and come from a blues background too so I've got to share whats worked for me as well.  The myxolodians and what not was way too much memory work for me and playing guitars we think in shapes more than straight lines so I just learned all the chords in the major progression I-ii-iii-IV-V-vi and then the diminished chord which is rarely used but important for soloing.  By knowing the chord shapes all the way up and down the neck I know the scales and I know how they relate to the chords played.  This is the best!
Answer: A couple majors scale songs ,I ran across was 38 special hold on loosley and bostons more than a feeling .
I think if you find one lead, like i did, with the 38 special guy, Jeff Carlisi.
albumn 1981 & 82      there are way more where that came from.  but i havent checked that yet. A guitar player I dont think would go learn to go that route
for just one song. Its  style hes good at and most likley uses over and over.
Answer: You are asking for a song that doesn't even use the seventh. That's hard. You still have the sus, major seventh and ninth to use. I would say look for songs that are all about the major seventh our ninth. Songs like Lonely Night in Georgia or some Menken songs from Disney like beauty and the beast come to mind. But really, give them the seventh and so many doors will open.


ARIMA Question: Is it more preferable to use monthly data over quarterly, or vice-versa?

Question: I'm an actuary trying to model future losses. I have the ability to use monthly or quarterly data, and I'm curious if there is any material difference in using either periods. I understand there may be no simple answer, so I'll provide more info if needed to get a substantive response.
Thank you!
StrappingYL
Answer: It's hard (I would say "impossible") to answer this in an abstract sense. Which approach is better could vary in different examples.
Try both approaches, forecasting on both levels, and then either aggregate the monthly forecasts to quarterly, or disaggregate the quarterly ones to months, dependending on what granularity you are interested in.
Alternatively, forecast on both granularities and then combine the forecasts using the optimal combination approach of Hyndman et al. (2011, Computational Statistics & Data Analysis). When the hierarchy in question is one of time, this has been called MAPA by Kourentzes et al. (2014, International Journal of Forecasting).
Comment: I'll run both models and compare the results. Thank you for the insight!


Desabilitar 'disabled' de um botão com nível de acesso

Question: Tenho uma lista de itens, onde é possível editar e excluir eles através de um botão, e temos níveis de acesso nesse sistema, possuindo 'Vendedores' e 'Usuários Master', mas os vendedores não podem excluir nada, apenas os Masters, portanto, no botão de excluir, eu coloquei um 'disabled' portanto, ele fica desabilitado, e quero fazer uma verificação para quando for Usuário Master, tirar esse disabled, permitindo a exclusão, tentei um utilizar um removeAttribute, mas retorna esse erro:
TypeError: Cannot read property 'removeAttribute' of null
HTML:

        Tem certeza que deseja excluir o Ramo ?

     <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        ×
     </button>

     <button type="button" class="btn btn-secondary" data-dismiss="modal">
        Não
     </button>
     <button type="button" class="btn btn-danger" data-dismiss="modal" (click)="del()" disabled id="delete">
        Sim
     </button>

TS:
  disableDelete() {
    let username = JSON.parse(localStorage.getItem('username'));
    console.log('Username: ', username);

    if(username === 'Arthur' || username == 'admin') {
      let btnRemove = document.getElementById('delete').removeAttribute('disabled');
    }
  }

Comment: Está utilizando **Angular**?
Comment: Sim, mas um dos mais atuais
Answer: Você está utilizando Angular logo não precisa de função nenhuma para fazer o quer, no TS é só verificar qual o tipo do usuário no ngOnInit() e guardar o valor em uma propriedade da classe do componente e no Html no botão fazer o property binding com a propriedade:
HTML

    Tem certeza que deseja excluir o Ramo ?

 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    ×
 </button>

 <button type="button" class="btn btn-secondary" data-dismiss="modal">
    Não
 </button>
 <button type="button" class="btn btn-danger" data-dismiss="modal" (click)="del()"
    [disabled]="verifica" id="delete">Sim
 </button>

TS
export class SeuComponent implements OnInit {
  verifica: boolean;
  tipoUser = 'Admin';   // pega o que vem do storage

  ngOnInit() {
    if(this.tipoUser == 'Qualquer coisa' || this.tipoUser == 'Admin') this.verifica = false;
    else this.verifica = true;
  }
}

Para saber mais sobre property binding em Angular veja aqui.
Para ver um exemplo funcionando veja aqui.
Answer: Não é necessário atribuir a ação a uma variável. Teste da maneira abaixo.
if(username === 'Arthur' || username == 'admin') {
  document.getElementById('delete').disabled = false;
}

Para desabilitar o botão, basta mudar para true.
Comment: Concordo, realmente não é necessário a variável, mas o .disable não é entendível, pelo menos não no typescript eu acho, retorna isso:

Property 'disable' does not exist on type 'HTMLElement'
Comment: Na verdade, esse erro é corrigido se eu colocar isso:
(document.getElementById('delete')).disabled = true;... Porém, retorna o mesmo erro, que a pergunta acima: TypeError: Cannot set property 'disabled' of null


O que e quais são os tipos de ambiente de desenvolvimento?

Question: Ocasionalmente vejo algo deste gênero em diversos projetos:
env: 'production'

O que é isso? Quais são as outras opções convencionais (além de "production") e para que serve?
Por que devo usar isso na minha aplicação?
Answer: Normalmente você encontra pelo menos 2 ambientes de desenvolvimento:

desenvolvimento
produção

Dependendo da criatividade e da burocracia envolvida no processo, você pode ter outros ambientes:

desenvolvimento
teste (*)
homologação
beta
produção

(*): aqui destacando o teste e separando do desenvolvimento, pois muitas vezes o ambiente de desenvolvimento o próprio programador viciou ele. Pode ser colocando dados artificiais para prosseguir na tarefa ou normalizando dados selvagens para dados comportados e controlados. O ambiente de teste nesse caso é de responsabilidade do setor de testes/qualidade/QA, que mantém os dados mais próximos possíveis da selvageria de produção (ou o forçam para um tipo específico de selvageria para testar algum aspecto).

Vou focar no resto da resposta apenas na divisão mais notória: desenvolvimento e produção.
Por que separar?
Para que o desenvolvedor possa quebrá-lo. Sem medo. Para que seja sua caixinha de areia e ele possa fazer o que quiser ou precisar sem se preocupar com consequências.
O ambiente de produção é um lugar sensível. Normalmente se costuma dizer que "não se faz teste em produção", e essa frase é verdade quase sempre.
No meu caso, eu trabalho com um sistema de vendas. Para fazer alguma mudança que o cliente pediu para acrescentar alguma regra de venda, eu preciso realizar uma venda. Posso fazer boa parte do que eu quero e testar essas mudanças e não salvar o pedido de venda no último instante. Mas nem sempre é possível.
Imagine o seguinte cenário:

eu preciso que o pedido fique pendente para clientes que estejam com títulos atrasados; cada grupo de clientes terá um limite de atraso distinto.

Eu só posso garantir que o pedido para o cliente do grupo "bom pagador" que está atrasado a 90 dias ficará pendente se eu fizer o pedido, salvar e conferir. Agora, imagina que eu ainda estou desenvolvendo o sistema e por um bug o pedido não ficou pendente. Isso significa que automaticamente esse pedido será processado e emitido para o cliente. Quando o pedido chegar na porta do cliente, ele falará que não fez esse pedido e mandará voltar.
Além do incômodo do frete de ida e volta das mercadorias, ainda terei causado um estresse desnecessário entre o vendedor e o cliente. No ambiente de teste, esse pedido não seria processado, mesmo por bug. Portanto, nunca iria parar na porta dele. Não teria estresse para ninguém e eu posso desenvolver tranquilamente sem me preocupar se vou causar prejuízo a alguém (além das eventuais atrasos nas entregas).
Outra situação que pode acontecer, também, e que geraria dor de cabeças. Imagina que você resolveu mudar a infraestrutura do sistema para usar um ORM, que precisou fazer isso para dar maior manutenabilidade no sistema. Você aplicou inicialmente a forma mais ingênua disso, e não percebeu que estava verificando quais objetos dentro de 1.000.000 se relacionavam a outros 1.000.000 de objetos, então o sistema precisou testar todas as possibilidades para montar o mapeamento. Dá para ver que esse mapeamento possível ocupa mais do que 10 bilhões de itens (ocupa na verdade 10^12, um trilhão de itens). E você fez tudo isso, para cada mapeamento distinto desses 1 trilhão, fazendo uma consulta no banco. Seu banco de dados teria de lidar com 1 trilhão de consultas, o que é muito. Se seu banco for muito bom e em 100% da capacidade atender 1 bilhão de requisições por segundo, ainda seria necessário esperar mais ou menos 20 minutos até ele estar disponível para quem usa ele em produção. Você sem querer fez um ataque de negação de serviço ao seu servidor, e seus usuários ficaram sem entender por um terço de hora o que estava de fato acontecendo.
Quando devo usar esses ambientes?
Se você está desenvolvendo algo, então é sinal que você deve selecionar o ambiente de "desenvolvimento". Isso deveria ser óbvio.
Se você já fechou o seu produto e está entregando ele para o cliente, então selecione que está em produção.
Se você usar outros ambientes (como a escala de cinco ambientes que eu mencionei), então o responsável por colocar no ar essas coisas sabe qual ambiente usar em cada situação.
De quem é a responsabilidade de configurar isso?
Essa responsabilidade cabe ao setor de "operações". Desenvolvedores não deveriam mexer nisso (exceto para "testar em produção", e isso deve ser feito com todo o carinho do mundo). O desenvolvedor deveria colocar para desenvolvimento e esquecer sobre a existência disso em... quase todos os casos que não envolvam bugs?
Claro, a filosofia DevOps é para deixar desenvolvimento e produção mais próximos. Mas é bom separar quem é quem. Por exemplo, o Jefferson desenvolvedor gosta de desbravar e tentar algoritmos e técnicas inovadoras para resolver seus problemas, mas o Jefferson de operações gosta que as coisas tenham uma evolução mais paulatina e controlada, mais garantida e segura. O conflito interno entre meus dois Jeffersons fazem com que eu tente tomar uma decisão equilibrada.

 O Jefferson desenvolvedor é mais teimoso e costuma vencer

Ele sempre apresenta a separação desse jeito?
Não, nem sempre é assim. Onde trabalho, temos os arquivos jdbc-dev.properties, jdbc-prod.properties. Em algum lugar da inclusão de dependências é apontado qual dessas configurações do banco de dados é de fato usada naquele momento, apontando para o nome do arquivo.
Devo usar na minha aplicação?
Talvez. Provavelmente. Pelos motivos acima mencionados. Agora, saiba que isso é uma burocracia, que isso aumenta a segurança do desenvolvimento em detrimento de alguma velocidade (possivelmente). Então, se você está fazendo isso só para desenvolver seu portfólio, ou só para estudos, não sei se vale a pena perder um tempinho com isso.
Comment: Um exemplo bem básico da distinção entre desenvolvimento e produção é poder começar uma manutenção de código às 17:30 de um dia, terminar no outro, sem se preocupar em gerar erro de sintaxe no sistema funcionando.
Comment: @lffg poderia ir mais longe, mas acho que fugiria do foco principal =] Resolvi deixar assim, "sucinto" porém completo o suficiente