Q: AJAX URL requests in Drupal 7 on localhost Apache2 don't include base URL or base path I am currently stuck with a problem in my local Drupal 7 environment. As Drupal 7 site configurations can get very complex, I will try to explain my problem in as much details as possible.
The site sits in a sub folder in my local environment, I have more projects running on my localhost, so preferably I would like to keep the projects separated. In addition, for this site I have two separate folders, one for development and one for production that share the same database, so a solution by adding fake domains would not work here I think (correct me if I'm wrong).
So the main problem seems to be that AJAX requests don't include the base URL or base path and I can't login on http://localhost/mysite/devel/docroot/user because the AJAX request would go to http://localhost/system/ajax or http://localhost/ajax_register/login/ajax and therefore would not return the correct JSON response.
How can this be solved? Are configurations in Apache's httpd.conf or .htaccess enough to make this work?
Here's what I did so far, first in settings.php:
$base_url = 'http://localhost/mysite/devel/docroot';
$base_path = '/mysite/devel/docroot/';

Next, I've tried the following with rewrite rules in httpd.conf:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_REFERER} .*devel.*$ [OR]
    RewriteRule ^/sites/(.*)$ /mysite/devel/docroot/sites/$1
    RewriteRule ^/system/(.*)$ /mysite/devel/docroot/system/$1
    RewriteRule ^/ajax_register/(.*)$ /mysite/devel/docroot/ajax_register/$1
</IfModule>

Here I got the following pop up with HTML (that seems to be from index.php) in the response text instead of the expected JSON response:
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: http://localhost/ajax_register/login/ajax
StatusText: error
ResponseText: lots of HTML...

Then without rewrite rules but using proxies instead in httpd.conf:
<IfModule mod_proxy.c>

    ProxyRequests Off
    ProxyPreserveHost On

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    RewriteEngine on

    ProxyPass /system/ http://localhost/mysite/devel/docroot/system/
    ProxyPassReverse /system/ http://localhost/mysite/devel/docroot/system/
    <Location /system/>
        Order allow,deny
        Allow from all
    </Location>

    ProxyPass /ajax_register/ http://localhost/mysite/devel/docroot/ajax_register/
    ProxyPassReverse /ajax_register/ http://localhost/mysite/devel/docroot/ajax_register/
    <Location /ajax_register/>
        Order allow,deny
        Allow from all
    </Location>

</IfModule>

For the proxy directives, a similar 404 not found error was given for the POST AJAX request, except that now the response text is in JSON format.
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: http://localhost/ajax_register/login/ajax
StatusText: error
ResponseText: some JSON code...

Without both the rewrite rules and the proxy directives I get the following error in the JavaScript pop up:
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: http://localhost/ajax_register/login/ajax
StatusText: error
ResponseText:
404 Not Found
Not Found
The requested URL /ajax_register/login/ajax was not found on this server.

Finally in .htaccess I've tried to rewrite the base to the following:
RewriteBase /mysite/devel/docroot/

and here I get the same 404 error as was the case when both the rewrite rules and proxy directives are commented out in httpd.conf. I would also like to add that in the database, in the table languages I've set the domain for the English language to localhost.
I don't understand, why is the base not included in front of the AJAX URL requests? And how can I add it? When I query Drupal.settings.basePath in Firebug I do get the value that I've set in settings.php :S - Does someone have any ideas?

A: There are many solutions for your problem, but I'm gonna try to focus on the most mature one. I assume you are using windows as your environment.
You said you were running your projects on localhost, which is where your first mistake is.
Localhost is nothing but a form of weird domain name you specify. When you request a domain like "www.google.com" or "localhost" the following steps occur:

*

*The browser checks a specific file for the requested domain. This file is called hosts file

*If the domain name is found in the hosts file, the browser sends a request to the IP address specified in the hosts file

*If the domain name is not found in the hosts file, the browser queries domain name servers which return the corresponding IP adress.

Now localhost is nothing but a domain name specified in your hosts file, which points to the loopback address.(127.0.0.1).
So the magic trick here is to bind your custom hosts like "project1", "project2" etc.. to that loopback adress(127.0.0.1).
Than when you send a request to "project1" in your browser, the server running on port 80 will respond as if you typed "localhost".
The second part you need to take care of is called virtual hosts. When you send a request with a specific domain name, a special header is included in your http request called "Host".
Lets assume, that you redirect all this custom domains to the same IP (127.0.0.1). In order for apache to serve a different project, you should instruct apache to look at the "Host" header and resolve it for the corresponding project.
Again you do that by setting virtual hosts.
A lot of frameworks and content managing systems in PHP have some ugly ways to insert some magic "$BASE_PATH" variable, which is a bad practice as that could be achieved with relative paths in pure html and a properly configured server.


Q: Toggle a div in Angular How can I make a toggle in Angular.JS so a div will open and close when clicked on the same div again. For now it perfoms the action so it opens the div but whenever I click again on it, the div needs to close again.
 Zerg

and this opens:

  info

JS:
  $scope.activeRows = "";
  $scope.isAccordionOpen = function(row) {
    if ($scope.activeRows === row) {
      return true;
    } else {
      return false;
    }
  }

  $scope.openAccordionRow = function(row) {
    $scope.activeRows = row;
  }

Problem here is that the same clicked div doesn't close when pressing on it again.

A: Currently your code doesn't have anything that even attempts to collapse the row. You could change your code to this.
HTML:
 Zerg

JavaScript:
  $scope.activeRows = "";
  $scope.isAccordionOpen = function(row) {
    if ($scope.activeRows === row) {
      return true;
    } else {
      return false;
    }
  }

  $scope.toggleAccordionRow = function(row) {
    $scope.activeRows = $scope.isAccordionOpen(row) ? "" : row;
  }

A: If you want toggle. Just use these code.
$scope.activeRows = true // Am setting this for default to show
ng-click="$scope.activeRows = !$scope.activeRows" // change ng-click event
ng-show = "$scope.activeRows" // bind directly $scope.activeRows to show.

A: the easy way to do such a thing is the way bellow
 Zerg

  info


Q: Spark Structured Streaming with Azure EventHub In the context of Spark Streaming with Azure EventHub, technically i need some help in understanding the differrence b/w EventPosition.fromStartOfStream, EventPosition.fromEndOfStream. If i need to trigger the Streaming job only once a day with checkpointing enabled, what difference will the below code do.
Gone through couple of docs, couldn't find much information on this. Any help would be appreciated.
val ehConf = EventHubsConf(cs).setStartingPositions(positions).setStartingPosition(EventPosition.fromStartOfStream)

val ehConf = EventHubsConf(cs).setStartingPositions(positions).setStartingPosition(EventPosition.fromEndOfStream)

A: If you are checkpointing then position given by setStartingPosition won't have any use. it is only used if there is no checkpoint found.
Please see sample code and description here - https://github.com/Azure/azure-event-hubs-spark/blob/564267dd1287b0593f8914b1acf8ff7796b58e3b/docs/spark-streaming-eventhubs-integration.md#per-partition-configuration


Q: Docker different digest when push same images with different tags I built one docker image with one tag and then tag it with a new tag (both tags include registry URL).
I push the first tag, then the second tag, the push digest from 2 tags are different:
16:10:47 + docker build -t 10.88.102.47:8443/my-project/foo:jenkins-305 .
...
16:11:26 + docker tag 10.88.102.47:8443/my-project/foo:jenkins-305 10.88.102.47:8443/my-project/foo:latest

16:11:26 + docker push 10.88.102.47:8443/my-project/foo:jenkins-305
...
16:11:34 jenkins-280: digest: sha256:22a4cd54bf43f03530c475832ca4432adfcf02c796e9c1cdafea72cf07ce7bf4 size: 3654

16:11:35 + docker push 10.88.102.47:8443/my-project/foo:latest
...
16:11:36 latest: digest: sha256:ccb4e8c41339b1a5d780cc5d28064cabf839657617a9c1e1d14eaee507405b20 size: 3632

Pushing tag jenkins-305 - digest 22a4cd54bf43f03530c475832ca4432adfcf02c796e9c1cdafea72cf07ce7bf4
Pushing tag latest - digest ccb4e8c41339b1a5d780cc5d28064cabf839657617a9c1e1d14eaee507405b20
Shouldn't 2 digests of 2 tags from same image identical?
Update
I downloaded both tags on a different machines and see those tags have the same IMAGE ID (digest?)
10.88.102.47:8443/my-project/foo   jenkins-305      sha256:5537979d74ac00f75b7830c41c27be5f545ec55b0ab12622f9fad2eec8583a6e   21 minutes ago      689.2 MB
10.88.102.47:8443/my-project/foo   latest           sha256:5537979d74ac00f75b7830c41c27be5f545ec55b0ab12622f9fad2eec8583a6e   21 minutes ago      689.2 MB

But this digest is different from the digest provided by docker push, why?

A: The docs on the registry report that the digest contains the image manifest, and the manifest is made up of the tag amongst other things.


Q: Is there any function/implementation in python similar to peaks(N) in MATLAB? I can obtain a 2D matrix/3D plot using peaks(N) where N is any number in MATLAB. Is there any way to do this in python?
MATLAB example:
Create a 5-by-5 matrix of peaks and display the surface:
figure
peaks(5);

How to do this in python?

A: You can use SciPy
from scipy.signal import find_peaks
peaks, _ = find_peaks(x, height=0) # x is the signal

print("x-values: ", peaks," y-values: ",  x[peaks])

SciPy documentation for finding peaks
.. Or a quick solution if you signal is not too noisy then you can manually smooth the signal, differentiate the smoothed signal, find a threshold value and count the zeroes :)


Q: Fixing a git mess during a Pull Request I have a large series of git commits made during a pull request for a github project. I've been asked to squash all of the commits together, however since then I have made an incredible mess of merges, resets and accidentally merging over other commits that I've pulled to the repo whilst the PR has been underway.
What i'd like to be able to do, is simply copy the two files that are actually involved in the pull request to another directory, reset back to the very first commit I made for the PR, re-paste my new files with the latest changes and then commit them, so that the PR shows up with a single commit. Is this possible? Thanks!

A: If you want it to look like a single commit, you'll need to use git squash. Is there a reason why you can't use this?


