text:
Q: How to change image when I select dropdown in Bootstrap I have a dropdown list in Bootstrap. How to change img src (<img src="img/website_building.jpg"...) when selecting items in the dropdown list. Is this possible?

        Test

        1
        2
        3

A:
when selecting items in the dropdown list

You can add an event to listen to when the drop down is about to be shown: bootstrap 4 dropdown events
eg:
$('.dropdown')
  .on('show.bs.dropdown', function() {
    // do something
  })
  .on('hide.bs.dropdown', function() {
    // do something
  })

within these events you can change the src attribute of the image.
Here's an example:

var imgOff = "https://i.stack.imgur.com/lxthA.jpg";
var imgOn = "https://i.stack.imgur.com/OVOg3.jpg";

$('.dropdown')
  .on('show.bs.dropdown', function() {
    $(".img-thumbnail").attr("src", imgOn);
  })
  .on('hide.bs.dropdown', function() {
    $(".img-thumbnail").attr("src", imgOff);
  })
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

        Test

        1
        2
        3

A: The simplest way is just to create event listeners for the dropdown items and change the URL based on a dictionary or some other source.
For instance, you can create event listeners for the click event as such:
$(".dropdown-item").click(function () {
  console.log('I clicked', this.innerHTML)
});

The next step is to come up with a way to map each dropdown item to the desired image URL. There are a number of ways you can do that, like using dictionaries in which ids of the items are keys and URLs are values. Below I show you an example using data attributes.

$(".dropdown-item").click(function() {
  const imageURL = $(this).data("image");
  $("img").attr("src", imageURL);
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

Select any item in the dropdown below to change the image.

    Test

          1
          2
          3


text:
Q: How do Death Eaters fight against Dementors? It's quite popularly stated that Snape was the only Death Eater capable of creating a Patronus (due to his love for Lily). Also, a Patronus is the only weapon against Dementors.
How do Death Eaters (except Snape of course) fight against Dementors? Do they just die after encountering Dementors as there's no other option?
Or, do Dementors just not attack Death Eaters because there's nothing to feed on?

A: There are ways to fight Dementors other than a Patronus.
When Harry has to write an essay for Snape, he's fairly sure he'll get a bad grade since he doesn't agree with him on how best to fight Dementors - proving that there have to be other ways. If the Patronus Charm was the only way to fight Dementors, there'd be no possibility of disagreement.

"Harry fully expected to receive low marks on his, because he had disagreed with Snape on the best way to tackle Dementors, but he did not care: Slughorn's memory was the most important thing to him now." - Harry Potter and the Half-Blood Prince, Chapter 21 (The Unknowable Room)

So, there are other ways to fight Dementors than the Patronus Charm, so Death Eaters could use another method. It's simply not true that a Death Eater would never need to fight off Dementors. They're only the Death Eaters' "natural allies" because the Death Eaters provide them with more victims when they're in power. However, Death Eaters are not immune to Dementors, and Dementors don't care much about the moral alignment of their dinner.

A: The Patronus Charm isn't the only way to to fight off the dementors as Harry argues with Professor Snape on the best way to tackle the Dementors in his sixth year.
I don't have the exact quotation at hand, however you may see this here under the heading of protection.

A: Death Eaters have no need of Patronus charms.
From this interview with JK Rowling:

Samantha: Was snape the only death eater who could produce a full patronus
J.K. Rowling: Yes, because a Patronus is used against things that the Death Eaters generally generate, or fight alongside. They would not need Patronuses.

Quote to support the above assertion, from Lord V talking to his recently recalled Death Eaters in Goblet of Fire:

Voldemort moved on, and stopped, staring at the space - large enough for two people - that separated Malfoy and the next man.
'The Lestranges should stand here,' said Voldemort quietly. 'But they are entombed in Azkaban. They were faithful. They went to Azkaban rather than renounce me…When Azkaban is broken open, the Lestranges will be honored beyond their dreams. The dementors will join us…they are our natural allies… we will recall the banished giants…I shall have all my devoted servants returned to me, and an army of creatures whom all fear…'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert a html table markup to MS Word table programmatically I've got a markup for a html table stored in a variable. It will basically contain the start and end tag for a table:

      ...

   .
   .

I need this to appear as a table in my word document. Of course, my word document is programmatically "open"; there are other sections to fill in the word document. Its only at a certain section in the document I want to insert this table.
Would appreciate if people gave me some directions on how to achieve this? I am looking for some .net code to do the same.

A: You can use an altChunk, provided the document is to be opened in Word (since Word will do the work to convert the HTML). Word is not required at the time the document is created; only for opening it.
In terms of Microsoft's OpenXML SDK classes: you want AlternativeFormatImportPart of type AlternativeFormatImportPartType.Html or Xhtml or if you have images in your table, Mht.
See http://sunnyhasan.blogspot.com/2010/04/html-to-word-document-converter-using.html or http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/d8595e50-76f6-42ab-a7d7-7bfc92a3655e/ for examples


text:
Q: Which function describes the trace of a hinged, 2 segmented slat, with one fixed endpoint? I've been staring at my closet door's trace for a while now, trying to figure out which function describes that trace it makes on the carpet below, and realised I have no idea whether the function that is associated with the geometrical description of the system is a commonly established function that I've simply never heard of (entirely possible, I am not a mathematician, I just do maths recreationally) or whether this is a set of parametric functions that doesn't really have any established research behind it because it's easy to work out and I'm just missing something that'll be obvious oncce explained.
The diagram for the sytem is the following:

We have two connected rigid bodies which for the purposes of maths are simply lines of equal length $R$, connected with a hinge. The left side of the connected pair is anchored, so it can rotate, and the right side of the connected pair is fixed to a rail (set as the x-axis in the diagram), so it can rotate and translate but with the constraint that its end point is always on the rail. As the left side is rotated the right side undergoes a transformation with its endpoints on the circle that the left side traces and the x-axis, and the collective pair "sweeps the floor" and traces the plot of a parametric function.
I would like to express this trace function in terms of the angle of rotation, and it seems appropriate to do this in two parts: the circular part from $\theta = 0$ to $\theta = \frac{\pi}{4}$, and then what looks a lot like a quadratic Bezier, but then over a dilated interval and a non-linear transformation being applied to one of the Bezier coordinates.
Would anyone happen to know the description for this function, or -if it fits a known bit of maths- what the name is that I should be googling for to help myself figure out what the function description is?
(I'm also not entirely sure what the best tags for this question is, so I've used 'geometry' but there's probably a more specific tag I should be using...)

A: If the length of each segment is $1$, when the angle is $\theta$ the second segment is a straight line from $(\cos \theta, \sin(\theta))$ to $(2 \cos(\theta), 0)$, and has Cartesian equation $F(x,y,\theta) = y \cos(\theta) + x \sin(\theta) - \sin(2\theta) = 0$.  The envelope of these will satisfy
$$\dfrac{\partial F}{\partial \theta} = -y \sin(\theta) + x \cos(\theta) - 2 \cos(2\theta) = 0$$
Letting $\sin(\theta)= s$ and $\cos(\theta) = c$, and eliminating $s$ and $c$ from the equations $$ \eqalign{y c + x s - 2 s c &=0 \cr
                               -y s + x c - 2 (c^2 - s^2) &= 0\cr
                                c^2 + s^2 - 1 &= 0\cr}$$
I get
$$ {x}^{6}+3\,{x}^{4}{y}^{2}+3\,{x}^{2}{y}^{4}+{y}^{6}-12\,{x}^{4}+84\,{x
}^{2}{y}^{2}-12\,{y}^{4}+48\,{x}^{2}+48\,{y}^{2}-64=0
$$
Despite being a sextic, this actually has a nice solution for $y$:
$$ y = \sqrt{4 - 3 (4 x)^{2/3} + 3 (4 x^4)^{1/3} - x^2} $$
where we take this for $1/\sqrt{2} \le x \le 2$.

A: If the hinge is at origin $(0,0)$, the midpoint is at
$$\begin{cases}x_m(\varphi) = r_1 \cos\varphi\\y_m(\varphi) = r_1 \sin\varphi\end{cases}$$
where $\varphi$ is the hinge angle ($0$ for completely closed, $\pi/2$ for completely open) and $r_1$ is the width of the inner door (next to the hinge). If $r_2$ is the width of the outer door, and its other end is on the $x$ axis, it must be at
$$\begin{cases}x_e(\varphi) = r_1 \cos\varphi + \sqrt{r_2^2 - r_1^2 \sin^2\varphi}\\y_e(\varphi) = 0\end{cases}$$or, in other words, at distance $r_2$ from the midpoint.
To simplify things, let us assume $r_1 = r_2 = 1$. Then,
$$\begin{cases}x_m(\varphi) = \cos\varphi\\y_m(\varphi) = \sin\varphi\end{cases}$$$$\begin{cases}x_e(\varphi) = 2\cos\varphi\\y_e(\varphi) = 0\end{cases}$$because $\sqrt{1-\sin^2\varphi} = \cos\varphi$. (Remeber, we have $0 \le \varphi \le \pi/2$).
Let's consider the points that form the outer door. They span from $(x_m(\varphi),y_m(\varphi))$ to $(x_e(\varphi),y_e(\varphi))$,
$$\begin{cases}x_d(t,\varphi) = (1-t)x_m(\varphi) + t x_e(\varphi) = (1+t)\cos\varphi\\
y_d(t,\varphi) = (1-t)y_m(\varphi) + t y_e(\varphi) = (1-t)\sin\varphi\end{cases}$$
where we just interpolate between the outer door endpoints, using $0 \le t \le 1$.
Given some point $x$ and hinge angle $\varphi$, our interpolation variable $t$ is
$$x_d(t,\varphi) = x = (1+t)\cos\varphi \iff t = \frac{x-\cos\varphi}{\cos\varphi} = \frac{x}{\cos\varphi}-1$$
Substituting into $y_d$ we get
$$y_d(x, \varphi) = \left(2 - \frac{x}{\cos\varphi}\right)\sin\varphi = 2\sin\varphi - x\frac{\sin\varphi}{\cos\varphi}$$
or
$$y_d(x, \varphi) = 2\sin\varphi - x\tan\varphi$$
which tells us the $y$ coordinate of the outer door ($x_m(\varphi) \le x \le x_e(\varphi)$) when the hinge angle is $\varphi$.
The points on the curve reach their extremum (minimum or maximum) when the derivative is zero. Here, we are interested in how the hinge angle varies the $y$ coordinates on the outer door:
$$\frac{d y_d(x,\varphi)}{d\varphi} = 0 = 2\cos\varphi - x(1 + \tan^2\varphi) = 2\cos\varphi - \frac{x}{\cos^2\varphi}$$
This has only one real solution where $0 \le \varphi \le \pi/2$:
$$\varphi(x) = \arccos\left(\left(\frac{x}{2}\right)^\frac{1}{3}\right)$$
Note, this function tells us the hinge angle where the outer door is furthest from the wall, at this point $x$. Substituting into $y_d$ we get the equation for the outer doors furthest from the wall,
$$y(x) = y_d(x,\varphi(x)) = \sqrt{4 - (4x)^{2/3}}\left(1 - \left(\frac{x}{2}\right)^\frac{2}{3}\right) = \sqrt{ 4 - 3(4x)^{2/3} + 3(4x^4)^{1/3} - x^2 }$$
Summary:
The maximum distance from the wall as a function of $x$ is
$$y(x) = \begin{cases}
\sqrt{1 - x^2},\; 0 \le x \le \sqrt{\frac{1}{2}}\\
\sqrt{4 - (4x)^{2/3}}\left(1 - \left(\frac{x}{2}\right)^\frac{2}{3}\right), \; \sqrt{\frac{1}{2}} \le x \le 2 \end{cases}$$
The distance from the wall as a function of $x$ and hinge angle $\varphi$ is
$$y(x, \varphi) = \begin{cases}
x \tan\varphi, \; 0 \le x \le \cos\varphi \\
2 \sin\varphi - x \tan\varphi, \; \cos\varphi \le x \le 2\cos\varphi
\end{cases}$$
with $0 \le \varphi \lt \pi/2$. It is a piecewise-defined curve consisting of two lines, from $(0,0)$ to $(\cos\varphi,\sin\varphi)$ to $(2\cos\varphi,0)$.


text:
Q: Get value of item on OnItemClick Listview I try to get the value of a selected Item within a custom adapter on a listview. I try this with following code:
public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {

                    View curr = parent.getChildAt((int) id);
                    TextView c = (TextView)curr.findViewById(R.id.tvPopUpItem);
                    String playerChanged = c.getText().toString();

                    Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();

                }

At the beginning, if I click, the values are good, but once I scrolled and I click on another Item, I get the wrong value of that clicked item... Any idea what is causing this?

A: The parameter v is the current row. so use:
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
    String playerChanged = c.getText().toString();

    Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}

(Or you could use getChildAt(position) but this would be slower.)
Understand you might be able to simplify this more depending on your layout.

A: Just Small Change is Required
TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);

Since you are using custom view you need to pass the View argument in your OnItemClickListener then you need to use that value to get the Details of TextViews present in that

A: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i=new Intent(ListOfAstrologers.this,AstroProForUser.class);
                i.putExtra("hello",adapter.getItem(position).getUsername() );
                startActivity(i);
            }
        });

