text:
Q: Matlab curve fitting lines trough letters with image processing For a project i am trying to make a reference trajectory writing some sort of handwritten font. Therefore I am using .png files for all the letters, for example:

So what i want to do in Matlab is something like this: (but than neater and not done with paint)

Meaning the red line should be a single line through the letter.
I have already tried using:
bwboundaries: this gives me the boundary and i cannot really see how this will give me the "average"

houghlines:  does not give the result i want (although close)

code bwboundaries:
BW = imbinarize(I,'adaptive','Sensitivity',1);
BW = imcomplement(BW)
[IM_b,~,~,IM_a] = bwboundaries(BW,'holes');
for i = 1:length(IM_b)
plot(IM_b{i}(1:end,2),-IM_b{i}(1:end,1)); hold on;
end

code houghlines:
BW = imbinarize(I,'adaptive','Sensitivity',1);
BW = imcomplement(BW)
[H,T,R] = hough(BW);
imshow(H,[],'XData',T,'YData',R,...
'InitialMagnification','fit');
xlabel('\theta'), ylabel('\rho');
axis on, axis normal, hold on;

P  = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));
x = T(P(:,2)); y = R(P(:,1));
plot(x,y,'s','color','white');

lines = houghlines(BW,T,R,P,'FillGap',2,'MinLength',25);
figure, imshow(I), hold on
max_len = 0;
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');

% Plot beginnings and ends of lines
plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');

% Determine the endpoints of the longest line segment
len = norm(lines(k).point1 - lines(k).point2);
if ( len > max_len)
max_len = len;
xy_long = xy;
end
end


text:
Q: Django URL and making a portion of it optional, but using the same class API View So I have this API URL on the back-end and I am wondering how to make a portion of it optional.
url(r'^api/documents/(?P<id>[0-9]+)$', GetDocumentsAPIView.as_view(), name='documents'),

So two things can happen coming from the front-end.
1) When the user logs in, it brings them to the /home which lists all of their projects. Clicking on the project brings them /documents/85 where the number is the number of the project and it lists all the documents for that project. This is sent to the API URL /api/documents/85. This much is working fine.
2) The other option is the user will just click on a Documents link in the navbar, which will just bring them to /documents. This should just go to the API URL /api/documents/ and eventually onto the serializer.py where their most recent project is determined and the documents for that are returned and rendered in the front-end
This I can't get working. Not sure if I can do it with just one url(), or if I need two. Was hoping the one I posted would look at the (?P<id>[0-9]+)$ as optional and if nothing was there would return the same GetDocumentsAPIView, but this is not the case.
EDIT: Including the view I am using for testing at this point. Just print() to see if anything is being routed to the view.
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class GetDocumentsAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        print(kwargs.get('id'))
        return Response('Test')

A: No you need to add a URL pattern for r'^api/documents/$', which can launch the same view by the way. Only inside the view you'll have to assume id is optional:
if kwargs.get('id'):
    # return specific document
else:
    # return list of documents

I would rename your first URL pattern to 'view_document' so you can use the name 'documents' on the other, more generic view.
Note: I think your URL structure is wrong. Reading your URL, according to REST, I would expect to see the document with id 85 when fetching documents/85. If you actually are listing the docs of a project, the URL should be projects/85/documents/ or if unspecified projects/documents.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to import local CSV via cypher-shell+bolt from my computer on a server? I need to import CSV from a local folder (on my computer) on a server.
First I start the cypher-shell:
cypher-shell.bat -a bolt://<address>:7687 -u user -p secret
That works (I can do any Cypher-operation I want to do).
After that I try to load the data from my local neo4j-installation:
USING PERIODIC COMMIT
LOAD CSV FROM 'C:/Users/.../neo4j-community-3.5.6/import/file.csv' AS line FIELDTERMINATOR ';'
CREATE (:Term { name: line[1], description: line[2]});
I get an error: "unknown protocol: c". So I think, the declaration of the local path is wrong.

A: You need to prepend file:/// in the file path to specify when loading from the local file system.
USING PERIODIC COMMIT
LOAD CSV FROM 'file:///C:/Users/.../neo4j-community-3.5.6/import/file.csv' AS line FIELDTERMINATOR ';'
CREATE (:Term { name: line[1], description: line[2]});

By default, the neo4j import directory is set to $NEO4J_HOME/import.
You need to comment following line in the neo4j.conf file:
dbms.directories.import=import


text:
Q: Using OpenXML, my VLOOKUP formula doesn't work, until the user manually edits the cell The sequence of events I am trying to create is this:

*

*My OpenXML app generates a new Excel file, populating it with data from a database.

*User opens the file and goes to the Order sheet.

*User makes a selection from the Customer dropdown.

*On the Product sheet, there is a VLOOKUP, which checks the Customer drop down and displays optional special products, based on the customer name selected.

*Back on the Order sheet, the Products drop down shows the customised list of products.

Formula I am inserting:
string theFormula = "IFERROR( IF(VLOOKUP(CustomerNameRange, CustomerTable, 8, FALSE) = 0,\"\", VLOOKUP(CustomerNameRange, CustomerTable, 8, FALSE)),\"\")";

Code I am using to do the insert:
    Row r = new Row();
    r.RowIndex = (UInt32)index;

    Cell c = new Cell();
    c.CellReference = index;
    c.DataType = new EnumValue<CellValues>(CellValues.String);

    c.CellFormula = new CellFormula(theFormula);
    c.CellFormula.CalculateCell = true;
    r.AppendChild(c);

Code I am using to force the sheet to recalc:
CalculationProperties prop1 = workbookPart1.Workbook.GetFirstChild<CalculationProperties>();
prop1.ForceFullCalculation = true;
prop1.FullCalculationOnLoad = true;
prop1.CalculationMode = CalculateModeValues.Auto;
prop1.CalculationCompleted = false;

However, none of this extra recalc code seems to be working.  The special product VLOOKUP doesn't recalc successfully, until the user manually edits that cell.  How can I force Excel to treat the inserted formula cell like normal?
I understand that OpenXML doesn't and isn't meant to do the recalc (it's a document editor, not a fully-fledged spreadsheet engine).

A: Resolution was to not programmatically enter the formula, but to have the formula permanently on the sheet.


text:
Q: symfony3 doctrine2 association counter field Consider the following case: I have two entities: Article and ArticleComment:
// \AppBundle\Entity\Article

/**
 * @ORM\OneToMany(targetEntity="ArticleComment", mappedBy="article")
 */
private $comments;

I need to store the amount of comments in a field on the article (eg. articles.comments_count). The field needs to be updated whenever a comment is created or deleted.
Previously I used the CakePHP framework which has built-in CounterCache behavior which does this automatically. I've tried my best to find something similar for Doctrine 2 (starting with DoctrineExtensions library) but nothing seems to do what I'm looking for.
Any library that does this? Or do I have to come up with my own solution?
Edit: I've tried using Entity Events but I require this behavior on many entities so I'm interested in a reusable solution

A: You can take a look at the extra lazy associations. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html
This way you don't need to store the comment_counter as you will be able to use the count() function on your collection without loading the full collection.
Internally, Doctrine will issue a "select count" query.

A: Here is another answer which avoids storing this kind of aggregate and enables you to use the paginator as you've requested in comments. I didn't test it yet so there could be some errors.
$qb = $em->createQueryBuilder();
$qb
  ->select('a.title, a.author, count(c)')
  ->from('Article', 'a')
  ->leftJoin('a.comments', 'c')
  ->groupBy('a.id');

$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate($qb, $page, $limit);

As I said, this issue is not really Doctrine related because your initial model design is bad.
Usually, you don't need to store an aggregate which can be computed with a count/groupby query.
This kind of aggregate is useful when you have a lot of joined entities which creates a real overhead during computing. Else, you don't need it.


text:
Q: Chrome Canvas Linear Gradient != Firefox Canvas Linear Gradient Well , the problem is the next :
   canvas = GreenCanvas.get(0).getContext('2d');
   grad = canvas.createLinearGradient(0,0,255,0);
   grad.addColorStop(0, 'rgb('+r+','+0+','+b+')');
   grad.addColorStop(1, 'rgb('+r+','+255+','+b+')');
   canvas.fillStyle = grad;
   canvas.fillRect(0,0,256,34);

256 pixels . from for example rgb(0,0,0) to rgb(0,255,0)
Chrome 6.0.472: gradient (0,0,0) (0,1,0) (0,2,0) (0,3,0) (0,4,0) ... (0,255,0)
Firefox 3.6.6: gradient (0,0,0) (0,0,0) (0,1,0) (0,2,0) ... (0,255,0)
i would like to see who programs that gradient function in firefox  . But anyway , i would like to know if its a real problem , or is that in firefox the gradient is done that manner. Or if it exist another manner to do a well done gradient without using too much memory.

A: It's known that Chrome has problems with the Canvas gradients at the moment.
I submitted a bug to Chromium because of how many of hixie's (the specification writer) tests were failing on Chrome.
In short, you can't make your 'grad' variable. You have to set it directly.
This works:
   var context = document.getElementsByTagName('canvas')[0].getContext('2d');
   context.fillStyle = context.createLinearGradient(0, 0, 500, 300);
   context.fillStyle.addColorStop(0, '#0000ff');
   context.fillStyle.addColorStop(1, '#ff00ff');
   context.fillRect(0, 0, 500, 300);

This does NOT work, even though they are SUPPOSED to do the same thing:
   var context = document.getElementsByTagName('canvas')[0].getContext('2d');
   var g = context.createLinearGradient(0, 0, 500, 300);
   g.addColorStop(0, '#0000ff');
   g.addColorStop(1, '#ff00ff');
   context.fillStyle = g;
   context.fillRect(0, 0, 500, 300);

For now, just do it the first way.
Here's the filed bug report from early September.
http://code.google.com/p/chromium/issues/detail?id=54070&can=4&colspec=ID%20Stars%20Pri%20Area%20Feature%20Type%20Status%20Summary%20Modified%20Owner%20Mstone%20OS


text:
Q: How to use subprocess to capture output & allow for the output to print to screen? In my Python 3 script I am starting another program that normally prints out what its doing as its doing if I don't capture the output with PIPE such as below:
proc = subprocess.run("program")
But when I do capture the output for saving to a text file with:
proc = subprocess.run("program", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
it no longer prints out as the subprocess is running but does capture the output for saving to a text file. Is there a way to have the program print to the screen and capture that output. I have read through subprocess but I cannot figure out a way to do so.

A:
Is there a way to have the program print to the screen and capture that output.

Capture it and print it yourself.
If you want to print the output as it's going, use subprocess.Popen, then stdout and stderr will be streams, you can read their content in a loop and print that as it gets output (though beware that the process's stdout will most likely be fully buffered while stderr is unbuffered).


text:
Q: What is the difference between #> and ->> operator in PostgreSQL? We can access any JSON element in PostgreSQL 9.3 using the -> and ->> operators. Seems to me that the #> along with #>> only provide a shorter form of writing the JSON path. Or is there a bigger picture behind the #> operator? Does it serve a special purpose/provide any advantage over the arrow notation? Which one is the preffered method of writing paths?
It all comes to the question: why should I use the #> and #>> operator over the -> and ->>?
The docs are a bit enigmatic about this.
Both queries below give the same result:
=> select '{"a":[1,2,3],"b":[4,5,6]}'::json#>'{a,2}';
 ?column?
----------
 3

=> select '{"a":[1,2,3],"b":[4,5,6]}'::json->'a'->>2;
 ?column?
----------
 3

A: Consider nesting.
{
  "a" : {
    "b" : {
      "c" : 1,
      "d" : 2
    }
  }
}

Imagine that you have a json document, and you don't know in advance how it will be nested. If you knew you needed a three level path, you could write:
SELECT '{
  "a" : {
    "b" : {
      "c" : 1,
      "d" : 2
    }
  }
}'::json -> 'a' -> 'b' -> 'c';