Q: Pentaho Kettle/ETL integration with Subversion or Git We are using Pentaho ETL (aka Kettle). Pentaho has a built in enterprise repository for versioning. However, it is very poor. First, there's no way to go through an entire Pentaho project looking for changes. Each file is its own individual change. Second, there doesn't appear to be a way to tag an entire release.
We could use a file based system for storing our Pentaho objects. Jobs will end with a .kjb suffix and Transformations will end with a .ktr suffix. If that file system happened to be a Git or Subversion workspace, we could checkout/push/sync a revision of the Pentaho project, do the changes, and then commit/push those changes back to the repository.
However, there doesn't appear to be a way to check in and out of files from Pentaho itself like you can with Eclipse, or VisualStudio, or any other IDE environment.
Is there a way to integrate Subversion with Pentaho? Is it possible to use Eclipse (which not only integrates with Subversion and Git, but also integrates with Jira and Rally) with Pentaho ETL/Kettle?


Q: Debugging Paging in Sql Reporting Services I'm working on my first significant Sql Reporting Services project and am having problems with paging.  Most of the reports are already working.
What is happening is that I"m getting different numbers and locations of page breaks between Web Reportviewer, PDF and Word documents.  The word is the closest, but none of the three are really correct.
I've looked for the for the obvious like extra paging and making sure the report does not go outside of the left or right margins.  My problem is that I'm not sure how to go about troubleshooting reports that pages that do not break in the correct location.
Does anyone have a suggestion where to start?
I'm using VS2008, SQL2008 DE on Vista Dev box.

A: This isn't really a problem - the different renderers are rendering the report appropriately for their output. The web viewer is optimised for screen-based reading and generally allows more content per page than the PDF viewer does as the PDF viewer is constrained by the paper size that it formats to. Thus you get more pages when rendering for PDF than web; however, the content of the report is exactly the same.
The best illustration of this is the Excel renderer - the Excel renderer renders the entire report onto a single worksheet in most cases (for reports with grouping and page breaks set on the group footer it will render each group on its own worksheet). You wouldn't want the Excel renderer to artificially create worksheets to try to paginate your report. It does the appropriate thing which is to include all the data in one big worksheet even though that may be logically thought of as one big "page".
The web renderer page length is determined by the InteractiveHeight attribute of the report (in the InteractiveSize property in the Properties pane for the report) but the interactive height is an approximation rather than a fixed page break setting and your page breaks may still not conform to the PDF version even though the InteractiveHeight is set to the same length as your target page length.


Q: Posting rendered html page to a web service? Best way to transmit data? I am creating a web service that will send an email via Amazon SES. I want to separate the service(API) from the actual application that is going to take in data to be sent. So all I want to send the service is the to address, subject line, and rendered html body of the message. The service in this case is going to be an MVC action result method in C#, and I would like to post the information in JSON. Typically when I post data to a webservice, the data is pretty small and concise.
So my question is, is there a better way to submit html to a webservice as opposed to just sending JSON formatted like this? Would it be a good idea to base64 encode it? Or is there a better way to do this all together?
Post body.
{
   "to" : "asdasd@email.com",
   "subject":"hello",
   "body":"
asdasd
"
}

My model would look something like.
public class EmailMessage
{
    public string toAddress { get; set; }
    public string subject { get; set; }
    public string body { get; set; }
}

Then my action result would look something like...
 [HttpPost]
 public ActionResult SendEmail(EmailMessage msg)
 {

      //Send an email

 }

Is there a better way to do this? Thanks in advance for the help.

A: If you are worried about size of request an response, you can add GZip support.
public class CompressAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP") && response.Filter != null)
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE") && response.Filter != null)
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }

then in your controller add attribute to the action or the controller itself:
[Compress]
public class AccountController : Controller


Q: jquery eq selector loop for tumblr I have a question that I've been stuck with for awhile:
I'm using tumblr and trying to flip the img and the text of a "text post". So currently I'm doing it manually, selecting the 8th eq of .text img to insert before the 8th eq of .text p:first-child.
So in a photo/photoset post I could point to the captions and make them appear after the images, but in a text post everything is wrapped in the {body}, thus needing to select the particular post's image eq(8) to be matched and called up before that particular post's text eq(8)
$(".text img").eq(8).insertBefore($('.text p:first-child').eq(8));
$(".text img").eq(7).insertBefore($('.text p:first-child').eq(7));
$(".text img").eq(6).insertBefore($('.text p:first-child').eq(6));
$(".text img").eq(5).insertBefore($('.text p:first-child').eq(5));
$(".text img").eq(4).insertBefore($('.text p:first-child').eq(4));
$(".text img").eq(3).insertBefore($('.text p:first-child').eq(3));
$(".text img").eq(2).insertBefore($('.text p:first-child').eq(2));
$(".text img").eq(1).insertBefore($('.text p:first-child').eq(1));
$(".text img").eq(0).insertBefore($('.text p:first-child').eq(0));

The reason for using a text post to post images was to workaround the 10 imgs restriction on tumblr photoset posts.
Is there a way that I can code it such that every time a new text post is posted it will select that and insertbefore accordingly? The insertbefore is so that in my index-page, the first-child image and the first-child text would appear.
I know perhaps selecting eq is not the way to go...
(I've placed the relevant portion of the html and css code here, if I'm still lacking anything please let me know!!)
My Html code:

        {block:Posts inlineMediaWidth="1280"}

            {block:Text}

                {block:IndexPage}

                    {body}

                {/block:IndexPage}

            {block:PermalinkPage}

                    {body}

{body}

            {/block:PermalinkPage}

            {/block:Text}

         {block:Photo}
            {block:IndexPage}

                {block:Caption}

                    {Caption}

                {/block:Caption}

            {/block:IndexPage}

        {block:PermalinkPage}

                 {block:Caption}

{Caption}

                 {/block:Caption}

        {/block:PermalinkPage}
        {/block:Photo}

            {block:Panorama}

                    {LinkOpenTag}

                    {LinkCloseTag}
                    {block:Caption}

{Caption}

                    {/block:Caption}

            {/block:Panorama}

        {block:Photoset}
            {block:IndexPage}

                        {block:Photos}

                        {/block:Photos}

                    {block:Caption}

                        {Caption}

                     {/block:Caption}

            {/block:IndexPage}

            {block:PermalinkPage}

                        {block:Photos}

                        {/block:Photos}

                       {block:Caption}

{Caption}

                       {/block:Caption}

            {/block:PermalinkPage}
        {/block:Photoset}

            {block:Quote}

                    "{Quote}"

                    {block:Source}

{Source}

                    {/block:Source}

            {/block:Quote}{block:Link}

                    {Name}

                    {block:Description}

{Description}

                    {/block:Description}

            {/block:Link}{block:Chat}

                    {block:Title}

{Title}

                    {/block:Title}

                        {block:Lines}

                                {block:Label}
                                    {Label}
                                {/block:Label}{Line}

                        {/block:Lines}

            {/block:Chat}

            {block:Video}

                    {Video-500}{block:Caption}

{Caption}

                    {/block:Caption}

            {/block:Video}{block:Audio}

                    {AudioEmbed}{block:Caption}

{Caption}

                    {/block:Caption}

            {/block:Audio}

             {/block:Posts}

My CSS code:
.index-page .grid-item .caption p,
    .index-page .grid-item .text p {
        margin:auto;
    }
    .index-page .grid-item .caption p {
        display: none;
        padding-top:15px;
        line-height:125%;
        color:#fff;
        text-align:center;
    }
    .index-page .grid-item .caption p:first-child{
        display:block;
    }
    .index-page .photos img{
        display: none;
    }
    .index-page .photos img:first-child{
        display: block;
    }

    .index-page .text a {
        text-decoration:none;
    }

    .index-page .text p {
        display:none;
       padding-top:15px;
        line-height:125%;
        color:#fff;
        text-align:center;
       max-width:90%;
    }
    .index-page .text p:first-of-type{
        display: block;
    }

    .read_more {
        display: none;
    }


Q: How to generate different pages from a click in ng-repeat list? I have this code, and this is what it does:
It generates a list of topics from a json.
These topics will be used to determinate a page in the "CONTENT" area.
But, how can i make a "link" or "way" to call/create every page for every item in that list.
Exists a way to verify what item has been clicked? and call the respective page from that item ?

angular.module('duall')
.controller('documentationController', ['$scope', '$http', function($scope, $http){

 $scope.docs = [];

 $http.get('static/titles.json').success(function(doc){
  $scope.docs = doc;
 }).error(function(error){
  console.log(error);
 });

}]);

      <input id="search" type="search" ng-model="q" aria-label="filter docs"/>

                Pesquise Algo! :)

      search

          {{docs.title}}

        Nada encontrado :(

CONTENT


Q: Installing R under Program Files I installed R version 3.2.0 in my "C:\Program Files" folder, and then installed RStudio. When I tried to run an R markdown file, it prompted me to install the Rmarkdown package from source. However, I found that Installing RMarkdown packages in RStudio does not work on Windows 7.
Digging a little deeper I found that the R CMD --help command worked, but every R CMD <command> and R CMD <command> --help fails with
'C:\Program' is not recognized as an internal or external command, operable program or batch file

If I had tested my installation, I would have found the problem with
Sys.setenv(LC_COLLATE = "C", LANGUAGE = "en")
library("tools")
testInstalledBasic("both")

since that fails by calling R CMD BATCH during its execution.
The only solution I could find was to uninstall R and reinstall it a "C:" instead of "C:\Program Files."
It seems like installing R into the "Program Files" folder should be possible. Is there some configuration that would make that possible? Or is there some reason this basic scenario isn't supported?


Q: Защита от множественного подключения заголовочного файла Какой метод лучше использовать:
#pragma once

или
#ifndef XXX_H
#define XXX_H
...
#endif

A: У обоих методов есть свои преимущества и недостатки.
#define кроссплатформенный, соответствует стандарту, поддерживается всеми компиляторами, но у него есть очевидный недостаток: если в проекте случайно найдутся два header-файла с одинаковым именем, необъяснимые ошибки гарантированы. Особенно неприятно это в случае больших проектов с 3rdparty-кодом. Можно придумать более продвинутую схему, при которой вероятность коллизии уменьшится (например, включать в guard полный путь к файлу в проекте или UUID), но гарантии вам никто не даст. (И вы не сможете потребовать от разработчиков посторонних библиотек следовать вашему стандарту.)
#pragma once лишено этих недостатков, потому что теперь ваше намерение прямо сообщается компилятору, а не посредством маломощного препроцесора. Но этот формат поддерживается не всеми компиляторами, поэтому наверняка будут проблемы с портируемостью.
Тем не менее, #pragma once поддерживается большим количеством компиляторов, так что если вы рассчитываете лишь на популярные компиляторы (MSVC, GCC, Clang, Intel compiler) свежих версий, имеет смысл остановиться на этом варианте. Имейте в виду, что многие опытные Unix-разработчики недолюбливают #pragma once, так что вам придётся обосновывать свой выбор.

Если ваш код есть часть какого-либо проекта, всё становится проще: просто спросите руководителя проекта о том, что рекомендуется к использованию. Выбор между include guard и #pragma once — часть coding standards любого проекта.


Q: Tail probability of a max of iid If $X_{i}$ are iid random variables with $X_{i}>0$ and $\mathbb{P}(X_{i}>t)\sim t^{-\alpha}$ as $t\to \infty$.
Then my question is:  Is it also true that $\mathbb{P}(\max_{1,\dots n} X_{i}>t)\sim t^{-\alpha} $ or something similar of this form?

A: Let $W$ be the maximum of the $X_i$, where $n$ is fixed.
Then $W\le t$ if and only if all the $X_i$ are $\le t$. This has probability $\sim(1-t^{-\alpha})^n$. Thus
$$\Pr(W\gt t)\sim 1-(1-t^{-\alpha})^n.$$
But for fixed $n$ and large $t$ we have, taking the first two terms of the binomial expansion,  $1-(1-t^{-\alpha})^n\sim nt^{-\alpha}$.


Q: Netbeans + jquery = error I'm working in a php project and Netbeans insists on marking lines like
        $.get("/adminc/utilsAjax.php", { function: "orderIsOpenOrClosed", orderID: orderID, rand: randn }, function(data)

and the closings
        });