Here username is a string field declared in a class and you must over ride getItem() method in adapter class to get the details of inflated row when you click.

A: I dont have much experience but I think if you want to pass a variable from an OnClick (which is an anonimous class) to the outside of the onClick and to the other activity, you want to pass it via Intent intent.putExtra... (it's quite easy)
Otherwise you might end up using "public static" variable, which might be a memory leak...


text:
Q: Java filter failing to set response headers I am trying to create a Java "Filter" which detects a custom HTTP Request Header, and inserts response headers so that the file will download automatically.  The response header that is most important for this is the "Content-Type = Attachment" response header.  I have created an HTTP request object that inserts the custom Header:
function myHttpObject(filePath){
function makeHttpObject() {
    return new XMLHttpRequest();
}

var request = makeHttpObject();

request.open("GET", filePath, false);
request.setRequestHeader("X-Wria-Download", "PDFdownload");
request.send(null);
window.open(filePath);
console.log(request.getAllResponseHeaders());
}

This will insert the X-Wria-Download header into the request.
Then I have a Java Filter which looks for that request header and should set the response header to "Content-Type=attachment"
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Contenttypefilter implements Filter  {

protected FilterConfig filterConfig;

public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
}

public void destroy() {
    //noop
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    //get the headers we placed in the request
    //based on those request headers, set some response headers

    if(req.getHeader("X-Wria-Download") != null){
        res.setHeader("Content-Type", "application/pdf");
        res.setHeader("Content-Disposition", "attachment; filename=success.pdf");
    }

    chain.doFilter(req,res);
}

}

And then of course the web.xml has the code to include the Filter on all jsp files.
The thing that is baffling me, is that the header is being set on the response file, but it is not downloading as it should.  If I put the res.setHeader("Content-Disposition", "attachment; filename=success.pdf"); line outside the "if" statement, then it will work, but it will apply the download behavior to all JSP's which I don't want.
Why is it applying the content-disposition but not working when I have the res.setHeader in the if statement; and then working when it is outside the if statement?  Any ideas for how I can get the desired behavior (only applying content disposition to jsp's that I have applied a custom request header to)?

A: Assuming you use a response wrapper as described here by others, the whole secret is when to call getWriter() on the original response! That's because the response object ignores all headers added AFTER you asked for a writer!
So, make sure you add all your headers Before you call getWriter().
Here is my recommended sequence for doFilter():

*

*Create a response wrapper

*chain.doFilter (origRequest, wrapper);

*Assign all required headers to the original (!) Response

*Get writer from original response

*Copy the wrapper's content to this writer

A: I think your issue is related to the Filter order of execution of your Web Context, i.e. some filters, in you web context, executes after your filter and override the header.
The Servlet Filter is an implementation of the Chain of Responsibility pattern
So you may try to:

*

*Set the headers after the call to chain.doFilter:

.
...

chain.doFilter(req,res);

HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;

//get the headers we placed in the request
//based on those request headers, set some response headers

if(req.getHeader("X-Wria-Download") != null){
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", "attachment; filename=success.pdf");
}

In this way your code will be executed after that the Servlet is called and, as explained below, if your filter is the first declared in web.xml, then the setHeader code will be the last executed (see image below).

*

*make sure that your filter is the last to be executed after the Servlet is executed, i.e. it should be the first servlet Filter declared as explained here:

As you can see Filter1 (the first declared in web.xml) is the first one executed before the servlet is executed and the last one executed after the servlet is executed. So if you want to be sure to be the last Filter setting the header then declare it as Filter1.
The order of execution is determined by the order of declaration in your Deployment Descriptor (web.xml):

Servlet spec (section 6.2.4):
"The order the container uses in building the chain of filters to be
  applied for a particular request URI is as follows:
"1. First, the  matching filter mappings in the same
  order that these elements appear in the deployment descriptor.
"2. Next, the  matching filter mappings in the same
  order that these elements appear in the deployment descriptor."

So to be sure simply declare it as the first filter in your web.xml. In this way it will be the very last filter setting the header. And, of course, set the header in your code after calling chain.doFilter, as already said.

A: Try this: set an attribute on the request if the request header is present.  Then, check for the attribute after the chain.doFilter(...) and set the response headers then.

A: The problem is the header(X-Wria-Download) of your AjaxRequest (here XMLHttpRequest) is not being set in your HttpServletRequest object before the filter is being served.
I think better Idea will be to  use a Dedicated Servlet to handle your ajax request.


text:
Q: Scrapy scrapes data but no output to file I've been getting blank json files despite successfully being able to execute most of the lines in scrapy shell.
When I run the command scrapy crawl courses with my courses bot being:
from scrapy.spiders import CrawlSpider
from scrapy.linkextractors import LinkExtractor
from tutorial.items import CoursesItem
from bs4 import BeautifulSoup
import scrapy

class CoursesSpider(CrawlSpider):
    name = 'courses'
    allowed_domains = ['guide.berkeley.edu']
    start_urls = ['http://guide.berkeley.edu/courses/ast',
                   ]

def parse(self, response):
    soup = BeautifulSoup(response.body_as_unicode(), 'lxml')
    items = []
    for course_info, course_desc, course_req in zip(soup.find_all('p',class_='courseblocktitle'), \
                                                soup.find_all('p', class_='courseblockdesc'), \
                                                soup.find_all('div', class_='course-section')):
        item = CoursesItem()
        item['title'] = course_info.text
        item['description'] = course_desc.text
        item['requirements'] = course_req.text
        yield items

and by settings.py being
BOT_NAME = 'courses'

SPIDER_MODULES = ['tutorial.spiders']
NEWSPIDER_MODULE = 'tutorial.spiders'

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0.3'

# ITEM_PIPELINES = {
#   'tutorial.pipelines.JsonExportPipeline': 300
# }

FEED_URI = 'output.json'
FEED_FORMAT = 'json'

As you can see in the commented section, I've also tried making a pipeline.
My pipeline file looks like this:
from scrapy import signals
from scrapy.exporters import JsonLinesItemExporter

class JsonExportPipeline(object):

    def __init__(self):
        self.files = {}

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls()
        crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def spider_opened(self, spider):
        file = open('%s_spider.json' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporter = JsonLinesItemExporter(file)
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

But I feel that might not be where the error lies although it's possible since I largely followed a couple of tutorials I found.
I used BeautifulSoup to simplify the way I select the items.
Last but not least, the terminal looks like this after I run it.
2015-08-07 23:58:44 [scrapy] INFO: Scrapy 1.0.1 started (bot: courses)
2015-08-07 23:58:44 [scrapy] INFO: Optional features available: ssl, http11
2015-08-07 23:58:44 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tu
torial.spiders', 'FEED_URI': 'output.json', 'SPIDER_MODULES': ['tutorial.spiders
'], 'BOT_NAME': 'courses', 'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv
:39.0) Gecko/20100101 Firefox/39.0.3', 'FEED_FORMAT': 'json'}
2015-08-07 23:58:44 [scrapy] INFO: Enabled extensions: CloseSpider, FeedExporter
, TelnetConsole, LogStats, CoreStats, SpiderState
2015-08-07 23:58:44 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddl
eware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultH
eadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMidd
leware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-08-07 23:58:44 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-08-07 23:58:44 [scrapy] INFO: Enabled item pipelines:
2015-08-07 23:58:44 [scrapy] INFO: Spider opened
2015-08-07 23:58:44 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 i
tems (at 0 items/min)
2015-08-07 23:58:44 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2015-08-07 23:58:45 [scrapy] DEBUG: Redirecting (301) to <GET http://guide.berke
ley.edu/courses/ast/> from <GET http://guide.berkeley.edu/courses/ast>
2015-08-07 23:58:45 [scrapy] DEBUG: Crawled (200) <GET http://guide.berkeley.edu
/courses/ast/> (referer: None)
2015-08-07 23:58:45 [scrapy] INFO: Closing spider (finished)
2015-08-07 23:58:45 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 537,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 22109,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/301': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2015, 8, 8, 6, 58, 45, 600000),
 'log_count/DEBUG': 3,
 'log_count/INFO': 7,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2015, 8, 8, 6, 58, 44, 663000)}
2015-08-07 23:58:45 [scrapy] INFO: Spider closed (finished)

I've ran most of my options thoroughly. Running the singular option of --parse tells me that I'm off in parsing the items, but even then, I'd like to know where to go beyond the parse bug fix (ie outputting to json). Ultimately, I want to pipe all this data into a database.
I know it's a lot to look through, but any help is appreciated, thanks!