but what if you want to write a query that doesn't know that in advance? That's where the path-based operators are useful; the path can be supplied along with the document, and there's no longer any assumption about the document structure in the query.
SELECT '{
  "a" : {
    "b" : {
      "c" : 1,
      "d" : 2
    }
  }
}'::json #>> ARRAY['a','b','c']


text:
Q: C Programming: Weird characters in char output I'm doing a TCP socket programming in C (Client & Server).
I'm experiencing some problem with my outputs.
OUTPUT IN CMD:
Initialising Winsock...Initialised.
Socket created.
Connected
Enter message : hello
Server reply :10╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠hello
THATS IT
Enter message :

As you have noticed, there's a lot of this ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ character and I have not much clue on why it happens.
The correct output should just be "10 [NEWLINE] THATS IT" without the garbage text in between
Anyone can help me out on this?
SERVER CODE:
//Receive a message from client
while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
{
    char temp[2000] = {0};
    sprintf(temp, "%d", someintvariable);

    //Send the message back to client
    write(client_sock , temp , strlen(temp));
}

CLIENT CODE:
char message[2000];
char server_reply[2000];

... << some socket comms code here >> ...

//keep communicating with server
while(1)
{
    printf("Enter message : ");
    scanf("%s" , message);
    if(strcmp(message,"quit") == 0)
        break;
    fflush(stdin);
    //Send some data
    if( send(s , message , strlen(message) , 0) < 0)
    {
        puts("Send failed");
        return 1;
    }

    //Receive a reply from the server
    if( recv(s , server_reply , 2000 , 0) < 0)
    {
        puts("recv failed");
        break;
    }
    puts("Server reply :");
    puts(server_reply);
    puts("THATS IT");
}

return 0;

A: There are two problems in your code:

*

*Server does not send null terminator - your code passes strlen(temp) to write(client_sock, ...), meaning that null terminator would not be sent to the client. You need to use strlen(temp)+1 instead.

*Client code uses strlen - instead of strlen(server_reply) you should use sizeof(server_reply)
Another alternative to having the server send you '\0' is to null-terminate the string that you receive yourself, like this:
ssize_t len;
if((len = recv(s , server_reply , 2000 , 0)) < 0)
{
    puts("recv failed");
    break;
}
server_reply[len] = '\0';
puts("Server reply :");
puts(server_reply);
puts("THATS IT");

This would make the client more robust, avoid undefined behavior in situations when the server sends invalid replies.


text:
Q: Model name is being displayed in Django template I'm new to Django so I'm just building a few simple apps to increase my knowledge. I am trying to display a concatenated list, however when I display the list it shows the model names like so:
[<FamousQuote: Be yourself; everyone else is already taken>][<InfamousQuote: . I dunno. Either way. >]

This is my views.py file:
def index(request):
    famous_quote = FamousQuote.objects.all().order_by('?')[:1]
    infamous_quote = InfamousQuote.objects.all().order_by('?')[:1]

    compiled = [famous_quote, infamous_quote]

    return render(request, 'funnyquotes/index.html', {'compiled': compiled})

and my index.html file:
{% if compiled %}
    {{ compiled|join:"" }}
{% else %}

No quotes for you.

{% endif %}

Is there something I'm doing wrong, or a better way I could do this?

A: You have a list of lists, so the unicode representation of the list contains the <ObjectName:string>, where if you had a list of model objects, you'd get a proper __unicode__ representation of your objects.
Ultimately, the template is automatically trying to convert python objects into its string representations, which in the case of the QuerySet is [<object: instance.__unicode__()>].
You have clearly already defined your desired string representation for object instances - you just need to make sure the template engine receives those instances - not other classes.
Look at the difference in output in a shell.
print(FamousQuote.objects.all().order_by('?')[:1])   # calls str(QuerySet)
# vs
print(FamousQuote.objects.order_by('?')[0]) # calls str(FamousQuote)

Either update your view
compiled = [famous_quote[0], infamous_quote[0]]

Or your template
{% for quotes in compiled %}{{ quotes|join:"" }}{% endfor %}

TL;DR
You have lists of lists so you are joining the string representation of the lists, not the instances.


text:
Q: 14.0.4 LTS can not do anything I have a new distro of LTS Ubuntu on a 4 GB flash drive. Nothing has been installed because from minute 1 I can not download anything.
I have downloaded Teamviewer and can not install via Software center, it just has the install button, but when clicked does nothing.
The DPKG command can not find the file.
When running apt-get upgrade I get this error:

Here are the results for df-h

Internet is up and running and works just fine.
Flash was formatted with Rufus, I have also tried my CD boot of Ubuntu 15.04 (same issues) and also unetbooting boot on 32 GB flash drive.
same error...
Please help as I know there must be a root to all of these issues

A: There's no team-viewer package in Ubuntu repositories, you need to download the .deb file from their website and run these commands:
cd ~/Downloads
sudo dpkg -i teamviewer_i386.deb

And then if installation fails because of a dependency issue:
sudo apt-get update
sudo apt-get install -f
sudo dpkg -i teamviewer_i386.deb


text:
Q: Is there a way to generate non-normal correlated random variates? This is my first post so excuse me for any inconveniences.
My goal is to simulate asset return timeseries, which typically are fat-tailed. Therefore, I must look further than generating correlated normal variates. I came across this package that basically does exactly what I want. However, it is for python 2.x.x and I'm on python 3.8.
from connorav import CorrelatedNonNormalRandomVariates
returns = pd.read_csv(r'datasets/eurostoxx_share_returns.csv', sep=';', parse_dates=True, index_col='Date')
nsim = 10
corr = returns.corr()
corr = posdef.nearestPD(returns.cov())
stats = pd.DataFrame(data={'mean': returns.mean(),
                           'std': returns.std(),
                           'skew': returns.skew(),
                           'kurt': returns.kurt()
                           }).to_numpy()
corr = corr.to_numpy()
rv = CorrelatedNonNormalRandomVariates(stats,corr,nsim)

I received an error because python 2 would return a list upon map() where python 3 does not. So I adjusted in correl_rv.py:
self.moments = moments
self.correlations = correlations
self.distributions = map(MSSKDistribution,moments.tolist())

to
self.moments = moments
self.correlations = correlations
self.distributions = list(map(MSSKDistribution,moments.tolist()))

Yet now I receive the following output:
~\Anaconda3\envs\python\lib\site-packages\connorav\correl_rv.py in __init__(self, moments, correlations, num_samples, method)
     21         self.moments = moments
     22         self.correlations = correlations
---> 23         self.distributions = list(map(MSSKDistribution,moments.tolist()))
     24
     25         self.generate(num_samples,method)

~\Anaconda3\envs\python\lib\site-packages\connorav\distribution.py in __init__(self, mean, std, skew, kurt)
     12         self.skew = skew
     13         self.kurt = kurt
---> 14         self.fit()
     15
     16     def fit(self):

~\Anaconda3\envs\python\lib\site-packages\connorav\distribution.py in fit(self)
     16     def fit(self):
     17
---> 18         if abs(self.skew) < NORMAL_CUTOFF and abs(self.kurt) < NORMAL_CUTOFF:
     19             # It is hard to solve the johnson su curve when it is very close
     20             # to normality, so just use a normal curve instead.

TypeError: bad operand type for abs(): 'NoneType'

The data I use are daily stock returns from all 50 EuroSTOXX firms over 2000-2021.
Thanks to you all!


text:
Q: Access WebHostBuilder's host with WebClient gets rejected I'm trying to access a controller's route which is hosted using this code:
var configuration =
            new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    ["urls"] = url
                })
                .Build();

        var hostBuilder = new HostBuilder()
            .ConfigureWebHost(webHost =>
            {
                webHost.UseConfiguration(configuration);
                webHost.UseUrls(url);
                webHost.UseTestServer();
                webHost.UseStartup<TestStartup>();

            });

        var host = await hostBuilder.StartAsync();

While accessing it with
 var client = host.GetTestClient();
 var response = await client.GetAsync("/api/test/testdata");

works fine I'll get a WebException saying 'No connection could be made because the target machine actively refused it' when I try to access it using a WebClient
var webClient = new WebClient();
var response = webClient.DownloadString(url + "api/v1/test/validData");