As errors
I tried using the non minifierd version of jquery and no change.
It's like Netbeans ignores the jquery syntax.
Any ideas?

A: The "function" is a reserved word, and in object notation may require quotes, Netbeans is expecting () after the Function key word.

A: As Bodman Said, function is a reserved word so you need to quote that. But you may also need to quote all the hash keys for netbeans to interpret them correctly for example:
    $.get("/adminc/utilsAjax.php", {
        "function": "orderIsOpenOrClosed",
        "orderID": orderID,
        "rand": randn
      },
      function(data){
        // fun body
    });

A: You have missed a { after function(data)


Q: Как показать или сохранить картинку Pillow, используя класс Есть класс с одним из методов, который должен рисовать или сохранять картинку при помощи библиотеки Pillow. Как правильно это записать?
class Rectangle:
    """smth"""
    def __init__(self):
    ...
    def image_gen(self):
        background = Image.new('RGB', (640, 480), self.color())
        background.show()


Q: Rails4 Form with remote - handling error message I have a simple remote form like this:
= form_for :question, :url => question_path, :remote => true, :html =>{:class => 'question-form'} do |form|
and in my controller I check if in the form the EULA is accepted:
  def create
    if (params[:question][:eula] != 1)
      puts "ERROR!"
      respond_to do |format|
          return format.json {render :json => {:error_message => "FOOOO", :success => false } }
      end
    end
    @question = Question.new(question_params)

    respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'question was successfully created.' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

How can I access :error_message or :success in my create.js.erb file?

A: You can do Ajax request
add id to form :id => "question-form"
= form_for :question, :url => question_path, :remote => true,
                  :html =>{:class => 'question-form', :id => "question-form"} do |form|

and anywhere in javascript file
$("#question-form").on("submit", function(e){
    e.preventDefault();
    var form = $(this);
    var request = $.ajax({
        method: "POST",
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
        url: "/questions",
        dataType: "json",
        data: form.serialize()
    })

    request.done(function(res){
        console.log(res.success);
    })

    request.catch(function(jqXHR){
        console.log(jqXHR.responseJSON)
    })

})


Q: How to reduce ipa size Xamarin.ios I am trying to reduce my ipa size, but cant succeed. I tried with linking SDK assemblies only but when the app is archived it shows 189 MB of the app store and 75mb for ipa. I tried different options but it never worked.
Then I looked into my bin folder and I found out that Xamarin.swift4 is taking about 80 MB of the size, When I removed that package my ipda was reduced to 34mb and playstore size was reduced to 89 MB, but because of this my app crashed instantly after opening. So it means that I can not remove Xamarin.swift 4 libraries.
I have attached my bin folder pic and packages.congifg file, let me know if there is any solution

    <?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Answers" version="1.4" targetFramework="xamarinios10" />
  <package id="Crashlytics" version="1.4" targetFramework="xamarinios10" />
  <package id="dannycabrera.GetiOSModel" version="1.4.0" targetFramework="xamarinios10" />
  <package id="Fabric" version="1.4" targetFramework="xamarinios10" />
  <package id="iOSCharts" version="3.1.1.2" targetFramework="xamarinios10" />
  <package id="Microsoft.CSharp" version="4.4.1" targetFramework="xamarinios10" />
  <package id="Microsoft.NETCore.Platforms" version="2.0.2" targetFramework="xamarinios10" />
  <package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="NETStandard.Library" version="2.0.3" targetFramework="xamarinios10" />
  <package id="Newtonsoft.Json" version="11.0.2" targetFramework="xamarinios10" />
  <package id="System.AppContext" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Collections" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.ComponentModel.TypeConverter" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Console" version="4.3.1" targetFramework="xamarinios10" />
  <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Globalization" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Globalization.Calendars" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.Compression" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.FileSystem" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Linq" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Linq.Expressions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Net.Http" version="4.3.3" targetFramework="xamarinios10" />
  <package id="System.Net.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Net.Sockets" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.ObjectModel" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Reflection" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Reflection.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Handles" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Serialization.Formatters" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Serialization.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="xamarinios10" />
  <package id="System.Text.Encoding" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Threading" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Threading.Tasks" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Threading.Timer" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Xml.ReaderWriter" version="4.3.1" targetFramework="xamarinios10" />
  <package id="System.Xml.XDocument" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Xml.XmlDocument" version="4.3.0" targetFramework="xamarinios10" />
  <package id="UITextFieldShaker" version="2017.10.19" targetFramework="xamarinios10" />
  <package id="Xam.Plugin.Connectivity" version="3.1.1" targetFramework="xamarinios10" />
  <package id="Xamarin.Forms" version="3.0.0.446417" targetFramework="xamarinios10" />
  <package id="ZXing.Net.Mobile" version="2.3.2" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4" version="4.0.0.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Core" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreAudio" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreData" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreFoundation" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreGraphics" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreImage" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreMedia" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Darwin" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Dispatch" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Foundation" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Metal" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.ObjectiveC" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.OS" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.QuartzCore" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.UIKit" version="4.1.0" targetFramework="xamarinios10" />
</packages>

A: You should remove only the libraries you don't use in your project.
Two weeks ago my ipa file was at almost 200 MB, then I deleted all the Swift libraries that was unnecessary for the project, and now I create smaller ipa files than the previous one (80 MB).
So you need to check your application, see if you have unnecessary libraries and delete it, this way you will reduce the ipa size.

A: I would suggest looking into the 'Linker', which you will find in your iOS build options within Visual Studio
A brief overview:

*

*Don't Link - all assemblies left untouched (largest ipa size)

*Link SDK assemblies only - reduces size of SDK (Xamarin.iOS) assemblies by removing everything that your application doesn't use

*Link all assemblies - reduces size of all assemblies by removing everything that your application doesn't use (smallest ipasize)

Note that 'link all assemblies' can cause issues as the linker can't always determine what is used and can therefore remove code from an assembly that is actually required (think web services, reflection, serialisation). In such cases you can set a manual mtouch argument to prevent a specific assembly (or assemblies) from having being touched by the linker as below:
--linkskip=NameOfAssemblyToSkipWithoutFileExtension

or
--linkskip=NameOfFirstAssembly --linkskip=NameOfSecondAssembly

A real use case I've come across where the above is necessary is when using Entity Framework with Xamarin.iOS, as the linker removes code which is then called using reflection which causes the app to crash.
The full documentation for the Linker is available here: https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/linker?tabs=vsmac


Q: SwiftUI - Changing parent @State doesn't update child View Specific question:
SwiftUI doesn't like us initializing @State using parameters from the parent, but what if the parent holding that @State causes major performance issues?
Example:
How do I make tapping on the top text change the slider to full/empty?

Dragging the slider correctly communicates upwards when the slider changes from full to empty, but tapping the [Overview] full: text doesn't communicate downwards that the slider should change to full/empty.
I could store the underlying Double in the parent view, but it causes major lag and seems unnecessary.
import SwiftUI

// Top level View. It doesn't know anything about specific slider percentages,
// it only knows if the slider got moved to full/empty
struct SliderOverviewView: View {

    // Try setting this to true and rerunning.. It DOES work here?!
    @State var overview = OverviewModel(state: .empty)

    var body: some View {
        VStack {
            Text("[Overview] full: \(overview.state.rawValue)")
                .onTapGesture { // BROKEN: should update child..
                    switch overview.state {
                    case .full, .between: overview.state = .empty
                    case .empty: overview.state = .full
                    }
                }
            SliderDetailView(overview: $overview)
        }
    }
}

// Bottom level View. It knows about specific slider percentages and only
// communicates upwards when percentage goes to 0% or 100%.
struct SliderDetailView: View {

    @State var details: DetailModel

    init(overview: Binding<OverviewModel>) {
        details = DetailModel(overview: overview)
    }

    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(details.percentFull)")

            Slider(value: $details.percentFull)
                .padding(.horizontal, 48)
        }
    }
}

// Top level model that only knows if slider went to 0% or 100%
struct OverviewModel {
    var state: OverviewState

    enum OverviewState: String {
        case empty
        case between
        case full

    }
}

// Lower level model that knows full slider percentage
struct DetailModel {
    @Binding var overview: OverviewModel
    var percentFull: Double {
        didSet {
            if percentFull == 0 {
                overview.state = .empty
            } else if percentFull == 1 {
                overview.state = .full
            } else {
                overview.state = .between
            }
        }
    }

    init(overview: Binding<OverviewModel>) {
        _overview = overview

        // set inital percent
        switch overview.state.wrappedValue {
        case .empty:
            percentFull = 0.0
        case .between:
            percentFull = 0.5
        case .full:
            percentFull = 1.0
        }
    }
}