A: You write a wrong word. In parse function change items -> item.
def parse(self, response):
    soup = BeautifulSoup(response.body_as_unicode(), 'lxml')
    items = []
    for ...
        item = CoursesItem()
        item['title'] = course_info.text
        item['description'] = course_desc.text
        item['requirements'] = course_req.text
        yield items # -> item

`


text:
Q: Postgres: Selecting records where left joined records, all don't meet certain criteria For example I have a posts table and a users table.
users has, :post_id, :user_id, :published_date, :body
What I want to do is select users that have never set a published_date on any their posts.
I was thinking start with user then left join posts table but im not sure what to put on my where clause as it needs to on pick out users where all their posts don't have a published date

A: How about something like:
SELECT user.user_id
FROM user
LEFT JOIN post ON post.user_id=user.user_id AND post.published_date IS NOT NULL
WHERE post.post_id IS NULL

You match each user with his posts that have a published date. If there are none, the left join will return null values for matchings in the post table (even for columns that should never be NULL such as the post_id primary key). You use this in your WHERE clause to return only rows with no match.

A: select user_id
from t
group by user_id
having bool_and(published_date is null)

bool_and

bool_and(expression) - true if all input values are true, otherwise false


text:
Q: Is it possible to communicate with an iPhone over a serial-bt-bridge? I have a device with an rs-232 port and a btm222-bt-serial bridge. Is it possible to communicate with an iPhone using this setup?
Does the iPhone have the Bluetooth serial port profile?

A: It is not directly possible.
You will have to change the RS322 device firmware (and possibly hardware) to be compatible with Apple  accessory (joining Apple MFi will give more details).
So it can be done if you can do a ground up design change.


text:
Q: Too many indices for array | python I'm trying to copy arrays to a pandas Dataframe and get the error "too many indices for array".
temp =  pd.date_range(date_from, date_to)[:len(pr_daily)]

for index in range(len(a_id)):
    if index == 0:
        finalDataframe['date'] = temp
    finalDataframe[f'pr_{a_id[index]}'] = pr_daily[:, index]
    finalDataframe[f'gloabl_irradiance_tilted_in_kWh_per_m2_{a_id[index]}'] = rad_daily[:, index]
    finalDataframe[f'system_id_{a_id[index]}'] = a_id[index]

The error occurs in these lines:
finalDataframe[f'pr_{a_id[index]}'] = pr_daily[:, index]
finalDataframe[f'gloabl_irradiance_tilted_in_kWh_per_m2_{a_id[index]}'] = rad_daily[:, index]

pr_daily and rad_daily are numpy arrays of of the same length.

Traceback (most recent call last):
File "C:\Users...\Downloads\python_scripts\pv.py", line 277, in

finalDataframe[f'pr_{a_id[index]}'] = (pr_daily[:,index])
IndexError: too many indices for array

A: This error is thrown when you try to access an array element by providing too much indices.
e.g You try to access the second dimension of a 1-dimension array.
Check the shape of pr_daily and rad_daily if they indeed are 2D arrays.
a = np.random.rand(5,)
b = np.random.rand(5,5)

print(f'b[:,1] :: {b[:,1]}') --> OK
print(f'{a[:,1]}') --> IndexError: too many indices for array

You can access a numpy array shape with the shape attribute


text:
Q: Change text color of a predefined layout I searched everywhere but I cannot find a solution for this simple question: I'm using a predefined layout R.layout.simple_list_item_1 but I cannot find the way to modify the text color of the TextViews inside it.

A: If you don't want to use your own XML layout, you can get the TextView from that layout and set the color on that. The ID of the TextView in R.layout.simple_list_item_1 is android.R.id.text1 (see the source for that layout).
TextView tv = (TextView) findViewById(android.R.id.text1);
tv.setTextColor(getColor(R.color.new_text_color);


text:
Q: How to pass variable to callback function? I have a simple example:
   for ( i in dbs ) {
       var db = dbs[i].split(':')
       var port = dbs[i][0]
       var host = dbs[i][0]
       var client = redis.createClient( port, host )
       tasks = [ [ "info" ] ]
       client.multi(tasks).exec(function (err, replies ) {
           console.log(port)
       })

How to print corrent port for each client connect ?

A: A simple way is to enclose the loop body in a self-invoking anonymous function:
for (var i in dbs) {
    (function(i) {
        var db = dbs[i].split(":");
        var host = db[0];  // Probably 'db[0]' instead of 'dbs[i][0]'.
        var port = db[1];  // Probably 'db[1]' instead of 'dbs[i][0]'.
        var client = redis.createClient(port, host);
        tasks = [ [ "info" ] ];
        client.multi(tasks).exec(function(err, replies) {
            console.log(port);
        });
    })(i);
}

That way, the current value of port is properly captured by the closure and will be available in the callback passed to exec().
Note this answer assumes that dbs is an object, not an array, even though you're using i as the loop variable. If dbs is an array, you should use an indexed loop instead:
for (var i = 0; i < dbs.length; ++i) {
    // ...
}

Because for... in loops are not meant to iterate over arrays.


text:
Q: Palindrome function in python Hey so my assignment is:
palindrome = reverse    is  the same    as  the itself, e.g.
"doggod" is a   plaindrome), scan   a   file     line   by  line     find   the palindrome  in  it  and
return  a   list     with   palindrome  found.
This is what I have so far:
def find_palidrome(word):
    if len(word) < 1:
        return True
    else:
        if word[0] == word[-1]:
            return find_palidrome(word[1:-1])
        else:
            return False
def fileInput(alice.txt):
    f = open(alice.txt,'r')
    line = f.readline().strip()
    while line != '':
        if(find_palidrome(line)):
            print(line)
        else:
            print("No palindromes found")
        line = f.readline().strip()
    file.close()

Its not working and keeps saying syntax error IDK whats wrong.
Can someone please help!!?  Thanks!

A: This is a much simpler way to find a palindrome of a word:
def is_palindrome(word):
    return word == word[::-1]

And then to read the file:
def check_file(file_name):
    with open(file_name, 'r') as f:
        for line in f:
            if is_palindrome(line):
                print(line)
            else:
                print("No palindromes found")

if __name__ == '__main__':
    f_name = input('Enter a file path')
    check_file(f_name)

As others have pointed out the problem was not passing in your file name as a string. In the code I have posted the file name is entered as a string by default from the input() built in. Wrapping everything up in an if __name == '__main__' block makes it so that you can import these functions into other programs with out running the whole script.


text:
Q: Timing? - cocoa How would I be able to use timers? For example I want to show a certain text for 10 seconds and then I want to show a different text for the rest of the duration.
Thanks,
Kevin

A: The easiest way to defer an action is to use NSObject's performSelector:withObject:afterDelay:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

Set your text the first time (or at init time) and then do something like:
[self performSelector:@selector(changeText) withObject:nil afterDelay:10.0];

You can cancel the request with:
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument

which you will need to do if you want your object to be deallocated as performSelector retains both your object and the withObject parameter.

A: Start with the Timer Programming Topics for Cocoa.

A: NSTimer documentation.


text:
Q: Poisson Distribution vs Binomial Distribution I have a specific problem here. It is stated as:
"Assume that 30% of students in a university take public transportation daily to commute to their college. Suppose 10 of the students are randomly selected.
What is the appropriate probability distribution? Also, what is the probability that at least 2 out of 10 students take public transportation daily?"
I looked into jbstatistics for the answer, but I would just like to cross verify. Kindly tell me which distribution you would choose (poisson/binomial) and also, why?
Thanks,
Chris

A: It is a binomial question as the number of students investigated is fixed at exactly 10 and the probability is "per student".
"Given n = 10, each with a constant probability (p = 0.30) what is the probability of at least 2 positives" is a standard question for a binomial distribution.
Poisson distributions do not have an upper limit.

distr <- dbinom(x=0:10, size=10, p=.3)
plot(0:10, distr, main = "Binomial with n = 10, p = .3", type="h",
     xlab="Students out of 10", ylab = "Probability")
text(0:10, y = distr, labels = round(distr,3))

A: Further to what @Bernhard has noted, you are after the binomial distribution as you have yes/no trials (did they take public transport or not).
You might use the Poisson distribution when:

*

*The experiment results in outcomes that can be classified as successes or failures.

*The average number of successes (μ) that occurs in a specified region is known.

*The probability that a success will occur is proportional to the size of the region.

*The probability that a success will occur in an extremely small region is virtually
zero.

A way to show the 'no upper limit' might be goals in football (or any sport where the highest score is not limited (e.g. not tennis)). There could be between 0 and any number of goals in a game. You would have an average number of goals in a game though and from that you can calculate the probability of (for example) six goals in a game. Example here.


text:
Q: HttpPostedFileBase not binding to model here is my ViewModel
public class FaultTypeViewModel
{
    [HiddenInput(DisplayValue = false)]
    public int TypeID { get; set; }

    [Required(ErrorMessageResourceType = typeof(AdministrationStrings), ErrorMessageResourceName = "FaultTypeNameRequired")]
    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeName")]
    public string TypeName { get; set; }

    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeDescription")]
    [DataType(DataType.MultilineText)]
    public string TypeDescription { get; set; }

    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeImageFile")]
    public HttpPostedFileBase TypeImageFile { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string TypeImageURL { get; set; }
}

Notice I have a "TypeImageFile" HttpPostedFileBase
I would expect that the model binder would bond that property from the form to the model passes to the controller bu I just keep receiving null.
here is the relevant code in the View:
@using (Html.BeginForm("AddFaultType","Administration", FormMethod.Post))
{

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×</button>

@SharedStrings.Add @SharedStrings.FaultType

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.TypeName)

            @Html.EditorFor(model => model.TypeName)
            @Html.ValidationMessageFor(model => model.TypeName)

            @Html.LabelFor(model => model.TypeDescription)

            @Html.EditorFor(model => model.TypeDescription)
            @Html.ValidationMessageFor(model => model.TypeDescription)

            @Html.LabelFor(model => model.TypeImageFile)

            <input type="file" name="TypeImageFile" id="TypeImageFile" />

        <input type="submit" value="@SharedStrings.Add" class="btn btn-primary" />
        @Html.ActionLink(SharedStrings.Cancel, "Index", "Administration", null, new { Class = "btn", data_dismiss = "modal", aria_hidden = "true" })

}

and here is the controller:
        [HttpPost]
        public ActionResult AddFaultType(FaultTypeViewModel i_FaultToAdd)
        {
            var fileName = Path.GetFileName(i_FaultToAdd.TypeImageFile.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            i_FaultToAdd.TypeImageFile.SaveAs(path);

            return RedirectToAction("Index");
        }

A: Make sure you've set the enctype attribute on your form to multipart/form-data on your form if you want to be able to upload files:
@using (Html.BeginForm("AddFaultType", "Administration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    ...
}

A: Completing Darin's answer:
Make sure you've set the enctype attribute on your form to multipart/form-data on your form if you want to be able to upload files:
@using (Html.BeginForm("AddFaultType", "Administration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    ...
}

To ensure your <input> is transmitted to the controller as part of the model use the  Html Helpers for Id and name like below:
<input type="file" id="@Html.IdFor(x=>x.HttpPostedFileBase)" name="@Html.NameFor(x=>x.HttpPostedFileBase)" accept=".csv,.txt"/>

Works in MVC5 sorry I cant find any reference to which helpers are available in MVC3


text:
Q: Enigmail Error - "no matching secret key found to decrypt message" After switching the Linux Distributions, gpg changed and I could not encrypt any emails. Even my own. Enigmail gave me "No matching secret key found to decrypt message" error message.
Before:
$gpg --version
gpg (GnuPG) 2.1.18
libgcrypt 1.7.6-beta

Now:
$gpg2 --version
gpg (GnuPG) 2.2.13
libgcrypt 1.8.4

Both have Enigmail 2.0.9.

A: In the end, this helped: https://sourceforge.net/p/enigmail/forum/support/thread/03ebee57/
gpg2 --edit-key 0xYourKeyId setpref save

(0xYourKeyId taken from gpg2 --list-secret-keys)
EDIT: ok, this does not work. I can decrypt messages for like 5 minutes since I had to unlock the keychain in the dialog.

A: It's been long time since you wrote. Nevertheless I'd try to give it a chance, as I think similar problem still might happen (again).

*

*First of all try this command:
gpg-agent --daemon
Expectation is, it would show you if something is wrong with config file(s). Example output:
gpg-agent[22861]: /home/<REPLACE_WITH_YOUR_USERNAME>/.gnupg/gpg-agent.conf:13: invalid option

This, for example, is telling you: "Line 13 in that file contains invalid setting option".
In this case, edit that file, remediate the error or comment out the line creating the error for example like this:

*Edit the file. Example, in your console/terminal, try one of this:
nano /home/REPLACE_WITH_YOUR_USERNAME/.gnupg/gpg-agent.conf
gedit /home/REPLACE_WITH_YOUR_USERNAME/.gnupg/gpg-agent.conf
editor /home/REPLACE_WITH_YOUR_USERNAME/.gnupg/gpg-agent.conf

*now go to that line (here in the example it is line 13), and replace its content, example
ignore-caching-for-signing
with the line
# ignore-caching-for-signing

Plsease note the '#' in front of the line, which is the comment sign to deactivate the invalid option.

*Go to line 1. above and repeat the gpg-agent command, and the steps up to this line, until the gpg-agent starts without complaining about invalid options
gpg-agent --daemon

*Now start thunderbird with enigmail, and click on the encrypted mail. From my experience, you should now be able to see its content.


text:
Q: Get User name in stead of DomainName\UserID in C# i am using User.Identity.Name to get User Name.
But in stead of User Name I am getting DomainName\UserID.
I am using Windows Authentication.
Can anybody please suggest any way to get User Name instaed of UserID in windows authentication. C#.
Thank you....

A: I think you are looking for user display name. Here is way to get it :
using System.DirectoryServices.AccountManagement;
var name = UserPrincipal.Current.DisplayName;

You need to add a reference to System.DirectoryServices.AccountManagement.dll

A: logon_user = Request.ServerVariables["LOGON_USER"].Substring(// you domain length here);

e.g :
if Domain is "8" character long then,
logon_user = Request.ServerVariables["LOGON_USER"].Substring(8);


text:
Q: UISearchDisplayController with more than one search term I wonder if there is any way to search for more than one word using UISearchDisplayController? If I for example want to search for posts containing both "James" AND "London"? Or "James" and "Smith"?
I have searched but not found an answer to this.
This is what I do now, to see if the search term is in either the name or address.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSMutableArray *searchItemsPredicate = [NSMutableArray array];
    NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
    [searchItemsPredicate addObject:namePredicate];
    NSPredicate *addressPredicate = [NSPredicate predicateWithFormat:@"address contains[c] %@", searchText];
    [searchItemsPredicate addObject:addressPredicate];
    NSCompoundPredicate *combinedPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:searchItemsPredicate];

    searchResults = [_array filteredArrayUsingPredicate:combinedPredicate];
}

A: A possible solution would be to separate each words.
You can use a NSRegularExpression or use simply componentsSeparatedByString: (to keep it simple).
NSArray *words = [searchText componentsSeparatedByString:@" "];
NSMutableArray *allPredicates = [[NSMutableArray alloc] init];
for (NSString *aWord in words)
{
     NSPredicate *addressPred = [NSPredicate predicateWithFormat:@"address contains[c] %@", aWord];
     NSPredicate *namePred = [NSPredicate predicateWithFormat:@"name contains[c] %@", aWord];
    [allPredicates addObject:addressPred];
    [allPredicates addObject:namePred];
}

NSCompoundPredicate *finalPredicate = [[NSCompoundPredicate alloc] initWithType: NSOrPredicateType subPredicates:allPredicates];

searchResults = [_array filteredArrayUsingPredicate: finalPredicate];

You can use a more complexe scheme for your "words limitations" (comma, etc.) to mark delimitations for example:
Searching @"Banana, Apple fruit" could be in fact looking for "words" : @"Banana" and @"Apple fruit", in that case the separator string would be "," (and you may have to trim for white spaces).


text:
Q: How do I calculate the structure-matrix and standardized discriminant coefficients from a Linear Discriminant model in R? First post here, but long-time lurker. I'm working on a batch of multivariate data and want to make comparisons between the standardized coefficients generated by an LDA and the standardized loadings generated by a PCA.
I've read through the posts (and here), where ttnphns and Etienne had a great exchange about PCA and LDA. I'm looking for some code in R to calculate what ttnphns describes as the standardized discriminant coefficients and pooled within-groups correlations between variable and discriminants.
I know that ttnphns offers the formulas for how these are calculated, in the posts above but it would be great to get some snippets of code that the community can use to generate these super-useful sets of values!
Does anybody have any experience with calculating these from the lda function in MASS?
Cheers!

A: It's a bit weird to answer your own question, I suppose, but hopefully this will be a useful bit of information for folks looking to do this in the future. I used the great package candisc, which has outputs for both the structure matrix and the standardized coefficients! Cheers!


text:
Q: What is the most efficient way to solve a workshop scheduling problem? I am trying to design an algorithm to solve a workshop scheduling problem.
The problem is as follows:
I have to schedule a workshop consisting of a finite number of time slots, and a finite number of students. Each time slot has a capacity, which must be fulfilled. Each student has a list of preference corresponding to a set of time slots, where he/she wants to work.
For instance picture the following work shop:

where time slot 1,1 has capacity 3 and time slot 1,2 has capacity 4 and so on.
I want to optimize my scheduling so that students has the least overhead as possible. Overhead is defined as having to "wait" between work. For instance the following picture shows a student, that can work all three time slots in a day, but is only assigned to the first and the last, thus having one time slot overhead.

Thus: My objective function is to find a feasible solution while minimizing the students' total overhead.
My idea on how to solve it, is to construct a graph (see underneath), run a max-flow algorithm to determine a feasible solution, compute the total overhead (penalty), introduce some sort of randomization to change the schedule and compute the new overhead. Repeat the last 3 steps an arbitrary number of times to find the local minimum.
Graph:

Edit: Explanation of graph: The above graph shows 5 students, which each can be connected to up til 3 time slots. Each edge between a student and a time slot symbolizes that the student wants to work on that specific time slot. Each of these edges has a capacity of 1. The source node, S has edges to every student with the capacity of infinite, because each student can work as much as he/she wants. Each edge from a time slot to the sink node T, has a capacity, of the specific time slot's capacity.
Pseudo code
function solve-this(timeslots, students) {
    create graph from time slots and students
    run ford-folkerson max-flow algorithm to determine a feasible solution
    while(local optimal solution not found) {
        compute penalty / overhead
        if(computed penalty < current solution) {
            current solution = this solution
        }
        change schedule based on some sort of randomization factor
    }
    return solution
}

Is there any smarter way to do this? Is this the best way to find an somewhat optimal solution, without checking every possible schedule?
Any help, comments and/or feedback is greatly appreciated.


text:
Q: Can't get visual studio to run projects on my browser I have worked within visual studio over 1,000 times. I'm trying to figure out how to attach a browser to my project so that I can view the solution.
Every time I try to run a file and click the 'play' button, there is no browser listed.
picture of visual my visual studio attach button
How do I attach chrome or internet explorer and start my project?


text:
Q: Ошибка Function implicitly has return type 'any' because it does not have a return type annotation interface Props {
  nameRu?: string,
  id?: number,
  nestedChildren?: Props[]
}

export const getData = <T extends Props>(data: T[]) => data.map(item => ({
  label: item.nameRu,
  value: item.id,
  ...((item.nestedChildren && !isEmpty(item.nestedChildren))
    ? { nestedChildren: getData(item.nestedChildren) }
    : {}),
}))

Есть такая функция, ts выдает такую ошибку.

Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.

Может есть у кого соображения как это испправить?

A: Ну если просто избавиться от ошибки, то можно так

export const getData = <T extends Props>(data: T[]): object => data.map(item => ({
 label: item.nameRu,
 value: item.id,
 ...((item.nestedChildren && !isEmpty(item.nestedChildren))
     ? { nestedChildren: getData(item.nestedChildren) }
     : {}),
}))

А вообще по-хорошему надо вместо object прописать интерфейс/тип, возвращаемый данной функцией

A: Указать возвращаемый тип:
interface Props {
  nameRu?: string,
  id?: number,
  nestedChildren?: Props[]
}

type Data = {
  label?: string,
  value?: number,
  nestedChildren?: Data[]
}

export const getData = <T extends Props>(data: T[]): Data[] => data.map(item => ({
  label: item.nameRu,
  value: item.id,
  ...((item.nestedChildren && !isEmpty(item.nestedChildren))
    ? { nestedChildren: getData(item.nestedChildren) }
    : {}),
}))


text:
Q: Sails.js object has undefined collection after populate Whenever I populate a collection in Sails.js, the values are populated inside modelName.associations.collectionName.value. The value of modelName.collectionName is always undefined even though when I represent the object as  JSON everything is shown perfectly.
Taking the example of a Many-to-Many relationship given in the documentation (http://sailsjs.org/#/documentation/concepts/ORM/Associations/ManytoMany.html), if I do the following query:
User.findOne(1)
.populate('pets')
.exec(function(err, owner) {...});

I would get the pets collection in owner.associations.pets.value, but owner.pets is undefined.
Any ideas what is going on here?
EDIT:
I have replicated the exact same example given in the documentation (the same Pet.js, User.js and bootstrap.js) and I have overridden the findOne blueprint of User.js in this way:
findOne: function (req, res) {

  User.findOne(req.params.id)
    .populate('pets')
    .exec(function(err, owner) {
      if (err) return res.send(err, 500);
      return res.json(owner);
    });

}

As I expected, the JSON response is alright, but if I set a breakpoint inside the exec(..) function, owner.pets is undefined. The data is only in owner.associations.pets.value.
Could it be my version of Sails.js? It's 0.10.0-rc11.


text:
Q: Why does Flash (2014) not simply disarm or knock out his opponents in the moment he arrives? I'am aware of the "Why is the Flash not unstoppable" question but it does not answer the question for the 2014 TV-show.
Here we see the following very often:
Flash arrives and stops and talks to his opponents, often giving them time to shoot at him or invoke environmental effects that harm him. Perhaps in the first season we could argue that he is overconfident and unexperienced, but later in the show this argument does not hold, I think.
He has to "distract" them somehow with some clever trick because he can't get near them (Why? With his speed he can be behind them, disarm them and/or knock them down before they can even "fire" once at him.)
When they are "distracted" he does exactly that. In a split second he just disarms them or knocks them down.
Yes. If an opponent creates conditions that harm or hinder Flash BEFORE he arrives, it makes sense. If the opponent has super fast reflexes (like Flash himself) so he can shoot and hit him even when speeded, it makes sense. If the opponent is invulnerable and the flash when trying to knock him out hurts himself it makes sense. If the flash is surprised by the opponent and not in speed mode, it makes sense.
But we often see opponents that shoot on him with some weapons or abilities and while they don't seem to have super fast reflexes and moving, Flash isn't able to get near them and just disarm them or knock them out.
This especially is obvious in some encounters with Captain Cold. It should be no problem for Barry to disarm him and get his gun in the moment he arrives before Captain Could could even think of firing at him (later he has a dead man switch at his could gun that could in some situations prevent this).
Another example is his encounter with Dr. Light. He has to move so fast that he creates several images of him where Dr. Light fires on. Then he is able to attack her from behind and knock her down. There shouldn't be any problem doing this without the false images.
On other occasions he has no problem even with warned opponents. When he is blackmailed to let his two opponents beat him to death (otherwise several bombs will kill 100 children) his team succeeds to disarm all the bombs. The villains (who in the past were a match for him even without the other) notice that (and even say "Oh oh") and in the next moment one is bound and the other nearly beaten to death.
So is it just very very bad writing or is there any theory why Flash has problems to handle such opponents without difficulties?


text:
Q: Using prevNext Modx Addon I need to display previous and next resource with tv in one parent using this addon in modx
http://modx.com/extras/package/prevnext
But there is some simple documentation, and i can see it has a lot of options, is it posible that someone can show me simple example of tlp.

A: Use pdoNeighbors (part of pdoTools) - it has better documentation and examples.

A: https://modx.com/extras/package/prevnext shows clear description and parameters.
[[!prevNext]]


text:
Q: Can I increase yield from blocks? Is there some way to increase the yield from every block? E.G. 5 diamonds from diamond ore instead of one.
Answers for either version of Minecraft are fine.
Edit: mods/trainers would be great

A: The Fortune enchantment can increase the amount of drops from an ore, up to 4 times as much. Fortune ranges in level from I to III.
Keep in mind that Fortune is incompatible with Silk Touch.

A: There's no enchantment that will allow you to get 2 or more block in vanilla minecraft. All Ores excluding iron and gold ore can give more than 1 drop if you use Fortune pickaxe. Also you can use fortune tools to increase the drops from wheat(seeds), potato, carrots, etc.


text:
Q: Force mysql varchar field to upper using select in update clause Trying to update a table so that a field has it's contents changed to UPPERCASE.
UPDATE `schools` SET `postcode` =
UPPER(
(SELECT `postcode` FROM `schools` WHERE 1)
)

Tried this
UPDATE `schools` SET `postcode` =
UPPER(
SELECT `postcode` FROM  (SELECT * FROM `schools`) AS x WHERE `postcode`!=''
) WHERE 1

I know it's possible but can't wrang that syntax

A: try this:
UPDATE `schools`
SET `postcode` =UPPER(`postcode`)

A:
you should try like this
UPDATE schools SET postcode =UPPER(SELECT `postcode` FROM `schools` WHERE ur_column = values)


text:
Q: Why does this algorithm fail for integers that are not powers of 2? Based on this answer, I'm implementing a simple algorithm in Python 3.x to determine whether or not a integer n is a power of another integer base. However, the algorithm doesn't return the correct result. The code in the linked answer is:
while (n % 3 == 0) {
    n /= 3;
}
return n == 1;

(A comment indicates that checking n == 0 is also necessary, logically). This is my code:
def is_power(n: int, base: int) -> bool:
    if n == 0:
        return false
    while (n % base == 0):
        n /= base
    return n == 1

I wrote simple testing code that tests a certain range of bases and exponents, but the results it returns are incorrect. Testing code:
for base in range(3, 10):
    print("Base: {0}".format(base))
    for exp in range(30, 40):
        b = is_power(pow(base, exp), base)
        if not(b):
            print("{: <3}: {: <5}".format(exp, str(b)))

I tested this with a much larger range, but for the sake of output, I limited it in this example. This outputs:
Base: 3
35 : False
36 : False
37 : False
38 : False
39 : False
Base: 4
Base: 5
30 : False
31 : False
32 : False
33 : False
34 : False
35 : False
36 : False
37 : False
38 : False
39 : False
Base: 6
35 : False
36 : False
37 : False
38 : False
39 : False
Base: 7
30 : False
31 : False
32 : False
33 : False
34 : False
35 : False
36 : False
37 : False
38 : False
39 : False
Base: 8
Base: 9
30 : False
31 : False
32 : False
33 : False
34 : False
35 : False
36 : False
37 : False
38 : False
39 : False

which is clearly incorrect. I've tried debugging a small example, where n = pow(3, 35) and base = 3 yields these values of n in the loop:
50031545098999707
1.6677181699666568e+16

and the loop ends, because 50031545098999707 / 3 == 1.667718169966656 9 e+16 (note that the last digit is different). Is this the problem? Are Python's calculations failing? If not, what is the problem with this algorithm?
The algorithm also fails even more if I use math.pow instead, but I'm not necessarily surprised by that, since checking one example demonstrates that pow and math.pow don't always return the same value.
import math
pow(3, 35) == math.pow(3, 35) # 50031545098999707 != 5.0031545098999704e+16

A: Since you are using Python 3, you should use
def is_power(n: int, base: int) -> bool:
    if n == 0:
        return false
    while (n % base == 0):
        n //= base
    #     ^^ note two slashes
    return n == 1

In Python 3.x, the / operation always perform "real division" and return a floating point number, but in the algorithm you've linked to, it expects the / to do integer division, which is done with the // ("floor division") operator instead.
And the test fails really because of the lack of precision in floating-point arithmetic, as you have expected. The algorithm is still correct when / returns an infinite-precision real number. Take 3.034 as an example,
3.0 ** 34 == 16677181699666569
          == 0b111011001111111100111011110011000100000011001010001001

The default floating-point format only supports 53 bits of precision, but the above number requires 54 bits to represent, so we have to round off the last bit (the 1), resulting in
             0b111011001111111100111011110011000100000011001010001000
                                                                    ^
          == 16677181699666568

which the modulus to 3 will return 2, which will break the loop and return false.
(I haven't checked why it rounds down instead of up, but even if it rounds up the modulus is still not zero, so it will still return false.)

A: Think about your algorithm: what do you want /= to do?
Floating point division? Or integer division? Your question clearly uses the former, but try it by hand and see if it will work--you will keep dividing by base and getting non-integers.
In python 3, integer division is //.


text:
Q: Hooks: processDatamap_preProcessFieldArray() I am about porting an Extention from T3-6.2 to T3-7.6+
public function processDatamap_preProcessFieldArray(
   &$fieldArray, $table, $id,
   \TYPO3\CMS\Core\DataHandling\DataHandler &$pObj
) {
    // t3_origuid is set? Yes, ist a Copy
   if(isset($fieldArray['t3_origuid']) && $table=='mytable') {
      $fieldArray['field1']++;
      $fieldArray['filed2']--;
   }
}

BUT:
To tell if it is a copy or not this needs the field 't3_origuid' in my record. It is not a standard field but if present it is filled by typo3.
Where does this filed come from? My I use this witout further problems?
If you know a hook/better way, (Slot, Signal?) to use in this case in T3 7.6+ please let me know.
Thanks a lot,
Christian.

A: This field is used by the sys extension workspace. If you change a tt_content element inside a workspace the original uid will be stored inside the field. So the changes,when they will be published, can be applied to the original element.


text:
Q: java string.replace running too slow with methods I have a method with a String as an argument that replaces specific placeholders with strings from methods:
public static String format(String in)
{
    in=in.replace("[time]",getTime()); //just some methods returning strings
    in=in.replace("[name]",getName());
}

my problem is that even if the string "[time]" doesn't occur in the string in, the methods getTime() and getName() are called every time format(String) is called. Since i call format(String) hundreds of times, it takes me up to an minute to parse all the strings. Since getTime() and getName() require much time to execute and the substrings "[time]" and "[name]" are rare, it would be much faster if the replace method only called getTime() or getName() when there is a placeholder. the fastest possible solution i see is to rewrite string.replace() to replace(String). Now my two questions are:

*

*is there a faster way to do this?

*which is the fastest way to write replace(String)?

A: If searching in the string takes less time than calling getTime() and getName(), then use contains first.
if (in.contains("[time]"))
{
    in=in.replace("[time]",getTime());
}

Then you only call getTime() if it's needed.  Same for getName().
Alternately, if getTime() and getName() always return the same result, then call them only once and store their results for later use.

A: Logically, replace must search for the string first before replacing it, so in cases where the string does not occur it's equivalent to calling contains, because contains simply does a search. So searching first would not speed it up.
It sounds like the code might be doing many repeated searches over the same source strings. If so, then the answer may be to stop doing it so much. You might want to scan everything first, store the replaced results and then retrieve those when necessary.

A: Performance testing is king to determine what's fastest.
A little code to benchmark three different ways to write this...
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

public class BenchmarkStringStuff {

    public static void main(String[] args) {
        try {
            System.getProperties().store(System.out, "");
        } catch (IOException ioe ) {
            System.out.println("Failed to write properties to STDOUT");
            return;
        }

        BenchmarkStringStuff bss = new BenchmarkStringStuff();
        bss.benchmark(10);
        bss.benchmark(1000);
        bss.benchmark(100000);
        bss.benchmark(1000000);
    }

    public void benchmark(int numTests)
    {
        Vector<Test> tests = new Vector<Test>();
        tests.add(new OriginalCode());
        tests.add(new TwoSearches());
        tests.add(new SearchOnceAndSubstring());

        Vector<String> testStrings = new Vector<String>();
        // we have a very poor sample, here.  You should test with a better
        // representation of your expected values
        testStrings.add("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[time]aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        Performance overallRuntime = new Performance("overall combined runtime");
        overallRuntime.setCount(numTests * testStrings.size() * tests.size());
        overallRuntime.start();
        for( Test test : tests )
        {
            Performance codePerformance = new Performance(test.getClass().getName());
            codePerformance.setCount(numTests * testStrings.size());
            codePerformance.start();
            for(String testString : testStrings)
            {
                //Performance stringPerformance = new Performance(testString);
                //stringPerformance.setCount(numTests);
                //stringPerformance.start();
                for(int i=0; i<numTests; i++)
                {
                    test.test(testString);
                }
                //stringPerformance.end();
                //System.out.println(stringPerformance.toString());
            }
            codePerformance.end();
            System.out.println(codePerformance.toString());
        }
        overallRuntime.end();
        System.out.println(overallRuntime.toString());
        System.out.println();

    }

    private static String getTime()
    {
        return "a date";
        // static value to avoid any caching behavior - we
        // want to test the algorithm, not the external stuff.
        // you should use your real getTime method to see real numbers
        // for your application
    }

    private static String getName(){ return "a name"; }

    private interface Test {
        public String test(String in);
    }

    public class OriginalCode implements Test {

        public String test(String in)
        {
            in=in.replace("[time]",getTime()); //just some methods returning strings
            in=in.replace("[name]",getName());
            return in;
        }
    }

    public class TwoSearches implements Test {
        public String test(String in)
        {
            if (in.contains("[time]"))
            {
                in=in.replace("[time]",getTime());
            }
            return in;
        }
    }

    public class SearchOnceAndSubstring implements Test {
        public String test(String in)
        {
            String REPLACEME = "[time]";
            int idx = in.indexOf(REPLACEME);
            if( idx == 0 )
            {
                in=getTime() + in.substring(REPLACEME.length());
            }
            else if( idx > 0 )
            {
                in = in.substring(0,idx) + getTime();
                if( idx+REPLACEME.length() < in.length())
                {
                    in += in.substring(idx+REPLACEME.length());
                }
            }
            return in;
        }
    }

    private class Performance
    {
        long start = 0;
        long end = 0;
        String name = null;
        public int count = 0;

        public Performance(String name)
        {
            this.name = name;
        }

        public void start(){ start = System.currentTimeMillis(); }
        public void end() { end   = System.currentTimeMillis(); }
        public void setCount(int count){ this.count = count; }

        /** be sure to call start & stop first **/
        public long total(){ return end - start; }

        public String toString()
        {
            return count + "cycles    start:"+start+"     end:"+end+"    total:"+total() + "   <---- " + name;
        }
    }
}

And the results of running this code (performance-unrelatedstuff redacted)...
#
#Thu Mar 14 18:45:37 EDT 2013
java.runtime.name=Java(TM) SE Runtime Environment
java.vm.version=20.5-b03
java.vm.vendor=Sun Microsystems Inc.
java.vendor.url=http\://java.sun.com/
java.vm.name=Java HotSpot(TM) Client VM
sun.java.launcher=SUN_STANDARD
sun.os.patch.level=Service Pack 1
java.vm.specification.name=Java Virtual Machine Specification
java.runtime.version=1.6.0_30-b12
os.arch=x86
java.vm.specification.vendor=Sun Microsystems Inc.
user.variant=
os.name=Windows 7
java.specification.name=Java Platform API Specification
java.class.version=50.0
sun.management.compiler=HotSpot Client Compiler
os.version=6.1
java.specification.version=1.6
java.class.path=REDACTED
java.vm.specification.version=1.0
sun.java.command=BenchmarkStringStuff
sun.arch.data.model=32
java.specification.vendor=Sun Microsystems Inc.
java.version=1.6.0_30
java.vendor=Sun Microsystems Inc.
sun.desktop=windows
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86
10cycles    start:1363301137531     end:1363301137531    total:0   <---- BenchmarkStringStuff$OriginalCode
10cycles    start:1363301137531     end:1363301137531    total:0   <---- BenchmarkStringStuff$TwoSearches
10cycles    start:1363301137531     end:1363301137531    total:0   <---- BenchmarkStringStuff$SearchOnceAndSubstring
30cycles    start:1363301137531     end:1363301137531    total:0   <---- overall combined runtime

1000cycles    start:1363301137531     end:1363301137546    total:15   <---- BenchmarkStringStuff$OriginalCode
1000cycles    start:1363301137546     end:1363301137546    total:0   <---- BenchmarkStringStuff$TwoSearches
1000cycles    start:1363301137546     end:1363301137562    total:16   <---- BenchmarkStringStuff$SearchOnceAndSubstring
3000cycles    start:1363301137531     end:1363301137562    total:31   <---- overall combined runtime

100000cycles    start:1363301137562     end:1363301138108    total:546   <---- BenchmarkStringStuff$OriginalCode
100000cycles    start:1363301138108     end:1363301138451    total:343   <---- BenchmarkStringStuff$TwoSearches
100000cycles    start:1363301138451     end:1363301138499    total:48   <---- BenchmarkStringStuff$SearchOnceAndSubstring
300000cycles    start:1363301137562     end:1363301138499    total:937   <---- overall combined runtime

1000000cycles    start:1363301138499     end:1363301143663    total:5164   <---- BenchmarkStringStuff$OriginalCode
1000000cycles    start:1363301143663     end:1363301146784    total:3121   <---- BenchmarkStringStuff$TwoSearches
1000000cycles    start:1363301146784     end:1363301147190    total:406   <---- BenchmarkStringStuff$SearchOnceAndSubstring
3000000cycles    start:1363301138499     end:1363301147190    total:8691   <---- overall combined runtime

The winner is SearchOnceAndSubstring, at a consistent order of magnitude faster than the others.
There may be other optimizations by playing directly with the char arrays, but I suspect that SearchOnceAndSubstring would be very close, with most of the time lost on the string concatenation.  I'll leave performance testing of that as an exercise for the reader.


text:
Q: for loop help and sprite addition I have two questions. what I am
trying to do is every time I shoot a enemy/vine it should be
removed and a explosion should occur. the removal works perfect
but the sprite is not called to explode

*

*What's this in the for loop #sections[sectInt]["vines"] ?
   Are they parent/ child references? Can someone break this
   down to the letter even telling me what the # is?

*How can I use my explosion sprite after each vine is destroyed?
   I am having a difficult time figuring out how to call every x and y
   vine in the for loop to explode when removed.
Code:
local sections = require("sectionData")

local lastSection = 0
function createSection()
    --Create a random number. If its eqaul to the last one, random it again.
    local sectInt = mR(1,#sections)
    if sectInt == lastSection then sectInt = mR(1,#sections) end
    lastSection = sectInt

    --Get a random section from the sectionData file and then
    --Loop through creating everything with the right properties.
    local i
    -- the random creation of vines throughout the screen
    for i=1, #sections[sectInt]["vines"] do
        local object = sections[sectInt]["vines"][i]
        local vine = display.newImageRect(objectGroup, "images/vine"..object["type"]..".png", object["widthHeight"][1], object["widthHeight"][2])
        vine.x = object["position"][1]+(480*object["screen"]); vine.y = object["position"][2]; vine.name = "vine"

        local rad = (vine.width*0.5)-8; local height = (vine.height*0.5)-8
        local physicsShape = { -rad, -height, rad, -height, rad, height, -rad, height }
        physics.addBody( vine, "static", { isSensor = true, shape = physicsShape } )
    end
end

-- explosion sprite
options1 =
{
    width = 96, height = 96,
    numFrames = 16,
    sheetContentWidth = 480,
    sheetContentHeight = 384
}
playerSheet1 = graphics.newImageSheet( "images/explosion.png", options1)
playerSprite1 = {
    {name="explosion", start=1, count=16, time = 400, loopCount = 1 },
}

explode = display.newSprite(playerSheet1, playerSprite1)
explode.anchorX = 0.5
explode.anchorY = 1
--player:setReferencePoint(display.BottomCenterReferencePoint)

-- i want to reference the for loop position if each vine so it plays sprite when they are removed
explode.x = "vine.x" ; explode.y = "vine .y"
explode.name = "explode"
explode.position=1
extraGroup:insert(explode)

A:
1) What's this in the for loop #sections[sectInt]["vines"] ? Are they parent/ child references? Can someone break this down to the letter even telling me what the # is?

As I said in my comment the # is table length.
The loop is looping over each bit of "vine" data in the selected segment data (whatever that means exactly in terms of the game) and then creates the objects for those vines.

A: When it's time to make your vine explode, you play the sprite. If you want to explode every vine, you would have something like:
sheetOptions =
{
    width = 96, height = 96,
    numFrames = 16,
    sheetContentWidth = 480,
    sheetContentHeight = 384
}
playerSheet = graphics.newImageSheet( "images/explosion.png", sheetOptions)
spriteSequence = {
    {name="explosion", start=1, count=16, time = 400, loopCount = 1 },
}

for i, vine in ipairs(objectGroup) do
    local explode = display.newSprite(playerSheet, spriteSequence)
    explode.anchorX = 0.5
    explode.anchorY = 1
    explode.x = vine.x
    explode.y = vine.y
    explode.name = "explode"
    explode.position=1
    explode:play()

    extraGroup:insert(explode)
end

Note: not tested, let me know of if any issues you can't resolve.

A: ok so, this is what i did to get my object to have a explosion, for anybody that is having the same issue.
function isShot( event )
           print('shot!!!')
        if (event.other.class == "enemy") then
            if (event.other.name == "limitLine") then
                event.target:doRemove() --remove bullet if hits the limitLine

            elseif (event.other.name == "vine") then

                event.other:doRemove()
                spriteExplode(event.other.x, event.other.y) -- this function calls itself & runs the sprite

                if event.other.name == "vine" then
                    if event.other.name == "explode" then
                        event.other:doRemove()  --this removes the explosion sprite
                    end
               end
            end
            -- remove the bullet & explosion sprite
            timer.performWithDelay( 5000, function(event) explode:doRemove(); end, 1 )
            event.target:doRemove()
       end
    return true
end

function spriteExplode( x, y)

        explode.isVisible = true
        explode:play()
        print("play explode")

        if (x and y) then   -- this is the code that keeps my sprite updating upon removal of vine
            explode.x, explode.y = x, y
        end

        function explode:doRemove(event)
            timer.performWithDelay(
                        1,
                            function(event)
                                display.remove(self)
                                self= nil
                            end,
                    1 )
        end

end

i added the isShot function eventListener inside of the Bullet function
 bullet:addEventListener("collision", isShot) & a bullet:doRemove function is inside the bullet function as well.
hope this helps.


text:
Q: Loading a converted pytorch model in huggingface transformers properly I converted a pre-trained tf model to pytorch using the following function.
def convert_tf_checkpoint_to_pytorch(*, tf_checkpoint_path, albert_config_file, pytorch_dump_path):
    # Initialise PyTorch model
    config = AlbertConfig.from_json_file(albert_config_file)
    print("Building PyTorch model from configuration: {}".format(str(config)))
    model = AlbertForPreTraining(config)

    # Load weights from tf checkpoint
    load_tf_weights_in_albert(model, config, tf_checkpoint_path)

    # Save pytorch-model
    print("Save PyTorch model to {}".format(pytorch_dump_path))
    torch.save(model.state_dict(), pytorch_dump_path)

I am loading the converted model and encoding sentences in the following way:
def vectorize_sentence(text):
    albert_tokenizer = AlbertTokenizer.from_pretrained("albert-base-v2")
    config = AlbertConfig.from_pretrained(config_path, output_hidden_states=True)
    model = TFAlbertModel.from_pretrained(pytorch_dir, config=config, from_pt=True)
    e = albert_tokenizer.encode(text, max_length=512)
    model_input = tf.constant(e)[None, :]  # Batch size 1
    output = model(model_input)

    v = [0] * 768
    # generate sentence vectors by averaging the word vectors
    for i in range(1, len(model_input[0]) - 1):
        v = v + output[0][0][i].numpy()

    vector = v/len(model_input[0])
    return vector

However while loading the model, a warning comes up:

Some weights or buffers of the PyTorch model TFAlbertModel were not
initialized from the TF 2.0 model and are newly initialized:
['predictions.LayerNorm.bias', 'predictions.dense.weight',
'predictions.LayerNorm.weight', 'sop_classifier.classifier.bias',
'predictions.dense.bias', 'sop_classifier.classifier.weight',
'predictions.decoder.bias', 'predictions.bias',
'predictions.decoder.weight'] You should probably TRAIN this model on
a down-stream task to be able to use it for predictions and inference.

Can anyone tell me if I am doing anything wrong? What does the warning mean? I saw issue #5588 on the github repo of Transformers. Don't know if my issue is the same as this.

A: I think you could try using
model = AlbertModel.from_pretrained

instead of
model = TFAlbertModel.from_pretrained

in the VectorizeSentence definition.
AlbertModel is the name of the class for the pytorch format model, and TFAlbertModel is the name of the class for the tensorflow format model.
I'm not sure exactly what load_tf_weights_in_albert() does, but I think that once you have done that your model is in pytorch format.


text:
Q: Segue in swift 2 issue I'm having a bit of a problem with a segue implementation in swift 2. So, I want to pass information from one ViewController to another. Here is what I do:

*

*I have OriginViewController and DestinationViewController.

*I override the prepareForSegue function as follows:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {

    let destination = segue.destinationViewController as! DestinationViewController

    destination.data = 155

}

*In DestinationViewController there is a variable data of Int? type without an initial value.

*I also created an Action Segue show, but it doesn't change the data variable in DestinationViewController after the button is pressed.
In output I have:

SegueProject[12451:998869] Unknown class OriginViewController in Interface Builder file.

To be more specific, here is my project: https://yadi.sk/d/DVZVv04BkrjnH

A: You have your file named OriginViewController, but class is named ViewController. Rename your class to OriginViewController as set in your storyboard. and everything will work. In your case:
class ViewController: UIViewController

change to
class OriginViewController: UIViewController


text:
Q: How to get id from foreign key model in django How Do I get id of to_user from the below model:
class Friend(models.Model):
     status = models.CharField(max_length=10)
     from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user')
     to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user")
     date_modified = models.DateTimeField(auto_now=True, blank=True)
     date_created = models.DateTimeField(auto_now_add=True, null=True)

     def create(self,request, **kwargs, ):
         friend = self.create(from_user_id=request.user.id, status="Pending")
         return friend

    class Meta:
        unique_together = (('from_user', 'to_user'),)

    def __str__(self):
        return self.to_user.email

my view :
def accept_friend_request(request, uidb64, status):
     """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected  based on status flag"""
      Friend.status = "pending"
      try:
         uid = urlsafe_base64_decode(uidb64)
         friend_user = User.objects.filter(id=Friend.to_user.id)
         f = Friend.objects.filter(friend_id = friend_user)
         if f:
             f.status=status
             f.save()
             f.status = "accepted"
            return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status})
          else:
             f.status = "rejected"
             f.save()
             return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status})
      except AttributeError:
          return render(request, 'blog/base.html')

I cannot retrieve the friend_user = User.objects.filter(id=Friend.to_user.id)
Thanking you in advance,

A: Friend is a model class, and you need an instance of such class in order to relate it to another model instance as a foreign relationship.
For example:
friend_instance = Friend.objects.get(name='Madeleaine')
...
friend_user = friend_instance.to_user.id


text:
Q: Javascript validation with bootstrap tooltip I have problem with initiate bootstrap tooltip for input field when validation is return false.
More details:
I have idea to validate my form with javascript function and this is working very well but something must happen when validation is false.
I was thinking about bootstrap tooltip, simple, easy to control and now the best solution for me (if is something like this but really for validation and balloons for forms)
My code in javascript onsubmit form:
function validateFault() {
    var phone_number = document.getElementById("phone_number").value;

    var phone_number_regex = new RegExp("^([+]?[1]?[0-9]{9,15})$");

    $('#phone_number').tooltip('destroy');
    if (!phone_number) {
        $('#phone_number').tooltip({placement: 'right', title: 'phone number is required', trigger: 'manual'}).tooltip('show');
    }
    else {
        if (!phone_number_regex.test(phone_number)) {
            $('#phone_number').tooltip({placement: 'right', title: 'allowed phone number format: +999999999 (9-15 digits with possible plus)', trigger: 'manual'}).tooltip('show');
        }
    }

    return false;
}

So this function is return when submit button is clicked in my form and it is working one on two times.
When I don't have any phone number I have tooltip with 'phone number is required' text and when I wrote something there I have second text showing in tooltip.
But when I clicked second time, when tooltip is showing I have this error:
Uncaught TypeError: Cannot read property 'trigger' of null
    at HTMLDivElement.q (bootstrap.min.js:6)
    at HTMLDivElement.e (jquery.min.js:3)
    at HTMLDivElement.handle (bootstrap.min.js:6)
    at HTMLDivElement.dispatch (jquery.min.js:3)
    at HTMLDivElement.q.handle (jquery.min.js:3)
    at Object.trigger (jquery.min.js:4)
    at HTMLDivElement.<anonymous> (jquery.min.js:4)
    at Function.each (jquery.min.js:2)
    at r.fn.init.each (jquery.min.js:2)
    at r.fn.init.trigger (jquery.min.js:4)

Probably problem is with not properly initiate tooltip, because I don't have any tooltip annotation in my input field or with my destroy command.
But I don't have idea how to change title in tooltip and show again after second field validation.
If somebody can help me or maybe is something better to show this validation error like a balloon, I will be grateful.

A: $('#phone_number').attr('data-original-title', 'phone number is required')
                  .tooltip('fixTitle')
                  .tooltip('show');

this is answer for my question, I searched it in this moment but maybe somebody has the same problem
without any destroy option and anything else, changing title of tooltip on submit
but important thing is 'data-original-title' because with 'title' this not working like I want.


text:
Q: Java EE security roles setup confusion if we wanted to define security roles in the deployment descriptor, we do it this way right?
<security-constraint>
    <web-resource-collection>
        <web-resource-name>Protected Area</web-resource-name>
        <url-pattern>/jsp/security/protected/*</url-pattern>
        <http-method>PUT</http-method>
        <http-method>DELETE</http-method>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <role-name>role1</role-name>
        <role-name>employee</role-name>
    </auth-constraint>
</security-constraint>

 <!-- Security roles referenced by this web application -->
<security-role>
    <role-name>role1</role-name>
</security-role>
<security-role>
    <role-name>employee</role-name>
</security-role>

Let's say my application has 50 users. Let's say User1 to User50 and are stored in my application's database.
question is, how to I connect a certain user to a security role defined in web.xml? let's say upon successful authentication of User1, I want him to have "employee" role. For User2, I want him to have "role1".
thanks.

A: Mapping of application security roles to users or groups from your user registry is platform dependent. Each application server provides some mechanism, it can be during installation, via some xml file contained in the application or in server configuration. You could hard code that in your application also.
Some servers will also provide integration with existing user registries, like LDAP, so you don't have to write user management code by yourself.
So specify application server you are using or planning to use, then you will have more detailed answers ;)

A: I don't know how you do it but I am doing it this way

In the database i am storing both User information and its role information and in the security.xml i am doing both autherization and authentication by runing sql query you can do the same.

for eg.'<security:authentication-manager>
           <security:authentication-provider>
           <security:jdbc-user-service
            data-source-ref="dataSource"
            users-by-username-query="select username,password,enabled from users where username=?"
            authorities-by-username-query="select u1.username, u2.role from user_roles u1, user_roles u2 where u1.user_role_id = u2.user_role_id and u1.username =?" />
           </security:authentication-provider>
        </security:authentication-manager>`