I'm not sure if setting the url actually works (that's why I got multiple test code in the configuration) but using the hosts baseaddress returns the same result.
Any help would be much appreciated.

A: GetTestClient returns a HttpClient, that uses a special HttpMessageHandler that dispatches the request directly into the ASP.NET Core server pipeline. This specialized code avoids sending actual data over the network by orchestrating the application code directly.
This allows doing efficient integration tests that will test all of your application code set up properly. But since this will emulate network traffic without opening actual sockets, you will not be able to use this for end-to-end tests with foreign clients.
So since WebClient does not support message handlers, you will not be able to use it for integration tests. You will have to use the HttpClient the test server gives you.


text:
Q: C++ console app: matrix (+ operator overloading error) I'm currently implementing a matrix class and I have a problem overloading + operator.
The detailed implementation is below:
**matrix.h:**

#pragma once
#include <iostream>
using namespace std;

template <typename t>
class Matrix
{
    int n, m;
    t **data;
public:
    Matrix(int, int, t);
    Matrix(Matrix &);
    ~Matrix();

    Matrix<t> operator+(const Matrix<t> &);
};

template<typename t> Matrix<t>::Matrix(int n = 1, int m = 1, t data = 0)
{
    this->n = n;
    this->m = m;
    this->data = new t*[this->n];

    for (int i = 0;i < n;++i)
    {
        this->data[i] = new t[this->m];
        for (int j = 0;j < m;++j)
        {
            this->data[i][j] = data;
        }
    }
}

template<typename t> Matrix<t>::Matrix(Matrix &m)
{
    this->n = m.n;
    this->m = m.m;
    this->data = new t*[this->n];

    for (int i = 0;i < n;++i)
    {
        this->data[i] = new t[this->m];
        for (int j = 0;j < this->m;++j)
        {
            this->data[i][j] = m.data[i][j];
        }
    }
}

template<typename t> Matrix<t>::~Matrix()
{
    for (int i = 0;i < this->n;++i)
        delete[] data[i];
    delete[] data;
}

template<typename t> Matrix<t> Matrix<t>::operator+(const Matrix<t> &x)
{
    if (x.n == n && x.m == m)
    {
        Matrix<t> temp(n, m, 0);
        for (int i = 0; i < n;++i)
            for (int j = 0; j < m;++j)
            {
                temp.data[i][j] = data[i][j] + x.data[i][j];
            }
        return temp;
    }
    else
    {
        return *this;
    }
}

**main.cpp:**

#include "matrix.h"

int main()
{
    Matrix<double> x(1, 1, 2); // defines a matrix 1x1 with all elements 2
    Matrix<double> y(1, 1, 3); // defines a matrix 1x1 with all elements 3
    Matrix<double> z(1, 1, 0); // defines a matrix 1x1 with all elements 0
    z=x+y;
}

I get a runtime error when a + operation is to be done. What could be the problem here?


text:
Q: Select and Count with Null values I have the following select:
SELECT
    COALESCE (opened.ano, closed.ano) AS ano,
    COALESCE (opened.mes, closed.mes) AS mes,
    COALESCE (opened.cnt, 0) AS opened_cases,
    COALESCE (closed.cnt, 0) AS closed_cases
FROM
    (
        SELECT
            YEAR (OPEN_DATE) AS ano,
            MONTH (OPEN_DATE) AS mes,
            COUNT (*) AS cnt
        FROM
            TABLE1,
            TABLE2
        WHERE
            TABLE1.USERNAME = TABLE2.USERNAME
        AND TABLE2.GROUP = 'SUPPORT'
        GROUP BY
            YEAR (OPEN_DATE),
            MONTH (OPEN_DATE)
    ) opened
FULL OUTER JOIN (
    SELECT
        YEAR (CLOSE_DATE) AS ano,
        MONTH (CLOSE_DATE) AS mes,
        COUNT (*) AS cnt
    FROM
        TABLE1,
        TABLE2
    WHERE
        TABLE1.USERNAME = TABLE2.USERNAME
    AND TABLE2.GROUP = 'SUPPORT'
    GROUP BY
        YEAR (CLOSE_DATE),
        MONTH (CLOSE_DATE)
) closed ON opened.ano = closed.ano
AND opened.mes = closed.mes
ORDER BY
    COALESCE (opened.ano, closed.ano) ASC,
    COALESCE (opened.mes, closed.mes) ASC;

The result is:

The situation:
The first line with null values are lost because there is no null condition in the select.
Thanks

A: select
  coalesce(opened.ano, closed.ano) as ano,
  coalesce(opened.mes, closed.mes) as mes,
  coalesce(opened.cnt, 0) as opened_cases,
  coalesce(closed.cnt, 0) as closed_cases
from
(
  select
    year(open_time) as ano,
    month(open_time) as mes,
    count(*) as cnt
  from table1
  where groupdesc = 'SUPPORT'
  group by year(open_time), month(open_time)
) opened
full outer join
(
  select
    year(close_time) as ano,
    month(close_time) as mes,
    count(*) as cnt
  from table1
  where groupdesc = 'SUPPORT'
  group by year(close_time), month(close_time)
) closed
  on opened.ano = closed.ano and opened.mes = closed.mes
where closed.mes is not null
order by coalesce(opened.ano, closed.ano) desc, coalesce(opened.mes, closed.mes)    desc;

This is your SQL with an added WHERE clause.
Your comments seem to show that what you are looking for IS contained in this results set.
There are 10 Opened_cases and 8 closed_cases.

A: So in your fiddler example there should be 10 opened cases and 8 closed?
Is so, Then try this: (http://sqlfiddle.com/#!3/3bf0ac/9)
;
with opened AS (
  select
    year(open_time) as ano,
    month(open_time) as mes,
    count(*) as cnt
  from table1
  where groupdesc = 'SUPPORT'
  group by year(open_time), month(open_time)
  ),
closed AS (
  select
    year(close_time) as ano,
    month(close_time) as mes,
    count(*) as cnt
  from table1
  where groupdesc = 'SUPPORT'
  group by year(close_time), month(close_time)
)
SELECT
    COALESCE (opened.ano, closed.ano) AS ano,
    COALESCE (opened.mes, closed.mes) AS mes,
    COALESCE (opened.cnt, 0) AS opened_cases,
    COALESCE (closed.cnt, 0) AS closed_cases
FROM opened
FULL OUTER JOIN closed on opened.ano = closed.ano and opened.mes = closed.mes
WHERE COALESCE (opened.ano, closed.ano) IS NOT NULL
ORDER BY coalesce(opened.ano, closed.ano) desc, coalesce(opened.mes, closed.mes) desc;


text:
Q: PageObject/Cucumber String being input incorrectly In my scenario outline I have the below
Examples:
    | user   | password | from            | to            | amount | date      | message           |
    | joel10 | lolpw12  | bankA           | bankB         | $100   | 1/30/2015 | Transfer Success. |

in my step definitions I have the below
And(/^the user inputs fields (.*), (.*), (.*)$/) do |from, to, amount|
  on(TransferPage).from = /#{from}/
  on(TransferPage).to = /#{to}/
  on(TransferPage).amount = /#{amount}/
  on(TransferPage).date = /#{date}/
end

The FROM, TO, and AMOUNT all comes out correct from the table but when it inputs the date, it comes out (?-mix:1/30/2015)
why is this happening and how do i fix?

A: When you do /#{date}/ you are taking the value returned from the parsing of the step definition and then turning it into a regular expression:
/#{date}/.class
#=> Regexp

You presumably want to leave the value in its original String format:
on(TransferPage).date = date


text:
Q: How to create same animation as it in square application in ios? AppStore link https://itunes.apple.com/us/app/square-one-shopping-centre/id400294134?mt=8
I want to create same animation as it is SQUARE application's first screens tableview.
When tableview scroll is up and down cell comes with animation. Can any one help me to   achieve this.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"notificationCell";
    notificationCell *cell = (notificationCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"notificationCell" owner:self options:nil];

        for (id currentObject in topLevelObjects){
            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                cell =  (notificationCell *) currentObject;
                break;
            }
        }

    }
    cell.imgFacebookTwitter.image=[UIImage imageNamed:@"tw_icon.png"];

    return cell;

}

A: You have to play with CATransform3D animations and apply it in
willDisplayCell:cellforRowAtIndexPath: method.
Check out this tutorial - Animating UITableView Cells.
It should point you in the right direction.


text:
Q: Mostrar todos los resultados de una regla en Prolog Quisiera saber si hay una manera de mostrar todas las salidas cuando se hace una consulta en Prolog de una regla, me explico.
Teniendo las reglas
padres(david,jose).
padres(david,martin).
padres(hector,mariana).

cuando se crea una regla donde se pregunta cuales son los hijos de esos padres ejemplo
espadre(A):- padres(A,X),display(X).

el resultado de la siguiente regla en caso de ser David son las siguientes
   ?-espadre(david).
//jose;
//martin

estos serian los resultados que arrojaria prolog, pero estos no despliegan todo, solo arroja "Jose" al menos que se le de enter, visualisaria "martin"
Quisiera hacer que con una regla, me muestre todos sus resultados posibles que tenga, sea 1 o 20 que cumplan, ya sea que esten dentro de un arreglo , o seguidos
De antemano gracias

A: Al menos en swi-prolog el predicado se llama bagof/3 y su sintaxis se eplica de la siguiente manera:
bagof(UnaVariable, tupredicado(UnaVariable,LoQueSea, EnSerioLoQueSea, YCuantosSean), UnasVariables)

Y como te imaginarás, todo se almacenará en una lista que es la parte de UnasVariables, mientras que UnaVariable será la variable que usará para consultar todos los posibles resultados.
?- bagof(Padre,espadre(Padre),Padres).

josemartinmariana
Padres = [david, david, hector].

Como verás en el resultado de consola salen otros nombres y es debido a que tienes display(X)
Enlaces
Documentación oficial


text:
Q: Accessing Advanced Custom Fields by Page Name I am trying to retrieve all advanced custom fields tied to a particular page. This is different than iterating through posts, I am familiar with the following:
$posts = get_posts(array(
    'post_type'     => 'post_name',
    'meta_key'      => 'color',
    'meta_value'    => 'red'
));