struct SliderOverviewView_Previews: PreviewProvider {
    static var previews: some View {
        SliderOverviewView()
    }
}

Why don't I just store percentFull in the OverviewModel?
I'm looking for a pattern so my top level @State struct doesn't need to know EVERY low level detail specific to certain Views.
Running the code example is the clearest way to see my problem.
This question uses a contrived example where an Overview only knows if the slider is full or empty, but the Detail knows what percentFull the slider actually is. The Detail has very detailed control and knowledge of the slider, and only communicates upwards to the Overview when the slider is 0% or 100%
What's my specific case for why I need to do this?
For those curious, my app is running into performance issues because I have several gestures that give the user control over progress. I want my top level ViewModel to store if the gesture is complete or not, but it doesn't need to know the specifics of how far the user has swiped. I'm trying to hide this specific progress Double from my higher level ViewModel to improve app performance.

A: Here is working, simplified and refactored answer for your issue:
struct ContentView: View {
    var body: some View {
        SliderOverviewView()
    }
}

struct SliderOverviewView: View {
    @State private var overview: OverviewModel = OverviewModel(full: false)
    var body: some View {
        VStack {
            Text("[Overview] full: \(overview.full.description)")
                .onTapGesture {
                    overview.full.toggle()
                }
            SliderDetailView(overview: $overview)
        }
    }
}

struct SliderDetailView: View {
    @Binding var overview: OverviewModel
    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(tellValue(value: overview.full))")
            Slider(value: Binding(get: { () -> Double in
                return tellValue(value: overview.full)
            }, set: { newValue in
                if newValue == 1 { overview.full = true }
                else if newValue == 0 { overview.full = false }
            }))
        }
    }

    func tellValue(value: Bool) -> Double {
        if value { return 1 }
        else { return 0 }
    }
}

struct OverviewModel {
    var full: Bool
}

Update:
struct SliderDetailView: View {
    @Binding var overview: OverviewModel
    @State private var sliderValue: Double = Double()
    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(sliderValue)")
            Slider(value: $sliderValue, in: 0.0...1.0)
        }
        .onAppear(perform: { sliderValue = tellValue(value: overview.full) })
        .onChange(of: overview.full, perform: { newValue in
            sliderValue = tellValue(value: newValue)
        })
        .onChange(of: sliderValue, perform: { newValue in
            if newValue == 1 { overview.full = true }
            else { overview.full = false }
        })
    }
    func tellValue(value: Bool) -> Double {
        value ? 1 : 0
    }
}

A: I present here a clean alternative using 2 ObservableObject, a hight level OverviewModel that
only deal with if slider went to 0% or 100%, and a DetailModel that deals only with the slider percentage.
Dragging the slider correctly communicates upwards when the slider changes from full to empty,  and
tapping the [Overview] full: text communicates downwards that the slider should change to full/empty.
import Foundation
import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @StateObject var overview = OverviewModel()

    var body: some View {
        SliderOverviewView().environmentObject(overview)
    }
}

// Top level View. It doesn't know anything about specific slider percentages,
// it only cares if the slider got moved to full/empty
struct SliderOverviewView: View {
    @EnvironmentObject var overview: OverviewModel

    var body: some View {
        VStack {
            Text("[Overview] full: \(overview.state.rawValue)")
                .onTapGesture {
                    switch overview.state {
                    case .full, .between: overview.state = .empty
                    case .empty: overview.state = .full
                    }
                }
            SliderDetailView()
        }
    }
}

// Bottom level View. It knows about specific slider percentages and only
// communicates upwards when percentage goes to 0% or 100%.
struct SliderDetailView: View {
    @EnvironmentObject var overview: OverviewModel
    @StateObject var details = DetailModel()

    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(details.percentFull)")
            Slider(value: $details.percentFull).padding(.horizontal, 48)
                .onChange(of: details.percentFull) { newVal in
                    switch newVal {
                    case 0: overview.state = .empty
                    case 1: overview.state = .full
                    default: break
                    }
                }
        }
        // listen for the high level OverviewModel changes
        .onReceive(overview.$state) { theState in
            details.percentFull = theState == .full ? 1.0 : 0.0
        }
    }
}

enum OverviewState: String {
    case empty
    case between
    case full
}

// Top level model that only knows if slider went to 0% or 100%
class OverviewModel: ObservableObject {
    @Published var state: OverviewState = .empty
}

// Lower level model that knows full slider percentage
class DetailModel: ObservableObject {
    @Published var percentFull = 0.0
}


Q: NgRx8 destruct values from action everyone, I would like to destruct action type and props in ngrx effect, I'm in a stuck with how I can do it
My actions:
export const addTab = createAction(
  '[SuperUserTabs] add tab',
  props<{ tab: SuperUserHeaderTab, tabType: TabType }>()
);

export const searchCompanyTab = createAction(
  '[SuperUserTabs] search company tab'
);

export const searchCardholderTab = createAction(
  '[SuperUserTabs] search cardholder tab'
);

Effect:
@Effect({ dispatch: false })
  addTab$ = this.actions$.pipe(
    ofType(
      TabsActions.addTab,
      TabsActions.searchCompanyTab,
      TabsActions.searchCardholderTab
    ),
    withLatestFrom(this.store.pipe(select(getTabs))),
    tap(([action, tabs]) => {
      // destruct here
      const {type, props} = action;
      // some logic
    })
  );

Any suggestions?

A: Updated: ofType accept action creator, so you can using it directly:
@Effect({ dispatch: false })
  addTab$ = this.actions$.pipe(
    ofType(
      TabsActions.addTab,
      TabsActions.searchCompanyTab,
      TabsActions.searchCardholderTab
    ),
    withLatestFrom(this.store.pipe(select(getTabs))),
    tap(([action, tabs]) => {
      // this object will contain `type` and action payload
      const {type, ...payload} = action;
      // some logic
      console.log(payload)
    })
  );

==============
Old answer also work:
because you're using action creator, which return a function, so you can access action type through type property like this:
@Effect({ dispatch: false })
  addTab$ = this.actions$.pipe(
    ofType(
      TabsActions.addTab.type,
      TabsActions.searchCompanyTab.type,
      TabsActions.searchCardholderTab.type
    ),
    withLatestFrom(this.store.pipe(select(getTabs))),
    tap(([action, tabs]) => {
      // this object will contain `type` and action payload
      const {type, ...payload} = action;
      // some logic
      console.log(payload)
    })
  );

demo: https://stackblitz.com/edit/angular-3t2fmx?file=src%2Fapp%2Fstore.ts


Q: onlongclick listner in android 2.0.3 In my java code i used onLongClickListener and opened 1 AlerDailogBox that shows delete or not!!but i want to show some options on my longclick and according to the choice i want to do further.i dont want to use context menu.plz suggest me in current code what changes should i make?
 OnLongClickListener myListener = new OnLongClickListener() {
                         public boolean onLongClick(final View v) {

                         // do something on long click
                         AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();
                         alertDialog.setTitle("Do you want to Delete?");
                         alertDialog.setMessage(" "+temp_name);
                         alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                EstimateTrackerActivity.this.dh.deleteexp(inc_id);
                                /*//Toast.makeText(EstimateTrackerActivity.this, "id"+id,Toast.LENGTH_LONG).show();
                                onclick_addcategory(v);*/
                                onclick_listexpense(v);
                                spinner.setSelection(temp3);
                            }
                         });
                         alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                onclick_listexpense(v);
                                spinner.setSelection(temp3);
                            }
                         });
                         alertDialog.show();
                       return false;
                     }
                 };  tr_inc.setOnLongClickListener(myListener);
                 }

A: Sound from your problem, I think you are new to Android.
Ok, look at code below.
To create an AlertDialog with a list of selectable items like the one shown to the right, use the setItems() method:
final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();

For more info look at Creating an AlertDialog.


Q: Changing text format based on language I have this large MS Word document which contains irregularly formatted text that contains both arabic and english words.
What I want to do is to format this document based on language. Ex: All text in arabic should be 16pt bold and all text in english should be in 14pt italic.
I want to select  all text of a particular langauge so I can change the font. Ability to select all text of a particular font would also be useful since two languages use two different fonts.
Any idea how to do this without going through the whole document manually?