Search article like authentication in spring with databases you will get lots of useful information.It will work for you surely .
Thanks,
Himanshu


text:
Q: HTML5 Websocket and ISA Proxy issue I'm not an expert in ISA server, my issue is the following:
var wsUri = "ws://192.168.1.7:8887";
websocket = new WebSocket(wsUri);
these two lines work fine.
But when I try to get 192.168.1.7 from the external computers I set up rule in ISA server:
websocket.domain.com -> (redirect to 192.168.1.7, bridging = redirect request to HTTP port 8887)
And the following doesn't work:
var wsUri = "ws://websocket.domain.com";
websocket = new WebSocket(wsUri);
I see in ISA log "Status: 10061 No connection could be made because the target machine actively refused it."
It seems that websocket doesn't transform message to HTTP so that it tunneled to the destination server.
Thanks in advance!

A: Finally I've made workaround. Just installed another PC, gave it public static IP and deploy websocket on it.So I get PC out of my network and it doesn't deal with ISA.
I came to a conclusion that ISA 2006 do not pass original HTTP message and somehow corrupted it.


text:
Q: How to make COUNTIF only count subtotal for visible records when filter is applied I would like a formula to COUNTIF the Brand 3 column and if filtered the COUNTIF changes to filtered criteria.
                    TOTAL COUNT 0        0          3   COUNTIF(H3:H5,"VoID")