However this method is specific to posts and does not allow me to retrieve all ACF by page name.
I appreciate any suggestions on how to accomplish this.

A: The are too ways to do this that come to mind...
1. Using the Loop
Using WP_Query you can do something like this...
<?php

// WP_Query arguments
$args = array (
    'pagename'               => 'homepage',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        the_field( "field_name" );
    }
} else {
    // no posts found
}

// Restore original Post Data
wp_reset_postdata();

?>

In place of the 'homepage' in 'pagename' => 'homepage', you want to put the page slug of your page. And of course in place of the_field( "text_field" ); you want to add your fields/content.
You can also query by Page ID and some other parameters. You can find all other parameters that you can use here:
https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
2. Adding second parameter to the_field() function
More simple way, without custom loop, is just to use ACF's built-in the_field() function with the $post->ID parameter added as a second parameter.
<?php the_field('field_name', 123);

This might be the way to go since you want to show the content of only one page, and therefore don't really need to loop.
Reference: http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/

A: You can use ACF's get_fields() function -
<?php $fields = get_fields( $post->ID ); ?>

You could then loop through them or simply print the array for testing.
http://www.advancedcustomfields.com/resources/get_fields/


text:
Q: How does Entity Framework generate a GUID for a primary key value? When we run the ASP.NET application and register the user, Entity Framework automatically sets the unique id (PK) in AspNetUser table:

The same is true for other AspNetRoles, AspNetUserLogins, AspNetUserRoles
except AspNetUserClaims which has identity enabled.
Can anybody explain how Entity framework create this unique Id? And if we want to create our own table with identity disabled in EF, how will we generate this kind of Id for primary key?

A: This unique Id is created by SQL Server on insert.
If you want to let SQL Server generate the value on insert, you have to use the following attributes in your model :
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }

Or if you want to manage the Id by yourself, just generate it :
var id = Guid.NewGuid();

A: EF isn't generating that value. That's a GUID (uniqueidentifier in T-SQL) value which is auto-generated by SQL Server when a new row is INSERTed,.

A: Using Identity in ASP .NET,id are automatically generated in db (uniqueidentifier data type). In C#  you can generate GUID  using method Guid.NewGuid()

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

Here you find C# and T-SQL

A: The GUID is not generated by Entity Framework nor by SQL. It is handled by Identity framework. Just navigate to IdentityModels.cs
public class ApplicationUser : IdentityUser
{
   // ...
}

This class is inherited from Microsoft.AspNet.Identity.EntityFramework.IdentityUser and constructor for this class is defined as (Source)
public IdentityUser()
{
    Id = Guid.NewGuid().ToString();
}

So GUID is generated in the constructor. This is same for other Identity tables too.
Note: Id Field is varchar (string) in database.

A: in EF core and poco:
...
.Property(p => p.Id)
    .ValueGeneratedOnAdd()
;

A: I think this is more a feature of SQL-Server, than of EF directly. EF creates the table with a unique-id field with identity on.
If you want to do that yourself, you need a unique-id field. Your object should then have a GUIDproperty Id, which you assign Guid.NewGuid()for instance.
Hope that helps


text:
Q: How to solve PCollection with more than one element accessed as a singleton view The pipeline of beam job give the following exception
java.lang.RuntimeException: java.lang.RuntimeException: Exception while fetching side input:
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output(GroupAlsoByWindowsParDoFn.java:184)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue(GroupAlsoByWindowFnRunner.java:102)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.lambda$onTrigger$1(ReduceFnRunner.java:1057)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnContextFactory$OnTriggerContextImpl.output(ReduceFnContextFactory.java:438)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SystemReduceFn.onTrigger(SystemReduceFn.java:125)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTrigger(ReduceFnRunner.java:1060)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.emit(ReduceFnRunner.java:930)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTimers(ReduceFnRunner.java:790)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:95)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:42)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement(GroupAlsoByWindowFnRunner.java:115)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement(GroupAlsoByWindowFnRunner.java:73)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.LateDataDroppingDoFnRunner.processElement(LateDataDroppingDoFnRunner.java:80)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement(GroupAlsoByWindowsParDoFn.java:134)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
        org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.process(StreamingDataflowWorker.java:1316)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.access$1000(StreamingDataflowWorker.java:149)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker$6.run(StreamingDataflowWorker.java:1049)
        java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: Exception while fetching side input:
        org.apache.beam.runners.dataflow.worker.StateFetcher.fetchSideInput(StateFetcher.java:196)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.fetchSideInput(StreamingModeExecutionContext.java:313)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.access$500(StreamingModeExecutionContext.java:70)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext$StepContext.issueSideInputFetch(StreamingModeExecutionContext.java:660)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext$UserStepContext.issueSideInputFetch(StreamingModeExecutionContext.java:723)
        org.apache.beam.runners.dataflow.worker.StreamingSideInputFetcher.storeIfBlocked(StreamingSideInputFetcher.java:184)
        org.apache.beam.runners.dataflow.worker.StreamingSideInputDoFnRunner.processElement(StreamingSideInputDoFnRunner.java:72)
        org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:335)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output(GroupAlsoByWindowsParDoFn.java:182)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue(GroupAlsoByWindowFnRunner.java:102)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.lambda$onTrigger$1(ReduceFnRunner.java:1057)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnContextFactory$OnTriggerContextImpl.output(ReduceFnContextFactory.java:438)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SystemReduceFn.onTrigger(SystemReduceFn.java:125)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTrigger(ReduceFnRunner.java:1060)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.emit(ReduceFnRunner.java:930)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTimers(ReduceFnRunner.java:790)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:95)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:42)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement(GroupAlsoByWindowFnRunner.java:115)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement(GroupAlsoByWindowFnRunner.java:73)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.LateDataDroppingDoFnRunner.processElement(LateDataDroppingDoFnRunner.java:80)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement(GroupAlsoByWindowsParDoFn.java:134)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
        org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.process(StreamingDataflowWorker.java:1316)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.access$1000(StreamingDataflowWorker.java:149)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker$6.run(StreamingDataflowWorker.java:1049)
        java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalArgumentException: PCollection with more than one element accessed as a singleton view.
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2050)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache.get(LocalCache.java:3952)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4871)
        org.apache.beam.runners.dataflow.worker.StateFetcher.fetchSideInput(StateFetcher.java:192)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.fetchSideInput(StreamingModeExecutionContext.java:313)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.access$500(StreamingModeExecutionContext.java:70)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext$StepContext.issueSideInputFetch(StreamingModeExecutionContext.java:660)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext$UserStepContext.issueSideInputFetch(StreamingModeExecutionContext.java:723)
        org.apache.beam.runners.dataflow.worker.StreamingSideInputFetcher.storeIfBlocked(StreamingSideInputFetcher.java:184)
        org.apache.beam.runners.dataflow.worker.StreamingSideInputDoFnRunner.processElement(StreamingSideInputDoFnRunner.java:72)
        org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:335)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output(GroupAlsoByWindowsParDoFn.java:182)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue(GroupAlsoByWindowFnRunner.java:102)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.lambda$onTrigger$1(ReduceFnRunner.java:1057)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnContextFactory$OnTriggerContextImpl.output(ReduceFnContextFactory.java:438)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SystemReduceFn.onTrigger(SystemReduceFn.java:125)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTrigger(ReduceFnRunner.java:1060)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.emit(ReduceFnRunner.java:930)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTimers(ReduceFnRunner.java:790)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:95)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:42)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement(GroupAlsoByWindowFnRunner.java:115)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement(GroupAlsoByWindowFnRunner.java:73)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.LateDataDroppingDoFnRunner.processElement(LateDataDroppingDoFnRunner.java:80)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement(GroupAlsoByWindowsParDoFn.java:134)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
        org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.process(StreamingDataflowWorker.java:1316)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.access$1000(StreamingDataflowWorker.java:149)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker$6.run(StreamingDataflowWorker.java:1049)
        java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: PCollection with more than one element accessed as a singleton view.
        org.apache.beam.sdk.values.PCollectionViews$SingletonViewFn.apply(PCollectionViews.java:231)
        org.apache.beam.sdk.values.PCollectionViews$SingletonViewFn.apply(PCollectionViews.java:160)
        org.apache.beam.runners.dataflow.worker.StateFetcher.lambda$fetchSideInput$1(StateFetcher.java:162)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4876)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3528)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2277)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2154)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2044)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache.get(LocalCache.java:3952)
        org.apache.beam.vendor.guava.v26_0_jre.com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4871)
        org.apache.beam.runners.dataflow.worker.StateFetcher.fetchSideInput(StateFetcher.java:192)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.fetchSideInput(StreamingModeExecutionContext.java:313)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext.access$500(StreamingModeExecutionContext.java:70)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext$StepContext.issueSideInputFetch(StreamingModeExecutionContext.java:660)
        org.apache.beam.runners.dataflow.worker.StreamingModeExecutionContext$UserStepContext.issueSideInputFetch(StreamingModeExecutionContext.java:723)
        org.apache.beam.runners.dataflow.worker.StreamingSideInputFetcher.storeIfBlocked(StreamingSideInputFetcher.java:184)
        org.apache.beam.runners.dataflow.worker.StreamingSideInputDoFnRunner.processElement(StreamingSideInputDoFnRunner.java:72)
        org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:335)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn$1.output(GroupAlsoByWindowsParDoFn.java:182)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner$1.outputWindowedValue(GroupAlsoByWindowFnRunner.java:102)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.lambda$onTrigger$1(ReduceFnRunner.java:1057)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnContextFactory$OnTriggerContextImpl.output(ReduceFnContextFactory.java:438)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SystemReduceFn.onTrigger(SystemReduceFn.java:125)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTrigger(ReduceFnRunner.java:1060)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.emit(ReduceFnRunner.java:930)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.ReduceFnRunner.onTimers(ReduceFnRunner.java:790)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:95)
        org.apache.beam.runners.dataflow.worker.StreamingGroupAlsoByWindowViaWindowSetFn.processElement(StreamingGroupAlsoByWindowViaWindowSetFn.java:42)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.invokeProcessElement(GroupAlsoByWindowFnRunner.java:115)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowFnRunner.processElement(GroupAlsoByWindowFnRunner.java:73)
        org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.LateDataDroppingDoFnRunner.processElement(LateDataDroppingDoFnRunner.java:80)
        org.apache.beam.runners.dataflow.worker.GroupAlsoByWindowsParDoFn.processElement(GroupAlsoByWindowsParDoFn.java:134)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
        org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
        org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
        org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.process(StreamingDataflowWorker.java:1316)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker.access$1000(StreamingDataflowWorker.java:149)
        org.apache.beam.runners.dataflow.worker.StreamingDataflowWorker$6.run(StreamingDataflowWorker.java:1049)
        java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        java.lang.Thread.run(Thread.java:745)

