text:
Q: Simple math and saving to file takes too much time, compared to other languages Recently me and my friends were benchmarking different programming languages. As I'm learning Haskell lately, I wanted to show that a functional language will perform nearly as good as C with simpler code. But the code I pasted below, compiled with GHC's -O3 option, was executing about 1.6 s on my machine. Equivalent scripts in Python and Ruby executed faster (it was a simple for loop).
import System.IO

saveLine fh x = hPutStrLn fh $ show x ++ "\t" ++ show (x^2)

main = do
    fh <- openFile "haskell.txt" WriteMode
    mapM (saveLine fh) [1..999999]
    hClose fh

You can check out codes in other languages here (I wrote only the ones in Python and Ruby).
The question is - how to make it run faster?

A: The problems are: 1) using String, and 2) the formatting of integer values to character data (either ByteString or String).
{-# LANGUAGE OverloadedStrings #-}

import System.IO
import qualified Data.ByteString.Char8 as BS

-- saveLine fh x = hPutStrLn fh $ show x ++ "\t" ++ show (x^2) -- original version
-- saveLine fh x = hPutStrLn fh "123456\t123456789012" -- String version
saveLine fh x = BS.hPutStrLn fh "123456\t123456789012" -- ByteString version

main = do
    fh <- openFile "haskell.txt" WriteMode
    mapM_ (saveLine fh) [1..999999]
    hClose fh

The run times on my machine are (GHC 7.8.3):
original version:   1.6 secs
String version:     0.7 secs
ByteString version: 0.3 secs

Thus, the run time can be significantly improved if one can find a faster way to format integer values to ByteStrings.

A: First off, benchmarks where you perform some simple calculation and write each result to a file are only useful to test the IO system. They say nothing at all about computation efficiency, because most of the time is spent with file accesses. If you want to compare how fast languages are for calculating things, you need to do something processor-intensive (e.g. summing all those square values) and then output only that single result.
If you actually want to compare file-output performance, the main problem in Haskell is its String type. It's a simple list of characters, handy for doing simple text manipulations by hand but with ridiculous overhead for standard tasks. For faster performance, use bytestrings or Text. Specifically, you need a faster alternative to show. Check out the text-format package.

A: First, you should avoid using -O3, because it could sometimes break your code ( even in gcc ). Just stick to -O2.

Second, Haskell Strings are really slow.
But, there are faster alternatives - and for me, the easiest one is to use is Data.ByteString ( little and old tutorial ).

Third, if you don't need Maybe results from mapM use mapM_ - it's much faster!

Finally, here is my version of your code, using Data.ByteString:
{-# LANGUAGE OverloadedStrings #-}
--  that line is so You could use "\t" instead of T.pack "\t"

import System.IO
import qualified Data.ByteString.Char8 as T

helperFun x = T.concat [y, "\t", z]
          where
            y = T.pack $ show x
            z = T.pack $ show $ x^2

saveLine fh x = T.hPutStrLn fh $ helperFun x

main = do
    fh <- openFile "haskell.txt" WriteMode
    mapM_ (saveLine fh) [1..999999]
    hClose fh

Edit:
user5402 said in comments it's not so "much faster" then Strings version.
You should keep in mind that this code is still using Strings, and had additional overhead ( packing Strings into ByteString ) with only concat and hPutStrLn used from ByteString.


text:
Q: Quite new rails developer confused over content_tag and helpers I am trying to create a calendar table to display the daily availability of every staff member of a company. What I think I need is a header with the days of the month and then a row (with as many cells as the number of the days) for each staff member. The different background color of each cell will represent a different availability status and the staff members change so I want all this to be dynamically generated.
After researching online and with Ryan Bates' Railscast #213 (Calendars Revised) as my guide, I have so far managed to generate the header of my table that displays the days of the month in each cell.
And that's my code so far:
module ReceptionHelper
def reception(date = Date.today, &block)
    Reception.new(self, date, block).table
end

class Reception < Struct.new(:view, :date, :callback)
    delegate :content_tag, to: :view

    def table
        content_tag :table, class: "calendar" do
            daysHeader
        end
    end

    def daysHeader
        last_day = date.end_of_month.strftime("%d").to_i
        (0..last_day).to_a.map { |day| content_tag :th, day }.join.html_safe
    end
end

Now, here is where the questions and confusion begins:

*

*Removing &block and :callback takes away the { ... } functionality, as I found out. I can't really say I understand why though. Anyone with a good explanation?

*Why does the above work but I can't use (..).each do and the content_tag block below?
(0..last_day).to_a.each do |day|
    content_tag :th do
        day
    end
end

*In my effort to display the rows for each staff, I went with this:
def table
    content_tag :table, class: "calendar" do
        daysHeader + staffRows
    end
end

def staffRows
    staff.to_a.map { |staff| content_tag :tr, staff.name }.join.html_safe
end

I added staff to the Reception class definition and I call with <%= reception @staff %> - if that's not a very good practice please feel free to shout at me :D
However, instead of getting one row per staff member I get all the member names next to each other in one row and right above the header. Changing content_tag :tr to content_tag :td results in a cell with the name of each staff after the last header cell.
As you understand, I am quite lost in this and it seems I am not even clearly getting why the part that works as I want it to is correct. I hope this post doesn't give the impression that I am looking to have everything served to me in a dish - I am rather looking for directions that will help me understand. :)
EDIT:
I've made some progress by changing the staffRows method to this:
def staffRows
    staff.to_a.in_groups_of(1).map do |staff|
        content_tag :tr do
            staff.map { |room| content_tag :th, staff.name }.join.html_safe
        end
    end.join.html_safe
end

However this produces only one cell for each room while I want a row with as many cells as the header.

A: First of all ruby conventions: use 2 spaces for spacing and use _ for method names.
Now meet your best friend when writing complex helpers: concat. What it does is outputs string directly to ERB buffer. To show you and example:
def my_helper
  concat "hello world"
end
<% my_helper %>

would output hello world in html even though we used <% and not <%=.
It's very important method when dealing with blocks in helpers, as it means you can call concat multiple times in block and both strings will be output. Here's an example:
def my_helper
  content_tag :div do
    concat "Hello "
    concat "World"
    concat "!"
  end
end
<%= my_helper %>

would output
Hello World!
. So using same idea you could do something like this:
def my_helper
  content_tag :ul do
    @people.each do |person|
      concat content_tag(:li, person.name)
    end
  end
end
<%= my_helper %>

which would result in something like this:

John Doe

Mike Tyson

.
So I would rewrite days_helper to something like this:
def days_header
  (0..date.end_of_month.day).each { |day| concat content_tag(:th, day) }
end

do something similar with staff_rows method and then table method would look simply like this:
content_tag :table, class: "calendar" do
  days_header
  staff_rows
end

As for the callback part of question: &block captures block that is passed to method into Proc object. This object can later be passed around to other methods or called directly. As you're not using callback object I would simply advise to remove it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap Carousel Prev/Next malfunctioning in Angular-seed app I have added Bootstrap in Angular-Seed project. The carousel-indicators are working fine but there is problem with the Prev/Next button.
On clicking Prev button, it switches to Last image & stays on it even if you click prev again. On clicking Next button, it switches to 2nd image & stays on it.
Tried replacing JQuery/Bootstrap with the CDN links but their versions is not the issue.
Here is the carousel I'm using:-

        <li data-target="#carouselControls" data-slide-to="0" class="active"

            Previous

            Next


text:
Q: What event(s) to choose to delegate a handler from  to the selected ? When another <option> is selected in a <select> control, it is possible to process this event with a <select>-triggered handler in a quite straight way.
However for some reasons it would be much convenient for my project to use a delegated <option>-triggered handler instead.
I tried to trigger and delegate a needed handler with using different events. The results were unsatisfactory:

*

*onfocus, onchange and onkeyup handlers were triggered only on the <select> control and were not triggered on a nested <option>.

*onclick handler worked as needed and was delegated (triggered on the selected <option>). However, it obviously makes no sense to use this handler, as another option in a select control can be chosen by keyboard too, rather than only by mouse.

Am I right? Did I missed any standard DOM event that can be used in the case? Or I have to use only a kind of polyfill, like jQuery's focusin and focusout?

A: It follows from the discussion there are no DOM event(s) that meet the specified requirements.

A: I am not sure I understand perfectly your need but I will try to answer.
As you are talking about jQuery, I have this solution :
$("#my-select").change(function() {
    // $(this) refers to the select element
    $(this).find("option:selected").each(function() {
        // this function is called only once per change
        // $(this) refers to the selected option
    })
});

LIVE EXAMPLE :

$("#my-select").change(function() {
  // $(this) refers to the select element
  $("#s_value").text($(this).val());
  $("#s_text").text($(this).find("option:selected").text());
  $(this).find("option:selected").each(function() {
    // this function is called only once per change
    // $(this) refers to the selected option
    $("#o_value").text($(this).val());
    $("#o_text").text($(this).text());
  })
})

<select id="my-select">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

SELECTED (FROM SELECT) :

Value :

Text :

SELECTED (FROM OPTION) :

Value :

Text :


text:
Q: How can I implement a content converter in Firefox for all page elements? I'm attempting to port over an Internet Explorer plugin to Firefox, but I'm not sure where to look for what I need.
Basically I need to be able to filter all content that is received by the browser with a certain Content-Type header. I tried implementing a stream converter, and this works, but only for the top-level document in the page, frame, or iframe. I had the same problem with IE, and getting around it was really hacky, and since I would ideally like this to be cross platform I would really like to be able to do this in Firefox without resorting to vtable hacks.
The content is served compressed with a proprietary compression format. So I need to receive the data, decompress it, and change the Content-Type back to what the original uncompressed file should have.
If there is a way to just filter all data received, that would probably be acceptable, I could handle parsing the header myself.
Thanks

A: I think I may have found what I needed. I came across this link which is used for tracing HTTP calls: http://blues.ath.cx/firekeeper/resources/http_tracer.html
There seems to be some problems with the JavaScript implementation for some reason, and I'm not a JavaScript guru to figure it out, but I've implemented it in C++ and initial results suggest that I should be able to modify it for my needs.
Basically we're replacing the nsIHttpProtocolHandler service with our own implementation, which keeps a reference to the initial implementation. When a call is made to the service, we just proxy it over to the saved original implementation. Then we provide our own implementation of nsIHttpChannel and nsIStreamListener which we use as proxies too.
Again we proxy most of the calls back off to the original handlers. But in OnDataAvailable, instead of passing the data on to the underlying nsIStreamListener, we save it using nsIStorageStream. Then in OnStopRequest, after we've gotten all of the data, we can decompress it and then call OnDataAvailable on the original handler, followed by OnStopRequest.
It has worked on some small simple tests so far, but I'll have to put it through some more rigorous tests... I'll also have to figure out if I can do the same thing with HTTPS.
The biggest problem I see at the moment is that it relies on some unfrozen interfaces such as nsIHttpChannelInternal. Can't be helped though as far as I can tell, and my version compatibility requirements are pretty small, so I can live with it if I have to.
In the meantime, if anybody has any other suggestions, I'm all ears :D


text:
Q: How to disable anti-aliasing in git-gui and gitk After an upgrade to Tcl/Tk 8.5, git-gui and gitk are using anti-aliased fonts which look ugly on my display.  I can select different fonts in the preferences dialog, but the fonts I was using before (Helvetica and Courier bitmap fonts) don't seem to appear in the list.  How do I restore the previous fonts?

A: There doesn't seem to be a way to solve this that doesn't involve re-compiling Tk, so I had to downgrade to Tcl/Tk 8.4.  Since the Debian package manager didn't let me do this (git-gui and gitk require current tcl and tk which conflict with tcl8.4 and tk8.4), I ended up manually backing up the 8.4 files and copying them back after the upgrade, which is obviously a terrible solution.
I'd be happy to know if there is a better way to do this.


text:
Q: How to run a PySpark job with Airflow in a dockerized environment I followed the official  Airflow docker guide.
It works fine for most of the simple jobs I have.
I tried to use this guide for that I needed to add in the .env file this line:
_PIP_ADDITIONAL_REQUIREMENTS=pyspark xlrd apache-airflow-providers-apache-spark

Unfortunately, the dag is not being loaded.
The problem seems to be related to JAVA_HOME because the docker output shows this message:
airflow-scheduler_1  | is not set

In the Airflow web GUI it shows the following erro:

Broken DAG: [/opt/airflow/dags/SparkETL.py] Traceback (most recent call last):
  File "/home/airflow/.local/lib/python3.7/site-packages/pyspark/context.py", line 339, in _ensure_initialized
    SparkContext._gateway = gateway or launch_gateway(conf)
  File "/home/airflow/.local/lib/python3.7/site-packages/pyspark/java_gateway.py", line 108, in launch_gateway
    raise RuntimeError("Java gateway process exited before sending its port number")
RuntimeError: Java gateway process exited before sending its port number

I tried to add install -y openjdk-11-jdk command in the docker-compose, and set JAVA_HOME: '/usr/lib/jvm/java-11-openjdk-amd64' also in the docker compose. In this situation airflow_schedule dumps that the path does not exist.


text:
Q: Detaching Pages from the Site Defintion I am creating a template .aspx page  for use on a SharePoint site. I need to include my own CSS reference and jquery reference in the head of the page.
SPD only allows this when I edit the page in advanced mode, this gives me a warning stating it will detatch it from the site definition.
Is this the only way in which I can include these references to my CSS file and jquery. The CSS is only relevant to this template I've created so I don't want it in the master page template.
If I do this will it cause problems later down the line if a change is made to the master page? Will my page not receive those changes?
Thanks

A: you can add a content editor web part to the page and paste your css in a style tag and the scripts in a script tag


text:
Q: font-size on 2K and higher resolution devices I have a screen with resolution 1680 x 1050.
I work as a web developer and while building websites, we use font-sizes that are easily readable on laptops with resolutions ranging between 1366 x 768 to 1920 x 1080.
While using Chrome developer tools, I chose Amazon Kindle Fire HDX which has resolution of 2560 x 1600. On this device (which chrome is simulating), the font-size renders very small due to high-res. I tried many font-size units such as vw, vh, % so that the font-size appears same on all resolutions but failed.
I even opened StackOverflow using Chrom Dev Tool and saw the font-size appearing to be too small. I don't know if the font size that appears on the real Kindle HDX is the same as what I'm seeing on Kindle HDX that chrome is simulating and I don't have a real 2K res device to test my websites as well. How to counter this issue? I want my websites to be readable on all resolutions.

A: I suggest you use em as the unit for fonts to make it more cross-browser/device compatible. em should work off the browser's own built-in font sizes to make things more readable as well as the browser's zoom settings.
Also, you may want to try out various CSS frameworks that may try to handle more consistent cross-browser/device consistency to keep fonts at more relative sizes according to device/dpi settings. (Unfortunately, I haven't experience in this scenario, but should be a good place to start your research).

A: If your font sizes are in relative units then you are likely just fine.
I think what you are seeing in Chrome Dev Tools is the "Zoom to fit" feature that will zoom the page of the targeted device to fit your browser window. Uncheck "Zoom to fit" and I think you will see the text is legible. And take notice that the ruler values will change to be more accurate representation as well.
You can see in this screenshot that the rulers indicate that the device simulation is being rendered at 1600px wide even though this screenshot was definitely not taken at 1600px wide. It was zoomed to fit my window.


text:
Q: Regularity of Parabolic pde In Evans' pde Book, In Theorem 5, p. 360 (old edition) which concern regularity of parabolic pdes. he consider the case where the coefficients $a_{ij},b_i,c$ of the uniformly parabolic operator (divergent form) $L$ coefficients are all smooth and don't depend on the time parameter $t$
\begin{cases}
\mathbf{u}_t + L \mathbf{u}= \mathbf{f} &\text{ in } U\times [0,T] \\
\mathbf{u} = 0 &\text{ in } \partial U \times [0,T]\\
\mathbf{u}(0) = g &\text{ in } U
\end{cases}
where $\mathbf{f} \in L^{2}(0,T; L^2(U))$, $g \in H^1_0(U)$ and $U$ is a open, bounded subset of $\mathbb{R}^N$ with smooth boudary.
The second assertion (ii) of theorm is the following
if in addition $g \in H^1_0(U)\cap H^2(U)$ and $\mathbf{f} \in H^{1}(0,T; L^2(U))$ then we have
(ii) $u' \in L^\infty(0,T; L^2(U) \cap L^2(0,T; H_1^0(U))$ and $u'' \in L^\infty(0,T; H^{-1}(U)$.
For proving (ii) Evans use Galerkin approxitamtion.
My question is, is there any generalization for proving regularty of time deivative u' in general abstract Cauchy problem, or can we obtain, at least, the previous result by semigroups theory ? Thank you for any help.

A: Yes, there is a generalization of this result. Let us again consider the abstract Cauchy problem
$$\begin{cases}
u_t + L u= f &\text{ in } U\times [0,T] \\
u(0) = g &\text{ in } U
\end{cases}$$
equipped with some boundary conditions. We consider the Gelfand tripel $V \hookrightarrow H \hookrightarrow V'$. In your case we had $V=H_0^1(U)\cap H^2(U), H=L^2(U)$ with homogeneous Dirichlet boundary. This is the first generalization.
First of all, the general existence result gives us a unique solution $$u \in L^2(0,T;V) \cap H^1(0,T;V')$$
if we assumed $f\in L^2(0,T;V'), g \in H$. See e.g. Wloka's book "Partielle Differentialgleichungen".
Now, you are interested in regularity results. And yes, we can generalize your result. For the solution $u$ we get the regularity
$$u \in H^k(0,T;V) \cap H^{k+1}(0,T;V')$$
if we assumed $f \in  H^k(0,T;V')$, $\frac{d^j u}{dt^j}(0) \in V$ for all $j=0,...,k-1$ and $\frac{d^k y}{dt^k}(0)\in H$.
You can also check that for $\mathbf{k=0}$ the existence result generalizes to the one above and for $\bf{k=1}$ we have
$$u \in H^1(0,T;V) \cap H^2(0,T;V')$$
if we assumed $f \in H^1(0,T;V'), g \in V, u_t(0) \in H$. This is what Evans has. Indeed, he additionally assumed $f\in H^1(0,T;H) \hookrightarrow C([0,T];H)$ which implies $u_t(0) \in H$. Further, the $L^\infty$ spaces can be achieved from several embedding results, e.g. $$u' \in L^2(0,T;V) \cap H^1(0,T;V') \hookrightarrow C([0,T];H).$$


text:
Q: Adding tuples in lists in Python I have lists of tuples and I cut each of the lists into two parts at the point when tuples = (x, y=-1)
This is the code:
testList = [
[(0.0, -1.0), (0.5, -0.002), (2.0, -0.1613676), (2.5, 1.08492417852)],
[(0.0, -0.99604032), (0.5, -1.0), (2.0, -0.1613832766676), (2.5, 1.0849852)],
[(4.5, 0.154484), (5.0, -1.0), (5.5, -0.34), (6.0, -0.44)],
[(88.5, 3127.7763767), (89.0, 13.449714), (90.0, -1.0)]]

def c_slice(lst):
    for slst in lst:
        start = 0
        for idx,(_,y) in enumerate(slst):
            if y == -1:
               yield [slst[start:idx+1], slst[idx:]]
               break

out = list(c_slice(testList))

print(out[0])
# [[(0.0, -1.0)], [(0.0, -1.0), (0.5, -0.002), (2.0, -0.1613676), (2.5, 1.08492417852)]]
print(out[1])
# [[(0.0, -0.99604032), (0.5, -1.0)], [(0.5, -1.0), (2.0, -0.1613832766676), (2.5, 1.0849852)]]
print(out[2])
# [[(4.5, 0.154484), (5.0, -1.0)], [(5.0, -1.0), (5.5, -0.34), (6.0, -0.44)]]
print(out[3])
# [[(88.5, 3127.7763767), (89.0, 13.449714), (90.0, -1.0)], [(90.0, -1.0)]]

How could I set some limits to my result? For example,

*

*If the first list in the result doesn't have (x, y>0), add (0, 0) into the beginning of the list. (Like out[0][0] and out[1][0]).

*If the second list in the result doesn't have (x, y>0), add (90, 0) into the end of the list. (Like out[2][1] and out[3][1])

p.s. The position to add tuples is based on the x coordinate. For example, (0, 0) has the smallest x, so it is always added at the beginning of the list. In contrast, (90, 0) has the biggest x coordinate, so it is always added at the last of the list.
I am trying to get this:
print(out[0])
# [[(0.0, 0.0), (0.0, -1.0)], [(0.0, -1.0), (0.5, -0.002), (2.0, -0.1613676), (2.5, 1.08492417852)]]
print(out[1])
# [[(0.0, 0.0), (0.0, -0.99604032), (0.5, -1.0)], [(0.5, -1.0), (2.0, -0.1613832766676), (2.5, 1.0849852)]]
print(out[2])
# [[(4.5, 0.154484), (5.0, -1.0)], [(5.0, -1.0), (5.5, -0.34), (6.0, -0.44), (90.0, 0.0)]]
print(out[3])
# [[(88.5, 3127.7763767), (89.0, 13.449714), (90.0, -1.0)], [(90.0, -1.0), (90.0, 0.0)]]

A: you can try it like this
testList = [
    [(0.0, -1.0), (0.5, -0.002), (2.0, -0.1613676), (2.5, 1.08492417852)],
    [(0.0, -0.99604032), (0.5, -1.0), (2.0, -0.1613832766676), (2.5, 1.0849852)],
    [(4.5, 0.154484), (5.0, -1.0), (5.5, -0.34), (6.0, -0.44)],
    [(88.5, 3127.7763767), (89.0, 13.449714), (90.0, -1.0)]
]

def c_slice(rows):
    for row in rows:
        for idx, (_, y) in enumerate(row):
            if y == -1:
                start = row[:idx + 1]
                end = row[idx:]
                start = [(0, 0)] + start if all([y < 0 for _, y in start]) else start
                end = end + [(90, 0)] if all([y < 0 for _, y in end]) else end
                yield [start, end]
                break

out = list(c_slice(testList))

for i in out:
    print(i)

A: I coded this solution:
testList = [
[(0.0, -1.0), (0.5, -0.002), (2.0, -0.1613676), (2.5, 1.08492417852)],
[(0.0, -0.99604032), (0.5, -1.0), (2.0, -0.1613832766676), (2.5, 1.0849852)],
[(4.5, 0.154484), (5.0, -1.0), (5.5, -0.34), (6.0, -0.44)],
[(88.5, 3127.7763767), (89.0, 13.449714), (90.0, -1.0)]]

def c_slice(lst):
    for slst in lst:
        start = 0
        for idx,(x,y) in enumerate(slst):
            if y == -1:
                if x <= len(slst)/2:
                    yield [[(x, 0)] + slst[start:idx+1], slst[idx:]]
                else:
                    yield [slst[start:idx+1] + [(x, 0)], slst[idx:]]
                break

out = list(c_slice(testList))

print(out[0])
print(out[1])
print(out[2])
print(out[3])


text:
Q: When a woman says ''no problem'' to thank you, is she being disrespectful? I am curious to read your thoughts on the matter.

A: The phrase "no problem" is not at all disrespectful.  The general meaning is "[helping you was] no problem".  Think of it as the person reassuring you that it was not an inconvenience to help you.
The phrase can be considered casual, but there are very few situations where it would be considered out of place or incorrect.


text:
Q: Filtering my matrix in R I don't know exactly what is going on, because when I attempt what I want to do in a simple manner at the prompt, it works fine, but when I do in my function it simply doesn't work.
This is the simple version
p
    x  y
1   1  2
2   2  3
3   3  4
4   4  5
5   5  6
6   6  7
7   7  8
8   8  9
9   9 10
10 10 11
> p[,2][y!=2]
[1]  3  4  5  6  7  8  9 10 11

And this is my function
corr <- function(directory, threshold = 0) {

  #setwd(directory)

  # Correlations of all the monitors

  corr_all_monit <- data.frame(id = 1:332, corrs = 0)

  for(i in 1:332){

# Reading the files in the directory

idi <- paste(formatC(i, width=3, flag="0"), "csv", sep=".")
onedataset <- read.csv(idi)

# Eliminating the NAs

onedataset <- onedataset[complete.cases(onedataset),]

# Getting the length of the filtered data

monitor_length <- length(onedataset[,1])

# Doing the correlation of the data which surpass the threshold

if(monitor_length > threshold){
  corr_all_monit[i,2] <- cor(onedataset[,2],onedataset[,3])
}

  }

  # Picking up only the correlations which surpass the threshold

  return(corr_all_monit[,2][corrs != 0])

}

When I try to run it, I get:
source("corr.R")
corr("/Users/Fanaro/specdata",150)
Error in corr("/Users/Fanaro/specdata", 150) : object 'corrs' not found


text:
Q: Re-installed node cannot join Kubernetes cluster I had a working 3 node k8s cluster (v1.21.0 on Ubuntu 20.04 bare metal) installed using kubeadm. I removed one of the nodes and re-installed it from scratch (wipe disks, new OS but IP address is the same). Now it is unable to join the cluster:
# kubeadm join k8s.example.com:6443 --token who21h.jolq7z79twv7bf4m \
--discovery-token-ca-cert-hash sha256:f63c5786cea2be46c999f4b5c595abd0aa24896c3b37616c347df318d7406c00 \
--control-plane
...
[check-etcd] Checking that the etcd cluster is healthy
error execution phase check-etcd: etcd cluster is not healthy: failed to dial endpoint https://65.21.128.36:2379 with maintenance client: context deadline exceeded
To see the stack trace of this error execute with --v=5 or higher

I ran the same (after kubeadm reset) with --v=5 and it gets stuck logging these:
Failed to get etcd status for https://123.123.123.123:2379: failed to dial endpoint https://123.123.123.123:2379 with maintenance client: context deadline exceeded

123.123.123.123 is the IP address for the node I am trying to return to the cluster.
Running kubectl get nodes on one of the other masters just lists the 2 remaining masters. I removed the node in question properly:
kubectl get nodes
kubectl drain <node-name>
kubectl drain <node-name> --ignore-daemonsets --delete-local-data
kubectl delete node <node-name>

Any ideas? Tx.

A: Take a closer look at the error message you get:
Failed to get etcd status for https://123.123.123.123:2379: failed to dial endpoint https://123.123.123.123:2379 with maintenance client: context deadline exceeded

This is quite common issue, related with etcd cluster, which is well-documented. Compare with the following threads:

*

*Control plain won't join #81071

*kubeadm join is not fault tolerant to etcd endpoint failures #1432

*etcd becomes unhealthy after I delete one of master node, I am look for a fix

*Restoring etcd quorum
Specifically, this is related with the loss of etcd quorum. You can check it as described here.
The solution is described step by step in this comment:

For the record here the command to run on one of the remaining etcd
pod :
Find the id of the member to remove
ETCDCTL_API=3 etcdctl --endpoints 127.0.0.1:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert
/etc/kubernetes/pki/etcd/server.crt --key
/etc/kubernetes/pki/etcd/server.key member list
5a4945140f0b39d9, started, sbg2-k8s001, https://192.168.208.12:2380, https://192.168.208.12:2379
740381e3c57ef823, started, gra3-k8s001, https://192.168.208.13:2380, https://192.168.208.13:2379
77a8fbb530b10f4a, started, rbx4-k8s001, https://192.168.208.14:2380, https://192.168.208.14:2379

I want to remove 740381e3c57ef823
ETCDCTL_API=3 etcdctl --endpoints 127.0.0.1:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert
/etc/kubernetes/pki/etcd/server.crt --key
/etc/kubernetes/pki/etcd/server.key member remove 740381e3c57ef823
Member 740381e3c57ef823 removed from cluster a2c90ef66bb95cc9

Checking
ETCDCTL_API=3 etcdctl --endpoints 127.0.0.1:2379 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert
/etc/kubernetes/pki/etcd/server.crt --key
/etc/kubernetes/pki/etcd/server.key member list
5a4945140f0b39d9, started, sbg2-k8s001, https://192.168.208.12:2380, https://192.168.208.12:2379
77a8fbb530b10f4a, started, rbx4-k8s001, https://192.168.208.14:2380, https://192.168.208.14:2379

Now I can join my new master.


text:
Q: HTML select with angularjs ng-options to MVC Model, can't do it I'm trying to insert my selected value to MVC model.
I saw some answers with @Html.DropDownList but i can't figure it out.
this is my select code :
Manufacturer : <select ng-model="UserCarManufacturer" ng-options="I.id as I.name for I in CountryList" ng-change="GetState()" class="form-control" id="CarManId">
                  <option value="">Select Manufacturer</option>
               </select>
              {{UserCarManufacturer}}

{{UserCarManufacturer}} is the selection id.
I just want to be clear, I want to insert the selected value to this model : @model CreatorModel

A: after few days of searching, I didn't find a way to it so I made this solution:
make an unvisiable "  @Html.TextBoxFor" and set the value in the TextBox each time value change in the HTML select.
this is the code I added, and it works great :
<div class="form-group" style="visibility:hidden;display:none">
                @Html.TextBoxFor(m => m.UserCarModel, new { @class = "form-control", @id = "UserCarModel", @placeholder = "UserCarModel" })
</div>

and in JS I added:
var lbCarMan = document.getElementById("UserCarManufacturer");
lbCarMan.value = $scope.CarManufacturerID;


text:
Q: Detect Python Indent Start in C# I am writing a piece of code to automatically generate indentation in an embedded Python editor, and I am struggling to detect all use cases.

*

*foo -> no indent on next line

*foo: -> indent

*foo: #bar -> indent

*foo: #bar: -> indent

*foo #bar: -> no indent

So far I have this:
Match ColonMatch = Regex.Match(curLineText, @"((:)[^:]*|#.*:)\s*$");
if (ColonMatch.Success && (ColonMatch.Groups.Count == 3) &&
   (ColonMatch.Groups[2].Value == ":"))
{
    // indent on next line

This works for all cases except case four.
I don't need to consider C-style comments or multi-line python comments.
Can anyone help with some fancy regex-foo? Thanks!

A: Actually (at least for these 5 cases) you don't need Regular Expressions:
curLineText = curLineText.Trim();
bool indent = curLineText.Contains("#")?
              curLineText.Substring(0, curLineText.Length - 1).Contains(":"):
              curLineText.EndsWith(":");

Update:
I looked at python and # is for commenting (didn't know that), so omitting that would give us either it ends with : or not. so even simpler:
bool indent = curLineText.Split('#')[0].Trim().EndsWith(":");


text:
Q: Setting automatic GIT deployment of PHP project What I want to do is, to switch from FTP deployment into GIT. I mean, I want to keep automatically keep synced my Bitbucket private repo and my shared webhosting. I googled and found following script to deploy my webserver (based on this article).
// Set these dependant on your BB credentials
$username = 'username';
$password = 'password';

// Grab the data from BB's POST service and decode
$json = stripslashes($_POST['payload']);
$data = json_decode($json);

// Set some parameters to fetch the correct files
$uri   = $data->repository->absolute_url;
$node  = $data->commits[0]->node;
$files = $data->commits[0]->files;

// Foreach through the files and curl them over
foreach ($files as $file) {
    if ($file->type == "removed") {
        unlink($file->file);
    } else {
        $url  = "https://api.bitbucket.org/1.0/repositories"
            . $uri . "raw/" .$node ."/" . $file->file;
        $path = $file->file;

        $dirname = dirname($path);
        if (!is_dir($dirname)) {
            mkdir($dirname, 0775, true);
        }

        $fp = fopen($path, 'w');

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_FILE, $fp);

        $data = curl_exec($ch);

        curl_close($ch);
        fclose($fp);
    }
}

The problem is, this works on simple changesets like 5-10 file change. But when I push the whole project for the first time (for example with 600-700 files and folders) into my bitbucket private profile, this script doesn't work. (just doesn't, no error on errors.log)
What am I missing?
By the way, Can I do something like that:
As we know, Bitbucket can send POST information into an exact url (given by user) directly after a commit has been made. So when deploy.php receives POST, we can get the entire commit as a zip or tar, clean our current files and unzip the new commit into webserver.
Is that possible? If yes then how? Any other good way?
Update
I found the code below for automated deploying php project. The problem is https://bitbucket.org/$username/$reponame/get/tip.zip this url doesnt work on bitbucket private git repo: probably related with authentication (I haven't tested this on public repo) What i need is to get the last commit's zip file and unzip inside my project.
<?

// your Bitbucket username
$username   = "edifreak";

// your Bitbucket repo name
$reponame   = "canvas-game-demo";

// extract to
$dest       = "./"; // leave ./ for relative destination

////////////////////////////////////////////////////////
// Let's get stuff done!

// set higher script timeout (for large repo's or slow servers)
set_time_limit(380);

// download the repo zip file
$repofile = file_get_contents("https://bitbucket.org/$username/$reponame/get/tip.zip");
file_put_contents('tip.zip', $repofile);
unset($repofile);

// unzip
$zip = new ZipArchive;
$res = $zip->open('tip.zip');
if ($res === TRUE) {
    $zip->extractTo('./');
    $zip->close();
} else {
    die('ZIP not supported on this server!');
}

// delete unnecessary .hg files
@unlink("$username-$reponame-tip/.hgignore");
@unlink("$username-$reponame-tip/.hg_archival.txt");

// function to delete all files in a directory recursively
function rmdir_recursively($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir."/".$object) == "dir") rmdir_recursively($dir."/".$object); else unlink($dir."/".$object);
            }
        }
        reset($objects);
        rmdir($dir);
    }
}

// function to recursively copy the files
function copy_recursively($src, $dest) {
    if (is_dir($src)) {
        if($dest != "./") rmdir_recursively($dest);
        @mkdir($dest);
        $files = scandir($src);
        foreach ($files as $file)
            if ($file != "." && $file != "..") copy_recursively("$src/$file", "$dest/$file");
        }
    else if (file_exists($src)) copy($src, $dest);
    rmdir_recursively($src);
}

// start copying the files from extracted repo and delete the old directory recursively
copy_recursively("$username-$reponame-tip", $dest);

// delete the repo zip file
unlink("tip.zip");

// Yep, we're done :)
echo "We're done!";

?>

A: This solution do not provides authentication:
// download the repo zip file
$repofile = file_get_contents("https://bitbucket.org/$username/$reponame/get/tip.zip");
file_put_contents('tip.zip', $repofile);
unset($repofile);

But curl allows it. So a zip archive can be downloaded from a private repository in same way like in first script.
$node = ''; // a node from repo, like c366e96f16...

$fp = fopen($path, 'w');

$ch = curl_init("https://bitbucket.org/$username/$reponame/get/$node.zip");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

I have tested it for my bitbucket account. It's work very well.
If necessary to get last changeset node that we should use bitbucket api GET a list of changesets:
$username = 'login';
$password = 'pass';
$owner = $username; // if user is owner
$repo = 'repo name';

$response = "";
$callback = function($url, $chunk) use (&$response){
    $response .= $chunk;
    return strlen($chunk);
};

$ch = curl_init("https://api.bitbucket.org/1.0/repositories/$owner/$repo/changesets?limit=1");

curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent:Mozilla/5.0'));
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_exec($ch);
curl_close($ch);

$changesets = json_decode($response, true);
$node = $changesets['changesets'][0]['node'];
$raw_node = $changesets['changesets'][0]['raw_node'];

print($node . PHP_EOL);
print($raw_node . PHP_EOL);

A: I recently discovered Capistrano which is a great tool. It was initially developed for ruby but it's also great in combination with php http://www.davegardner.me.uk/blog/2012/02/13/php-deployment-with-capistrano/

A: Based on your update, replace you php files contents with code below:
<?php
// Set these dependant on your BB credentials
$username = '';
$password = '';

// your Bitbucket repo name
$reponame   = "";

// extract to
$dest = "./"; // leave ./ for relative destination
// Grab the data from BB's POST service and decode
$json = stripslashes($_POST['payload']);
$data = json_decode($json);

// set higher script timeout (for large repo's or slow servers)
set_time_limit(5000);

// Set some parameters to fetch the correct files
$uri = $data->repository->absolute_url;
$node = $data->commits[0]->node;
$files = $data->commits[0]->files;

// download the repo zip file
$fp = fopen("tip.zip", 'w');

$ch = curl_init("https://bitbucket.org/$username/$reponame/get/$node.zip");
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

// unzip
$zip = new ZipArchive;
$res = $zip->open('tip.zip');
if ($res === TRUE) {
    $zip->extractTo('./');
    $zip->close();
} else {
    die('ZIP not supported on this server!');
}

// function to delete all files in a directory recursively
function rmdir_recursively($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (filetype($dir . "/" . $object) == "dir")
                    rmdir_recursively($dir . "/" . $object); else
                    unlink($dir . "/" . $object);
            }
        }
        reset($objects);
        rmdir($dir);
    }
}

// function to recursively copy the files
function copy_recursively($src, $dest) {
    if (is_dir($src)) {
        if ($dest != "./")
            rmdir_recursively($dest);
        @mkdir($dest);
        $files = scandir($src);
        foreach ($files as $file)
            if ($file != "." && $file != "..")
                copy_recursively("$src/$file", "$dest/$file");
    }
    else if (file_exists($src))
        copy($src, $dest);
    rmdir_recursively($src);
}

// start copying the files from extracted repo and delete the old directory recursively
copy_recursively("$username-$reponame-$node", $dest);

// delete the repo zip file
unlink("tip.zip");
?>

Update
Here are repositories of this script (Modified by Me) on

*

*GitHub

*Bitbucket


text:
Q: Database archiving with full database Am having relational database MySQL. The requirement is to archive the records of few tables and their related records to be completely removed from the active database and archive it to access later if required. The web application is built on Rails BTW.
Is there a way, where any insertion or update on the original database is reflected to the archived database and deletions on original database are not updated to the archived database.
That way archived database has complete data both active and archived. And the original database has only live-accessible data.
Or is there any different and efficient solution. Why because, if we were to do brute force approach, by whenever the data moved to the archived database, all the records and their dependent records need to be identified and moved to the archived database and then remove the respective records in the original database.
With the Rails framework deleting the related and dependent records is relatively easy when dependent: :destroy is configured correctly.

A:
Is there a way, where any insertion or update on the original database is reflected to the archived database and deletions on original database are not updated to the archived database.

Counterexample "I"
Insertions and updates are reflected, deletions are not. But an evil colleague might just replace any content with dummy content before deleting a record, so only the relations between the records will remain, but everything else will be gone. This may make the "no-delete mirroring approach" useless (except you can deduct valuable information from the link graph itself).

If the archived database also has all technical properties of the original one, this is counterexample "II":
Imagine a table that has UNIQUE groups defined for some of the columns:
UNIQUE (Name, Surname, Birthplace, Birthdate)
Now someone deletes Jane Doe, London, 2000-01-01. The shadow table will preserve this record, though.
After a week, you note that this was a mistake made by some colleague. You want to re-create Jane, but since her data is still present in the shadow table, this will be refused and the transaction won't commit.


text:
Q: ttys no longer show release version after 16.04 Update (from 14.04.4) On Ubuntu 14.04.4 (and previous), there was a message at the top of each tty (1-6) that said

Ubuntu 14.04.4 LTS $HOST tty1 #or tty2 etc.
$HOST login:

I upgraded to 16.04 (with sudo do-release-upgrade -d).
During the upgrade, I loaded tty3, and it said

Ubuntu 16.04 LTS $HOST tty3
$HOST login

However, after the upgrade, all the ttys said was

$HOST login:

Without the Ubuntu version or the tty number.

Is this intended for 16.04? If so, is there a way to change it back to showing the version? (like with getty configs or something?)

A: That message comes from the file /etc/issue and/or /etc/issue.net.
I would imagine that you either lost these files or they are not readable by root (?!?) or they do not get printed anymore.
The files should automatically have been updated.
It would be set to the output of lsb_release -d or something of the sort.
If that does not work for you, you could create a script under /etc/profile.d/... and put:
lsb_release -a

In that script. That being said, the motd (Message of the Day) should be displayed when you log in and that should already include all the necessary information about the machine.


text:
Q: Using MVC dropdown list how to edit form and show the data in dropdown and previously selected item in dropdown? I am using MVC4 and displaying categories in drop down list. Foam allow user to edit the previously added data. So when i perform update action all the other data that user enter can easily displayed but who to display the selected category value from drop down list and show that valve in drop down?
Controller
using (var catRepo = new BusinessLayer.Repostories.CategoryRepository())
{
  ViewBag.VBCategoryList = new SelectList(catRepo.GetAllCategories(),"CategoryId","Name");
}

View
 @Html.DropDownList("CategoryId", ViewBag.VBCategoryList as SelectList)

A: Your Model should contains CategoryId
public int CategoryId{get;set;}

Your Edit Action will be similar to below code
public ActionResult Edit(int id)
{
   using (var catRepo = new BusinessLayer.Repostories.CategoryRepository())
   {
      var itemToEdit=catRep.GetItemById(id);// replace your method
      ViewBag.VBCategoryList = new  SelectList(catRepo.GetAllCategories(),"CategoryId","Name",itemToEdit.CategoryId);
   }
   return View(itemEdit);
}

A: you can also use javascript to do this.you have just write your javascript code in document.ready(function()
document.getElementById("your dropdown id").value = '@Model.yourDropdownValue';


text:
Q: The current SEDE refresh was delayed overnight On Saturday, January 22nd, we had a failure on a backup share that won't be fully resolved until Monday.
We've immediately re-routed backups to multiple secondary locations, so that concern has been mitigated.
Unfortunately, the Data Explorer refresh job and the processes that feed into it were disabled as a precaution.
We had two options:

*

*Cancel the SEDE refresh job and wait until the underlying issue is resolved

*Dig into the processes to determine how to make them piece together backups from different locations

Due to it being the weekend, we decided that option #1 was the only feasible one, and hoped to refresh Data Explorer as soon as everything was back in order. Expectation was Monday at the earliest and hopefully no later than Tuesday.
Option #2 wasn't something I felt comfortable loading onto probably multiple people as a surprise weekend project, a mere few hours before the job was scheduled to run.
This precaution turned out to be unnecessary, as my digging into the process yielded today and as my answer below explains.

A: The weekly SEDE refresh was started about 12 hours later on Sunday, January 23rd, at 14:40 UTC and finished in 8h 24m (a little after 23:00 UTC).
A bit of a mea culpa: as I dug into the refresh job today to see if I could tinker with where it looks for backup files, I realized that it actually doesn't rely on the backup files directly, and that there is no effort required to make this process more tolerant.
SEDE should be all refreshed with last week's data by about 23:00 UTC, including some fresher data from overnight while the job was disabled.
Sorry for the delay, the interruption, and the slightly misguided panic.


text:
Q: Executing a PHP file from iOS app and refreshing label text In my app I need to include a button action to update the value of a MySQL field in a remote server. When the user taps on the button, the app should add 1 to a field value.
The MySQL value is shown in a UILabel.
I have written the PHP file to make the update to the database.
In my viewController I am getting the id field to be passed to the PHP file.
This is the button action that performs the value update:
- (IBAction)votarAction:(id)sender {
    //URL definition where php file is hosted
    int categoriaID = [[detalleDescription objectForKey:@"idEmpresa"] intValue];

    NSString *string = [NSString stringWithFormat:@"%d", categoriaID];
    NSLog(@"ID EMPRESA %@",string);
    NSMutableString *ms = [[NSMutableString alloc] initWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
    [ms appendString:string];
    // URL request
    NSLog(@"URL = %@",ms);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
    //URL connection to the internet
    [[NSURLConnection alloc]initWithRequest:request delegate:self];

}

What I need is that after tapping on the button, and the field value is updated, to show the new value at the UILabel.
Which is the best way to do this?

A: This is a good way do it:
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.domai.queue", 0);

dispatch_async(backgroundQueue, ^{

    int categoriaID = [[detalleDescription objectForKey:@"idEmpresa"] intValue];

    NSString *string = [NSString stringWithFormat:@"%d", categoriaID];
    NSLog(@"ID EMPRESA %@",string);
    NSMutableString *ms = [[NSMutableString alloc]
                                      initWithString:@"http://url.php?id="];
    [ms appendString:string];

    // URL request
    NSLog(@"URL = %@",ms);
    NSURLRequest *request =
                      [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];

    //URL connection to the internet
    NSData *responseData = [[NSURLConnection alloc]
                                    initWithRequest:request delegate:self];
    NSLog(@"responseData= %@",responseData);//["34"]

    //Parse JSON
    NSMutableDictionary  * json = [NSJSONSerialization
                               JSONObjectWithData:responseData
                                          options: NSJSONReadingMutableContainers
                                            error: &error];

    NSString *labelValue = (NSString*) [json objectAtIndex:0];

    dispatch_async(dispatch_get_main_queue(), ^{
        //update your UIlabel dataLabel
        dataLabel.text = labelValue;
    });
});

You should make the request and return the JSON in a background thread, then update the UILabel in the main queue.


text:
Q: Page main content not showing up on Chrome until after clicking on the inspect elements The page content in #main area is not showing up only on Chrome browser. But I can see the code is there when I view the page source. And when I click on the "inspect elements" or by clicking on any CSS style on the "inspect elements" popup, the content can just appear suddenly. Here is the page URL you can take a look on Chrome browser,
http://ssf-qa.uchicago.edu/Home.html
The version of the Chrome I'm using is,
Version 33.0.1750.146 m
And we have custom fonts on the page.
Thanks a lot!

A: I've seen this recently with Modernizr, which I see you have running on there too. If you remove the reference to modernizr it works right away!  I think we just have to wait for a bug fix.


text:
Q: Soot: soot.jimple.JimpleBody cannot be cast to soot.dava.DavaBody I ran the following code to get the exception handler in .class file:
public void getException(SootMethod method){
    DavaBody db = (DavaBody) method.retrieveActiveBody();
    IterableSet excepFacts = db.get_ExceptionFacts();
    Iterator<ExceptionNode> it = excepFacts.iterator();
    while(it.hasNext()){
        ExceptionNode en = it.next();
        ...
    }
}

I got errors after running above code:
Exception in thread "main" java.lang.ClassCastException:
soot.jimple.JimpleBody cannot be cast to soot.dava.DavaBody

The method method.retrieveActiveBody() returns Body type, not JimpleBody, so why is this error happening?

A: Body is the declared type. In your configuration of Soot, it actually returns a JimpleBody.

A: By the documentation, public Body retrieveActiveBody() is:

Returns the active body if present, else constructs an active body and returns that.

Let's look at the Body class:
public abstract class Body
extends AbstractHost
implements Serializable

So it is Abstract class, and by your exception, it returns JimpleBody, subclass of Body.
If Rabbit is Animal, and Wolf is also Animal, Rabbit is not a Wolf.
You can edit code like that:
if (method.retrieveActiveBody() instanceof JimpleBody) {

} else if (method.retrieveActiveBody() instanceof DavaBody) {

} else if (method.retrieveActiveBody() instanceof BafBody) {

} else if (method.retrieveActiveBody() instanceof StmtBody) {

} else {

}


text:
Q: How to show that the matrix of the following map has positive determinant? Let $(v_1,v_2)$ and $(h_1,h_2)$ and be two basis of a plane $P$ in $\mathbb{R}^3.$ Then I want to show that,
$$\hat{v} = \frac{v_1 \times v_2}{||v_1\times v_2||}= \hat{h}= \frac{h_1 \times h_2}{||h_1\times h_2||}\iff \det(A) > 0$$
where $A$ is the isomorphism that sends $v_i\to h_i$ for $i=1,2.$
I understand geometrically the problem statement but I am not sure how to prove it since
the expression for the map $A$ is not clear to me. Any hints will be much appreciated.

A: Assuming $\;T\;$ is the matrix corresponding to the isomorphism you mention with respecto to those given two basis , then it equals $\;\begin{pmatrix}1&0\\0&1\end{pmatrix}\;$, which obviously has positive determinant....and that's all.
If you would want to express your isomorphism with respect to any other two basis of that plane, then you'll get the very same determinant, as determinant is an invariant of linear operators.

A: Define a linear map $B$ on $\mathbb R^3$ by $B=A$ on $P$ and $B=$ the identity map on $V=\operatorname{span}\{\hat{v}\}$. Then
$$
\det(B)\det[v_1,v_2,\hat{v}]=\det[Bv_1,Bv_2,B\hat{v}]=\det[h_1,h_2,\hat{h}].
$$
Note that $\det[v_1,v_2,\hat{v}]=(v_1\times v_2)\cdot\hat{v}=(v_1\times v_2)\cdot\frac{v_1\times v_2}{\|v_1\times v_2\|}=\|v_1\times v_2\|>0$ and similarly, $\det[h_1,h_2,\hat{h}]>0$. Therefore $\det(B)>0$.
However, since $\mathbb R^3=P\oplus V$ and both $P$ and $V$ are invariant subspaces of $B$, we have
$$
\det(B)=\det(B|_P)\det(B|_V)=\det(A).
$$
Hence $\det(A)>0$.


text:
Q: Understanding inner generic classes I wrote the following code:
public class Test<T> {

    public void method(){
        B b = new B();
    }

    public class B{ }
}

//Some method in some class contains the following lines
Test<Integer> t = null;
Test.B b = t.new B(); //warning Test.B is a raw type

Why did I get this warning? The declation of the inner type B doesn't contain type parameter, therefore it's not a generic type. Moreover, the specification gives us the following:

A class is generic if it declares one or more type variables

The class B doesn't declare the type variables. So why is it a generic type?

A: Although the inner class B does not declare any type variables, an instance of it implicitly references an instance of the outer class, which does.

Why did I get this warning?

Test<Integer> t = null;
Test.B b = t.new B(); //warning Test.B is a raw type

Because you declared the variable b with a raw type. Instead, you could declare:
Test<Integer>.B b = t.new B(); // no warning!

A: I agree that the specification of generic classes does not clearly cover your scenario. But the specification of raw types does:

More precisely, a raw type is defined to be one of:

*

*The reference type that is formed by taking the name of a generic type declaration without an accompanying type argument list.

*An array type whose element type is a raw type.

*A non-static member type of a raw type R that is not inherited from a superclass or superinterface of R.

A: You do not really use the generic type. I will explain it on a slightly more elaborate example:
public class Test<T> {
    public B method(T t) {
        B b = new B(t);
        return (b);
    }

    public class B {
        T value;

        public B(T value) {
            this.value = value;
        }
    }
}

Here you can see clearly, that B depends on the generic parameter T, without being generic itself. As explained by Andy Thomas, an instance of B can only be created in co-existence with an instance of Test. Therefore, B is (indirectly) generic. In your given example:
Test<Integer> t = null;
Test.B b = t.new B(); //warning Test.B is a raw type

b does not specify a generic parameter, but t does. This is, why you get the warning.
The proper way to write this code would be:
Test<Integer> t = null;
Test<Integer>.B b = t.new B();

With this, B is fully specified and the types match.

A: Although B is not parameterized, Test.B b = t.new B(); contains a raw reference to Test, which is parameterized. I got the warning to disappear when I changed the warning line to Test<Integer>.B b = t.new B();

A: What you're trying is not working because B's type is not B but Test<T>.B
To get this to work, make class B static.
public static class B{ }

A: B is an inner class. It cannot exist without an instance of Test. Thus, it also depends on any type parameters of Test. When compiled, class B is transformed into the following:
public class Test$B {
  public Test$B(Test paramTest) {}
}

(That's what you'll get if you compile it and then decompile it.)
You can see that it takes an Test in its constructor. Though type parameters are erased when compiling, if you wrote a class like that yourself, you would probably give it a type parameter to be passed along to Test.


text:
Q: Parsing directories and detecting unexpected blanks I'm trying to parse some directories and identifying folders witch do not have a specific correct pattern. Let's exemplify:
Correct: Level1\\Level2\\Level3\\Level4_ID\\Date\\Hour\\file.txt
Incorrect: Level1\\Level2\\Level3\\Level4\\Date\\Hour\\file.txt

Notice that the incorrect one does not have the _ID. My final desired goal is parse the data replacing the '\' for a delimiter to import for MS excel:
Level1;Level2;Level3;Level4;ID;Date;Hour;file.txt
Level1;Level2;Level3;Level4; ;Date;Hour;file.txt

I had successfully parsed all the correct data making this steps:
Let files be a list of my all directories
for i in arange(len(files)):
    processed_str = files[i].replace(" ", "").replace("_", "\\")
    processed_str = processed_str.split("\\")

My issue is detecting whether or not Level4 folder does have an ID after the underscore using the same script, since "files" contains both correct and incorrect directories.
The problem is that since the incorrect one does not have the ID, after performing split("\") I end up having the columns mixed without a blanck between Level4 and Date:
 Level1;Level2;Level3;Level4;Date;Hour;file.txt

Thanks,

A: Do the "_ID" check after splitting the directories, that way you don't loose information. Assuming the directory names themselves don't contain escaped backslashes and that the ID field is always in level 4 (counting from 1), this should do it:
for i in arange(len(files)):
    parts = files[i].split("\\")
    if parts[3].endswith("_ID"):
        parts.insert(4, parts[3][:-len("_ID")])
    else:
        parts.insert(4, " ")
    final = ";".join(parts)


text:
Q: Access ViewController in iOS-Native Extension for Adobe Air Short:
The Android-API for Air-Native-Extensions provides a getActivity() on the Context-Object.
I am looking for a way, to get the current ViewController in iOS-Native-Extensions
Long:
We need to extend Air with more than just some iOS-API-Calls to access vibration etc, but want to display a View (MPMediaPickerController to select a File from the iTunes library). In the Keynote to native extensions on Adobe MAX 2011 (http://tv.adobe.com/watch/max-2011-develop/how-to-extend-your-mobile-air-applications-using-native-extensions/) Oliver Goldman said, it is okay to show complete Views by using native extensions.
To show the MPMediaPickerController (or any other View), I need to call presentModalViewController on the current ViewController or need access to the Navigation Controller.
I hoped there is a way to get a pointer to the controller somehow, but I have not found any documentaion about it.

A: You can use this piece of code. It works.
UIViewController * myViewController;
id delegate = [[UIApplication sharedApplication] delegate];
UIWindow * win = [delegate window];
myViewController = [[MyView alloc] init];
// CGRect rect = CGRectMake(x,y,w,h);
// init the view position some how  myViewController.viewFrame = rect;

[win addSubview:myViewController.view];

Hope this helps.
Best,
Emil


text:
Q: Change input size of vggface pretained model It been a week that Im trying to change the input size of the pertrained  Vgg face model every time I change something it got me an error how can I change the input size from 224x224x3 to 64x64x3 is there a way to change it directly without training again the model just using the pertrained weights directly
model.add(ZeroPadding2D((1, 1),include_top=False,input_shape=(64, 64, 3)))

model.add(Convolution2D(64, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(Convolution2D(4096, (7, 7), activation='relu'))
model.add(Dropout(0.5))
model.add(Convolution2D(4096, (1, 1), activation='relu'))
model.add(Dropout(0.5))
model.add(Convolution2D(2622, (1, 1)))
model.add(Flatten())
model.add(Activation('softmax'))

from keras.models import model_from_json

deep= model.load_weights('/Users/macbookpro/PycharmProjects/untitled/venv/vgg_face_weights.h5')

code:
vggface
When I try to call include_top i got this error:
TypeError: ('Keyword argument not understood:', 'include_top')

When I change directly the input size i got this error:
ValueError: Negative dimension size caused by subtracting 7 from 2 for 'conv2d_14/convolution' (op: 'Conv2D') with input shapes: [?,2,2,512], [7,7,512,4096].

A: First of all, remove the include_top=False.
Your problem is that this architecture is too deep for a 64x64 input. In particular, this line:
model.add(Convolution2D(4096, (7, 7), activation='relu'))

is trying to perform a 7x7 convolution on an input of size 2x2 which is impossible.
A possible solution is to remove the Convolutions after the last MaxPooling layer and use some Dense layer instead.


text:
Q: How to hide before click submit and show after click submit How to hide this output box before I click submit button and show after I click submit button

<form method="post" action="">

        Total Twitter (0)

        <textarea id="ids" class="input-block-level" name="ids" type="text" placeholder="Email:Password" rows="15" onKeyDown="countFakes()" onChange="countFakes()" style="width:60%;height:35%;"></textarea>

<input type="submit" class="button button-submit" name="dot" Value="Submit"/>

</form>

    Result of Checker

Result


text:
Q: storing and retrieving json objects to / from a cookie Im attempting to store json objects in a cookie, but im running into a few problems.
I can create my object like this:
product = {
   "name" : "prodname",
   "quantity" : 4
}

i then save this object in my cookie. As more products are added (its a shopping basket) i add further strings by appending new objects onto the end of the cookie string (so i essentially have lots of small seperate objects) . Im having trouble getting the objects back out of the cookie string though. Both $.parseJSON and eval fail when i attempt to read the objects back from the cookie. Any help would be appreciated.

A: its not a good practice to save the value that returned from JSON.stringify(cookieStr) to the cookie. it can lead to a bug in some browsers.
before using it you should convert it to base64 (using btoa), and when reading it, converting from base64 (using atob)
val = JSON.stringify(cookieStr)
val = btoa(val)

write_cookie(val)

A: It should probably be like:
{"products": [
    {
       "name" : "prodname",
       "quantity" : 4
    },
    {
       "name" : "prodname2",
       "quantity" : 3
    }
]}

The [] signifies an array.  When you want add another product, you load it from the cookie, update the array, then save it again.  If you wanted, you could skip the outer object and have the cookie just be the array.
EDIT: Say cookieStr is your cookie.
var root = $.parseJSON(cookieStr);
root.products.push(newProduct);
cookieStr = JSON.stringify(root);


text:
Q: Is it possible for ansible inventory to use variables according to group? I'm new to ansible. I'm sorry if my question is basic.
Let's say I have a web server in a group called web in my inventory file. The same server is also in the test group. Something like this:
web:
  hosts:
    vm01:
      ansible_host: foo.example.com
      ansible_user: user1
test:
  hosts:
    vm01:
      ansible_user: user2

If I run:
ansible-inventory -i inventory.yaml --list

I get the following output:
{
    "_meta": {
        "hostvars": {
            "vm01": {
                "ansible_host": "foo.example.com",
                "ansible_user": "user2"
            }
        }
    },
    "all": {
        "children": [
            "test",
            "ungrouped",
            "web"
        ]
    },
    "test": {
        "hosts": [
            "vm01"
        ]
    },
    "web": {
        "hosts": [
            "vm01"
        ]
    }
}

First of all, why vm01 is getting ansible_user variable from the test group?? Isn't it supposed to get it from the web??? According to documentation, variables at the same level will have values according to the parent's ASCII order.
Second, is it possible to run ansible somehow, to use ansible_user variable from test group instead??

A:
Why vm01 is getting ansible_user variable from the test group??

According Understanding variable precedence

In general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope.

In other words, the last definition wins always.

Isn't it supposed to get it from the web???

Therefore, no.

Is it possible to run ansible somehow, to use ansible_user variable from test group instead??

Yes, by limiting the execution to that group (test) in example via targeting hosts and groups.


text:
Q: Como crear un  con bg-img que contiene texto, y centrar texto sin flex-box estoy creando, para un lab una pagina donde tengo que crear un div con una img de bg y dentro un texto centrado horizontalmente y verticalmente.
  **

Apple Pies

**

estoy usando este estilo:
#topImage {
  background-image: url("../images/apple-pie.jpg");
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
  width: 500px;
  height: 500px;
}
h1 {
  font-family: "Roboto", sans-serif;
  font-size: 1, 5 rem;
  color: white;
}

Alguien tiene una idea?
Muchas gracias cracks

A: #topImage significa una id, pero topImage es una clase. Entonces necesitas usar .topImage.

.topImage {
  background-image: url("https://images.freeimages.com/images/large-previews/ae6/fresh-apple-pie-1327510.jpg");
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
  width: 500px;
  height: 500px;
}
h1 {
  font-family: "Roboto", sans-serif;
  font-size: 1, 5 rem;
  color: white;
}

Apple Pies

A: Tienes muchas maneras de hacerlo sin tener que recurrir al uso de las cajas flexibles. Una de ellas es hacer que el contenedor sea position: relative y el contenido position: absolute. A través de top: 0; bottom: 0; left: 0; right: 0; indicamos que queremos que el contenido esté a la misma distancia de los cuatro lados del contenedor.
Ponerle una altura determinada al contenido es necesario para que el margin: auto; pueda determinar como colocar el elemento y por último con text-align: center; lo centramos horizontalmente.

.topImage {
  background-image: url("https://www.simplyrecipes.com/wp-content/uploads/2014/09/apple-pie-horiz-a-1800.jpg");
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
  width: 500px;
  height: 500px;
}

h1 {
  font-family: "Roboto", sans-serif;
  font-size: 1, 5 rem;
  color: red;
  position:absolute;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
  height: 50px; /*requires explicit height*/
  text-align: center;
}

Apple Pies

Referencia: 13 ways to vertical center

A: Una alternativa mas rustica pero valida , mas en los casos cuando el contenedor no tengo que ajustarse a otras resoluciones es usar la propiedad line-height , podes usarla aprovechando que el contenedor ya tiene declarado un alto fijo que seria el mismo valor que el alto de linea

.topImage {
  background-image: url("https://images.freeimages.com/images/large-previews/ae6/fresh-apple-pie-1327510.jpg");
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
  width: 500px;
  height: 500px;
}
h1 {
  font-family: "Roboto", sans-serif;
  font-size: 1, 5 rem;
  color: white;
  text-align:center;
  line-height:500px;
}

Apple Pies


text:
Q: Barplot with significant differences and interactions? I would like to visualize my data and ANOVA statistics. It is common to do this using a barplot with added lines indicating significant differences and interactions. How do you make plot like this using R?
This is what I would like:
Significant differences:

Significant interactions:

Background
I am currently using barplot2{ggplots} to plot bars and confidence intervals, but I am willing to use any package/procedure to get the job done. To get the statistics I am currently using TukeyHSD{stats} or pairwise.t.test{stats} for differences and one of the anova functions (aov, ezANOVA{ez}, gls{nlme}) for interactions.
Just to give you an idea, this is my current plot:

A: As you are using function barplot2() from library gplots, will give example using this approach.
First, made barplot as given in help file of barplot2() function. ci.l and ci.u are fake confidence interval values. Barplot should be saved as object.
hh <- t(VADeaths)[1:2, 5:1]
mybarcol <- "gray20"
ci.l <- hh * 0.85
ci.u <- hh * 1.15
mp <- barplot2(hh, beside = TRUE,
               col = c("grey12", "grey82"),
               legend = colnames(VADeaths)[1:2], ylim = c(0, 100),
               cex.names = 1.5, plot.ci = TRUE, ci.l = ci.l, ci.u = ci.u)

If you look on object mp, it contains x coordinates for all bars.
 mp
     [,1] [,2] [,3] [,4] [,5]
[1,]  1.5  4.5  7.5 10.5 13.5
[2,]  2.5  5.5  8.5 11.5 14.5

Now I use upper confidence interval values to calculate coordinates for y values of segments. Segments will start at position that is 1 higher then the end of confidence intervals. y.cord contains four rows - first and second row correspond to first bar and other two rows to second bar. Highest y value is calculated from the maximal values of confidence intervals for each bar pair.
x.cord values just repeat the same values which are in mp object, each 2 times.
y.cord<-rbind(c(ci.u[1,]+1),c(apply(ci.u,2,max)+5),
          c(apply(ci.u,2,max)+5),c(ci.u[2,]+1))
x.cord<-apply(mp,2,function(x) rep(x,each=2))

After barplot is made use sapply() to make five line segments (because this time there are 5 groups) using calculated coordinates.
sapply(1:5,function(x) lines(x.cord[,x],y.cord[,x]))

To plot texts above the segments calculate x and y coordinates, where x is middle point of two bar x values and y value is calculated from the maximal values of confidence intervals for each bar pair plus some constant. Then use function text() to add information.
x.text<-colMeans(mp)
y.text<-apply(ci.u,2,max)+7
text(c("*","**","***","NS","***"),x=x.text,y=y.text)

A: I guess that now your question has been more or less addressed, so I will instead encourage you to use different method that is much better in visual representation of your data - dotplots. As an example compare your barplot to the dotplot constructed with similar data points:
#example data similar to your barplot
d <- data.frame(group=rep(c("control","group1","group2"),each=4),
                esker=c(1.6,1.4,1.8,1.5,2,1.8,1.6,1.4,2.3,2,1.7,1.4),
                se=rep(0.1,12),
                cond=rep(c("t1","t2","t3","t4"),3))
#dotplot - you need Hmisc library for version with error bars
library(Hmisc)
Dotplot(cond ~ Cbind(esker, esker+se, esker-se) | group, data=d, col=1,
        layout=c(1,3), aspect="xy",
        par.settings = list(dot.line=list(lwd=0), plot.line=list(col=1)))

Compare it to barplot. In the dotplot, it's much easier to see the differences when plotted horizontally, you don't need extra legend or bars or colours to show you the conditions, you don't need the guidelines and other noisy elements. You have everything contained within those three panels. Of course, I understand that you might want to highlight your significant effects, and that maybe it works fine for a small number of conditions. But if number of factor increases, the plot would overflow with stars and shit.
Keep it simple. Keep it dotplot. Check William Cleveland and Edward Tufte books for more on this.

A: I recommend using ggplot instead of barplot, and you can build the lines manually like this:
This is starting with a data.table like the following:
data.table used
gg <- ggplot(data, aes(x = time, y = mean, fill = type)) +
    geom_bar(stat = "identity", position = "dodge") +
    scale_fill_manual(values = c("RGX" = "royalblue2", "EX" = "tomato2")) +
    xlab("Post-treatment Time Point (months)") +
    ylab(paste("data", "Change Score")) +
    scale_y_continuous(expand = c(0, 0)) +
    ylim(c(0,max(data$mean*1.5)))

# add horizontal bars
gg <- gg + geom_errorbar(aes(ymax = hline, ymin = hline), width = 0.45)

# add vertical bars
gg <- gg + geom_linerange(aes(ymax = max(data$mean)+3, ymin = max(data$mean)+1), position = position_dodge(0.9))

# add asterisks
gg <- gg + geom_text(data = data[1:2], aes(y = max(data$mean)+4), label = ifelse(data$p_value[1:2] <= 0.4, "*", ifelse(data$p_value[1:2] <= 0.05, "*", "")), size = 8)

gg

plot output


text:
Q: How to get a circle drawn at pointer location to stay on screen in threejs (mouse trail) I'm trying to create a mouse trail effect with threejs, basing it off of this example: https://medium.com/epicagency/behind-the-scenes-of-we-cargo-3999f5f559c (near the bottom of the page).
I've been trying this for a few days now, but I cannot get the circle which is drawn with an intensity derived from the cursor speed and fades over time, to stay on the screen as is shown in the example on the link provided. Everything is working fine in terms of drawing the circle based on cursor delta, but I cannot figure out how to actually keep the trail on screen. The circle only is drawn where the cursor is and all trails are erased on each animation frame. I've tried setting the canvas alpha to 0, I've tried using a FBO and using the mouse trail as an intermediate render target, I've tried hijacking the render function in the middle of the RAF hook (I'm using React Three Fiber), and I keep getting the same results. I'm not using the bidello helper class that the author is using, maybe there is some subtle thing that I'm missing in those helper classes that is the secret sauce... I don't know.
Plane.js
const Geometry = props => {

    const width = window.innerWidth
    const height = window.innerHeight

    const pointer = new THREE.Vector2()
    let speed = 0

    const uniforms = useMemo(
        () => ({
            u_mouse: { value: new THREE.Vector2() },
            u_speed: {
                value: 0,
            },
            u_time: { value: 0.0 },
            u_resolution: { value: { x: width, y: height } },
            u_ratio: {
                value: window.innerWidth / window.innerHeight,
            },
            u_texture: {
                value: new THREE.DataTexture(
                    new Float32Array(width * height * 4),
                    width,
                    height
                ),
            },
        }),
        []
    )

    var diff = new MouseSpeed()
    diff.init()

    const pointerMove = e => {
        pointer.set(e.x / window.innerWidth, 1 - e.y / window.innerHeight)

        pointer.x = (e.clientX / window.innerWidth) * 2 - 1
        pointer.y = -(e.clientY / window.innerHeight) * 2 + 1

        uniforms.u_mouse.value.x = pointer.x
        uniforms.u_mouse.value.y = pointer.y
    }

    useFrame((state, delta) => {
        uniforms.u_time.value += delta

        uniforms.u_mouse.value.lerp(pointer, 0.2)
        uniforms.u_speed.value = speed
        // state.gl.render(state.scene, state.camera)
        // state.gl.setClearColor(0x000000, 0)

        const diffSpeed =
            Math.max(Math.abs(diff.speedX), Math.abs(diff.speedY)) * 0.05
        speed += diffSpeed
        speed *= 0.9
    })

    return (
        <>
            {/* {createPortal(<Trail />, scene)} */} // This was used when I was using an FBO
            <mesh onPointerMove={pointerMove}>
                <planeBufferGeometry args={[width, height, 1, 1]} />
                <shaderMaterial
                    uniforms={uniforms}
                    vertexShader={mainVert}
                    fragmentShader={mainFrag}
                    onUpdate={self => (self.needsUpdate = true)}
                />
            </mesh>
        </>
    )
}

shader.frag
uniform vec2 u_resolution;
uniform vec3 u_mouse;
uniform float u_time;
uniform float u_ratio;
uniform float u_speed;
uniform sampler2D u_texture;

void main() {
    vec2 uv = gl_FragCoord.xy / u_resolution.xy;
    vec4 color = texture2D(u_texture, v_uv + vec2(0.0, -0.002));

    vec2 center = (u_mouse.xy) / 2. + .5;
    uv.x *= u_ratio;
    center.x *= u_ratio;

    color.r += circle(uv, center, 0.0, .08) * u_speed;
    color.r = mix(color.r, 0.0, .009);
    color.r = clamp(color.r, 0.0, 1.0);

    color.g = color.r;

    gl_FragColor = color;
}

Basically I'm just wondering what I have to do to get this working like the mouse trail animation in the example that I provided. As I said, everything is fine except for the actual trail itself to remain on the screen. Any help is very much appreciated.
Thanks


text:
Q: How to check for roles in NestJS Guard I have an external service providing a JWT token. In Nestjs i first have JwtGuard class:
@Injectable()
export class JwtGuard extends AuthGuard('JWT_STRATEGY') {
  constructor() {
    super();
  }

  getRequest(context: ExecutionContext) {
    console.log('JwtGuard');
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
}

and then a passport strategy:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'JWT_STRATEGY') {
  constructor(private configService: ConfigService) {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: configService.get<string>('ADFS_KEYS_URL'),
      }),
      ignoreExpiration: false,
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: configService.get<string>('ADFS_AUDIENCE'),
      issuer: configService.get<string>('ADFS_ISSUER'),
      algorithms: ['RS256'],
    });
  }

  validate(payload: unknown): unknown {
    console.log('jwt strategy');
    console.log(payload);
    return payload;
  }
}

It seems that JwtGuard is running first, then the strategy. But if i want to do additional guards and checks, say for roles. Where does one do that? Do i need another guard that runs after the passport strategy? I have two roles "User" and "Admin".

A: First of all, define a global guard (called RolesGuard) in the AppModule as following:
providers: [
  AppService,
  {
    provide: APP_GUARD,
    useClass: JwtAuthGuard,
  },
  {
    provide: APP_GUARD,
    useClass: RolesGuard,
  },
]

Then within RolesGuard we have the following:
export enum FamilyRole {
  Admin = 'Admin',
  User = 'User',
}

...

export class FamilyRolesGuard implements CanActivate {

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRoles = this.reflector.getAllAndOverride<FamilyRole>(
      ROLES_KEY,
      [context.getHandler(), context.getClass()],
    );

    if (!requiredRoles) {
      return true;
    }

    const { user } = context.switchToHttp().getRequest();
    // do the rest and return either true or false
  }
}

Then create your own decorator and you can decorate your APIs if you need that API to protect your app based on your guard.
import { SetMetadata } from '@nestjs/common';

export const ROLES_KEY = 'FamilyRoles';
export const FamilyRoles = (...roles: FamilyRole[]) =>
  SetMetadata(ROLES_KEY, roles);

Then you can use your decorator in your API like this:
@Post('user')
@FamilyRoles(FamilyRole.Admin)
...

So, in your API, if you won't have FamilyRoles, in the guard you won't have requiredRoles, and the if block will return true.
More info: https://docs.nestjs.com/security/authorization


text:
Q: Batch processing: GNU-make, Snakemake or what? I need to process a group of files in a directory by passing them to a matlab or a python script.
For every input file FileName.IN in the directory I need to obtain a output file FileName.OUT.
It doesn't really matter if the solution is a Python or a bash script.
To achieve my goal I try GNU Make (or Python Snakemake), however I am a bit stuck on it.
It looks like I can say GNU Make to do:
" Hey, for every output (target) file FileName.out search the corresponding FileName.IN (prerequisites)".
However what I want to do is exactly the opposite, as stated before.

*

*Is make (or snakemake) the right choice?

*What else would you suggest?

My makefile code looks like this but it doesn't do the job (I am a newbie with GNU make):
in_files = *.IN
out_files = *.out
$(out_files) : $(in_files)
    matlab -nosplash -nodesktop -r "a_matlab_function('$<','$@')"

A: I don't know anything about Snakemake, but in GNU Make you can transform in_files to give the out_files:
in_files = $(wildcard *.IN)
out_files = $(in_files:.IN=.out)

Then you make a dummy target that depends on all the outputs:
all: $(out_files)
.PHONY: all

And finally a rule to create one output from one input:
%.out: %.IN
    matlab -nosplash -nodesktop -r "a_matlab_function('$<','$@')"

A: I think you just want a bash for loop:
for f in *.IN; do
   out=${f%IN}OUT                # Work out name of output file
   echo IN:"$f"                  # Show input file to user
   echo OUT:"$out"               # Show output file to user
   matlab <options> "$f" "$out"  # Run Matlab
done

So, if I have these files:
ls *IN

aThird.IN
another one.IN
b.IN

I'll get this:
IN:aThird.IN
OUT:aThird.OUT
IN:another one.IN
OUT:another one.OUT
IN:b.IN
OUT:b.OUT

Or, as a one-liner:
for f in *.IN; do out=${f%IN}OUT; matlab ... "$f" ... "$out"; done

Notes:
Although your question suggests using make, there is no certain indication whether you always expect to run all jobs, or whether sometimes some jobs do not need running - presumably because the output files already exist and it is not necessary to run them. If you don't want all the jobs run every time, you will probably be better off with make.
Also, if Matlab can run parallel instances, the GNU Parallel syntax is nice for things like this:
parallel --dry-run matlab {} {.}.OUT ::: *IN

Output
matlab another\ one.IN another\ one.OUT
matlab aThird.IN aThird.OUT
matlab b.IN b.OUT

Here, the --dry-run shows you the commands that would be run, though it currently does not run anything.


text:
Q: Apache camel exec message body I have the following route:
            <route id="import">
                    <from uri="file:/var/inputfolder?delete=true"/>
                            <log message="Importing ${file:name} started."/>
                            <setProperty propertyName="keepbody">
                                    <simple>${body}</simple>
                            </setProperty>
                            <setHeader headerName="BrandId">
                                    <simple>${file:name}</simple>
                            </setHeader>
                            <setHeader headerName="CamelExecCommandArgs">
                                    <simple>${file:absolute.path} ${header.BrandId.toString.split("_")[0]} Zip -a erase</simple>
                            </setHeader>
                    <to uri="exec://./transfile.php?workingDir=/usr/bin/&args&useStderrOnEmptyStdout=true"/>
                            <log message="stdout/stderr of /usr/bin/transfile.php:\n ${body}"/>

                    <choice>
                            <when>
                                    <simple>${bodyAs(String)} contains 'Return OK'</simple>
                                    <log message="Importing ${file:name} finished."/>
                            </when>
                            <otherwise>
                                    <log message="Importing ${file:name} failed."/>
                                    <setBody>
                                          <simple>${exchangeProperty.keepbody}</simple>
                                    </setBody>
                                    <to uri="file:/var/rejected"/>
                            </otherwise>
                    </choice>

            </route>

The route checks the folder /var/inputfolder for files. If it finds any, it executes the transfile.php script, and uses the file name in its arguments. If the output of this execution does not contain the string 'Return OK', the stdout will be put in a file with the original filename into the folder /var/rejected.
But I would like to achive, that in the /var/rejected folder the file with its original content appears, not the with output of the execution. I know, that this is the normal behavior of the exec component
https://camel.apache.org/exec.html
but how can I change this to implement the previously mentioned?
Thanks in advance!

A: You need to store the message body as an exchange property, and then replace the body afterwards the exec for example
<setProperty propertyName="keepBody">
  <simple>${body}</simple>
</setProperty>

And then restore it afterwards
<setBody>
 <simple>${exchangeProperty.keepBody}</simple>
</setBody>

Notice depending on how old Apache Camel you use, then the name exchangeProperty may be an older name such as property. See more at: http://camel.apache.org/simple
We are thinking about adding a push/pop to the Camel DSL to make this easier in the future: https://issues.apache.org/jira/browse/CAMEL-8958


text:
Q: Variable me aparece nula en el metodo, pero deberia tener valor  using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Collections;

namespace BootstrapTemplate
{
    public class SQL_Connection
    {
        private string NamereportSeleccionado;
        private string IDreporteSeleccionado;

        public void getInfoReporteseleccionado(string nombre, string id)
        {
            this.NamereportSeleccionado = nombre;
            this.IDreporteSeleccionado = id;
        }

En el metodo getInfoReporteseleccionado llegan dos datos, se asigna a las variables NamereportSeleccionado e IDreporteSeleccionado, y al correrlo con breakpoints puedo ver que tienen los valores que corresponden
El problema es que mas adelante cuando tengo que usar una de las variables, el valor de esta llega como nula (en la linea de string query hasta el final)
 public DataTable SQL_Leer_TablaReporteSeleccionado()
        {
            DataTable TablaReporteSeleccionado = new DataTable();
            string query = "  select  P.NombreProducto, DP.DemandaSemanal, DP.DemandaMensual, DP.Rate1,DP.Rate2,DP.SalidaDiaria,DP.DiasRequeridos,DP.Turnos,DP.HCTurno  FROM DatoProducto DP, Producto P WHERE P.IDProducto=DP.IDProducto and IDReporte=" + IDreporteSeleccionado;
            string con = System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
            using (SqlConnection SQLCon = new SqlConnection(con))
            {
                SQLCon.Open();
                SqlCommand cmd = SQLCon.CreateCommand();
                cmd.CommandText = query;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(TablaReporteSeleccionado);
                SQLCon.Close();
            }
            return TablaReporteSeleccionado;
        }

Alguna idea de que pueda ser, ya he usado ese codigo en otro programa y si me funciona no se por que ahora no.
Gracias espero su ayuda.


text:
Q: Is there a relationship between Rotors and the Rodrigues' rotation formula I am trying to understand quaternion in general, and it seems like the path to making sense of how they actually work is to first understand rotors and other techniques related to rotations. By looking at the equations and just reading briefly about these topics, it seems like there are relationships between all these topics: rotors, the Rodrigues' rotation formula which involves a scalar and a vector product as well as quaternions. Before getting on to the topic of quaternions all I am trying to do now, is finding out if there is any sort of connection between rotors (or more precisely using rotors to rotate a vector) as the equation to rotate a vector using a rotor also involves scalar and vector product, and the Rodrigues' formula:
$\mathbf{v}_\mathrm{rot} = \mathbf{v} \cos\theta + (\mathbf{k} \times \mathbf{v})\sin\theta + \mathbf{k} (\mathbf{k} \cdot \mathbf{v}) (1 - \cos\theta)$
If so, could someone explain it please?

A: We could "derive" the Rodrigues formula by "vectorizing" the quaternion sandwitch product. First, let us recall the sadwitch product:
$v' = Q \ v \ Q^*$
Where $v$ is a pure quaternion (its real part equal to zero) and $Q$ is a unit quaternion and $Q^*$ is its conjugate:
$Q^{*} = q_0 - i q_1 - j q_2 - k q_3$
Aplying the Euler relation:
$v' = Q \ v \ Q^{-1} = (\cos \frac{\theta}{2} + \sin \frac{\theta}{2} \ b) \ v \ (\cos \frac{\theta}{2} - \sin \frac{\theta}{2} \ b)$
$v' = (Q \ v) \ Q^{-1} = (\cos \frac{\theta}{2} \ v + \sin \frac{\theta}{2} \ b \ v) \ (\cos \frac{\theta}{2} - \sin \frac{\theta}{2} \ b)$
$v' = \cos^2 \frac{\theta}{2} \ v - (\cos \frac{\theta}{2} \ \sin \frac{\theta}{2}) \ v \ b + (\sin \frac{\theta}{2} \ \cos \frac{\theta}{2}) \ b \ v - \sin^2 \frac{\theta}{2} \ b \ v \ b$
The product $v \ b$ that apperars in the above expressions is the product of two
 pure quaternions and it is defined in vector form as:
$v \ b = (i v_0 + j v_1 + k v_2) \ (i b_0 + j b_1 + k b_2) = -v \cdot b + v \times b$,
where $v \cdot b$ is the dot product and $v \times b$ is the cross product.
Notice that the algebraic sum $-v \ b + b \ v$ is not zero, since the cross product is non-commutative. As a consequence $-v \ b + b \ v = (v \cdot b - v \times b) + (-b \cdot v + b \times v) = 0 + 2 \ b \times v = 0 - 2 \ v \times b$.
Replacing that into our last equation we get:
$v' = \cos^2 \frac{\theta}{2} \ v + 2 \ (\cos \frac{\theta}{2} \ \sin \frac{\theta}{2}) \ b \times v - \sin^2 \frac{\theta}{2} \ b \ v \ b$
Interestingly the expression $b \ v \ b$ is nothing more than the reflection of $v$ in the plane with normal $b$. Where $b$ and $v$ are pure quaternions. Reflection can be expressed in vector form as:
$b \ v \ b = 2 \ (-v \cdot b) \ b + v$
where the vector $v$ is translated in direction of the negative normal $b$ twice the distance of $v$ projected in $b$. Finally the equation is:
$v' = \cos^2 \frac{\theta}{2} \ v + 2 \ (\cos \frac{\theta}{2} \ \sin \frac{\theta}{2}) \ b \times v - \sin^2 \frac{\theta}{2} \ (2 \ (-v \cdot b) \ b + v)$
$v' = \cos^2 \frac{\theta}{2} \ v - \sin^2 \frac{\theta}{2} \ v + 2 \ (\cos \frac{\theta}{2} \ \sin \frac{\theta}{2}) \ b \times v + 2 \ \sin^2 \frac{\theta}{2} \ (v \cdot b) \ b$
Applying the following trigonometric identities:
$\cos \theta = \cos^2 \frac{\theta}{2} - \sin^2 \frac{\theta}{2}$
$\sin \theta = 2 \cos \frac{\theta}{2} \ \sin \frac{\theta}{2}$
$1 - \cos \theta = 2 \ \sin^2 \frac{\theta}{2}$
We get the Rodrigues formula:
$v' = \cos \theta \ v + \sin \theta \ b \times v + (1 - \cos \theta) \ ( v \cdot b ) \ b $
It was discovered by Olinde Rodriguez three years before Hamilton discover quaternions.

A: IMHO the set of quaternions is more appropriately viewed as a scalar bivector pair.  The rotation equation is a similarity transform.  It's certainly reasonable to take a GA rotor view. The best way to think about it is going to depend on what's more familiar to you.


text:
Q: tangent/normal space to set of symmetric isospectral matrices Let $\Lambda = \{\lambda_1, \ldots, \lambda_n\}$ be a set of $n$ distinct real numbers. $M_n(\mathbb{R})$ denotes the set of all $n \times n$ real matrices, and for $B\in M_n(\mathbb{R})$, $B^T$ denotes the transpose of B, and $\sigma(B)$ is the (multi)set of the eigenvalues of $B$.
I'm trying to figure out the tangent space and the normal space to the set
$$S = \{ B \in M_n(\mathbb{R}) \, : \, B^T = B, \sigma(B) = \Lambda\},$$
at the point $A= \text{diag}(\lambda_1,\ldots,\lambda_n)$, the diagonal matrix with diagonal entries $\lambda_i$'s.
Note that $S$ is a manifold in a neighborhood of $A$.
This is my thought process:
Define a path in $S$ as follows:
$$A(t)= Q(t) \, A \, Q(t)^T,$$ for a family of orthogonal matrices $Q(t)$, such that $Q(0) = I$, the identity matrix. Then $A(0) = A$.
\begin{align*}\dot{A}(t) &= \dot{Q}(t) \, A \, Q(t)\\ &+\, {Q}(t) \, \dot{A} \, Q(t)\\ &+ \,  {Q}(t) \, A \, \dot{Q}(t) \end{align*}
But $\dot{A} = O$, hence
$$\dot A(0) = \dot Q(0) \, A + A \, \dot Q(0)^T.$$
So, if I know all the tangents/normals to orthogonal matrices at $0$, that is, at $I$, I can describe all the tangents/normals to $S$ at $A$. But it is not too hard to show that the set of all skew-symmetric matrices (i.e. $\{B : B^T = -B\}$) is the tangent space to the orthogonal matrices at $I$. Hence, the tangent space to $S$ at $A$ is $$ T_A(S) = \{ B \, A + A \, B^T : B^T = -B \}.$$
So here are my questions:
Question 0: Is my argument above correct?
Question 1: Why are these all of the tangent vectors? I think(?) $S$ is an $n(n-1)/2$ dimensional manifold, and $T_A(S)$ is $n(n-1)/2$ dimensional, is that really the reason for $T_A(S)$ begin the whole tangent space? Can you elaborate on it, please?
Question 2.1: What is the normal space to the set of orthogonal matrices, at $I$?
Question 2.2: How do you find the normal space to $S$ at $A$? Is it the same as the following?
$$\{B \in M_n(\mathbb{R}) : C\, B = O, \forall C \in T_A\}.$$
Edit: Direct calculations yield that $T_A(S)$ is the set of all symmetric matrices with zero diagonals, as long as $\lambda_i$'s are all distinct.

A: A full explanation from a higher perspective can be found in Li, Rodman and Tsing, Linear operators preserving certain equivalence relations originating in system theory, Linear Algebra and Its Applications, 161:165-225, 1992.


text:
Q: vuetify temporary navigation drawer prevent closing from child element Hi everyone i'm struggling with what i thought could be easy.
I have a component with a main card that display some datas. in this card i also have a button that toggled a temporary navigation drawer.
In this drawer i have some filter, based on v-switches v-autocomplete v-text-input and v-select.
My issue is that as soon as i interact with one of my filters it closes the temporary navigation drawer.
i tryed @change.prevent on my elements but it doesn't work
i also see that i could use a :staless props on the drawer but have no idea on how to use it on multiple fields
so how can i apply some props to all my element to prevent them to close the temporary navigation drawer but keeping updating each v-model value
Thanks


text:
Q: Calling an API with secret and key in c# So I have worked with a Swagger API before but since there is a codegenerator for all API calls i did not really have to worry about that stuff. Now i want to use the following api https://docs.skincay.com/#introduction
public static HttpClient ApiClient { get; set; }

    public static void InitializeClient()
    {
        if (ApiHelper.ApiClient == null)
            ApiHelper.ApiClient = new HttpClient();

        ApiHelper.ApiClient.BaseAddress = new Uri("https://api.skincay.com/v1/");
        ApiHelper.ApiClient.DefaultRequestHeaders.Accept.Clear();
        ApiHelper.ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        ApiHelper.ApiClient.DefaultRequestHeaders.Add("Authorization", "Basic clientid:secret");
    }

I followed this guide: https://www.youtube.com/watch?v=aWePkE2ReGw
I just want to work with it in a normal console application but that should not be my problem.
The problem is whether the header information i am giving them is right or not since i do not get any response from my calls. I find it really hard working with this documentation and i have not found anyone trying to use this api.
I hope someone here can help me with this.

A: You should base64 encode your authorization credentials:
var bytes = Encoding.UTF8.GetBytes($"{clientId}:{secret});
var base64 = Convert.ToBase64String(bytes);
ApiClient.DefaultRequestHeaders.Add("Authorization", $"Basic {base64}");

Note: don't forget to replace values from the tutorial with your real uri, clientId and secret
ApiClient.BaseAddress = new Uri("https://docs.skincay.com/#introduction");
string clientId = "bob";
string secret = "derparole";