Area    Region  Branch  Member  Brand 1  Brand 2    Brand 3
East    NY        NY     1                           Void
West    CA        LA     2                           Void
North   IL      Chicago  3                           Void

With filter applied I get the same total count but need it to be 1 instead (count only the visible cells):
                    TOTAL COUNT 0        0          3   Answer needs to be 1
Area    Region  Branch  Member  Brand 1  Brand 2    Brand 3
East    NY        NY    1                            Void

A: You can use this formula
=SUMPRODUCT(SUBTOTAL(3,OFFSET(H3,ROW(H3:H5)-ROW(H3),0)),(H3:H5="void")+0)

That will give you a count of visible cells in H3:H5 (after filtering) that are "Void".


text:
Q: Is this a valid linear transformation? (1) Which of the following is a linear transformation?
$ \quad $ (a) $ T ( \begin{pmatrix} x \\ y \end{pmatrix} )= \begin{pmatrix}  0 \\ x \\y \end{pmatrix}$, $ \quad $ (b) $ T ( \begin{pmatrix} x \\ y \\ z \end{pmatrix} ) = \begin{pmatrix}  y \\ x \end{pmatrix}$ $ \quad $ (c) $ T (\begin{pmatrix} x \\ y \end{pmatrix} )= \begin{pmatrix}  x^2 \\ y^2 \\ 0 \end{pmatrix}$
$ \quad $ (d) $ T (\begin{pmatrix} x \\ y \end{pmatrix}) = \begin{pmatrix}  1 \\ x \\y \end{pmatrix}$ $ \quad $ (e) $ T ( \begin{pmatrix}\ x \\ y  \\ z \end{pmatrix} ) = x \begin{pmatrix}  1 \\ 1 \\ z \end{pmatrix}$
I am new to this topic, am I correct in saying that only (a) is a linear transformation?
(2) $ T (\begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix}) = \begin{pmatrix}  2 \\ 2 \\2 \end{pmatrix}$ , $ \quad $ $ T (\begin{pmatrix} 1 \\ 1 \\ 2 \end{pmatrix}) = \begin{pmatrix}  1 \\ -1 \\ -1 \end{pmatrix}$, $ \quad $ $ T (\begin{pmatrix} 0 \\ 1 \\ -2 \end{pmatrix}) = \begin{pmatrix}  0 \\ 0 \\ 0 \end{pmatrix}$ $ \quad $
$ \quad $$ M = \begin{pmatrix}1 & 1 & 0 \\ 2 & 1 & 1 \\ 3 & 2 & -2  \end{pmatrix}. $
$ \quad $ Then,  $ T (\begin{pmatrix} x \\ y \\ z \end{pmatrix}) = \begin{pmatrix}  2 &  1 & 0 \\ 2 & -1 & 0 \\ 2 & -1 & 0 \end{pmatrix} M^{-1}  \begin{pmatrix} x \\ y \\ z \end{pmatrix} $  ?