With codes snippets. And the beam job is read data from GCS through subscription and write bigquery after processing.
PCollection<KV<String, Long>> p1 = interToCount.apply("Daily Window",
        Window.<KV<String, Long>>into(FixedWindows.of(Duration.standardDays(1)))
                .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane()
                                                                  .plusDelayOf(Duration.standardMinutes(10))))
                .accumulatingFiredPanes()
                .withAllowedLateness(Duration.ZERO));

PCollectionView<Long> totalInters = p1.apply("All Keys", Keys.create())
                                      .apply("Count All Keys",
                                            Combine.globally(Count.<String>combineFn())
                                                                  .withoutDefaults()
                                                                  .asSingletonView());

PCollection<KV<String, Long>> p2 = p1.apply("Unit Keys", Keys.create())
                                      .apply("Count Per Unit Keys", Count.perElement());

PCollection<KV<String, Double>> unitRate = p2.apply("Compute Unit Rate",
                                                    ParDo.of(new ComputeUnitRate(totalInters))
                                                         .withSideInputs(totalInters));

unitRate.apply("Convert to BQ Row", ParDo.of(new ConvertStrToBQRow()))
        .apply("Write BQ", BigQueryIO.writeTableRows().to(INTERSHOWTABLE)
                                    .withMethod(BigQueryIO.Write.Method.STREAMING_INSERTS)
                                    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER)
                                    .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
....

    static class ComputeUnitRate extends DoFn<KV<String, Long>, KV<String, Double>> {
        private PCollectionView<Long> totalInters;

        ComputeUnitRate(PCollectionView<Long> totalInters) {
            this.totalInters = totalInters;
        }

        @ProcessElement
        public void processElement(ProcessContext c) {
            String unit = c.element().getKey();
            Long unitCount = c.element().getValue();
            Long totalCount = c.sideInput(this.totalInters);
            Double showRate = unitCount.doubleValue() / totalCount.doubleValue();
            c.output(KV.of(unit, showRate));
        }
    }

It seems this error comes from step "Compute Unit Rate", However I cannot figure out clearly through exception stack.
How to fix it? Or something am I missing here?
Beam version: 2.16.0

A: Per this doc

This is a known issue in the Beam model. Trigger firings should
automatically update downstream results, but instead they are treated as
new elements. The design for retractions will alleviate this problem
You can use View.asMultimap() which will mean each trigger firing for a
key will add a new element to the set of values for a key.

After change PCollectionView to PCollectionView<Map<Long, Long>> as below
PCollectionView<Map<Long, Long>> totalInters = p1.apply("All Keys", Keys.create())
        .apply("Count All Keys", Combine.globally(Count.<String>combineFn()).withoutDefaults())
        .apply("Map view multiMap", ParDo.of(new DoFn<Long, KV<Long, Long>>() {
            @ProcessElement
            public void process(ProcessContext ctx) {
                ctx.output(KV.of(ctx.pane().getIndex(), ctx.element().longValue()));
            }
        }))
        .apply(View.asMap())
        ;

The pipeline could work well now.
I think maybe it is one of work around for this issue for now. Maybe there are better solutions.

A: I have the same problem, and I set higher numWorkers and maxNumWorkers, it resolved the problem.
you can do either options.setNumWorkers(DEFAULT_NB_WORKER); in code
or use mvn to start DataflowRunner with --numWorkers=xx --maxNumWorkers=xx


text:
Q: LIbreOffice 3.4.4 won't update I have ubuntu 11.10 installed on my machine and LibreOffice 3.4.4 came with it. Since I know there is a newer version out there, I ran the following commands:
    sudo add-apt-repository ppa:libreoffice/ppa
    sudo apt-get update
    sudo apt-get upgrade