A: Assuming that you have applied language formatting to all of the text, you should be able to do this via Find/Replace.
In Find->Replace, click the "More > > " button if necessary to show the bottom part of the dialog.
Click in the "Find What" box, then click "No Formatting." Then click Format->Language..., and select the language, e.g. Arabic (In the case of Arabic, I think you will need to specify the variant you have used. If you have used more than one, you may need to repeat this process for each).
Then click in the "Replace With". Click "No Formatting" again to clear any formatting. Then click Format->Font... This is where the "catch" is: if you want to specify the font size for the LTR text, you need to specify it in the "Size:" box of the "Latin text" section of the dialog (you can probably ignore the fact that there is also an "Asian text" label there - both types of text share a size. If you want to specify the font size for the RTL text, you need to use the "Size:" box in the "Complex Scripts" section of the dialog.
After that, you should be able to use Replace All to modify the size of all the LTR or RTL text.
If you get that far, it may look as if you could replace the sizes of both types of text all in one by specifying both sizes in "Replace With" and no language in "Find What", but it doesn't work because the relevant buttons remain greyed until you select something in the Find What box.

A: The following option on the Home tab (in Word 2010/2013 at least) might help you:

Note that you'll need to select some text first, then click that option to select all text in the document with similar formatting.

A: You can do this in the following steps.

*

*select the whole contents of your typed word document by pushing Ctr+A buttons.

*go to Formant/ Font menu.

*select Font, Font type and Font size for Latin and Complex scripts.

It is done.


Q: Add column in hive not allowed from scala/spark code I am trying to add a column in a Hive table if the source data has new columns. All the detection of new columns works well, however, when I try to add the column to the destination table, I receive this error:
for (f <- df.schema.fields) {
  if ("[" + f.name + "]"==chk) {
    spark.sqlContext.sql("alter table dbo_nwd_orders add columns (" + f.name + " " + f.dataType.typeName.replace("integer", "int") + ")")
  }
}

Error:
WARN HiveExternalCatalog: Could not alter schema of table  `default`.`dbo_nwd_orders` in a Hive compatible way. Updating Hive metastore in Spark SQL specific format
InvalidOperationException(message:partition keys can not be changed.)

However, if I catch the alter sentence generated and execute it from hive GUI (HUE), I can add it without issues.
alter table dbo_nwd_orders add columns (newCol int)

Why that sentence is valid from the GUI and not from spark code?
Thank you very much.

A: It has been said multiple times here, but just to reiterate - Spark is not Hive interface and is not designed for full Hive compatibility in terms of language (Spark targets SQL standard, Hive uses custom SQL-like query language) or capabilities (Spark is ETL solution, Hive is a Data Warehousing solution).
Even data layouts are not fully compatible between these two.
Spark with Hive support is Spark with access to Hive metastore, not Spark that behaves like Hive.
If you need to access full set of Hive's features connect to Hive directly with native client or native (not Spark) JDBC connection, and use interact with it from there.


Q: Cannot resolve method 'setText(java.lang.String am trying to add a library called smooth check box while I trying to cast it it showed me an error Cannot resolve method 'setText(java.lang.String '
this is my Class
............................................................................
package abtech.waiteriano.com.retrievingcontactsexample;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.refactor.library.SmoothCheckBox;

/**
 * Created by Trinity Tuts on 10-01-2015.
 */
public class SelectUserAdapter extends BaseAdapter {

    public List<SelectUser> _data;
    private ArrayList<SelectUser> arraylist;
    Context _c;
    ViewHolder v;

    public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
        _data = selectUsers;
        _c = context;
        this.arraylist = new ArrayList<SelectUser>();
        this.arraylist.addAll(_data);
    }

    @Override
    public int getCount() {
        return _data.size();
    }

    @Override
    public Object getItem(int i) {
        return _data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        View view = convertView;
        if (view == null) {
            LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.contact_list_item, null);
            Log.e("Inside", "here--------------------------- In view1");
        } else {
            view = convertView;
            Log.e("Inside", "here--------------------------- In view2");
        }

        v = new ViewHolder();

        v.check = (SmoothCheckBox) view.findViewById(R.id.contactsCB);

        final SelectUser data = (SelectUser) _data.get(i);
        v.check.setText(data.getName());
        v.check.setChecked(data.getCheckedBox());;

        Log.e("Image Thumb", "--------------" + data.getThumb());

        /*// Set check box listener android
        v.check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    data.setCheckedBox(true);
                  } else {
                    data.setCheckedBox(false);
                }
            }
        });*/

        view.setTag(data);
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        _data.clear();
        if (charText.length() == 0) {
            _data.addAll(arraylist);
        } else {
            for (SelectUser wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    _data.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
    static class ViewHolder {
        SmoothCheckBox check;
    }
}

and the error in this line
v.check.setText(data.getName());

android Monitor Error
Information:Gradle tasks [:app:assembleDebug]
E:\AndroidWorkSpace\RetrievingContactsExample\app\src\main\java\abtech\waiteriano\com\retrievingcontactsexample\SelectUserAdapter.java
Error:(69, 16) error: cannot find symbol method setText(String)
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1.206 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console

............................................................................
I don't know how to solve this error it's ma pleasure if any could help me
sorry of any thing is not clear I hope this gonna be understandable
............................................................................

A: I assume you mean this SmoothCheckBox on github.
Looking at the source code, one finds no setText(String)-method. If I understand the readme correctly, those check boxes are designed to have a selected and unselected color, but no text.


Q: Can I mount Google cloud storage bucket to a pod as a persistent disk. If yes how? I have a gke cluster with nodes in 3 different Zones but same region. I want to use persistent disks to my pods. But the pods are created randomly in all the 3 zones.How can I use a gcePD (common for all the nodes). or Can I add the storage bucket in the pod deployment (Yaml) file. If it is podssible .kindly suggest me how to do it?

A: Follow this github link. You need to install fuse in the image. Your container should be in previliged mode and you need to use lifecycle.
https://github.com/maciekrb/gcs-fuse-sample


Q: Doubts on $ \lim_{x \rightarrow 0 } (1+\sin x) ^{\frac{1}{x}}$ . What is the limit of the following expression :
$$\lim_{x \rightarrow 0 } (1+\sin x) ^{\frac{1}{x}}$$
I tried doing the following :
$$\lim_{x \rightarrow 0 } (1+\sin x) ^{{\frac{1}{\sin x}}{\frac{\sin x }{x}}}$$
Now I know the formula $\lim_{x \rightarrow 0} (1+x)^{\frac{1}{x}} = e$ . I can do that in the above expression for $\sin x \rightarrow 0$ .
But I'm not sure if the limit $\lim_{x \rightarrow 0}$ can propagate up-to the power.  If not,  if I take $ln$ in both sides,  can then the limit propagate into the expression within the $ln$ operator ?

A: It is good to take $\log$ when you are solving $1^{\infty}$ limits
$$y=\lim_{x \rightarrow 0 } (1+\sin x) ^{\frac{1}{x}}$$
$$\log y=\lim_{x \rightarrow 0 } \frac{\log ({1+\sin x})}{x}$$
now use LHopital rule on the right hand side limit
it becomes
$$\log y=\lim_{x \rightarrow 0 } \frac{\cos x}{1+\sin x}=1$$
$$\log y=1$$
$$y=e^1$$

A: You basically figured it out already. As all mentioned functions are continuous, we have:
$$\lim_{x\to 0} (1+\sin x)^{\frac{1}{x}} = \lim_{x\to 0} (1+\sin x)^{\frac{1}{\sin x}\frac{\sin x}{x}}=\lim_{x\to 0} ((1+\sin x)^{\frac{1}{\sin x}})^{\frac{\sin x}{x}} = (\lim_{x\to 0}((1+\sin x)^{\frac{1}{\sin x}}))^{\lim_{x\to 0}\frac{\sin x}{x}} =e^{\lim_{x\to 0}\frac{\sin x}{x}}=e^1=e$$
I will leave to part to argue, that $\lim_{x\to 0}((1+\sin x)^{\frac{1}{\sin x}})=e$ to you though.

A: Start by rewriting by following the exponential rule:
\begin{equation}
\lim_{x\to 0} (1+\sin(x))^\frac{1}{x} =\lim_{x\to 0} e^{\frac{\ln(1+\sin(x))}{x}}.
\end{equation}
Using the chain rule, let everything in the exponent become the inner function. Then, simplify the inner function using L'Hopital's Rule:
\begin{equation}
\lim_{x\to 0} \frac{\ln(1+\sin(x))}{x} = \lim_{x\to0}\frac{\cos(x)}{sin(x)+1}
\\ = \frac{\cos(0)}{sin(0)+1} = 1.
\end{equation}
Finally, plug in the result from the inner function into the outer function to obtain the desired answer:
\begin{equation}
\lim_{u\to 1} e^{u} = e.
\end{equation}

A: You have correctly written
$$ \lim_{x\to 0}(1+\sin x)^{1/x} = \lim_{x\to 0} f(x)^{g(x)} $$
where $f(x)=(1+\sin x)^{1/\sin x}$ and $g(x)=(\sin x)/x$.
Since $f(x) \to e$ and $g(x)\to 1$ and $(a,b)\mapsto a^b$ is known to be continuous at $(e,1)$ you can safely take limits of $f$ and $g$ separately, and thereby find that the original limit is $e$.

A: Limits of $f(x)^{g(x)}$ in an indeterminate form are usually best treated by computing the limit of $\log(f(x)^{g(x)})=g(x)\log f(x)$. If $l$ is the limit you find, then the original one is $e^l$, when $l$ is finite; if $l=-\infty$, the original limit is $0$; if $l=\infty$, the original limit is $\infty$. This follows from the continuity of the exponential function and of its inverse, the (natural) logarithm.
In your case, you have to find
$$
\lim_{x\to0}\log\bigl((1+\sin x)^{1/x}\bigr)=
\lim_{x\to0}\frac{\log(1+\sin x)}{x}=
\lim_{x\to0}\frac{\sin x+o(\sin x)}{x}=
\lim_{x\to0}\frac{x+o(x)}{x}=1
$$
(using $\log(1+t)=t+o(t)$ and $\sin x=x+o(x)$). Thus
$$
\lim_{x\to0}(1+\sin x)^{1/x}=e^1=e
$$


Q: Does git create new files during merge or overwrite existing ones I have a script test.sh
#!/bin/bash
echo start old file
sleep 20
echo end old file

in the repository which I do execute, and in the mean time I git merge other-branch changes like
#!/bin/bash
echo start new file
sleep 20
echo end new file

into the current branch.
It seems that git on Unix (?) does not directly overwrite the existing file node (?) and does instead rm test.sh and creates the new file.
In that way its guaranteed that the script execution will always read the initial file test.sh and terminate with echo end old file.
Note: On my system (Ubuntu 20.04), while executing the script and directy overtwriting the content in an editor, results in executing the new code, which is bad...
Is that correct and is it also correct on Windows with git-for-windows?

A: I can't answer regarding Windows, but on Ubuntu 18.04 I can confirm that a git checkout or git merge will delete and recreate a changed file, rather than editing it in place.  This can be seen in strace output, for example:
unlink("test.sh")                       = 0

followed later by
openat(AT_FDCWD, "test.sh", O_WRONLY|O_CREAT|O_EXCL, 0666) = 4

It can also be seen if you create a hard link to the file before the git command and then look again afterwards, you will see that you have two different inodes, with different contents.  This is to be expected following deletion and recreation, whereas an in-place edit would have preserved the hard linking.
$ ls -l test.sh
-rw-r--r-- 1 myuser mygroup 59 Jun  5 17:04 test.sh

$ ln test.sh test.sh.bak

$ ls -li test.sh*
262203 -rw-r--r-- 2 myuser mygroup 59 Jun  5 17:04 test.sh
262203 -rw-r--r-- 2 myuser mygroup 59 Jun  5 17:04 test.sh.bak

$ git merge mybranch
Updating 009b964..d57f33a
Fast-forward
 test.sh | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

$ ls -li test.sh*
262219 -rw-r--r-- 1 myuser mygroup 70 Jun  5 17:05 test.sh
262203 -rw-r--r-- 1 myuser mygroup 59 Jun  5 17:04 test.sh.bak

You mentioned in a comment attached to the question that it is related to Overwrite executing bash script files.  Although it would seem not to be the best idea to run a git command affecting a script which is currently still being executed, in fact the delete and recreate behaviour should mean that the existing execution will be unaffected.  Even if the bash interpreter has not yet read the whole file into memory, it will have an open filehandle on the existing inode and can continue to access its contents even though that inode is no longer accessible via the filename that it had.  See for example What happens to an open file handle on Linux if the pointed file gets moved or deleted

A: On Windows with git-for-windows I see the same behavior:
$ mklink /H test.sh.bak
$ fsutil hardlink list test.sh.bak
test.sh.bak
test.sh
$ git merge test
$ fsutil hardlink list test.sh.bak
test.sh.bak

Meaning the hard link did not get preserved, meanin a new file has been created.


Q: footer sum data canot sum all data in serverside datatables i have a model like here
https://pastebin.com/HLNQZgkg
public function data_json_judulbuku() {
    error_reporting(-1);
    if( isset($_GET['id']) ){
        $id = $_GET['id'];
    }else{
        $id = '';
    }

and javascript to access datatable
https://pastebin.com/f2NrFbBr
i canot sum all data in datatables, the sum just page listed
result footer sum
total value must 135 and curent page 15 but on display total 15 and curent page 15


Q: varargs parameter list created at runtime public static void method(Set<?>... sets){}

Depending on program flow, above method is called with two sets, or with three sets, or more. (Not known at compile time).
Is there a way to constructing the argument list "on the fly"?
sets is of type Set< ?>[ ]
Following was not fruitful:
Set<Set<Integer>> varargs = new HashSet<Set<Integer>>();

(method recognizes varargs just as one set -> no solution)
Set<Integer>[] varargs = new HashSet<Integer>[2];

returns
"Cannot create generic array of HashSet<Integer>"

I would like to construct an array of arguments, while array size and content is filled at runtime.

A:  Set<Integer>[] varargs = new HashSet[2];
 varargs[0] = new HashSet<Integer>() ;

A: I believe array of Set should be defined like this:
Set<Integer>[] varargs = new Set[2];
varargs[0] = new HashSet<Integer>();
varargs[1] = new HashSet<Integer>();


Q: cmdline of vim on mac terminal or iTerm2 disappear very slow I type : and then type esc key to exit command mod, the cmdline disappear very slow, about 1s-2s, which actually you are in normal already.

A: vim is waiting a short time to allow for the possibility that the esc key might begin a special key (such as cursor-left or F1).
You can alter this behavior altering these settings: ttimeout, timeoutlen
and ttimeoutlen.
The timeoutlen mode is set by default to 1 second (1000 milliseconds).  If you set that to a shorter time (0.1 seconds is fast), it will help.
Some suggest (as in vim's documentation) reducing the timeout, e.g.,
set ttimeout set ttimeoutlen=100

Related discussion:

*

*Vim Command Line Escape Timeout

*Eliminating delays on ESC in vim and zsh


Q: Getting this error when I use IBM Watson Tone Analyzer API. How can I resolve this? requests.exceptions.ConnectionError:
    HTTPSConnectionPool(host='api.eu-gb.tone-analyzer.watson.cloud.ibm.com', port=443):
    Max retries exceeded with url:
        /instances/76db955a-ebbb-46c9-a9ca-121542253a0c/v3/tone?version=2017-09-21&sentences=true
    (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x05533928>:
    Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))`

The output console shows a part of the output I am getting while printing at runtime and then this max retries exceeded error message pops up. Please revert back as soon as possible.


Q: Firebase authentication phone number for android: SMS template in different languages I am using sms Firebase authentication on the android application. However, the SMS I am receiving is weird: Part of it is sometimes English and part of it is Arabic and the rest of the SMS I can't make out actually.

How to make the SMS's language received only Arabic without the other characters?

A: Check whether your phone language and Firebase console are same. Otherwise this can happen. Firebase rechecks the locale of the phone that's causing the issue.


Q: Create Pivot Table and get Count in Pandas Dataframe I have my dataframe -
import pandas as pd
data = [['2233', 'A', 'FY21'], ['441', 'C', 'FY20'], ['6676', 'A', 'FY19'], ['033', 'C', 'FY16'],
       ['12', 'A', 'FY18'], ['91', 'B', 'FY15'], ['6676', 'C', 'FY10'], ['441', 'C', 'FY17'],
       ['12', 'A', 'FY14'], ['441', 'C', 'FY12']]
df = pd.DataFrame(data, columns = ('emp_id', 'category', 'year'))
df

emp_id   category   year
0   2233    A       FY21
1   441     C       FY20
2   6676    A       FY19
3   033     C       FY16
4   12      A       FY18
5   91      B       FY15
6   6676    C       FY10
7   441     C       FY17
8   12      A       FY14
9   441     C       FY12

So basically I want the categories should be created as individual column i.e A, B, & C and each column should contain the counts of them.
What I want as my output -
emp_id    A   B   C
0   2233  1
1   441           3
2   6676  1
3   033           1
4   12    2
5   91        1
6   6676          1

What I was trying -
df['count'] = df.groupby(['emp_id'])['category'].transform('count')
df.drop_duplicates('emp_id', inplace = True)
df
emp_id  category year   count
0   2233    A    FY21   1
1   441     C    FY20   3
2   6676    A    FY19   2
3   033     C    FY16   1
4   12      A    FY18   2
5   91      B    FY15   1

please help me to get my desired output in python.

A: Use pd.crosstab:
df1 = pd.crosstab(df['emp_id'], df['category']).rename_axis(
    columns=None).reset_index()

OUTPUT:
  emp_id  A  B  C
0    033  0  0  1
1     12  2  0  0
2   2233  1  0  0
3    441  0  0  3
4   6676  1  0  1
5     91  0  1  0

NOTE:
If you don't need 0 in the output you can use:
df = pd.crosstab(df['emp_id'],  df['category']).rename_axis(
    columns=None).reset_index().replace(0, '')

OUTPUT:
  emp_id  A  B  C
0    033        1
1     12  2
2   2233  1
3    441        3
4   6676  1     1
5     91     1

Updated Answer:
df = (
    df.reset_index()
    .pivot_table(
        index=['emp_id', df.groupby('emp_id')['year'].transform(', '.join)],
        columns='category',
        values='index',
        aggfunc='count',
        fill_value=0)
    .rename_axis(columns=None)
    .reset_index()
)

OUTPUT:
  emp_id              year  A  B  C
0    033              FY16  0  0  1
1     12        FY18, FY14  2  0  0
2   2233              FY21  1  0  0
3    441  FY20, FY17, FY12  0  0  3
4   6676        FY19, FY10  1  0  1
5     91              FY15  0  1  0

A: You can also use pivot table:
pv = pd.pivot_table(df, index='emp_id', columns='category', aggfunc='count')
pv.fillna('', inplace=True)

print(pv)

         year
category    A  B  C
emp_id
033               1
12          2
2233        1
441               3
6676        1     1
91             1


Q: I wonder how to create a proportional table for one categorical variable and one numerical variable (numerical data is proportion)? library(ggplot2)
library(tidyverse)
library(dplyr)
aqi <- read.csv("aqi12_21.csv")
aqi <- select(aqi,State.Name,county.Name,Date,AQI,Category,Defining.Parameter)
aqi <- rename(aqi,State=State.Name,County=county.Name)
aqi <- separate(aqi, Date, c("Year", "Month", "Day"))
AQI_HIGH<-filter(aqi,AQI>100)
average_aqi_state <- AQI_HIGH %>% group_by(State) %>% summarise(average_aqi = mean(AQI))

So I have my average data which looks like:

I don't know how to create a proportional graph (average aqi is shown in percentage) while the state remains categorical variable

A: Suppose this simplified form of data represents your actual data:
dat <- structure(list(State = c("Alabama", "Alaska", "Arizona", "Others"
), average_aqi = c(300, 550, 150, 1000)), class = "data.frame", row.names = c(NA,
-4L))

If I understand your purpose correctly, you want to get the proportion of average_aqi in this way:
dat |> mutate(avaqi_perc = average_aqi/sum(average_aqi))

#    State average_aqi avaqi_perc
#1 Alabama         300      0.150
#2  Alaska         550      0.275
#3 Arizona         150      0.075
#4  Others        1000      0.500


Q: Is there a way to change the browser's address bar without refreshing the page? I'm developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content.
After the user clicked the category I want to change the browser's address bar url from
www.mysite.com/products

to something like
www.mysite.com/products/{selectedCat}

without refreshing the page.
Is there some kind of JavaScript API I can use to achieve this?

A: I believe directly manipulating the address bar to a completely different url without moving to that url isn't allowed for security reasons, if you are happy with it being
www.mysite.com/products/#{selectedCat}
i.e. an anchor style link within the same page then look into the various history/"back button" scripts that are now present in most javascript libraries.
The mention of update panel leads me to guess you are using asp.net, in that case the asp.net ajax history control is a good place to start

A: To add to what the guys have already said edit the window.location.hash property to match the URL you want in your onclick function.
window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name

A: I don't think this is possible (at least changing to a totally different address), as it would be an unintuitive misuse of the address bar, and could promote phishing attacks.

A: With HTML5 you can modify the url without reloading:
If you want to make a new post in the browser's history (i.e. back button will work)
window.history.pushState('Object', 'Title', '/new-url');

If you just want to change the url without being able to go back
window.history.replaceState('Object', 'Title', '/another-new-url');

The object can be used for ajax navigation:
window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');

window.onpopstate = function (e) {
  var id = e.state.id;
  load_item(id);
};

Read more here: http://www.w3.org/TR/html5-author/history.html
A fallback sollution: https://github.com/browserstate/history.js

A: This cannot be done the way you're saying it. The method suggested by somej.net is the closest you can get. It's actually very common practice in the AJAX age. Even Gmail uses this.

A:
"window.location.hash"

as suggested by sanchothefat should be the one and only way of doing it. Because all the places that I have seen this feature, it's all the time after the # in URL.


Q: jquery $.post, to django view method, request.method shows GET, and cannot retrieve parameters I'm trying to figure out how I can send some data to a view in django vis POST, and return some data, depending on the data sent in the request, from the view to the client via an HttpResponse.
When the POST request is sent from the client, the web console prints,
POST http://<myurl>
GET  http://<myurl>/

And the message returned is "get".  In the view method, When I try to access the parameters via response.GET.get("key"), None is returned.
I must be misunderstanding something, anyone know what is going on?
views.py
    from django.http import HttpResponse

    def test(request):

        msg = ""

        if request.method == "POST":
            msg = "post"

        elif request.method == "GET":
            msg = "get"

        return HttpResponse(msg)

javascrip/jquery
  function _req(url, params, callback ) {

    function onResponse( data ) {
      console.log( data );
      callback(data);
    };

    $.post(
      url,
      JSON.stringify(params),
      onResponse,
      "text");
   };

A: The two URLs that are printed show exactly what is happening. You are posting to a URL without a final slash, but you have the default APPEND_SLASH setting, so Django is redirecting to the URL with a final slash appended. Redirects are always GETs.
Make sure you post to the URL with the slash.


Q: Is the sequence space $\ell^p$ closed under the Cauchy product? Given that two formal power series have coefficients in $\ell^p$,
$$a(x)=\sum_{n=0}^\infty a_nx^n,\quad\sum_{n=0}^\infty|a_n|^p<\infty$$
$$b(x)=\sum_{n=0}^\infty b_nx^n,\quad\sum_{n=0}^\infty|b_n|^p<\infty,$$
does it follow that their product $a(x)b(x)$ also has coefficients in $\ell^p$?
I'm particularly interested in the case $p=2$ (Hilbert space).

I've found that the multiplication operator is unbounded with respect to the $\ell^2$ norm; consider the polynomials
$$p_n(x)=\frac{1-x^n}{1-x}=1+x+x^2+\cdots+x^{n-1}.$$
$$\lVert p_n\rVert_2^2=n$$
$$p_n(x)^2=1+2x+3x^2+\cdots+(n-1)x^{n-2}+nx^{n-1}+(n-1)x^n+\cdots+2x^{2n-3}+x^{2n-2}$$
$$\lVert p_n\!^2\rVert_2^2=2(1^2+2^2+3^2+\cdots+n^2)-n^2$$
$$=2\frac{n(n+1)(2n+1)}{6}-\frac{n(3n)}{3}$$
$$=\frac{n(2n^2+1)}{3}$$
So for all $n$,
$$\sup_{a,b}\frac{\lVert ab\rVert_2}{\lVert a\rVert_2\lVert b\rVert_2}\geq\sup_a\frac{\lVert a^2\rVert_2}{\lVert a\rVert_2^2}\geq\frac{\lVert p_n\!^2\rVert_2}{\lVert p_n\rVert_2^2}=\sqrt\frac{2n^2+1}{3n}$$
and thus $$\sup_{a,b}\frac{\lVert ab\rVert_2}{\lVert a\rVert_2\lVert b\rVert_2}=\infty.$$
But is this supremum actually a maximum? Is there any case where $\lVert a\rVert_2$ and $\lVert b\rVert_2$ are finite, but $\lVert ab\rVert_2$ is infinite?

A: For $p\leq1$, using the concavity condition $(|x|+|y|)^p\leq|x|^p+|y|^p$, we have
$$\lVert ab\rVert_p^p=|a_0b_0|^p+|a_1b_0+a_0b_1|^p+|a_2b_0+a_1b_1+a_0b_2|^p+\cdots$$
$$\leq|a_0b_0|^p+(|a_1b_0|+|a_0b_1|)^p+(|a_2b_0|+|a_1b_1|+|a_0b_2|)^p+\cdots$$
$$\leq|a_0b_0|^p+|a_1b_0|^p+|a_0b_1|^p+|a_2b_0|^p+|a_1b_1|^p+|a_0b_2|^p+\cdots$$
$$=(|a_0|^p+|a_1|^p+|a_2|^p+\cdots)(|b_0|^p+|b_1|^p+|b_2|^p+\cdots)$$
$$=\lVert a\rVert_p^p\lVert b\rVert_p^p$$
$$<\infty$$
so $\ell^p$ is closed under multiplication. (And $\ell^1$ is also a Banach algebra.)

For $p>1$, consider for example the function
$$a_3(x)=\frac{1}{\sqrt[3]{1-x}}$$
whose third power's coefficients are clearly not in any $\ell^p$ (except $\ell^\infty$, but even that is lost by squaring again) :
$$a_3(x)^3=\frac{1}{1-x}=1+x+x^2+x^3+\cdots$$
But $a_3$ itself is in some $\ell^p$, which would therefore not be closed under multiplication. Indeed, from the binomial theorem,
$$a_3(x)=1+\Big(\frac13\Big)x+\Big(\frac13\cdot\frac43\Big)\frac{x^2}{1\cdot2}+\Big(\frac13\cdot\frac43\cdot\frac73\Big)\frac{x^3}{1\cdot2\cdot3}+\cdots$$
$$=1+\frac13x+\frac{1\cdot4}{3\cdot6}x^2+\frac{1\cdot4\cdot7}{3\cdot6\cdot9}x^3+\cdots.$$
Now, taking inspiration from this question to use the AM-GM inequality,
$$3n=\frac{(3n-2)+(3n+1)+(3n+1)}{3}\geq\sqrt[3]{(3n-2)(3n+1)(3n+1)}$$
so the coefficients of $a_3(x)$ are
$$\frac{1\cdot4\cdot7\cdots(3n-5)\cdot(3n-2)}{3\cdot6\cdot9\cdots(3n-3)\cdot(3n)}$$
$$\leq\frac{1\cdot4\cdot7\cdots(3n-5)\cdot(3n-2)}{(\sqrt[3]{1}\cdot\sqrt[3]{4}^2)\cdot(\sqrt[3]{4}\cdot\sqrt[3]{7}^2)\cdots(\sqrt[3]{3n-5}\cdot\sqrt[3]{3n-2}^2)\cdot(\sqrt[3]{3n-2}\cdot\sqrt[3]{3n+1}^2)}$$
$$=\frac{1}{\sqrt[3]{3n+1}^2}$$
which implies
$$\lVert a_3\rVert_p^p\leq\sum_{n=0}^\infty\frac{1}{(3n+1)^{2p/3}}.$$
This is finite for $\frac23p>1$, that is, $p>\frac32$. So for any such $p$ (including $p=2$), $a_3$ is in $\ell^p$ and $a_3\!^3$ is not.
Similar arguments applied to the functions
$$a_m(x)=\frac{1}{\sqrt[m]{1-x}}$$
show that, for $p>\frac{m}{m-1}$, $a_m$ is in $\ell^p$ and $a_m\!^m$ is not. Therefore, for any $p>1$, $\ell^p$ is not closed under multiplication.


Q: No trusted certificate found using CAS and JBoss I'm trying to authenticate through CAS+LDAP in a Jboss app. The config is like this:

*

*Server 1: Jboss 6.10. Cas is deployed here.

*Server 1: LDAP using OpenDS.

*Server 2: Jboss whith the app to login into.

I've configured both jboss to use SSL correctly and the CAS succesfyuly reads and authenticates against the LDAP.
When I get to (through https) server1:8443/app/ i'm redirected to server2:8443/cas/ and the login screen is displayed. I login with a valid user on the LDAP but when the flow gets back to the app i'm always getting this:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found

I've read its a certificate problem and, as it is a dev enviroment i'm trying the self-signed certificate. So I did this:

*

*Gen the self signed in Server1 with
keytool -genkey -alias jbosskey -keypass password -keyalg RSA -keystore server.keystore

*Get the certificate of the Server1 with:
keytool -export -alias jbosskey -keypass password -file server.crt -keystore server.keystore

*Copy the server.crt to Server2 and import it to the truststore of Jboss.
keytool -import -alias server1 -file server.crt -keystore C:\dev\jboss-6.1.0.Final\server.truststore

*This gets me the eception. So I also imported to the cacerts of the JVM.
keytool -import -alias server1 -file server.crt -keystore C:\dev\jdk160_18\jre\lib\security\cacerts

*Not working, so I tried to add the certificate to the keystore of the Jboss at Server2.
keytool -import -alias server1 -file server.crt -keystore C:\dev\jboss-6.1.0.Final\keystore.jks
The Server1 Jboss server.xml
  <Connector protocol="HTTP/1.1" SSLEnabled="true"
       port="${jboss.web.https.port}" address="${jboss.bind.address}"
       scheme="https" secure="true" clientAuth="false"
       keystoreFile="${jboss.server.home.dir}/conf/server.keystore"
       keystorePass="password" sslProtocol = "TLS"
/>

The Server2 Jboss server.xml
<Connector protocol="HTTP/1.1" SSLEnabled="true"
            port="8443" address="${jboss.bind.address}"
            scheme="https" secure="true" clientAuth="false"
            keystoreFile="C:\dev\jboss-6.1.0.Final\keystore.jks"
            keystorePass="password"
            truststoreFile="C:\dev\jboss-6.1.0.Final\server.truststore"
            truststorePass="password"
            sslProtocol = "TLS" />

I've been stuck on this for a couple of days and don't know if i'm missing something. Did I missed something important with the keytool?
Thanks in advance.


Q: How to get SetBinding method I need to do something like this:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/982e2fcf-780f-4f1c-9730-cedcd4e24320/
I decided to follow the best way as John Smith advised.
I tried to set binding in xaml, it didn't work (target was always null).
I decide to set binding manually in code (for debugging purpose), so I need to execute "SetBinding" method of the DateRange object.
This method doesn't exists in object of type DateRange.
Any ideas?
<TextBox Grid.Row="1"
         Grid.Column="1"
         Name="Xml_Name"
         >
    <TextBox.Text>
        <Binding XPath="@name" UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
                <local:UniqueValidationRule x:Name="uniqueDatasourcesRule001" >
                    <local:UniqueValidationRule.UniqueCollection>
                        <local:UniqueDependencyObject uu="{Binding  ElementName=Xml_Name, Path=Name, UpdateSourceTrigger=PropertyChanged}" />
                    </local:UniqueValidationRule.UniqueCollection>
                </local:UniqueValidationRule>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

public class UniqueDependencyObject : DependencyObject
{
    public static readonly DependencyProperty uu11Property =
        DependencyProperty.Register("uu", typeof(string), typeof(UniqueDependencyObject));

    public string uu
    {
        set {
            SetValue(uu11Property, value); }
        get {
            return (string)GetValue(uu11Property); }
    }

}

public class UniqueValidationRule : ValidationRule
{
    public UniqueDependencyObject UniqueCollection
    {
        get;
        set;
    }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        // I set breakpoint to this line and check UniqueCollection.uu - it is always null
        ////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////
        return new ValidationResult(true, null);
    }
}

//  And binding in code:
                Binding binding = new Binding();
            binding.ElementName = "Xml_Name";
            binding.Path = new System.Windows.PropertyPath("Name");
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

            UniqueValidationRule uVal = new UniqueValidationRule();
            uVal.UniqueCollection = new UniqueDependencyObject();

            BindingOperations.SetBinding(uVal.UniqueCollection, UniqueDependencyObject.uu11Property, binding);

A: I haven't read all the details of the forum post you're referring to, but i'm sure you need to know a few things about data binding before you can start using it.

*

*The target of a data binding is a dependency
property

*A dependency property has to be declared in a class that is derived from DependencyObject (at least when it is not an attached property, but we don't talk about those here)

*The SetBinding method you're looking for is either a static method in BindingOperations, or a method of FrameworkElement.
So when you're going to set up a binding on some property of your DataRange class, it would have to be derived from DependencyObject, and you would set the binding like this:
DataRange dataRange = ...
Binding binding = ...
BindingOperations.SetBinding(dataRange, DataRange.StartProperty, binding);

If DataRange were derived from FrameworkElement, you could write this:
dataRange.SetBinding(DataRange.StartProperty, binding);

Here DataRange.StartProperty is of type DependencyProperty and represents the Start dependency property of class DataRange.
You should at least read the MSDN articles Data Binding Overview, Dependency Properties Overview and Custom Dependency Properties.


Q: How to implement the generalized form of std::same_as (i.e. for more than two type parameters) that is agnostic to parameter order? Background
We know that the concept std::same_as is agnostic to order (in other words, symmetric): std::same_as<T, U> is equivalent to std::same_as<U, T> (related question). In this question, I would like to implement something more general: template <typename ... Types> concept same_are = ... that checks whether types in the pack Types are equal to each other.
My attempt
#include <type_traits>
#include <iostream>
#include <concepts>

template <typename T, typename... Others>
concept same_with_others = (... && std::same_as<T, Others>);

template <typename... Types>
concept are_same = (... && same_with_others<Types, Types...>);

template< class T, class U> requires are_same<T, U>
void foo(T a, U b) {
    std::cout << "Not integral" << std::endl;
}

// Note the order <U, T> is intentional
template< class T, class U> requires (are_same<U, T> && std::integral<T>)
void foo(T a, U b) {
    std::cout << "Integral" << std::endl;
}

int main() {
    foo(1, 2);
    return 0;
}

(My intention here is to enumerate over every possible ordered pair of types in the pack)
Unfortunately, this code would not compile, with the compiler complaining that the call to foo(int, int) is ambiguous. I believe that it considers are_same<U, T> and are_same<T, U> as not equivalent. I would like to know why the code fails how I can fix it (so that the compiler treats them as equivalent)?

A: From cppreference.com Constraint_normalization

The normal form of any other expression E is the atomic constraint whose expression is E and whose parameter mapping is the identity mapping. This includes all fold expressions, even those folding over the && or || operators.

So
template <typename... Types>
concept are_same = (... && same_with_others<Types, Types...>);

is "atomic".
So indeed are_same<U, T> and are_same<T, U> are not equivalent.
I don't see how to implement it :-(

A: The problem is, with this concept:
template <typename T, typename... Others>
concept are_same = (... && std::same_as<T, Others>);

Is that the normalized form of this concept is... exactly that. We can't "unfold" this (there's nothing to do), and the current rules don't normalize through "parts" of a concept.
In other words, what you need for this to work is for your concept to normalize into:
... && (same-as-impl<T, U> && same-as-impl<U, T>)

into:
... && (is_same_v<T, U> && is_same_v<U, T>)

And consider one fold-expression && constraint to subsume another fold-expression constraint && if its underlying constraint subsumes the other's underlying constraint. If we had that rule, that would make your example work.
It may be possible to add this in the future - but the concern around the subsumption rules is that we do not want to require compilers to go all out and implement a full SAT solver to check constraint subsumption. This one doesn't seem like it makes it that much more complicated (we'd really just add the && and || rules through fold-expressions), but I really have no idea.
Note however that even if we had this kind of fold-expression subsumption, are_same<T, U> would still not subsume std::same_as<T, U>. It would only subsume are_same<U, T>. I am not sure if this would even be possible.

A: churill is right .Using std::conjunction_v might be helpful.
   template <typename T,typename... Types>
   concept are_same = std::conjunction_v<std::same_as<T,Types>...>;


Q: Разметка элемента Интересующий пример
В данном элементе есть общий контейнер и два внутри него, один из них "полоса с градиентом", а второй описание, тобишь description. Изначально задана высота в 90пкс, но после добавления большого количества текста див описания растягивается, как сделать что б вместе с ним тянулась и полоса с градиентом ?
A: Мне кажется, что самым простым вариантом будет HTML5 и CSS3: например, так
A: нужно что бы градиент был родителем "описания" и с width:auto; а лучше вобще код привести


Q: How to scalar multiply array Write a method scalarMultiply which takes as input a double[] array, and a double scale, and returns void. The method should modify the input array by multiplying each value in the array by scale.
. Question to consider: When we modify the input array, do we actually modify the value of the
variable
array
?
Here is what i did until now, but i dont know what i did wrong because it still is not working.
public class warm4{

  public static void main(String[] args){
    double[] array1 = {1,2,3,4};
     double scale1 = 3;
    }
 }
   public static void scalarMultiply(double[] array, double scale){
     for( int i=0; i<array.length; i++){
     array[i] = (array[i]) * scale;
     System.out.print(array[i] + " ");
     }
   }
 }

A: You're never calling the scalarMultiply method.

A: You're never calling scalarMultiply and the number of the brackets is incorrect.
public class warm4{

  public static void main(String[] args){
     double[] array1 = {1,2,3,4};
     double scale1 = 3;
     scalarMultiply(array1, scale1);
   }

   public static void scalarMultiply(double[] array, double scale){
       for( int i=0; i<array.length; i++){
       array[i] = (array[i]) * scale;
       System.out.print(array[i] + " ");
     }
   }
 }

A: Your method is OK. But you must call it from your main:
public static void main(String[] args){
    double[] array1 = {1,2,3,4};
    double scale1 = 3;
    scalarMultiply(array1, scale1);
    for (int i = 0; i < array1.length; i++) {
        System.out.println(array1[i]);
    }
}


Q: Animate not queueing correctly I have this working code for moving a heading icon forth and back if you hover over heading
jQuery('h1.heading').hover(
  function(){
    $icon = jQuery('.heading-icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
          $icon.animate({ "margin-left" : "-=7px" }, 400, function(){
             $icon.css('margin-left','auto');
          } );
        } );
    }
  },
  function(){}
);

However if you hover faster over heading (faster than the animation is completed) it gets buggy and ends up moved away from original location.
I use onComplete functions, I even tried to use ! $('...').is(':animated') as you can see above, did not help, so I thought at least I would reset the position after animation end so then even if it would get buggy it would at least reset to the original position after all animation would end... That worked only partially and still gets buggy and ends up in the wrong position...
So whats wrong?
How come that e.g. shake effect from jQuery UI enques good?
Note: I don't care if the animation runs a few times more, the goal is to make it stay at the right position when (all) the animation(s) end.
Any help ? :)
EDIT
I finally reproduced the problem on JSFiddle - http://jsfiddle.net/yhJst/
 ==> try to hover up and down faster over the headings
EDIT2
It doesn't seem to be happening when there is only one heading ... http://jsfiddle.net/scZcB/3/

A: Here's the problem, in your callback function, you are using animate on the $icon variable. But when you hover an other element, that variable is changed for the new hovered element.
Use $(this) in the callback or the natural queuing :
Natural queuing
jQuery('h1.sc_blogger_title').on('mouseenter', function(){
    $icon = jQuery('.sc_title_bubble_icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200).animate({ "margin-left" : "-=7px" }, 400);
    }
});

http://jsfiddle.net/yhJst/1/
$(this)
jQuery('h1.sc_blogger_title').on('mouseenter', function(){
    $icon = jQuery('.sc_title_bubble_icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
            $(this).animate({ "margin-left" : "-=7px" }, 400);
        });
    }
});

http://jsfiddle.net/yhJst/2/

Or use a local variable.
as you discovered, the current variable is a global one. Just add the keyword var.
jQuery('h1.sc_blogger_title').on('mouseenter', function(){
    var $icon = jQuery('.sc_title_bubble_icon', this);
    if( ! $icon.is(':animated') ){
        $icon.animate({ "margin-left" : "+=7px" }, 200, function(){
            $icon.animate({ "margin-left" : "-=7px" }, 400, function(){
                $icon.css('margin-left','auto');
            } );
        } );
    }
});


Q: Can't append char to a StringBuffer 2-dimensional array Does anybody know why i can't append a char to this StringBuffer array (in my example below) and can somebody please show me how i needs to be done?
public class test {
    public static void main(String args[]){

        StringBuffer[][] templates = new StringBuffer[3][3];

        templates[0][0].append('h');
    }
}

My output to this code is:
output:     Exception in thread "main" java.lang.NullPointerException
            at test.main(test.java:6)

It would help me so much so if you know any solution, please respond to this

A: Below statement will just declare an array but will not initalize its elements :
    StringBuffer[][] templates = new StringBuffer[3][3];

You need to initialize your array elements before trying to append the contents to them. Not doing so will result in NullPointerException
Add this initialization
    templates[0][0] = new StringBuffer();

and then append
    templates[0][0].append('h');

A: You need to initialize the buffers before you append something
templates[0][0] = new StringBuffer();

A: Others correctly pointed out the correct answer, but what happens when you try to do something like templates[1][2].append('h');?
What you really need is something like this:
public class Test {          //<---Classes should be capitalized.

    public static final int ARRAY_SIZE = 3;  //Constants are your friend.

    //Have a method for init of the double array
    public static StringBuffer[][] initArray() {
       StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE];
       for(int i = 0;i<ARRAY_SIZE;i++) {
            for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer();
        }
        return array;
    }

    public static void main(String args[]){

       StringBuffer[][] templates = initArray();

        templates[0][0].append('h');
        //You are now free to conquer the world with your StringBuffer Matrix.
    }
}

Using the constants are important, as is is reasonable to expect your matrix size to change.  By using constants, you can change it in only one location rather then scattered throughout your program.