A: $(a)$ and $(b)$ are.  The others do not possess the properties that $T(cv)=cT(v)$ and $T(v+w)=T(v)+T(w)$.

A: I think you need to understand the definition of linear transformation. Note that:

Let $V$ and $W$ vector spaces over field $F$. Let $T: V\to W$ a function, so $T$ is said linear transformation if, and only if,
$1.$ $\forall v_{1},v_{2}\in V: T(v_{1}+v_{2})=T(v_{1})+T(v_{2})$.
$2.$ $\forall \alpha \in F, \forall v \in V: T(\alpha v)=\alpha T(v)$.

Now, you can prove in this sense that
\begin{eqnarray}
T \text{is a linear transformation}  \iff \forall \alpha, \beta\in F, \forall v_{1},v_{2} \in V: T(\alpha v_{1}+\beta v_{2})=\alpha T(v_{1})+\beta T(v_{2})
\end{eqnarray}

Now, for your question you need to see if $T$ is a linear transformation, so:
b) $T$ Is a linear transformation, because
\begin{eqnarray}
T\left(\alpha \begin{pmatrix} x \\ y \\ z \end{pmatrix} +\beta \begin{pmatrix} a \\ b \\ c \end{pmatrix} \right)
&=& T\begin{pmatrix} \alpha x+\beta a \\ \alpha y +\beta b \\ \alpha z +\beta c \end{pmatrix}\\
&=&\begin{pmatrix} \alpha y +\beta b \\ \alpha x +\beta a \end{pmatrix}\\
&=&\alpha \begin{pmatrix} y \\ x \end{pmatrix} +\beta \begin{pmatrix} b \\ a \end{pmatrix}\\
&=&\alpha T\begin{pmatrix} x \\ y \\ z \end{pmatrix} +\beta T\begin{pmatrix} a \\ b \\ c \end{pmatrix}
\end{eqnarray}
a) Also $T$ is linear transformation (I think you can do this part).
c) $T4 is not linear transformation (I think you can do this part).
d) $T$ is not linear transformation, because
\begin{eqnarray}
T\left( \alpha \begin{pmatrix} x \\ y \end{pmatrix} +\beta\begin{pmatrix} a \\ b \end{pmatrix} \right)&=& T\begin{pmatrix} \alpha x+\beta a \\ \alpha y +\beta b \end{pmatrix}\\
&=&\begin{pmatrix} 1 \\ \alpha x+\beta a \\ \alpha y +\beta b \end{pmatrix}\\
&\not=& \alpha \begin{pmatrix} 1 \\ x \\ y \end{pmatrix}+\beta \begin{pmatrix} 1 \\ a \\ b \end{pmatrix}\\
&=& \alpha T \begin{pmatrix} x\\ y \end{pmatrix} +\beta T\begin{pmatrix} a \\ b \end{pmatrix}
\end{eqnarray}
e) $T$ is not linear transformation ( I think you can do this part).