However it won't install a newer version and I'm stuck with 3.4.4 (a version I'm not completely a fan of). Any ideas?

A: you may need to update your version of Ubuntu to 12.04 to take advantage of the newer versions of LibreOffice.
Remember some newer software does not always work on older operating systems.
If you do decide to update your version of Ubuntu all you need to do is go to update manager > settings > then make sure you have notify me of new Ubuntu version (go with the LTS versions) and that will give you the option to download a newer version of Ubuntu and plus an updated version of LibreOffice

A: Apparently, the PPA only provides packages for:
Lucid - 10.04 LTS
Precise - 12.04 LTS
Quantal - 12.10
It doesn't have any packages for Oneiric - 11.10, which is about to go End of Life on May 9. I'd also suggest upgrading asap.


text:
Q: Jira XRAY - how to import an xml using xray API? I'm trying to import an xml report to Jira xRay - to a Test Execution item.
The documentation I can find makes reference to client_id and client_secret, which should be generated by Create API key. Create API key only generates one string, a token.
As such I can't figure out how to use just the token to submit the xml report.
For example, this command:
curl -H "Content-Type: application/json" -X POST --data @"cloud_auth.json" https://xray.cloud.getxray.app/api/v2/authenticate
I can't use it, as it needs client_id and client_secret. Also, the endpoint itself returns
Cannot GET /api/v2/authenticate

.
Using this command:
curl -H "Content-Type: text/xml" -X POST -H "Authorization: Bearer $token"  --data @"data.xml" https://xray.cloud.getxray.app/api/v1/import/execution/junit?testExecKey=XNP-23
from: https://docs.getxray.app/display/XRAYCLOUD/Import+Execution+Results+-+REST#ImportExecutionResultsREST-JUnitXMLresults
results in "{"error":"Invalid JWT: JsonWebTokenError: jwt malformed"}"
.
Please can anyone help?

A: first you need to clarify if you're using Xray on Jira server/datacenter or Jira Cloud, because they are different products and have slightly different APIs; besides Jira Cloud and Jira server/datacenter are also different products. To find out, you can ask your Jira admin for example.
If you're using Xray Cloud, then this is documentation site.
In this case, in order to submit the JUnit XML report you need to make an authencation with a client id and client secret that you obtain on Xray API Keys section. The authentication request is detailed here, and that will return a token that you'll use on the second request.
The second request is an HTTP POST, as described here, and you need to pass the token obtained earlier.
The main REST API documentation site is this one.
If you're using Xray on Jira server/datacenter, then this is proper documentation site.
In Xray server, the authentication mechanism is provided by Jira itself.
You can either use basic authentication or Personal Access Tokens (if you have Jira >= 8.14). This is detailed on Xray server/datacenter page dedicated to its REST API.
After choosing the authentication mechanism to use, you just need to make a HTTP POST request as detailed here.
There is an open-source GitHub project with some code snippets, both for Xray server/datacenter and cloud, using different test automation report formats and different authentication mechanisms.

A: I have faced the same error when I tried with postman, I have removed " from generated token from start and end position and passed token to API. That resolved this issue


text:
Q: How to plot a vector array having symbolic variables? **I want to plot an array vector having symbolic variables in it. But I am getting an error which is given below.
??? Error using ==> plot
Conversion to double from sym is not possible.
Error in ==> dsolvenew at 36
plot(t2,qn2) **
The code is given below.
syms A Epsilon0 k1 k2 e s d R s f T c0 v0 v
An        = 0.5*10^(-9);
Epsilon0n = 8.85*10^-12;
k1n       = 10;
k2n       = 10;
en        = 1.6*10^-19;
sn        = 1.8*10^(-9);%m gap size%
dn        = 3*sn; % total distance
Rn        = 1;
c0n=(An*Epsilon0n*k1n)/dn;
t1=0:0.1:5;
fn=1000;
v0n=7.5;
Tn=5/f;
vn=v0n*sin(2*3.14*fn*t1);
plot(t1,vn);
inits = 'q(0)=(20*10^(-20)),Q(0)=0';
[q,Q] = dsolve('Dq=((v/R)-(1/R)*(((d*q)+(s*Q))/(c0*d)))','DQ=   (((q+Q)/(A*Epsilon0*k1))*s)',inits);
qn1=vpa(subs(q,{A,Epsilon0,k1,k2,e,s,d,R,c0},  {An,Epsilon0n,k1n,k2n,en,sn,dn,Rn,c0n}),3);
i=1;
while i<length(t1);
qn2(i)=subs(qn1, v, vn(i));
i=i+1;
end
t2=t1(1:50);
plot(t2,qn2)


text:
Q: We're looking for a treasure Here's a problem my sister-in-law just sent me and she doesn't find the answer. It's to help her daughter.
We have a map of an island. On this island there's a palm tree P, a house M and a big rock R. The rock is 8 meters far from the palm tree, and 5 meters far from the house. The house is 4 meters far from the palm tree. And we know that:

*

*the treasure  is < 6 meters from the palm tree

*the treasure  is > 4 meters from the house

*the treasure  is < 5 meters from the rock

On the island below put points M and P using the previous clues.
Color the zone where we have to dig to be sure to find the treasure.

Could you explain the basic principles of how to solve that problem/draw what's asked (the picture is not the actual one)?

A: My answer is not much different than what @Nick, who was quicker, already posted. But here it is, there is one detail at the end that is a bit different.
See the picture below. Start with a circle centered at the rock, R, with radius $8$, I have labeled this circle 8R, meaning "8 from the rock". Pick a point P on that circle, and call it the palm. The house is on the circle 4P and also on 5R, these two circles intersect at two points, just pick one of them to be the house H. The treasure is inside <6P, outside >4H,and inside <5R, so it looks like a triangular area on the picture.
But, given we do not know which direction is North, etc, and which direction the palm is from the rock, etc, we have only determined how far away from the rock the treasure could be. If the palm was at a different direction from the rock, then that triangular area would end up in a different direction too, although certainly same distance from the rock. So it could be anywhere in the area sprinkled with blue on the picture, outside the green circle and inside the <5R circle.

A: I would say that the basic principle behind this question is the definition of a circle. A circle is the set of all points in a plane equidistant from a given point - the center. So, to set up the Rock, Palm, and House given that

We have a map of an island. On this island there's a palm tree P, a house M and a big rock R. The rock is 8 meters far from the palm tree, and 5 meters far from the house. The house is 4 meters far from the palm tree.

Basic Information
Basic principle: Knowing the distances between three objects, we can construct a triangle.

*

*Place the rock. Now draw a circle of radius 8 meters. All the points on the circle are 8 meters from the rock and thus candidates for the position of the palm tree. Pick a random point on the circle, and let's let that be the palm tree.

*Draw a circle of radius 5 with the rock as its center - all the points on this circle are candidates for the palm

*With the house at the center draw a circle with radius 4 - all the points on this circle are candidates for the palm

*The intersection points between the circles in step 2 and 3 must be the position of the palm which preserves all the clues up to this point.

Identifying the Treasure
Basic Principle: Again, using circles to identify all points in a plane at a given distance we can identify the region in which the treasure must lie.

*

*the treasure is < 6 meters from the palm tree

*the treasure is > 4 meters from the house

*the treasure is < 5 meters from the rock

*

*Construct three circles centered at the palm tree (radius 6), the house (radius 4), and the rock (radius 5).

*The treasure must lie inside the region bounded by the circles centered at the palm tree and the rock and also outside the region bounded by the circle centered at the house.

The Solution

On the island below put points M and P using the previous clues.
Color the zone where we have to dig to be sure to find the treasure.

A: First of all, to place the palm tree, house and big rock, we notice that any three points form a triangle or a line in the plane. Let's assume it is a triangle, with side lengths as given: 8, 5 and 4 meters respectively. Draw a triangle with these measurements (in centimeters).
The second step is to look at the distances of the treasure from the objects. In general, when an object is $<x$ meters from a point, it is within a circle of radius $x$ meters. So draw a circle of radius $6$ around the palm tree, an circle of radius $5$ around the rock and a circle of radius $4$ around the house. Your treasure is in the intersection of the two first circles, but outside the third circle.

A: The palm tree, the rock, and the house are three vertices of a triangle whose side lengths are $4$, $5$, and $8$:

The treasure must be within the circle of radius $6$ centered at $P$, outside the circle of radius $4$ centered at $H$, and inside the circle of radius $5$ centered at $R$. You should draw these circles and find the desired region, which should end up looking a bit like the Starfleet emblem from Star Trek.


text:
Q: How to get the rss feed of most visited video of last 24 hours in youtube How to get RSS feed of the most visited video of last 24hours from youtube?
I wanna list the most visited video of last 24hour on the front page of my website using php
I already checked this but no rss feed generator found for this purpose.
This website lists the most visited video of last 24 hours but I wonder what API or RSS feed it iuses!
Thank you for your help in advance

A: This documentation, Standard feeds for channels, also discusses on how to retrieve standard feeds that list the most viewed or most subscribed YouTube channels. To retrieve a standard channel feed, send a GET request to the URL associated with that feed.
You can also check the viewCount property which gives the number of times the video has been viewed.
"statistics": {
    "viewCount": unsigned long,
    "likeCount": unsigned long,
    "dislikeCount": unsigned long,
    "favoriteCount": unsigned long,
    "commentCount": unsigned long
  },

You can check these related SO threads:

*

*Youtube API to get most viewed video for a day

Yeah they don't have stats on a particular day but they do have a
  running viewCount. So you can use the API info at
https://developers.google.com/youtube/v3/docs/search/list

to make something like
https://www.googleapis.com/youtube/v3/search?part=snippet&order=viewCount&publishedAfter=2014-10-29T00%3A00%3A00Z&publishedBefore=2014-10-31T00%3A00%3A00Z&key={YOUR_API_KEY}

*

*How to get the most trends || interesting/most viewed videos from Youtube?

*How can I get a list of the most viewed Youtube videos of the day by region?

A: Like this I did it...
public void GetFeedList(int UserId, string channel)
{
var doc = XDocument.Load("https://www.youtube.com/feeds/videos.xml?" + channel);
XNamespace xmlns = "http://www.w3.org/2005/Atom";
XNamespace media = "http://search.yahoo.com/mrss/";
XNamespace community = "http://search.yahoo.com/mrss/community";
        var query =

            from entry in doc.Root.Elements(xmlns + "entry")
            let grp = entry.Element(media + "group")
            let com = grp.Element(media + "community")

            select new YouTubeFeedItem
            {
                User_Id = UserId,

                User_Channel = channel,

                Title = (string)grp.Element(media + "title"),

                Description = (string)grp.Element(media + "description"),

                Video = (string)grp.Element(media + "content").Attribute("url"),

                Image = grp.Elements(media + "thumbnail")
                    .Select(e => (string)e.Attribute("url"))
                    .First(),

                Views = com.Elements(media + "statistics")
                    //.Select(e => (string)com.Element("statistics"))
                    .Select(e => (string)e.Attribute("views"))
                    .First(),

                Count = com.Elements(media + "starRating")
                    .Select(e => (string)e.Attribute("count"))
                    .First(),

                Average = com.Elements(media + "starRating")
                    .Select(e => (string)e.Attribute("average"))
                    .First(),

                Min = com.Elements(media + "starRating")
                    .Select(e => (string)e.Attribute("min"))
                    .First(),

                Max = com.Elements(media + "starRating")
                    .Select(e => (string)e.Attribute("max"))
                    .First(),

            };

        List<YouTubeFeedItem> youTubeFeed = query.ToList();

Cheers,
Jo


text:
Q: Comparing two Objects by < and > Which method is used when checking if a object is bigger than another? I've tried to implement a compareTo Method but its only used when comparing if the Objects are equal (=).
For example
export class Check {
    check: string;
}

export class Test {
    constructor() {
        const c1 = new Check(),
        c1.check = '1-';
        const c2 = new Check(),
        c2.check = '1';
        console.log(c1 < c2); // returns false but in my case it should be true because 1- is not as good as 1
    }
}


text:
Q: blank pages and fancyhdr package
Possible Duplicate:
How to remove headers and footers for pages between chapters?

I have a document class set as book and added the \usepackage{fancyhdr} package. but now I have some blank pages that have the top line (the one of the heading). how can i remove only these that are the only thing (except from the page number) present on blank pages?


text:
Q: Using HttpClient to invoke a webservice in an android app I am new to android & web services.I I want to create an android app which consume a webservice using HttpClient.
Yet i am confused with, how to do this. I'll explain what i've needed to do.
Say,we have a webservice at http://www.w3schools.com/webservices/tempconvert.asmx
WSDL url=http://www.w3schools.com/webservices/tempconvert.asmx?WSDL
What I need is to call the method "FahrenheitToCelsius" & return values from it in an android app.Can't i do this using HttpClient? Since it seems to get only the HTTP methods like GET and POST.
When I search on  this ,I found  the below site as a more frequent suggestion. But it doesn't contain ,what I need to do.
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
(I could call "FahrenheitToCelsius" method & return values using ksoap library.But now i need to do it using HttpClient too)

A: To clarify-  When you connect to a webservice via its WSDL file, you're consuming a very specific kind of webservice— specifically, a SOAP webservice.
The typically way to connect to a SOAP webservice is to either find a library in your language of choice, or find a utility that will use the WSDL to generate code for you that communicates with the webservice.
One popular utility for connecting to SOAP on Android is called ksoap-android.


text:
Q: every $\sigma$ algebra is a monotone class I couldn't understand the monotone class theorem because of this lemma:
"Every $\sigma$ algebra is a monotone class."
How i can prove it?

A: A $\sigma$-algebra is closed under countable union and countable intersection, so in particular under increasing countable union and decreasing countable intersection.


text:
Q: javascript color change not working <!DOCTYPE html>

My First JavaScript

JavaScript can change the style of an HTML element.

<button type="button" onclick="myFunction()">Click Me!</button>

above code not working second time Click
i tried with many different colors
x.style.color not accepting in else block
else block not working
please help

A: A) use == instead of = in the if condition statement
B) check against rgb color notation and not hex
function myFunction() {

    x = document.getElementById("demo");
    if (x.style.color == "rgb(0, 0, 0)") {
        x.style.color = "#FF0000";
    } else {

        x.style.color = "#000000";
    }
}

http://jsfiddle.net/4QUWq/1/

A: When I test in chrome, color is rgb(255, 0, 0) that's why the if condition is always false. And your assigning in the if and not comparing (= vs ==)
Take a look at: Javascript - Converting colors (numbers -> strings) vice versa

A: Different browsers might return different values for the same colors. You better use different logic to toggle the colors. What I suggest, using pure JavaScript, is this:
var demoColors = ["#000000", "#FF0000"];
var demoFlag = true;
function myFunction()
{
    var demo = document.getElementById("demo");
    demo.style.color = demoColors[+demoFlag]
    demoFlag = !demoFlag;
}

Live test case.

A: When performing a comparison such as in a conditional use == instead of =.  = is the assignment operator.  After changing the comparison operator you must use rgb instead of the color code.
function myFunction()
{
  x=document.getElementById("demo");
  if (x.style.color=="rgb(0, 0, 0)")
  {
    x.style.color="#FF0000";
    //alert(x.style.color);
  }
  else
  {
    x.style.color="#000000";
  }
}

A: Use style.backgroundColor.
It returns name of the color or in RGB format so you will have to convert it.

A: Use rgb color notation instead of hex
<!DOCTYPE html>