text:
Q: RayCastingSupport.intersectRayWithTerrain always returns null I use my own interaction method because I embed NASA WorldWind into JavaFX not Swing. View is defined in FXML as follow:
<?xml version="1.0" encoding="UTF-8"?>
...
<Pane xmlns:fx="http://javafx.com/fxml" fx:id="_mainPane"
   fx:controller="view.MainCtrl" prefWidth="1600" prefHeight="900">
   <stylesheets><URL value="@NavDb.css" /></stylesheets>
   <BorderPane><SwingNode fx:id="_worldWindFxContainer" /></BorderPane>
   ...

Controller attributes:
   @FXML private SwingNode           _worldWindFxContainer;

   private final WorldWindowGLJPanel _worldWind   = new WorldWindowGLJPanel();
   private final RenderableLayer     _routeLayer  = new RenderableLayer();
   private final RenderableLayer     _alertLayer  = new RenderableLayer();
   private final Preferences         _preferences = new Preferences();

WW initialization code:
   private void initWorldWind() {
      WorldWind.setOfflineMode( _preferences.get( "WorldWind/offline", false ));
      final OrbitView orbitVw = new FlatOrbitView();
      final EarthFlat globe   = new EarthFlat();
      final Model     model   = new BasicModel();
      globe.setProjection( FlatGlobe.PROJECTION_MERCATOR );
      model.setGlobe( globe );
      orbitVw.getOrbitViewLimits().setZoomLimits( 1.2E+04, 2.2E+07 );
      _worldWind.setModelAndView( model, orbitVw );
      _worldWind.getSceneController().setDeepPickEnabled( true );
      _routeLayer.setName( "Route-Layer" );
      _routeLayer.setPickEnabled( false );
      _alertLayer.setName( "Alert-Layer" );
      _alertLayer.setPickEnabled( true );
      _alertLayer.setEnabled( true );
      final LayerList layers = model.getLayers();
      layers.add( _routeLayer );
      layers.add( _alertLayer );
      layers.removeIf( l -> l instanceof CompassLayer  );
      layers.removeIf( l -> l instanceof WorldMapLayer );
      for(int i = 0; i < layers.size(); i++) {
         final Layer l = layers.get( i );
         if( l instanceof SkyGradientLayer ) {
            layers.set( i, new SkyColorLayer());
          }
      }
      final double lat        = _preferences.get( "Startup/initial-location-lat", 0.0 );
      final double lon        = _preferences.get( "Startup/initial-location-lon", 0.0 );
      final double zoomFactor = _preferences.get( "Startup/initial-zoom", 1.0 );
      orbitVw.setEyePosition( Position.fromDegrees( lat, lon ));
      orbitVw.setZoom( zoomFactor );
      Platform.runLater(() -> {
         final Interactions handler = new Interactions( _worldWind );
         handler.setPicker( this );
         _worldWindFxContainer.addEventHandler( InputEvent .ANY, handler );
         _worldWindFxContainer.addEventFilter ( MouseEvent .ANY, event -> {
            handler.handle( event );
            event.consume();
         });
         _worldWindFxContainer.addEventFilter ( ScrollEvent.ANY, event -> {
            handler.handle( event );
            event.consume();
         });
      });
      _worldWind.redrawNow();
   }