My First JavaScript

 JavaScript can change the style of an HTML element.

<button type="button" onclick="myFunction()">Click Me!</button>


text:
Q: Regex - Skip first 12 characters How can I use regex to skip the lines with the text added or deleted and match text after the first 12 characters? For example,
1234567890ABTest
ABC4567890ABTestadded
ABC4567890ABTest2

Line 1 would match Test. Line 2 would not match. Line 3 would match Test2. So far, I have
.*(?<!added)(?<!deleted)$

A: ^.{12}\KTest(?!(?:added|deleted)\b).*$

You can use \K to skip first 12 characters.See demo.
https://regex101.com/r/fM9lY3/25

A: How about this?
^.{12}(.*)(?<!added)(?<!deleted)$

pattern{X} matches pattern repeated X times.
pattern{X,Y} matches pattern repeated X to Y times.
pattern{X,} matches pattern at least X.
pattern{,Y} matches pattern up to Y times.

A: I am using Notepad++ v5.7
Consider removing everything with the following patterns: ^............, .+added$ and  .+deleted$
Everything else is the expected result.
Don't forget to replace in Regular Expression mode.


text:
Q: Python SUblime Text 3 Curses I am trying to run a python file named cursesDb.py, but I get an error. That File import curses library, but when I use the sublime text editor, I can't run my program because an error occurs in this file: /usr/lib/python3.7/curses/__init__.py. I am using Linux Ubuntu 19 as my OS.
Somebody could tell me how could fix this? I am a beginner in python, exactly in these lines:
setupterm(term=_os.environ.get("TERM", "unknown")
**fd=_sys.__stdout__.fileno())**

The error occurs when I build ctr + b in sublime text, as follows below:
_curses.error: setupterm: could not find terminal

thanks!

A: Most likely this is due to the fact that curses is trying to determine what terminal type to use to do things like output colors and manipulate the cursor position.
When you use a standard build system in Sublime Text, all it does is capture the output of your program and dump it to a panel; that is, it's not a terminal at all. So there's likely no TERM variable set, and even if there was it would be meaningless because curses isn't going to work anyway.
An important note in this regard is that the "dumb terminal" that Sublime uses to dump output doesn't accept input, so if your program is expecting to gather some sort of input from the user to do something, that will also fail.
To solve both of these problems, you can do something like this:

*

*Install the Terminus package, which provides a terminal inside of Sublime

*Open up your sublime-build file and add the following keys inside of the { } characters (anywhere within there is fine).
"target": "terminus_exec",
"cancel": "terminus_cancel_build",

Now when you run the build, Terminus will open an actual terminal and run your code inside. This is more the sort of environment that curses is expecting, and is also needed if your program needs to be in any way interactive.
More details can be found in this video on making any build system interactive with Terminus if needed. This may be of particular benefit if you're not sure how to find and open the build file that you're using.


text:
Q: Differences between Windows Server 2008 and Windows MultiPoint Server 2011 I'm wondering about the differences between Windows MultiPoint Server 2011 and Windows Server 2008 R2 but only from a MultiPoint Server 2011 perspective. For example, I don't care what Multipoint Server 2011 has that Windows Server 2008 R2 doesn't, I only care about what windows Server 2008 R2 has that MultiPoint doesn't. Is there a product feature matrix available?

A: think this explans it all
http://www.youtube.com/user/msmultipoint#p/u/0/eT2zE5tMglM

A: There is a features matrix on Page 38 of the Deployment Guide.
That's about as specific as any of the MS literature on the subject gets, I think. Note that most of the features available in 2008 R2 Std appear to be available under Roles 7 Features, but a good chunk of them are untested or might be generally broken, especially running as a Domain Controller.
As for 2008 R2 Std itself, see here: http://www.microsoft.com/en-us/server-cloud/windows-server/2008-r2-features.aspx


text:
Q: Laravel custom user specific functions What and how would be the best method to create custom functions to use in views? I'm quite new to Laravel and I couldn't understand even after a lot of searching.
This is how I currently check if a user is an admin in my view for example:
@if (Auth::user()->group === "admin")

You're an admin

@endif

What would I have to do, to make this a function, so I could do something like this instead?
@if (Auth::user()->isAdmin)

You're an admin

@endif

A: Since Auth::user() returns an instance of the User model, you can simply add a method on there:
// this is in the User class
public function isAdmin()
{
    return $this->group == "admin";
}

And then call it like so:
@if (Auth::user()->isAdmin())

You're an admin

@endif

A: In your User model, add the following method:
public function inGroup($name)
{
     return $this->group == $name;
}

Now in your templates, you can do:
@if(Auth::user()->inGroup('admin'))

@endif

Note how naturally that reads: If the user is in the group named 'admin'.
As your application scales, you can keep this single method instead of having to define multiple methods to check the user's group (isAdmin, isSubscriber, isPremium, etc).


text:
Q: SVG Path : How to marker-end arrow head to circle border? I making circle (about Radian to 20). and have a few text on inside.
and I want to draw arrow-path to it.
So I use "marker-end" .  but circle override arrow.
How to (Can I ) move marker-end location to circle border?

<svg width="600px" height="400px" xmlns="http://www.w3.org/2000/svg" version="1.1">

<defs>
<marker id="endpoint" viewBox="-50 0 50 50" refX="0" refY="25" markerUnits="strokeWidth" markerWidth="20" markerHeight="20" orient="auto">
  <path d="M -50 0 L 0 25 L -50 50 z"></path>
</marker>
</defs>

<g>
<text x="10" y="50">Trouble : Arrow Hide(override) by Circle</text>
<path d="M 0,100 C 50,100 80,131 130,131 C 130,131 190,130 200,100"
        stroke="black" fill="none" marker-end="url(#endpoint)"></path>
  <path d="M 440,100 C 350,100 350,131 300,131 C 260,131 230,60 200,100"
        stroke="black" fill="none" marker-end="url(#endpoint)"></path>
 <circle cx="200" cy="100" r="20" stroke-width="2px" stroke="#aaa" fill="#fff" opacity="0.95"></circle>
<text x="165" y="105">Some Text</text>
 </g>
 <g>
 <text x="10" y="240">What I want?</text>
 <text x="10" y="260">Auto detect arrow head to border</text>
<path d="M 0,300 C 50,300 80,331 130,331 C 130,331 180,330 200,300" stroke="black" fill="none"></path>
<path d="M 185 315 L 174 312 L 185 326 z"></path>

<path d="M 440,300 C 350,300 350,331 300,331 C 260,331 230,260 200,300" stroke="black" fill="none"></path>
<path d="M 216 289 L 223 295 L 220 283 z"></path>

 <circle cx="200" cy="300" r="20" stroke-width="2px" stroke="#aaa" fill="#fff" opacity="0.75"></circle>
 <text x="165" y="305">Some Text</text>
 </g>

 </svg>

A: There is no way to have markers be drawn back along the line away from the end.
You wither need to draw the arrow heads yourself.  Or have the lines end at the circle border.

A: Thankyou everyone.I try another way.
Example.

var draw = function(type, opts) {
  var svg = document.createElementNS("http://www.w3.org/2000/svg", type);
  for (var k in opts) {
    svg.setAttribute(k, opts[k]);
  }
  return svg;
};

var getCircleDestination = function(from, to) {

  var tx = parseFloat(to.getAttribute("cx"));
  var ty = parseFloat(to.getAttribute("cy"));

  var fx = from.center.x;
  var fy = from.center.y;

  var w = fx - tx;
  var h = fy - ty;

  var z = Math.sqrt(w * w + h * h);
  var r = parseFloat(to.getAttribute("r"));

  var dz = z / r;

  var dx = tx + w / dz;
  var dy = ty + h / dz;

/* dx2,dy2 ...dz * 1.2 is no good idea. */
  var dx2 = tx + w / (dz * 1.2);
  var dy2 = ty + h / (dz * 1.2);

  var circle = draw("circle", {
    "cx": dx,
    "cy": dy,
    "r": 3,
    "fill": "red"
  });

  return {
    "s": {
      "x": dx2,
      "y": dy2
    },
    "svg": circle
  };
};

var canvas = draw("svg", {
  "width": "400",
  "height": "150",
  "style": "background-color:#f0f0f0;border:1px solid black;"
});
var def = draw("defs", {});
var marker = draw("marker", {
  "id": "endpoint",
  "viewBox": "-50 0 50 50",
  "refX": 0,
  "refY": 25,
  "markerUnits": "strokeWidth",
  "markerWidth": 10,
  "markerHeight": 10,
  "orient": "auto"
});
var marker_path = draw("path", {
  "d": "M -50 0 L 0 25 L -50 50 z"
});
var btn = document.createElement("button");
btn.style.display = "block";
btn.innerHTML = "Add Line";

canvas.appendChild(def);
canvas.appendChild(marker);
marker.appendChild(marker_path);

document.getElementById("canvas").appendChild(canvas);
document.getElementById("canvas").appendChild(btn);

var circle = draw("circle", {
  "cx": 200,
  "cy": 75,
  "r": 10,
  "fill": "white",
  "stroke": "black",
  "stroke-width": 1,
  "opacity": 0.5
});
canvas.appendChild(circle);

var paths = new Array();
btn.addEventListener("click", function() {
  var x = Math.random() * canvas.clientWidth;
  var y = Math.random() * canvas.clientHeight;
  var from = {
    "center": {
      "x": x,
      "y": y
    }
  };

  var svg = getCircleDestination(from, circle);
  var c = svg.svg;
  var stx = svg.s.x;
  var sty = svg.s.y;

  var ttx = svg.s.x + (Math.random() * 10 + 15) * (svg.s.x < x ? 1 : -1);
  var tty = svg.s.y + (Math.random() * 10 + 15) * (svg.s.y < y ? 1 : -1);

  var p = draw("path", {
    "d": "M" + x + "," + y + " Q " + ttx + "," + tty + " " + stx + "," + sty + " " + c.getAttribute("cx") + "," + c.getAttribute("cy"),
    "stroke": "black",
    "fill": "none",
    "marker-end": "url(#endpoint)"
  });

  canvas.appendChild(c);
  canvas.appendChild(p);
  paths.push({
    "c": c,
    "p": p
  });
  if (paths.length > 5) {
    var t = paths.shift();
    t.c.remove();
    t.p.remove();
  }
});


text:
Q: Acknowledgment for socket.io custom event I am looking for a method to acknowledge a socket.emit call.
socket.emit('message', msg);

I have seen a mechanism where the receiver would send another custom event as an acknowledgement, but this would add thousands of transports in my chat application. Please advice an efficient method.

A: The third argument to the emit method accepts a callback that will be passed to the server so that you can call in acknowledgement with any data you wish. It's actually really convenient and saves the effort of having paired call-response events.
I'm updating my answer with some code that I just tested.
First on the server side:
   io.sockets.on('connection', function (sock) {

    console.log('Connected client');
    sock.emit('connected', {
        connected: 'Yay!'
    });

    // the client passes 'callback' as a function. When we invoke the callback on the server
    // the code on the client side will run
    sock.on('testmessage', function (data, callback) {
        console.log('Socket (server-side): received message:', data);
        var responseData = {
            string1: 'I like ',
            string2: 'bananas ',
            string3: ' dude!'
        };
        //console.log('connection data:', evData);
        callback(responseData);
    });
});

On the client side:
console.log('starting connection...');
var socket = io.connect('http://localhost:3000');
socket.on('error', function (evData) {
    console.error('Connection Error:', evData);
});
// 'connected' is our custom message that let's us know the user is connected
socket.on('connected', function (data) {
    console.log('Socket connected (client side):', data);

    // Now that we are connected let's send our test call with callback
    socket.emit('testmessage', {
        payload: 'let us see if this worketh'
    }, function (responseData) {
        console.log('Callback called with data:', responseData);
    });
});


text:
Q: Language store view Url without slash return page with error message "no CMS page" I have a multistore with different languages, i have set the langue code to be in the URL, so
https://www.domain.com/en_ca gives page with this message
There was no Home CMS page configured or found.

https://www.domain.com/en_ca/ gives the correct CMS home page.
https://www.domain.com/fr_ca and https://www.domain.com/fr_ca/ works
The problem appears for https://www.domain.com/fr_ca and sometimes for https://www.domain.com/en_ca


text:
Q: Random filter in jinja2 reuse the same value everytime I'm trying to pick up a value from a list randomly in jinja2, this way:
{{ ['#EDD7C9', '#EDD7C9', '#EEE'] | random }}

It selects an element randomly, but it reuses it every next time. If I change something in my template, then it picks up a different number again.
But weirdly, if I use range, it works just fine:
{{ range(1,100) |random }}

Any ideas of how I can pick a random item from a fixed list without having to create my own filters?
Just to add a more complete example:
{% for i in range(5) %}
    {{ ['#EDD7C9', '#EDD7C9', '#EEE'] | random }}
    {{ range(1,100) | random }} <br/>
{% endfor %}

outputs:
#EEE 8
#EEE 61
#EEE 58
#EEE 64
#EEE 76
Any help is appreciated!
thanks :)

A: This appears to be a bug introduced in Jinja 2.9. I can reproduce it with any of the 2.9 releases (2.9 - 2.9.6). Jinja 2.8 and Jinja 2.8.1 work fine, and random values are mixed in the rendering:
$ cat test.py
from jinja2 import Template
template = Template('''
{%- for i in range(10) -%}
{{ ['foo', 'bar', 'baz', 'eggs', 'ham', 'spam'] | random }}{{ ' ' }}
{%- endfor %}
''')
print(template.render())
$ bin/python test.py
eggs eggs eggs eggs eggs eggs eggs eggs eggs eggs
$ bin/pip -U Jinja2==2.8.1
Collecting jinja2==2.8.1
  Using cached Jinja2-2.8.1-py2.py3-none-any.whl
Requirement already up-to-date: MarkupSafe in ./lib/python3.6/site-packages (from jinja2==2.8.1)
Installing collected packages: jinja2
  Found existing installation: Jinja2 2.9
    Uninstalling Jinja2-2.9:
      Successfully uninstalled Jinja2-2.9
Successfully installed jinja2-2.8.1
$ bin/python test.py
spam ham eggs spam spam eggs eggs baz bar foo

Note that this only applies to a list literal embedded in the template with random directly after. If you pass in the list as a variable, then you do get a random() result each time; that variable can also be set in the template with {% set ... %}. It appears the template compiler is optimising one step too far somewhere.
So for now the work-arounds are:

*

*Use {% set seq = ['#EDD7C9', '#EDD7C9', '#EEE'] %} and {{ seq | random }}

*Pass in a list as a variable into the template and apply random to that

*or to downgrade to 2.8.1.

I've filed issue #739 with the project to track this. The maintainers have excellent temporal skills and have fixed this a day ahead of time. A future version will include this fix (be it 2.9.7 or 2.10).


text:
Q: Configuring Servlet Security on Wildfly I am trying to run a basic project with a servlet requiring a specific role.
In the standalone.xml configuration file I have added a datasource with a JDBC binding to a derby DB containing the table enabling for authentication and authorization defined in a specific security domain I have added in the same file
 <datasource jndi-name="java:jboss/datasources/TestDS" pool-name="TestDS" enabled="true">
                    <connection-url>jdbc:derby://localhost:1527/JPADB</connection-url>
                    <driver-class>org.apache.derby.jdbc.ClientDriver</driver-class>
                    <driver>derbyclient.jar</driver>
                    <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
                    <pool>
                        <min-pool-size>10</min-pool-size>
                        <max-pool-size>100</max-pool-size>
                        <prefill>true</prefill>
                    </pool>
                    <security>
                        <user-name>user</user-name>
                        <password>passw0rd</password>
                    </security>
                    <statement>
                        <prepared-statement-cache-size>32</prepared-statement-cache-size>
                        <share-prepared-statements>true</share-prepared-statements>
                    </statement>
                </datasource>

...
<security-domains>
                <security-domain name="testDomain" cache-type="default">
                    <authentication>
                        <login-module code="Database" flag="required">
                            <module-option name="dsJndiName" value="java:jboss/datasources/TestDS"/>
                            <module-option name="rolesQuery" value="SELECT role, 'Roles' FROM users WHERE username=?"/>
                            <module-option name="hashAlgorithm" value="MD5"/>
                            <module-option name="hashEncoding" value="hex"/>
                            <module-option name="principalsQuery" value="SELECT password from users WHERE username=?"/>
                        </login-module>
                    </authentication>
                    <authorization>
                        <policy-module code="Database" flag="required">
                            <module-option name="dsJndiName" value="java:jboss/datasources/school"/>
                            <module-option name="rolesQuery" value="SELECT role, 'Roles' FROM users WHERE username=?"/>
                            <module-option name="hashAlgorithm" value="MD5"/>
                            <module-option name="hashEncoding" value="hex"/>
                            <module-option name="principalsQuery" value="SELECT password from users WHERE username=?"/>
                        </policy-module>
                    </authorization>
                </security-domain>

Now I have deployed a Dynamic Web Project and in the /WebContent/WEB-INF folder I have created a jboss-web.xml file

with this content
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <security-domain>testDomain</security-domain>
</jboss-web>

and a web.xml file with this content
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>WebApp</display-name>

  <welcome-file-list>
    <welcome-file>/webappname/index.xhtml</welcome-file>
  </welcome-file-list>

    <!--Defining security constraint for type of roles available-->
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>administrator</web-resource-name>
      <url-pattern>/webappname/MyServlet/*</url-pattern>
      <http-method>POST</http-method>
      <http-method>GET</http-method>
      <http-method>PUT</http-method>
      <http-method>DELETE</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>ADMINISTRATOR</role-name>
    </auth-constraint>
  </security-constraint>

  <login-config>
    <auth-method>FORM</auth-method>
    <realm-name>school</realm-name>
    <form-login-config>
        <form-login-page>/login.xhtml</form-login-page>
        <form-error-page>/error.xhtml</form-error-page>
    </form-login-config>
  </login-config>
    <!--Defining type of authenitcation mechanism-->

  <!--Denining security role-->
  <security-role>
    <role-name>ADMINISTRATOR</role-name>
  </security-role>

  <security-role>
    <role-name>USER</role-name>
  </security-role>
  <!--Denining security role-->

  </web-app>

The Server starts without any error.
The problem is that when I try to reach the servlet url http://127.0.0.1:8080/webappname/MyServlet the page is correctly rendered and no authentication is required.


text:
Q: Any convergent sequence is bounded. Don't we need to use the absolute value in this proof? We have the following elementary result on real sequences.
Any convergent sequence is bounded.
This is basically the proof given in my notes:
Suppose that $a_n \to a \in \mathbb{R}$. Now choose $\epsilon = 1$. From the $\epsilon-N$ definition of convergence, $\exists N \in \mathbb{N}: n > N \implies |a_n - a| < 1$. The triangle inequality gives us $|a_n| \leq |a| + 1$ for $n > N$. Therefore, choosing $C = \sup \{a_n | n \leq N\} \cup \{|a| + 1\}$ we obtain $|a_n| < C$, so $a_n$ is bounded. $\Box$
It seems to me that it is possible that, for $n < N$, $\sup \{a_n\} < -a_n$ and therefore$ \sup\{a_n\} < |a_n|$. This will be the case if, for $n < N$, $a_n$ is very negative but bounded above by a relatively small positive quantity. Therefore, we actually need $C = \sup \{|a_n| | n \leq N\} \cup \{|a| + 1\}$ for this proof to work.
Am I correct?

A: Yes, you are correct. Everything in their proof is correct until they choose $C$.
$|a_n|<|a|+1$ for all $n>N$ and $|a_n|\leq\sup\{|a_n|:n\leq N\}$, so $|a_n|\leq \sup(\{|a_n|:n\leq N\}\cup\{|a|+1\})$ for all $n$.
Take any sequence $(a_n)$ such that $a_n<0$ and $|a_n|>|a|+1$ for all $n\leq N$, and it will not be bounded in the way that their proof asserts.