From JavaFx init code:
   SwingUtilities.invokeLater( this::initWorldWind );

Interactions class:
public final class Interactions implements EventHandler<InputEvent> {

   private final WorldWindowGLJPanel _wwPanel;
   private final SceneController     _sceneController;
   private final OrbitView           _view;

   public Interactions( WorldWindowGLJPanel wwPanel ) {
      _wwPanel         = wwPanel;
      _sceneController = _wwPanel.getSceneController();
      _view            = (OrbitView)_sceneController.getView();
   }

   private Position getPositionFromScreenPoint( double x, double y ) {
      final View vw  = _sceneController.getView();
      final Line ray = vw.computeRayFromScreenPoint( x, y );
      if( ray != null ) {
         final Globe globe = _sceneController.getModel().getGlobe();
         final Vec4 origin = ray.getOrigin();
         final Vec4 direction = ray.getDirection().normalize3();
         final Position pos =
            RayCastingSupport.intersectRayWithTerrain( globe, origin, direction );
         return pos;
      }
      return null;
   }

Interactions.getPositionFromScreenPoint is called from FX Mouse handler.
The problem is: RayCastingSupport.intersectRayWithTerrain() always returns null after I switch from spheric representation of the world to flat one.

A: I haven't found the true answer but wrote a simplified approach to handle mouse clicks for moving the flat map:
   private Position getPositionFromScreenPoint( double x, double y ) {
      final View           vw        = _sceneController.getView();
      final Line           ray       = vw.computeRayFromScreenPoint( x, y );
      final Vec4           origin    = ray.getOrigin();
      final Vec4           direction = ray.getDirection().normalize3();
      final Globe          globe     = _sceneController.getModel().getGlobe();
      final double         gme       = globe.getMaxElevation();
      final Intersection[] inters    = globe.intersect( new Line( origin, direction ), gme );
      if( inters != null ) {
         final Vec4     pt  = inters[0].getIntersectionPoint();
         final Position pos = globe.computePositionFromPoint( pt );
         return pos;
      }
      return null;
   }

I don't understand why I have to check null for inters, but sometimes, it's null...


text:
Q: how to pass parameter value from a jquery function to struts2 url tag i am trying to pass parameter from a jquery function.
Everything is fine but only problem is passing the parameter value rowObject.themeScreenshot