text:
Q: Animated 3D Scatter-Plot in Matlab I have a set of data with a total of 4 independent variables, and I figure the only way to represent 4 independent variables and one dependent variables is to animate a 3D scatter-plot.
Let's say I have the following set of data:
W X Y Z Val
0 0 0 0 5.5
0 0 0 1 2.3
0 0 1 0 1.6
0 0 1 1 8.8
0 1 0 0 2.6
0 1 0 1 4.8
0 1 1 0 0.1
0 1 1 1 1.1
1 0 0 0 1.0
1 0 0 1 0.0
1 0 1 0 0.4
1 0 1 1 4.4
1 1 0 0 4.4
1 1 0 1 7.9
1 1 1 0 9.1
1 1 1 1 2.3

And the values were read in and converted to the following arrays:
W = {0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1}
x = {0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1}
X = {0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1}
Z = {0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1}
Val = {5.5,2.3,1.6,8.8,2.6,4.8,0.1,1.1,1.0,0.0,0.4,4.4,4.4,7.9,9.1,2.3}

I'm wondering how to create a 3D scatter-plot (scatter3) with X, Y, and Z as the independent variables, Val as represented by the colors of the dots, and to animate with respect with the variable W as time?
Basically, when the different values of Val for when W=0 and W=1 are plotted at different times with respect to X, Y, and Z.

A: Based on your edit, I have slightly refined my suggestions:
mat=cell2mat([W;x;X;Z;Val])'; %Convert cells into a matrix

colors=prism(numel(mat(:,1)));
scatter3(mat(1,2),mat(1,3),mat(1,4),100,colors(1,:),'filled');
axis tight;

for jj=1:8:numel(mat(:,1))
    scatter3(mat(jj:jj+7,2),mat(jj:jj+7,3),...
        mat(jj:jj+7,4),100,colors(jj:jj+7,:),'filled');
    drawnow
    pause(1)
end

In the above example the colors are sequentially assigned, but if you want the colors to be the same where VAL is the same, you could do something like the following:
mat=cell2mat([W;x;X;Z;Val])';
val_new=mat(:,5)/max(mat(:,5)); %0<VAL<1
scatter3(mat(1,2),mat(1,3),mat(1,4),100,[0 val_new(1) 0],'filled');
axis tight;

for jj=1:8:numel(mat(:,1))
    scatter3(mat(jj:jj+7,2),mat(jj:jj+7,3),...
        mat(jj:jj+7,4),100,[zeros(8,1) val_new(jj:jj+7,:) zeros(8,1)],'filled');
    drawnow
    pause(1)
end

Of course, both these examples assume that you will consistently have 8 entries at each time. And in the second instance there will be occasions where the differences in the colors are only very slight. If you want to actually save a video or a animated gif, just take a look at getframe and imwrite.


text:
Q: django allauth CSRF Verification fail error Let me explain what I am doing?
I have two tabs open on my browser both showing my login page (simple username and password form).
Using tab 1 : I login giving correct credentials. works correctly.
Using tab 2: (without refreshing) I again try to login using same or different credentials
this throws a 403 forbidden error
Reason given for failure: CSRF token missing or incorrect.
I know, I am doing something silly, that i am trying to log in when I am already logged it.
I want to prevent the dirty 403 error raised and make the process smooth as in the second login request should be just ignored when someone is already logged in or something else that does not break the flow. how should i go about doing this?
I am using Django==1.6.2 and django-allauth==0.14.1

A: First a quick bit of background, as you might find it interesting: this is partly related to the CSRF token and partly related to the session.
The way CSRF works in Django is that the same token is mirrored in both the template and the session - that's how Django checks that incoming form data matches the user's session and isn't an injection from someone evil.
When you go from being logged out to logged in, you're trading an unauthenticated session for an authenticated session, which means you get a new session -- complete with a new CSRF token in the session. That session is shared across all your tabs, even ones open already and even in a browser like Chrome which has separate processes for each tab.
So, logging in on tab A gives Tab B a session cookie which no longer matches the CSRF token embedded in the page, hence Tab B throws as CSRF exception. If you refreshed Tab B after logging in on Tab A (and assuming that a logged-in user can still see a login screen), it should let you log in in again, because the refreshed page's CSRF token will once again match the one in the session.
In terms of handling this gracefully, I suggest you add a custom 403 handler view which either shows a prettier 403 page of your own design, or -- if you think it's acceptable -- redirects the user to somewhere else (but i'd check that this redirect only happens if it's in response to a bogus login as described in your question)
The other thing to say is: the use-case you're talking about (two tabs open) is pretty slim - I'd just go with a custom 403 page to make it prettier, rather than redirect.

If you're interested, look at the source:
if SESSION_KEY in request.session:
    if request.session[SESSION_KEY] != user.pk:
        # To avoid reusing another user's session, create a new, empty
        # session if the existing session corresponds to a different
        # authenticated user.
        request.session.flush()
else:
    request.session.cycle_key()

When you start with an unauthenticated user, there's no way that user.pk would be the same as your authenticated user's PK, so you get a new session.
(If you log in again as the same user, you get cycle_key() called, which may actually preserve the CSRF token - I haven't checked)

A: you should do shomething like this:
def userlogin(request):
    if request.method=='POST':
        user = request.user
        if user.is_authentificated:
            return HttpResponceRedirect('some_url')
        else:
            #your login procedure

redpajama_set_name: RedPajamaStackExchange


text:
Q: R: Is there a good replacement for plyr::rbind.fill in dplyr? for tidyverse users, dplyr is the new way to work with data.
For users trying to avoid older package plyr, what is the equivalent function to rbind.fill in dplyr?

A: Yes. dplyr::bind_rows
Credit goes to commenter.

A: An alternative:
rbindf <- function(...) {

  l <- list(...)
  if(length(l) == 1) l <- l[[1]]
  nn <- length(l)

  x <- l[[1]]
  if(length(l)>1){
      for(i in 2:nn) {
        y <- l[[i]]
        if(nrow(x) > 0 & nrow(y) > 0) {
          if(!all(yinx <- names(y) %in% names(x))) {
            x[, names(y)[!yinx]] <- NA
          }
          if(!all(xiny <- names(x) %in% names(y))) {
             y[, names(x)[!xiny]] <- NA
          }
        }
        x <- rbind(x, y)
      }
  }
  return(x)
}

From https://github.com/sashahafner/biogas (originally from https://github.com/jonkatz2/monitoR).

A: Same Thing with R Base:
df2 <- data.frame(a = c(1:5), b = c(6:10))
df3 <- data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
df2[setdiff(names(df3), names(df2))] <- NA
df3[setdiff(names(df2), names(df3))] <- NA

rbind(df2, df3)


text:
Q: Override property in Swift 3 I want to override properties in the following class. Say I have a class A that has a boolean property r. For the superclass A, I want r to be set and get normally. For the subclass B, I want r to always be false. I'm not sure why this is harder than it should be...
class A {
    init(r: Bool) {
        self.r = r
    }

    var r: Bool {
        willSet(n) {
            r = n
        }
        get {
            return r
        }
    }
}

class B: A {
    override var r: Bool {
        willSet(n) {
            r = n
        }
        get {
            return false
        }
    }
}

let a = A(r: true)
a.r = false
print(a.r)  // prints 'false', which is good

let b = B(r: true)
print(b.r)  // prints 'true'
b.r = false // ERROR: I can't get pass this point 'Execution was interrupted on playground
print(b.r)

A: I agree with @Hamish: stored property in base class, with computed property override. Except, a read-only property can't override a mutable property. But, you can make the overridden setter do nothing, and the overridden getter return what you want.
class A {
    init(r: Bool) {
        self.r = r
    }

    var r: Bool
}

class B: A {
    override var r: Bool {
        set {}
        get {
            return false
        }
    }
}

let a = A(r: true)
print(a.r) // "true"
a.r = false
print(a.r) // "false"

let b = B(r: true)
print(b.r) // "false"
b.r = true
print(b.r) // "false"


text:
Q: How to compile nested css rules using javascript I need a little help with making my own css-compiler in JavaScript.
How can I make a compiler that compiles this nested rules example:
html{
    background: #2E2E2E;
    body{
        height: 200px;
        width: 100%;
        background: #fff;
        a{
            color: rgb(0, 0, 255);
            &:hover{
                color: rgb(200, 0, 255);
            }
        }
    }
}

Into this:
html{
    background: #2E2E2E;
}
html body{
    height: 200px;
    width: 100%;
    background: #fff;
}
html body a{
    color: rgb(0, 0, 255);
}
html body a:hover{
    color: rgb(200, 0, 255);
}

Thanks for any help!
If you vote down, please tell me why.

A: I would start by mentioning that building your own css-compiler is no joke. It is a serious thing. You should use something like Sass, Less, or Stylus. If they are missing a feature you need, you should build a plugin for them, rather than try to implement your own engine.
Having said that, an answer to your question may be reworkcss. It is a project that people will use to make their own CSS-compiler.


text:
Q: Second event handler cannot reach the global variable in the first event handler in jQuery? As you see in the following code snippet, selectedImageName variable is defined as global variable in first event handler. This global variable can be reached by the function afterRemoving() at the bottom of the code snippet, but this global variable cannot be reached by the second event handler and because of this, it outputs an error: Uncaught ReferenceError: selectedImageName is not defined Could you explain what is going on? How can I handle this problem?
JS:
$(document).ready(function() {

    // There are some codes...

    $(document).ajaxSuccess( function() {

        $("#imgOutput .removeInlineImage").on("click", function(){

            selectedImageName = $(this).prev().val();
--------------------^ (Everything is OK.)

            optionsRemove = {
                url: 'bilesenler/ajaxRemoveImage.php?imgName=' + selectedImageName,
                beforeSubmit: beforeRemoving,  // pre-submit callback
                success: afterRemoving,  // post-submit callback
                resetForm: false        // reset the form after successful submit
            };

            imgDelete = true;
            $("#addText").submit();
        });

        $("#imgOutput #imgName").on("keypress", function(){

            optionsUpdate = {
                url: 'jx.php?oldImgName=' + selectedImageName + '&newImgName=' + $(this).val(),
----------------------------------------------------^ (Trouble: Uncaught ReferenceError: selectedImageName is not defined)

                beforeSubmit: beforeUpdating,  // pre-submit callback
                success: afterUpdating,  // post-submit callback
                resetForm: false        // reset the form after successful submit
            };

            imgUpdate = true;
            $("#addText").submit();
        });
    });
});

// There are some codes...

function afterRemoving(responseText){
    var temp = selectedImageName.split(".");
-----------------------^ (Everything is OK)

    selectedImageNameWithoutExtension = temp[0];

    $('#imgOutput #' + selectedImageNameWithoutExtension).hide();

    imgDelete = false;

}

A: Unless click event is triggered, selectedImageName is null. After clicking process, selectImageName is initialized.


text:
Q: Print multibyte characters to stdscr/program window NCURSES Currently I try to simulate matrix rain using C and NCURSES. I need to print multibyte characters to the program window using NCURSES.
I have function that return random chars 12784-12799 range from Unicode. These are Japanese characters converted from hex to decimal.
Then I use this function to print the characters with different location:
mvwaddch(mainwin, j, i*2, col-rows[i]);

col-rows[i] contains the randombly created number.
This approach does not work for now, program print ^@ ^A ^e ^B etc, instead of Japanese characters.
I believe I use a wrong function and mvwaddch does not accept multibyte characters.
If so, please let me know which NCURSES function could be used for this purpose.


text:
Q: Short story where 2 zombies are in love Looking for author or book that had a short story about 2 zombies in love. There is one part that I really remember. The 2 zombies bit each other as a show of affection and as the female zombie bites the male on the neck a bunch of roaches comes gushing out of the wound. There were a lot of good stories in this book.
Any ideas?

A: The story is Eat Me by Robert R. McCammon, so I'd guess the anthology is Zombies Encounters with the Hungry Dead edited by John Skipp.

The scene you remember is:

Brenda's teeth closed on the back of Jim's neck, crunching through the dry flesh. Her eyes closed in rapture as Jim ate the rest of the fingers on her left hand-and suddenly there was a new sensation, a scurrying around her lips. The love wound on Jim's neck was erupting small yellow roaches, like gold coins spilling from a bag, and Jim's itching subsided. He cried out, his face burrowing into Brenda's abdominal cavity.


text:
Q: Mathematical Statistics Videos A question previously sought recommendations for textbooks on mathematical statistics
Does anyone know of any good online video lectures on mathematical statistics?
The closest that I've found are:

*

*Machine Learning

*Econometrics
UPDATE: A number of the suggestions mentioned below are good statistics-101 type videos.
However, I'm specifically wondering whether there are any videos that provide a rigorous mathematical presentation of statistics.
i.e., videos that might accompany a course that use a textbook mentioned in this discussion on mathoverflow

A: See Videos on data analysis using R on Jeromy Anglim's blog.  There are many links at that page and he updates it.  He has another post with many links to videos on probability and statistics as well as linear algebra and calculus.

A: The folks at SLAC put videos of their lecture series online.  Given that their audience is mostly physicists, they tend to be fairly mathematical.

*

*SLUO Lecture Series (see the "Stat" links)

A: There is one called Math and probability for life sciences, but I haven't followed it so I can't tell you if its good or not.

A: This site from Ecole normal Supérieure de Paris contains a lot of very interesting video
http://www.diffusion.ens.fr/index.php?res=themes&idtheme=30
I greatly encourage you to visit this site !!
Among other you will find there all video presentation from the conference "Mathematical Foundations of Learning Theory" that held in 2006.

A: I do not know at what level you want the videos to be but I have heard good things about Khan's Academy: http://www.khanacademy.org/#Statistics

A: Many of the Berkeley introductory statistics courses are available online (and on iTunes).  Here's an example: Stats 2.  You can find more here.

A: There is a new resources forming these days for talks about R:
https://www.r-bloggers.com/RUG/
Compiled by the organizers of "R Users Groups" around the world (right now, mainly around the States).
It is a new project (just a few weeks old), but already got good content on it, and good people wanting to take part in it.

(source: r-bloggers.com)

A: There are a bunch of helpful video tutorials on basic statistics & data mining with R and Weka at SentimentMining.net.

*

*http://sentimentmining.net/StatisticsVideos/

A: There is a series of Google Tech Talk videos called Stats 202 - Statistical Aspects of Data Mining

A: UCCS mathematics video archive has
archived videos from a range of courses in mathematics. Several subjects called Mathematical Statistics I and  Mathematical Statistics II are available. The main site requires a free registration to access.
Slightly more accessible are the videos for a subset of the courses on the UCCS MathOnline YouTube page. Two instances of this are as follows.
The lecture style often involves Dr. Morrow working through problems on the whiteboard.
 Linear Models

Taught by Dr. Greg Morrow, Math 483 from UCCS. Methods and results of
  linear algebra are developed to formulate and study a fundamental and
  widely applied area of statistics. Topics include generalized
  inverses, multivariate normal distribution and the general linear
  model. Applications focus on model building, design models, and
  computing methods. The Statistical Analysis System (software) is
  introduced as a tool for doing computations.

Course info: Seems to
 use Introduction to Linear Regression by Montgomery, Peck, and Vining.
Mathematical Statistics 1

Greg Morrow's Math 481 course from Math Online at the University of
  Colorado in Colorado Springs
  Course Description:  Exponential, Beta, Gamma, Student, Fisher and Chi-square
  distributions are covered in this course, along with joint and conditional
  distributions, moment generating techniques, transformations of random
  variables and vectors.

*

*Course info

*Syllabus from one year

*Mathematical Statistics and Data Analysis, 3rd   ed., by John A. Rice.

A: I found the 'Probability Primer' Lectures very useful and informative :

*

*http://www.youtube.com/playlist?list=PL17567A1A3F5DB5E4&feature=plcp

A series of videos giving an introduction
  to some of the basic definitions, notation, and concepts one
  would encounter in a 1st year graduate probability course.

A: MIT Open Courseware Discrete Stochastic Processes

Discrete stochastic processes are essentially probabilistic systems
  that evolve in time via random changes occurring at discrete fixed or
  random intervals. This course aims to help students acquire both the
  mathematical principles and the intuition necessary to create,
  analyze, and understand insightful models for a broad range of these
  processes. The range of areas for which discrete stochastic-process
  models are useful is constantly expanding, and includes many
  applications in engineering, physics, biology, operations research and
  finance.

The course includes videos, practice questions, slides, and an extensive set of notes.

A: Check out the following links. I'm not sure what exactly are you looking for.
Monte Carlo Simulation for Statistical Inference
Kernel methods and Support Vector Machines
Introduction to Support Vector Machines
Monte Carlo Simulations
Free Science and Video Lectures Online!
Video lectures on Machine Learning

A: I just came across this website, CensusAtSchool -- Informal inference. Maybe worth looking at the videos and handouts...

A: An introductory set of statistics lectures with a voice over a slide presentation.
http://www.online.math.uh.edu/Math2311/index.htm
The lecture series is elementary, but I like how the lecturer communicates clearly and shows how to speak the formulas encountered in statistics.

A: Years ago the ASA video taped workshop /short courses on special topics such as time series and survival analysis and categorical data analysis.  They were available for chapters to rent.  You might check to see what they have.  Short courses at the jSM were occasionally video taped.  I don't know if general math stat courses are available.

A: Bookmark http://www.edxonline.org, it's bound to have all the math videos you could wish for. I believe they are hoping to launch this fall.

A: Opinionated Lessons in Statistics
http://wiki.opinionatedlessons.org/coursewiki/index.php/OpinionatedLessons.org/
Around 50 videos on statistics by Professor William H. Press of the University of Texas at Austin. Each video is around 10 to 30 minutes long.
A number of more advanced topics are coverd such as mixture models, EM methods, MCMC, PCA, and more.

A: Biostatistical bootcamp is a Coursera course on mathematical statistics. The videos are also available on Brian Caffo's YouTube Channel.


text:
Q: Special divisors on hyperelliptic curves I was reading a proof that used the following result
Let $C$ be a hyperelliptic of genus $\ge 3$ and $\tau \colon C \to C$ the hyperelliptic involution.  If $D$ is an effective divisor of degree $g-1$ such that $h^0(D)>1$ then $D = x + \tau(x) + D'$ where $D'$ is an effective divisor.
My question is, how is this result proved?  It seems equivalent to showing that $|D|$ contains the unique $g^1_2$ and this made me think of Clifford's theorem but this didn't lead to much.  For $g = 3$ the result holds because then $|D| = g^1_2$.  But already for $g = 4$ I'm stuck.  I tried playing around with the Riemann-Roch theorem but didn't get far.

A: It is easy to see that $D + \tau^*D$ is a canonical divisor. Suppose that $p$ is a ramification point of the $g^{1}_{2}$; since there are $2g-2$ such points, we may assume that $p$ is not a base point of $|D|$. Then we have effective divisors $D'$ and $D''$ in $|D|$, such that $p$ lies on $D'$ but not on $D''$. So $D' + \tau^*D''$ is an effective canonical divisor containing $p$; by Riemann-Roch, it has to contain $2p$. Since $p$ does not lie on $\tau^*D''$, the divisor $D'$ has to contain $2p$, and we are done.

A: Suppose that $D=x_1+x_2+\cdots+x_{g-1}$. We may assume that $\tau(x_i)\neq x_j$
for all $i\neq j$. Now, assume that $D'=y_1+\cdots+y_{g-1}$ is an element of
$|K-D|$. Then $x_1+x_2+\cdots+x_{g-1}+y_1+\cdots+y_{g-1}$ is an element of $|K|$
but we know that any such element is of the form
$z_1+\tau(z_1)+\cdots+z_{g-1}+\tau(z_{g-1})$. After possibly renumbering the $z_i$ (as
well as possibly replacing $z_i$ by $\tau(z_i)$) we may assume $x_1=z_1$ and
then $x_2=z_2$ and so on. This gives $D'=\tau(D)$ which implies
$h^0(K-D)\leq 1$. However, R-R and gives $h^0(D)=h^0(K-D)\leq1$ which
contradicts assumptions.


text:
Q: Is my ssd realy broken, or is this still fixable? my first sdd, an OCZ Vertex 3, does not work anymore. It is like 'not found' in the bios while booting. However, I tried a bit more. I attached it to my PC using a SATA-to-USB3 cable/adapter.
dmesg output
Here's what dmesg says:
# USB device detected
[995674.616272] usb 2-1.4: new high-speed USB device number 5 using ehci-pci
[995674.739558] usb 2-1.4: New USB device found, idVendor=05e3, idProduct=0731
[995674.739561] usb 2-1.4: New USB device strings: Mfr=0, Product=1, SerialNumber=2
[995674.739564] usb 2-1.4: Product: USB Storage
[995674.739566] usb 2-1.4: SerialNumber: 0000000000000033

# this is where the device gets detected
[995674.740213] usb-storage 2-1.4:1.0: USB Mass Storage device detected
[995674.740451] scsi host9: usb-storage 2-1.4:1.0
[995676.205066] scsi 9:0:0:0: Direct-Access     Generic  USB3/SATA Bridge 9100 PQ: 0 ANSI: 5
[995676.205568] sd 9:0:0:0: Attached scsi generic sg4 type 0
[995676.208525] sd 9:0:0:0: [sdd] 0 512-byte logical blocks: (0 B/0 B)
[995676.208529] sd 9:0:0:0: [sdd] 0-byte physical blocks
[995676.210177] sd 9:0:0:0: [sdd] Test WP failed, assume Write Enabled
[995676.211910] sd 9:0:0:0: [sdd] Asking for cache data failed
[995676.211916] sd 9:0:0:0: [sdd] Assuming drive cache: write through
[995676.219509] sd 9:0:0:0: [sdd] Attached SCSI disk

See the size? It should be more like 60 GB (not GiB), not just 0 bytes.
First try: Gparted
Starting gparted, it said "device not found" using /dev/sdd as an argument.
Then I started gparted without arguments => device not listed.
2nd try: dd.
Didn't go that well either.
$ sudo dd if=/dev/zero of=/dev/sdd bs=1M
dd: error writing '/dev/sdd': No space left on device
1+0 records in
0+0 records out
0 bytes copied, 0,00073185 s, 0,0 kB/s

3rd try: testdisk
Not detected.
4th try: smart
So I thought: the disk does get detected, but 0 bytes means all sectors are broken? Perhaps smart will tell me.
Well, no.
$ sudo smartctl -a /dev/sdd
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-20-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

Read Device Identity failed: scsi error no medium present

A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.

$ sudo smartctl -a -T permissive /dev/sdd
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-20-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

Read Device Identity failed: scsi error no medium present

=== START OF INFORMATION SECTION ===
Device Model:     [No Information Found]
Serial Number:    [No Information Found]
Firmware Version: [No Information Found]
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   [No Information Found]
Local Time is:    Fri May 25 20:53:53 2018 CEST
SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.
SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.
A mandatory SMART command failed: exiting. To continue, add one or more '-T permissive' options.

$ sudo smartctl -a -T verypermissive /dev/sdd
smartctl 6.6 2016-05-31 r4324 [x86_64-linux-4.15.0-20-generic] (local build)
Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org

Read Device Identity failed: scsi error no medium present

=== START OF INFORMATION SECTION ===
Device Model:     [No Information Found]
Serial Number:    [No Information Found]
Firmware Version: [No Information Found]
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   [No Information Found]
Local Time is:    Fri May 25 20:54:02 2018 CEST
SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 82-83 don't show if SMART supported.
SMART support is: Ambiguous - ATA IDENTIFY DEVICE words 85-87 don't show if SMART is enabled.
                  Checking to be sure by trying SMART RETURN STATUS command.
SMART support is: Unknown - Try option -s with argument 'on' to enable it.
Read SMART Data failed: scsi error no medium present

=== START OF READ SMART DATA SECTION ===
SMART Status command failed: scsi error no medium present
SMART overall-health self-assessment test result: UNKNOWN!
SMART Status, Attributes and Thresholds cannot be read.

Read SMART Error Log failed: scsi error no medium present

Read SMART Self-test Log failed: scsi error no medium present

Selective Self-tests/Logging not supported

So no luck either…
I'm out of options?
Put it in the bin or is this fixeable?
update
I made sure it is not fixable anymore. I guess there was no way of fixing it anymore, so I took this option.

A: Your SSD is really broken. Even if you can somehow get it working again it will most likely die again is short order.
When you plug the device in via USB it's recognising the existence of a mass storage device - but it sees it as having 0 bytes of storage capacity.
What you are seeing is a textbook SSD failure.


text:
Q: Spark cluster Master IP address not binding to floating IP I'm trying to configure a Spark cluster using OpenStack. Currently I have two servers named

*

*spark-master (IP: 192.x.x.1, floating IP: 87.x.x.1)

*spark-slave-1 (IP: 192.x.x.2, floating IP: 87.x.x.2)

I am running into problems when trying to use these floating IPs vs the standard public IPs.
On the spark-master machine, the hostname is spark-master and /etc/hosts looks like
127.0.0.1 localhost
127.0.1.1 spark-master

The only change made to spark-env.sh is export SPARK_MASTER_IP='192.x.x.1'. If I run ./sbin/start-master.sh I can view the web UI.
The thing is I view the web UI using the floating IP 87.x.x.1, and there it lists the Master URL: spark://192.x.x.1:7077.
From the slave I can run ./sbin/start-slave.sh spark://192.x.x.1:7077 and it connects successfully.
If I try to use the floating IP by changing spark-env.sh on the master to export SPARK_MASTER_IP='87.x.x.1' then I get the following error log
Spark Command: /usr/lib/jvm/java-7-openjdk-amd64/bin/java -cp /usr/local/spark-1.6.1-bin-hadoop2.6/conf/:/usr/local/spark-1.6.1-bin-hadoop2.6/lib/spark-assembly-1.6.1-hadoop2.6.0.jar:/usr/local/spark-1.6.1-bin-hadoop2.6/lib/datanucleus-core-3.2.10.jar:/usr/local/spark-1.6.1-bin-hadoop2.6/lib/datanucleus-api-jdo-3.2.6.jar:/usr/local/spark-1.6.1-bin-hadoop2.6/lib/datanucleus-rdbms-3.2.9.jar -Xms1g -Xmx1g -XX:MaxPermSize=256m org.apache.spark.deploy.master.Master --ip 87.x.x.1 --port 7077 --webui-port 8080
========================================
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
16/05/12 15:05:33 INFO Master: Registered signal handlers for [TERM, HUP, INT]
16/05/12 15:05:33 WARN Utils: Your hostname, spark-master resolves to a loopback address: 127.0.1.1; using 192.x.x.1 instead (on interface eth0)
16/05/12 15:05:33 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
16/05/12 15:05:33 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
16/05/12 15:05:33 INFO SecurityManager: Changing view acls to: ubuntu
16/05/12 15:05:33 INFO SecurityManager: Changing modify acls to: ubuntu
16/05/12 15:05:33 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(ubuntu); users with modify permissions: Set(ubuntu)
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7077. Attempting port 7078.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7078. Attempting port 7079.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7079. Attempting port 7080.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7080. Attempting port 7081.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7081. Attempting port 7082.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7082. Attempting port 7083.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7083. Attempting port 7084.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7084. Attempting port 7085.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7085. Attempting port 7086.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7086. Attempting port 7087.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7087. Attempting port 7088.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7088. Attempting port 7089.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7089. Attempting port 7090.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7090. Attempting port 7091.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7091. Attempting port 7092.
16/05/12 15:05:33 WARN Utils: Service 'sparkMaster' could not bind on port 7092. Attempting port 7093.
Exception in thread "main" java.net.BindException: Cannot assign requested address: Service 'sparkMaster' failed after 16 retries!
  at sun.nio.ch.Net.bind0(Native Method)
  at sun.nio.ch.Net.bind(Net.java:463)
  at sun.nio.ch.Net.bind(Net.java:455)
  at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
  at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
  at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:125)
  at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:485)
  at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1089)
  at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:430)
  at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:415)
  at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:903)
  at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:198)
  at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:348)
  at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:357)
  at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:357)
  at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
  at java.lang.Thread.run(Thread.java:745)

Obviously the takeaway here for me is the line

Your hostname, spark-master resolves to a loopback address: 127.0.1.1;
  using 192.x.x.1 instead (on interface eth0) 16/05/12 15:05:33 WARN
  Utils: Set SPARK_LOCAL_IP if you need to bind to another address

but no matter what approach I then try and take I just run into more errors.
If I set both export SPARK_MASTER_IP='87.x.x.1' and export SPARK_LOCAL_IP='87.x.x.1' and try ./sbin/start-master.sh I get the following error log
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7077. Attempting port 7078.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7078. Attempting port 7079.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7079. Attempting port 7080.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7080. Attempting port 7081.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7081. Attempting port 7082.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7082. Attempting port 7083.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7083. Attempting port 7084.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7084. Attempting port 7085.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7085. Attempting port 7086.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7086. Attempting port 7087.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7087. Attempting port 7088.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7088. Attempting port 7089.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7089. Attempting port 7090.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7090. Attempting port 7091.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7091. Attempting port 7092.
16/05/17 11:00:55 WARN Utils: Service 'sparkMaster' could not bind on port 7092. Attempting port 7093.
Exception in thread "main" java.net.BindException: Cannot assign requested address: Service 'sparkMaster' failed after 16 retries!

This, despite the fact my security group seems correct
ALLOW IPv4 443/tcp from 0.0.0.0/0
ALLOW IPv4 80/tcp from 0.0.0.0/0
ALLOW IPv4 8081/tcp from 0.0.0.0/0
ALLOW IPv4 8080/tcp from 0.0.0.0/0
ALLOW IPv4 18080/tcp from 0.0.0.0/0
ALLOW IPv4 7077/tcp from 0.0.0.0/0
ALLOW IPv4 4040/tcp from 0.0.0.0/0
ALLOW IPv4 to 0.0.0.0/0
ALLOW IPv6 to ::/0
ALLOW IPv4 22/tcp from 0.0.0.0/0

A: I've set a spark cluster (standalone cluster) on Openstack myself and in my /etc/hosts file on the master, I have:
127.0.0.1 localhost
192.168.1.2 spark-master instead of 127.0.0.1
Now, since I have a virtual private network for my master and my slaves, I only work with the private IPs. The only time I use the floating IP is on my host computer when I launch spark-submit --master spark://spark-master (spark-master here resolves to the floating IP). I don't think you need to try to bind the floating IP. I hope that helps!
Bruno

A: As appears in logs,

Your hostname, spark-master resolves to a loopback address: 127.0.1.1; using 192.x.x.1 instead (on interface eth0)

Spark automatically try to get the IP of the host, and it uses the other IP 192.x.x.1 rather than the floating IP 87.x.x.1
To resolve this problem you should set SPARK_LOCAL_IP=87.x.x.1 (prefereably in spark-env.sh) and start your master again


text:
Q: How to forbid a specific named function with ESlint The Situation
In our current project we've had some recurring problems with people using 'asMutable' from seamless-immutable where it isn't actually necessary. This has resulted in 'search project for string "asMutable"' becoming part of every pull request. To speed this up we would like to add a rule warning that to our eslint. But I haven't figured out how.
The Question
What seems like the best solution to me right now, though I'm open to suggestions, is a rule that allows me to specify a function name to forbid. Does ESlint, or a plugin therefore, have that sort of functionality?
Additional Notes
I've looked a little into writing our own, but I was intimidated by AST and the startup difficulty to writing my first rule. I may take the plunge if I can't find a better answer, yes we're getting this enough in PRs to warrant it. This seems like something someone much smarter than me has already solved though, so I'd rather follow in their footsteps then build my own.

A: On top of @Eric Simonton's answer, since ESLint 3.5.0 we have the purpose-built no-restricted-properties:
"no-restricted-properties": [ "error", {
    "object": "Immutable",
    "property": "asMutable",
    "message": "optional explanation to the recurring problems we've had"
}]

If anyone comes here looking for ways to block functions that aren't class methods, you can similarly use no-restricted-globals

A: You can do some very fancy things when you combine ESLint's no-restricted-syntax rule with selectors. In your case you should be able to achieve the linting you want without writing your own plugin. The rule would look something like:
{
  rules: {
    'no-restricted-syntax': [
      'error',
      {
        message: "Please don't use asMutable. We don't like it!",
        selector:
          'MemberExpression > Identifier[name="asMutable"]'
      }
    ]
  }
}

Study the documentation page for selectors; it is very flexible!

A: I had the same problem not so long ago so I can help you with writing your own.
So, first, let's explain some basic structures:

*

*ESLint has plugins, and each plugin has rules.

*ESLint uses AST which is a syntax tree to find specific parts in the code. This helps ESLint find  what each rule is looking for.

So, let's start by creating a plugin with a rule in it:

1. Use The ESLint Generator for Yeoman
This makes things a lot easier.
Check it out here.
After you install yeoman and the yeoman eslint generator:

*

*go into the folder you want to create your project in

*run yo eslint:plugin to create a new ESLint plugin

*after creating the plugin, run yo eslint:rule in the same folder

I used suni as the plugin name, and check-as-mutable as the rule name.
Now we have all the initial files we need to write the rule.

2. Know what you need to look for using AST Explorer
AST Explorer Can help us find what type of thing we're looking for. This is important so we can tell ESLint what in the code we want our function to run on.
When you paste code into AST Explorer, it shows you what ESLint is seeing.
We want to target all MemberExpressions:

something.asMutable();

Inside that, we want the Identifier node to check the function name

3. Write the plugin itself
Open lib/rules/check-as-mutable.js and check it out. All the data you provided for Yeoman was used to fill some fields here.
Inside the rule, you have a create attribute. Here, we write our code. This function should return an object, with what we want our rules to run on as attributes. So, in this case, it will look like so:
create: function(context) {

    return {
      MemberExpression: function(node)...

    };
}

While writing the rule, you should check which fields you need using the AST Explorer.
here is the implementation:
create: function(context) {
  var UNWANTED_FUNCTION_NAME = 'asMutable';
  return {
    MemberExpression: function reportUnwantedName(node) {
      var functionName = node.property.name;

      if (functionName === UNWANTED_FUNCTION_NAME) {
        context.report({
          node: node,
          message: [
            'Please don\'t use ',
            UNWANTED_FUNCTION_NAME,
            '. We don\'t like it!'].join('')
        });
      }
    }
  };
}

After that, you need to install the plugin in your project.
To do that, upload it to GitHub, and install it using npm:
npm install --save-dev <user_name>/<repository_name>

And include the rule in your .eslintrc file as well:
{
    'plugins': ['suni'],
    'rules': {
      'suni/check-as-mutable': 1
    }
}

Notice that I gave it the value 1. This makes this rule show as a Warning and not as an Error

Notice that the warning highlights the Immutable itself, since that is the node we pass to context.report. You can tweak that to highlight the id node instead.
Here's the plugin I created for this answer
Good luck!


text:
Q: Can I create a custom "routerLink" in Angular? In my Angular application I have 2 different types or URLs. Some that contain an ELEMENT_ID, some that don't have it.
Instead of having to add the ELEMENT_ID on every "routerLink" (I have a lot of them..), I would like to create a custom "routerLink" directive, such as "customRouterLink" that always puts the ELEMENT_ID in front of the parameters given. So for example:

*

*[customRouterLink]="/questions/ask" will direct to "https://stackoverflow.com/ELEMENT_ID/questions/ask"

*[routerLink]="/questions/ask" will direct to "https://stackoverflow.com/questions/ask".
Is there a way to achieve that?
Thanks!


text:
Q: Failed to copy artifact or file with maven packaging a web application I have a problem packaging a web application based on vaadin. I have two projects in my workspace called project A and project B. Project A is referencing B and the dependencies are resolven within the workspace and degub mode correctly, by adding the project to the classpath.
Now if I try to maven package, I always get the error
Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project A: Failed to copy file for artifact [com.dscsag.dscxps:ProjectB:jar:0.0.1-SNAPSHOT:compile]: C:\some_path\target\classes (Access is denied) -> [Help 1]

What should I do?

A: This has nothing to do with security: under Windows, this problem occurs when a process doesn't "close" correctly its usage of a folder.
We got the problem with apt-maven-plugin: in a complex multi-modules project, when a module using this plug-in, is then later referenced in an über jar building pom, then we got this error during the build of the über jar on the target/classes folder of the module using apt-maven-plugin.
When resuming the build (mvn params -rf :offending_module), the problem disappears because the Maven process launching the apt-maven-plugin is dead, thus the lock of the folder is released.
Very annoying to say the least.

A: I had the same error message before. In pom.xml I changed maven-war-plugin version from 2.3 to 2.6, then the project was built successfully.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
</plugin>

A: It seems to relate with security because the log said "(Access is denied)". Maybe the output jar of project B exists and there are some processes still reading from it, so that you cannot overwrite the output file. Or maven doesn't have the appropriate privilege to write the output file to the class folder.

A: In my experience, in the Maven plugin doing the copying (artifact maven-resources-plugin for me), the outputDirectory element was the issue, because I just had a slash as the output directory. I think this was causing Maven to try to copy this to C:/, and I need admin access to place files in C:/. Changing the outputDirectory to ${basedir}/target/resources got rid of this error.


text:
Q: Creating dynamic pages within a function I have this function:
var getData = function (obj) {

    for(var i = 0, j = localStorage.length; i < j; i ++) {
        var newKey = localStorage.key(i);
        var newValue = localStorage.getItem(newKey);
        var newObj = JSON.parse(newValue);
        var ulListView = $('#container').append('

');
        var dynPage = $(newObj[1].value).trigger('create');
        //var dynPage = $('

"
');
        var insideLi = $('#ulOrigin'+i).append('

'+newObj[1].value+'

'+newObj[0].value+'
Delete Entry
');
        var pageNum = $('#ulOrigin'+i);
        console.log(newObj);

    }

};

I'm trying to create a dynamic page with the name taken from the newObj[1].value. When accessing the link, the error I get is Error Loading Page. In the console I have: OPTIONS file:///home/<address>/[object%20Object] marked as an error as well.
I'm using jQuery Mobile 1.3.0

A: The problem is dynPage is not a string, in your current implementation you have
var dynPage = $(newObj[1].value).trigger('create');

followed by
var insideLi = $('#ulOrigin'+i).append('
....

I am only assuming you get the error when you click on the href from above. I don't know exactly how create works but the href should point to a page so your href will have a correct URL.
If you are indeed getting the error when you click on the link created by your code, then you can update the question with your latest code and also add the generated html of that link so we can see exactly what's going on.


text:
Q: asp.net - trigger updatepanel on pressing the return key I have a page with an updatepanel which contains a small login form - it runs fine when the user clicks on the submit button, but if the user presses the return key after entering their password, it does not run.
Here's the code...
    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="loginButton" EventName="Click" />
        </Triggers>
        <ContentTemplate>
            <asp:TextBox ID="username" MaxLength="11" runat="server" />
            <asp:TextBox ID="password" MaxLength="64" runat="server" TextMode="Password" />
            <asp:LinkButton ID="loginButton" OnClick="Submit_login" runat="server" Text="" />
        </ContentTemplate>
    </asp:UpdatePanel>

A: If you add a panel in the Content template and assign the DefaultButton, it should submit the button when a user hits Enter.
<ContentTemplate>
<asp:panel id="p" runat="server" defaultbutton="loginButton">
            //Form here with loginButton
</asp:panel>
</ContentTemplate>

A: Put your the controls that are inside <ContentTemplate> inside an Panel and set it's default button to be loginButton.
Like this:
<asp:Panel id="defaultPanel" runat="server" DefaultButton="loginButton">
  <asp:TextBox ID="username" MaxLength="11" runat="server" />
  <asp:TextBox ID="password" MaxLength="64" runat="server" TextMode="Password" />
  <asp:LinkButton ID="loginButton" OnClick="Submit_login" runat="server" Text="" />
</asp:Panel>


text:
Q: Stacked MPI derived data types in Fortran MPI2 allows us to create derived data types and send them by writing
call mpi_type_create_indexed_block(size,1,dspl_send,rtype,DerType,ierr)
call mpi_send(data,1,DerType,jRank,20,comm,ierr)

By doing this the position dspl_send of data(N) are sent by the MPI library.
Now, for a matrix data(M,N) we can send its position via the following code:
call mpi_type_create_indexed_block(size,M,dspl_send,rtype,DerTypeM,ierr)
call mpi_send(data,1,DerTypeM,jRank,20,comm,ierr)

That is the entries data(i, dspl_send(j)) are sent.
My question concern the role of the 1 in the subsequent mpi_send. Does it has always to be 1? Is another size possible? MPI derived data types are explained nicely in many documents on the internet, but always the size in send/recv is 1 without mention if another size is allowed and then how it could be used.
If we want to work with matrices data(M,N) with a size M that varies between calls, do we need to always create a derived data type whenever we call it? Is it impossible to use DerType for sending a matrix data(M,N) or data(N,M)?

A: Each MPI datatype has two properties: size and extent. The size is the actual number of bytes that the datatype represent while the extent is the number of bytes that the datatype covers in memory. Some datatypes are not contiguous, which means that their size might be less than their extent, e.g. (shown here in pseudocode)
MPI_TYPE_VECTOR(count = 1,
                blocklength = 10,
                stride = 20,
                oldtype = MPI_INTEGER,
                newtype = newtype)

creates a datatype that takes the first 10 (blocklength) elements from a total of 20 (stride). This datatype has a size of 10 times the size of MPI_INTEGER which counts to 40 bytes on most systems. Its extent is two times larger or 80 bytes on most systems. If count was 2, then it would take 10 elements, then skip the next 10, then take another 10 elements and once again skip the next 10. Consequently its size and its extend would be twice as larger.
When you specify a certain element count in any MPI routine, e.g. MPI_SEND, MPI does something like this:

*

*It initialises the internal data buffer with the address of the source buffer argument.

*It consults the datatype type map to decide how many bytes and from where to take and appends them to the message being constructed. The number of bytes added equals the size of the datatype.

*It increments the internal data pointer by the extent of the datatype.

*It decrements the internal count and if it is still non-zero, repeats the previous two steps.

One nifty feature of MPI is that the extent of the datatype is not required to match its size (as shown in the vector example) and one can even bestow whatever value of the extent that he wants on the datatype using MPI_TYPE_CREATE_RESIZED. This allows for very complex data access patterns to be created. For example, using MPI_SCATTERV to scatter a matrix by blocks that do not span entire rows (C) or columns (Fortran) requires the use of such resized types.
Back to the vector example. Whether you create a vector type with count = 1 and then call MPI_SEND with count = 2 or you create a vector type with count = 2 and then call MPI_SEND with count = 1, the end result is the same. Often one constructs a datatype that fully describes the object that one wants to send. In this case one gives count = 1 in the call to MPI_SEND. But there are cases when it might be more beneficial to create a datatype that describes only a portion of the object, for example a single part, and then call MPI_SEND with count set to the number of parts that one wants to send. Sometimes it is a matter of personal preferences, sometimes it is a matter of algorithmic requirements.
As to your last question, Fortran stores matrices in column-major order, which means that data(i,j) is next to data(i±1,j) in memory and not to data(i,j±1). Consequently, data(M,N) consists of N consecutive column-vectors of M elements each. The distance between two elements, for example data(1,1) and data(1,2) depends on M. That's why you supply M in the type constructor. Matrices with different number of rows (e.g. different M) would not "fit" the type map of the created type and the wrong elements would be used to construct the message.

A: The description about extent in https://stackoverflow.com/a/13802243/7784768 is not entirely correct, as the extent does not take into account the padding in the end of datatype. MPI datatypes are defined by typemap:
typemap = ((type_0, disp_0 ), ..., (type_n−1, disp_n−1 ))

Extent is then defined according to
lb = min(disp_j)
ub = max(disp_j + sizeof(type_j)) + e)
extent = ub - lb,

where e can be non-zero due alignment requirements.
This means that in the example
MPI_TYPE_VECTOR(count = 1,
                blocklength = 10,
                stride = 20,
                oldtype = MPI_INTEGER,
                newtype = newtype)

with count=1, typemap is
((int, 0), (int, 4), ... (int, 36))

and extent is in most systems 40 and not 80 (i.e. stride has no effect for the typemap in this case). For count=2, typemap would be
((int, 0), (int, 4), ... (int, 36), (int, 80), (int, 84), ... (int, 116))

and extent 120 (40 bytes for the first block of 10 integers, 40 bytes for the stride, and 40 bytes for the second block of 10 integers, but the remaining stride is neglected in the extent). One can easily find out the extent with the MPI_Type_get_extent function.
Extent is quite tricky concept, and it is easy to make mistakes when trying to communicate multiple elements of derived datatype.


text:
Q: Perturbation theory - integrals over different wavefunctions I am reading a research paper on how to calculate g-tensors* computationally (Correlated four-component EPR g-tensors for doublet molecules).
In the theory section, they write "[...]from (quasi-)degenerate perturbation theory one gets an expression for the first order energy corrections":
$$\begin{aligned}
E_{i j}^{(1)} &=\left.\sum_{k=x, y, z} \frac{\partial E_{i j}}{\partial B_{k}}\right|_{\mathbf{B}=0} B_{k} \\
&=\left.\sum_{k=x, y, z}\left\langle\phi_{i}\left|\frac{\partial \hat{H}^{(B)}}{\partial B_{k}}\right| \phi_{j}\right\rangle\right|_{\mathbf{B}=0} B_{k}
\end{aligned}
$$
Where $B_k$ is a component of a B-field (a parameter). It looks like they made a Taylor expansion in the first step to get the first-order energy correction, but I cannot see how they obtained the last term. It resembles what could be obtained from the Hellmann-Feynman theorem, except $\phi_i$ and $\phi_j$ are not necessarily the same wavefunctions.
Can someone see how this expression is obtained?
*The g-tensor is a $3\times3$ matrix that couples an external magnetic field, $\mathbf{B}$ to the electron spin, $\mathbf{\hat{S}}$ in a molecule or atom, giving the spin Hamiltonian: $\hat{H}=\mathbf{B\cdot g \cdot \hat{S}}$. Note that the unperturbed Hamiltonian giving the $\phi$-wavefunctions is the unperturbed Dirac-Hamiltonian. The perturbation is a uniform external field described by $\hat{H}^{(B)}=c \overrightarrow{\boldsymbol{\alpha}} \cdot \hat{\vec{A}}$ where $\boldsymbol{\alpha}_{i}=\left(\begin{array}{ll}
\mathbf{0}_{2} & \sigma_{i} \\
\sigma_{i} & \mathbf{0}_{2}
\end{array}\right)$, $\hat{\vec{A}}$ a vector potential and $\mathbf{\sigma_i}$ the Pauli spin matrices.


text:
Q: Why "tableview.cellForRowAtIndexPath(indexPath)" give me a BAD_ACCESS error?
I attempted to use this method to get the cell of that indexPath, but I got this "EXC_BAD_ACCESS" error.
But if I use self.tableView(tableView, cellForRowAtIndexPath:indexPath), it works fine.
I am confused what's the difference between that two methods?

A: Using self.tableView(tableView, cellForRowAtIndexPath:indexPath) is the code is your View Controller, and it dequeue's a suitable new cell. Whereas, the cellForRowAtIndexPath method on the table view returns nil if the cell is not visible. Since heightForRowAtIndexPath is trying to work out which rows are visible, it's not surprising that it doesn't work.
This SO answer shows that calling cellForRowAtIndexPath within heightForRowAtIndexPath recursively calls itself. Which is why you're getting the error.

A: It is possible that the cell does not yet exist. Consider that the tableview may be asking for the height so that it can construct the cell. Hence, you are asking for a cell before it exists.  I would have to run a test to be certain.
UITableViewDelegate - tableView:heightForRowAtIndexPath:
Asks the delegate for the height to use for a row in a specified location.
For this function you should be returning the height that you want for that cell.
UITableViewDataSource - tableView:cellForRowAtIndexPath:
(Required)
Asks the data source for a cell to insert in a particular location of the table view.
UITableView - cellForRowAtIndexPath:
Returns the table cell at the specified index path.

A: These Two methods is totally different, one is for the users, one is for the table view's delegate


text:
Q: I saw this question on a test: How to make text appear in an area, on click, with only HTML? How do I make a text appear in an area, on click, with only HTML?
Like a opening a hidden section with JavaScript with an on-click action, but... with only HTML.
It was on a test, so I'm hoping it isn't impossible as it seemed, even though searching for a while still find an answer...
EDIT: Well, apparently it is possible, since I got an answer that would fit on the test's format...

A: The details element may fit but do consider if the semantics of it meet your particular use case.

  A summary goes here

And longer content here.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam euismod posuere justo, in sagittis purus rutrum sed. Ut et sollicitudin ante. Cras tristique velit id scelerisque malesuada. Maecenas finibus tortor ac venenatis maximus. Etiam sed mauris
    ultricies, egestas diam et, efficitur justo. Maecenas convallis est arcu, vel faucibus risus tempus rhoncus. Donec in felis urna. Duis id quam lobortis, tempor felis quis, cursus lectus. Quisque nec finibus erat, a tincidunt leo. Nam dictum convallis
    leo vel consectetur. Praesent condimentum mauris vel ante tincidunt, non dapibus nisi imperdiet. Suspendisse lacinia augue nec faucibus vehicula. Ut ex felis, dictum in vehicula ut, suscipit in mauris. Sed metus urna, tempus sed eros et, blandit ultrices
    lorem. Quisque sit amet magna sed nunc feugiat finibus. Nulla quis semper tellus, ut aliquet justo.

Donec auctor non justo a lacinia. Aenean varius ultrices diam, et sollicitudin enim varius non. Sed lorem enim, ultrices in risus at, rutrum faucibus mi. Maecenas eu scelerisque erat, non sodales lacus. Nulla varius tristique nulla, sed ultricies mauris
    fermentum quis. Pellentesque sit amet laoreet arcu. Quisque sollicitudin vitae quam eget tincidunt. Maecenas viverra erat a est vulputate pellentesque. Ut varius quis felis lobortis ullamcorper. Phasellus a sapien at sem finibus suscipit. Ut iaculis
    euismod blandit. Duis convallis aliquam nulla ut efficitur. Duis pellentesque vitae augue et luctus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.

Note that browser support is relatively limited.


text:
Q: After orientation change, optionsmenu of fragment doesn't disappear I implemented my layout based on this tutorial: http://android-developers.blogspot.hu/2011/02/android-30-fragments-api.html
The differences are:

*

*I have different fragments to show, based on the choice in the left
list

*The "details fragments" (those that come to the right) have different options menus

My problem is that if I have already selected something from the left and then rotate the phone to portrait, the last optionsmenu is still there and is visible.
I think the problem comes from the last active "details" fragment is recreated after the orientation change. to test it I created these two methods:
@Override
public void onStart() {
    super.onStart();
    setHasOptionsMenu(true);
}

@Override
public void onStop() {
    super.onStop();
    setHasOptionsMenu(false);
}

And I'm showing the right fragment like this:
case R.id.prefs_medicines:
        if (mDualPane) {

            // Check what fragment is shown, replace if needed.
            View prefsFrame = getActivity().findViewById(R.id.preferences);
            if (prefsFrame != null) {
                // Make new fragment to show this selection.
                MedicineListF prefF = new MedicineListF();

                // Execute a transaction, replacing any existing
                // fragment with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.preferences, prefF);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), MedicinePrefsActivity.class);
            startActivity(intent);
        }
        break;

in one of my "details" fragment. when I debugged it, the onstart was called after the rotation.
The problem in pictures:
1: in landscape it's OK
Landscape mode http://img834.imageshack.us/img834/8918/error1d.png
2: in portrait: optionsmenu not needed
Portrait mode http://img860.imageshack.us/img860/8636/error2r.png
How can I get rid of the optionsmenu in portrait mode?

A: I had the same problem, and resolved it by setting setHasOptionsMenu(true) in the fragment only when savedInstanceState is null. If onCreate gets a bundle then the fragment is being restored in an orientation change to portrait, so don't display the menu.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null) {
        setHasOptionsMenu(true);
    }
}


text:
Q: How to authenticate google login on backend I am trying validate that a proper google login was made, with this information I want to get certain information from the Id_token and create a MySQL query so that they are verified on my own server (so i can set their permissions etc)
When I do this on my local server (xampp) with this code, it works perfectly:

But when I upload this same script to my own server, it will return a Internal 500 Server error when it reaches $ticket = $client->verifyIdToken($id_token);
I have no idea why this is happening, both my live server and localhost are in the allowed javascript origins on my google dev:

Here is the full script:
<?php
/**
 * Created by PhpStorm.
 * User: kenji
 * Date: 1/11/2017
 * Time: 10:51 AM
 */
header("Access-Control-Allow-Origin:*");
require_once './vendor/autoload.php';
//define('DBSERVER','localhost');
define('DBSERVER','matypatty.zapto.org');
define('DBUSERNAME','***');
define('DBPASSWORD','***');
define('DBNAME','***');
$conn = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$CLIENT_ID = "***.apps.googleusercontent.com";
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$client->setApplicationName("Backend_Auth");
if(isset($_POST['id_token']) && !(empty($_POST['id_token']))) {
    $id_token = $_POST['id_token'];
    $ticket = $client->verifyIdToken($id_token);
    if ($ticket) {
        $data = $ticket;
        print_r($data);

        /*$query = mysqli_query($conn, "SELECT * FROM oauth_users WHERE id='".$payload['sub']."'");
        if (!$query) { die('Error: ' . mysqli_error($conn)); }
        if(!(mysqli_num_rows($query) > 0)){
            $sql = "INSERT INTO oauth_users (id, email, name, source, picture) VALUES ('" . $payload['sub'] . "', '" . $payload['email'] . "','" . $payload['name'] . "', '" . $payload['iss'] . "', '" . $payload['picture'] . "')";
            if ($conn->query($sql) === TRUE) {
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }*/
    }else{
        die("Not a valid id_token");
    }
}else{
    die("set id_token to post");
}

I am printing a fresh id_token for testing with my login function on my site so the post data is real, as shown in the localhost example

A: Its because its an outdated version of PHP ):
Youre going to need a new host or use google token verification which will be slower


text:
Q: Which of these old criticisms of common lisp still apply today? In A Critique of Common Lisp written by Rodney A. Brooks and Richard P. Gabriel from Stanford in 1984, some design decisions retained by the normalizing committee of Common Lisp are discussed.  While most of the discussion remains valid, there are two statements that refer to the technology available at the time and may be false today.
These two statements are:

Too many costs of the language were dismissed with the admonition that 'any good
  compiler' can take care of them. No one has yet written—nor is likely to without
  tremendous effort—a compiler that does a fraction of the tricks expected of it.

As I am a Common Lisp novice, or even an apprentice, I am not able to be more specific than the authors are.  They seem to state that a great generality and flexibility has been built into several aspects of the language, which makes writing a good compiler quite difficult.

In COMMON LISP a little too much control was
  placed on floating-point arithmetic. And certainly, although the correct behavior of a
  floating-point-intensive program can be attained, the performance may vary wildly.

As far I understand, it seems that writing efficient numerical code in Common Lisp is possible but more challenging than it has to be.
This was thirty years ago. How should I regard these statement today if I am willing to write Common Lisp programs for one of the common free software implementations (CLISP, SBCL et al.)?

A: The paper is interesting in many ways.
The most interesting part is this: the authors falsified the paper from 1984 just two years later in 1986 themselves. Brooks and Gabriel developed a highly optimizing Lisp compiler and sold it commercially very successful for several years: Lucid Common Lisp (PDF).
Maintenance for this Lisp compiler is still available from LispWorks: it is now called Liquid Common Lisp.
The compiler optimizations of Liquid CL are documented in Chapter 3 of the Advanced User's Guide: Optimizing Lisp Programs.
Several commercial applications have been written and deployed in Lucid CL. For example in my home town the first public transport information system for the HVV (Hamburger Verkehrsverbund) was deployed using Lucid CL on a SUN SPARCstation. It was available for the public in train stations using a large touch screen and in the call center.
Lucid CL was successful because its production mode compiler created fast Common Lisp applications, mainly for Unix / RISC platforms.
Brooks and Gabriel are writing about Lucid Common Lisp in 1986:

The dynamically retargetable compiler has been shown to be a means by
  which ease of compilation for a variety of Lisp implementations can be
  performed; a means of porting Lisp systems to a variety of computers;
  and a tool for producing high-quality, high-performance code for a
  variety of computers from a common source.

Thus they had just implemented what the A Critique of Common Lisp claimed to be difficult or impossible.
Nowadays the more advanced implementations are doing a lot of optimizations, but the hardware is also 1000+ times faster than what we had in 1984. A VAX 11/780 then had one MIPS (million instructions per second) and a Lisp Machine was also in that range. A Motorola 68000 had a clock rate of 8 MHz.
The criticism about floating point performance and generally varying performance is still valid, but this reflects implementors choice. Some implementations are not developed as high-performance compilers. Their main focus could be portability, compactness or something else and thus they have different implementation goals.
As a user/developer one is not forced to write portable code and use all of the ten+ currently supported Common Lisp systems. Use the implementation which is best suited to the application problem.

A: When this paper was written in 1984, a computer having 1 megabyte of RAM and a 20 megabyte hard drive, capable of sitting on your desk, was a big deal.  Naturally, disputes will arise over the practicality of a language as high-level as Lisp is on hardware that spartan.  The advances in both hardware and compiler technology that have taken place since then have made Lisp programs much easier to write and execute, regardless of any numerical inefficiencies that might be present in the language.
Programmers often trade computational efficiency for programming efficiency.  Lisp can be a slow language (in some implementations, but so can other languages), but it also has a well-deserved reputation for rapid development, and many programs do not require a highly-optimized infrastructure to exhibit adequate performance.
The choice of Lisp implementation can greatly affect the performance profile of your programs.  For example, CLISP readily admits that "If your code is heavily numeric, you might prefer CMUCL."  Several modern Lisp (and Scheme) implementations allow you to specify numeric type hints, which will increase numerical performance.
In short, the situation is much better today than it was then.


text:
Q: Perl 6 equivalents to Java's >> and >>> operators? I've started using Perl 6 and I'm currently porting over some code from my Java projects, and they use Java's shift operators << and >>, as well as the >>> operator.
Currently I'm using +> \ +< (and ~>) operators to compensate for this, but are they equivalent?

A: It all depends what you put on the left side of the operator.  Since Perl 6 works by default on bigints (aka, integer values that will grow in size until you run out of memory or get tired of waiting), it really depends on whether you have a negative value or a positive value when you right shift.
say  2**65 +> 63; #  4
say -2**65 +> 63; # -4

Consequently you can left shift as far as you want:
say  1 +< 65; #  36893488147419103232
say -1 +< 65; # -36893488147419103232

Now, if you want to limit yourself to native integers, usually 64-bit, then you get wrapping:
my int $i = 1;         say $i +< 65; # 2
my int $i = 1;         say $i +< 63; # -9223372036854775808
my int $i = 2**63 - 1; say $i +> 62; # 1

And one could argue these are then the equivalent of << and >> in Java.  And that Perl 6 does not have an equivalent of Java's >>> (yet anyway).
Also, the ~> operator, although specced, is currently not yet implemented.  Patches welcome!


text:
Q: random BAD ACCESS when saving user defaults I'm simply trying to save this array to the user defaults and it will crash at random. Sometimes it works, sometimes it gives me the EXC_BAD_ACCESS. Am I not releasing something properly?
- (void)setTextValue:(NSString *)valueText indexToSet:(NSUInteger)index
{
    [self.pageData replaceObjectAtIndex:index withObject:valueText];
    [[NSUserDefaults standardUserDefaults] setObject:self.pageData forKey:@"mynotes"];
}

Here is the method that i've determined is causing the errors. It was a method already created by Xcode that I added my own custom code to.
- (nbookDataViewController *)viewControllerAtIndex:(NSUInteger)index storyboard:(UIStoryboard *)storyboard
{
    nbookDataViewController *dataViewController = [storyboard instantiateViewControllerWithIdentifier:@"nbookDataViewController"];
    if (self.pageData.count > 0 && index < self.pageData.count)
    {
        NSString *val = (NSString *)[self.pageData objectAtIndex:index];
        dataViewController.dataObject = val;
    }
    else
    {
        NSDate *date = [NSDate date];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"MMMM d, YYYY"];
        NSString *dateString = [dateFormat stringFromDate:date];
        //[dateFormat release];
        [self.pageData addObject:dateString];
        dataViewController.dataObject = (NSString *)[self.pageData objectAtIndex:index];
    }
    dataViewController.myModel = (nbookModelController *)self;
    dataViewController.dIndex = index;
    //[self.mySaveData setObject:self.pageData forKey:@"mynotes"];
    return dataViewController;
}

A: This tip will allow you code to break on the exception and let you check directly why this is happening:
https://stackoverflow.com/a/616526/46970


text:
Q: What does the system time represent? When the system time is printed, for example 1331783190854, what time might this be? I'd figure it'd be that many milliseconds (millis was in the code), but the number is too big.

A: Assuming you mean in terms of System.currentTimeMillis()?
It's the number of milliseconds since midnight on 1st January, 1970, UTC.

A: Number of milliseconds from Jan 1, 1970.


text:
Q: How to cascade persist a @ManyToOne relation (TransientPropertyValueException)? I want to create a DB mapping using hibernate: each Person may only have one single Address, but the same address may be assigned to multiple persons (eg gamily members).
The following mapping does not work:
@Entity
public class Person {
    @ManyToOne
    @JoinColumn(name="fk_address_id", foreignKey = @ForeignKey(name="fk_addres"))
    private Address address;
}

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String city;
    private int zip;
    private String street;

    @OneToMany(mappedBy = "address", cascade = {CascadeType.ALL})
    private Set<Person> persons;
}

@Transactional
public void create() {
    Person person = new Person();
    Address address = new Address();
    address.setStreet("test 1");
    address.setCity("test");
    address.setZip(123);
    person.setAddress(address);
    dao.save(person);
}

Result:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : Person.address -> Address

Why am I getting this exception, and how can I prevent it? I thought due to the cascading the address should automatically get saved?

A: Add @Cascade({CascadeType.MERGE}) to private Set<Person> persons; or change from ALL to MERGE. The problem is that you are making changes to Person and not saving them before saving Address. The Merge Cascade will do this for you.

A: I don't really understand the answer given by Nicholas Robinson .. here is what's going on :
Person doesn't cascade changes to Address ... but Address does ... you then have to save the address
change
dao.save(person);
by
dao.save(address);


text:
Q: Why code reverts back on reconfiguring the Remote Setting on Azure Cloud Service? I have a Sitefinity project that I deployed on Windows Azure Cloud Service using Sitefinity Thunder. But the problem is that I had changed some files manually using VM instance (Note: this user name is used in other configurations on other Cloud Services). Now after few days when I tried to connect to the VM Instance I got the following error:
Remote Desktop can't find the computer [Azure Colud Service name]. This might mean that doesn't belong to the
specified network. Verify the computer name and domain that you are trying to connect to.

But, till then the website was running fine on Azure Cloud Service. Then I reconfigured the VM Instance & downloaded. But then the code on Cloud Service got reverted. Also the changes made on IIS for that instance were reverted back.
I searched a lot why this happened but got no valid reason. Please can anyone explain here, How can I avoid this situation. Also How can I deploy only changed files only on Azure Cloud Service. So that the code do not get revert back in any situation.
EDIT:
I mean reconfigured VM Instance here is the following step:
1) I Select the Cloud Service, the select the Configuration tab, then click on Remove button given at bottom. Plz. see image given below.

2) Then I fill the values & click the [Tick] icon.  Plz. see image given below.

3) Then, after completing the Reconfiguration, I select the Instances tab, then click the [Connect] to downnload the RDP file to connect to the VM Instance for Cloud Service. Plz. see image given below.

Thanks

A: If your question is about losing the changes you made to the VM by manually logging in to the VM, then it is the expected behavior. Essentially Cloud Services VMs are Stateless VMs i.e. any changes you make to the VM after the VM has been brought up are not persisted. For many reasons your VM could go down and Microsoft replaces the VM. When Microsoft replaces the VM, it takes the code/binaries and settings from the package you last uploaded thus the changes you made will be lost.
For this reason, when deploying your code in a cloud service it is not recommended that you make the changes manually. If you have to make some changes, it is recommended that you do via startup tasks. These are executed when your VM is brought up and are part of the package. Obviously other alternative is to use Virtual Machines (IaaS) instead of Cloud Services. Virtual Machines are Stateful VMs.
Regarding your question about deploying only the changed files, unfortunately this is not possibly with cloud services. Your option would be to go with Virtual Machines or Websites.


text:
Q: Wait vs No wait in Synchronized methods (java) Hi I'm pretty new to Java and now I'm getting into java concurrency. And I have a little doubt about Synchronized methods: i have seen that I can get the same results using an If else inside a Synchronized method, checking every time If the condition to do an action is fullfilled, as using a wait / notify approach.
Since i get the same result I'm wondering If the If else approach has any advantages or disadvantages over t'he wait and notify approach? I supose that efficiency will be a disadvantage, since If is always checking the  condition, Who le wait Just stops and waits for notify. But are any other advantages or disadvantages?
Thx!

A: You are mixing two concepts. If-Else vs Wait-Notify are totally different. You want two threads to communicate with each-other that is where Wait-Notify would be used while if-else is general conditional statement.
You cannot have two threads communicate with each other simply using if-else condition. You can write your code that makes it look like it does however you are simply not allowing threads to interact with each other.
Moreover it can lead to undesirable consequences/computational states. Sooner or later you would have hotchpotch code.

A: synchronized block makes the code thread safe. You would want to use wait() and notify() or notifyAll() if you want to be more efficient.
For example if your shared resource is a list, multiple threads share. If you put it in synchronized block of a monitor then threads will constantly jump in and run the code, during context switches. Even if the list is enpty!!
The wait() is hence used on the monitor (the object inside the synchronized(..)) as a mechanism to 'tell' all threads to chill out and stop using CPU cycles until further notice or notifyAll().
synchronized(monitor) {

    while( list.isEmpty() )
       monitor.wait();
    doSomething(...)
}

In the above example, doSomething() will be executed only when the list is not empty, after another thread executed notify() or notifyAll() somewhere else in the code.

*

*read more why use while surrounding wait()
BUT with the following code:
synchronized(monitor) {

    if(!list.isEmpty())
        doSomething(...)
}

When a thread comes in to the synchronized block, there are 3 possible scenarios:

*

*The list is empty: doSomething() will not be executed.

*The list is NOT empty: doSomething() may be executed properly, or...

*If there was a context switch right after the if and before doSomething, and the other thread got all list's items out, after another context-switch out thread will execute doSomethig() on an empty list.

So, just to sum everything up, if you use wait/notify, you guarantee more efficient code! thread will not work when they don't need to.


text:
Q: Amazon S3 Java SDK multiple files upload What I need is to download many files from Internet and upload them to S3 as fast as it possible. For now I open every file as a stream and upload them one after another. The average speed of this approach is one picture per second. What's the fastest way to achieve this?

A: Split in parts and upload in parallel would be a good start, the TransferManager class can help with that.
Also, the article "Pushing the Limits of S3 Upload Performance" has some nice ideas on the subject.


text:
Q: Href asp.net mvc Пытаюсь сделать ссылку по якорям.
Работает только от футера (от низа и вверх). А вот от хедера и к любому элементу ниже него не работает, из-за чего такое может быть
Якоря делаю правильно, пример снизу

A: Tам id надо указывать:
<div id="myattr" ...

Атрибут name работает для линков:
https://www.w3.org/TR/html4/struct/links.html

.spacer{
background:green;
margin:10px;
height:100px;
}

.navbar-header{
background:red;
height:50px;
}
AAA


text:
Q: How to get a handle to an instance of my Angular 2 directive? Angular 2 rc 5 written with typescript 1.9
I'd like to get a handle to the instance of my attribute directive. I'm using ViewChild which works with components, but it instead gives me a handle to the element that hosts the directive.
template
<span myHighlight #directive> Highlight me! </span>

component
/** Want handle to the directive. Instead gives handle to the span element */
@ViewChild('directive') directive:HighlightDirective;

ngAfterViewInit(){
   console.log(this.directive);
}

directive
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }
}

Running plunker
The <span> element is printed to the console, so ViewChild is not grabbing what I need. How can I get a reference to the directive instance?

A: @ViewChild('directive', {read: HighlightDirective}) directive:HighlightDirective;

or
@ViewChild(HighlightDirective) directive:HighlightDirective;

but this 2nd approach returns the first HighlightDirective, not a specific one.


text: Q: ViewController.swift cannot be seen upon accessing Automatic in xcode assistant I just started with iOS Development in Swift, and I am facing a small issue. In Xcode assistant, when I select Automatic I cannot see the option viewcontroller.swift, it rather shows viewcontroller.h. Would be great if someone has any idea how to see viewcontroller.swift upon select Automatic in Xcode asistant.


text:
Q: Exception: Assertion at ..., condition '' not met. What does that mean? I just published to Azure a Blazor Wasm app I am developing with VS Community 2019.  The app starts up successfully in VS, but the published version triggers the exception below (both in Chrome), which gives me no clue as to the problem.  Perhaps a problem with my Azure account?  I've just started to learn what I need to do to publish, now that I'm at a certain point in my development.  I published 2-3 months ago a much simpler early version of the app, which functionally did what's noted below, and it worked at that time.
Curiously, after I first published it a few minutes ago, my console log messages indicated it got through most of my main layout's OnInitializedAsync code, including a JSRuntime.InvokeAsync to my JavaScipt initialization code that opens an IndexedDB and returns its Index of keys.  But when I tried re-publishing and got the same exception, none my initialization code ran according to the console log.  I can post my OnInitializedAsync code, but since the exception is now happening before any of this code executes, I'm not sure it will be helpful.  Any idea what's going on?
Thanks.  Steve

A: When I ran into this issue it was due to my build pipeline BuildConfiguration setting being set to "debug" instead of "release" inside azure devops.
(EA. Pipelines -> Edit Blazor Web Project Pipeline -> Variables -> Build Configuration -> Release)


text:
Q: How to make sure several SELECTs are isolated? When we have to use several different SELECT queries to get data from various locations in the database, how to make sure they are isolated from queries such as INSERT, UPDATE or DELETE so that we can be sure that data selected are consistent with each other and not changed in between?
I know I can use transaction to achieve the same effect for INSERT, UPDATE and DELETE so changes are applied as a whole or not. But does it isolate SELECTs as well?
For example, 3 SELECT queries return 3 different values, either:
1, 3, 5
Or:
2, 4, 8
3 update queries are constantly switching the values. How to make sure I get either:
1, 3, 5
Or:
2, 4, 8
But not anything in between such as: 2, 3, 5, nor 2, 4, 5, etc.
I know I can get those updates in a transaction but I want double check.
So would it work if I put those 3 SELECTs in a transaction?

A: You are asking how to read the database "consistently".  Such matters are determined by the transaction isolation level.  You want REPEATABLE READ:

This is the default isolation level for InnoDB. For consistent reads, there is an important difference from the READ COMMITTED isolation level: All consistent reads within the same transaction read the snapshot established by the first read. This convention means that if you issue several plain (nonlocking) SELECT statements within the same transaction, these SELECT statements are consistent also with respect to each other. See Section 14.2.7.2, "Consistent Nonlocking Reads".

So, yes, it will work if you put your SELECT statements within a single transaction—provided that the transaction's isolation level is REPEATABLE READ (the default).

A: Yes. Normally exactly this is prevented with transactions. Look up transaction isolation levels of your dbms. For mysql for example see:
http://dev.mysql.com/doc/refman/5.6/en/dynindex-isolevel.html
Of Course the update statements that change all three values must be in ONE transaction. If they are in three different transactions then your select could catch states in beetween the updates.


text:
Q: Android Layout issues In my layout this is not moving the button to the right of the screen.
What am I missing?
The button is within a linear layout.
But has its own relative layout.

A: Try this, it works for me.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:orientation="vertical"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <Button
            android:text="Button"
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </Button>

   </LinearLayout>

</RelativeLayout>

A: Set the RelativeLayout android:width to "fill_parent", for the LinearLayout set the android:layout_gravity property to "right"

A: Something like this for main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="right" >
<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
        <Button android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        android:layout_alignParentRight="true"
        android:text="Right Button"
        </Button>
    </RelativeLayout>
</LinearLayout>

Cheers.


text:
Q: Return middleware in class I have a class with middleware function, which I want to return.
In middleware I want to use this statement, but now it is just undefined.
Class :
export class Validator {
    constructor(options: validatorOptions) {
        this.schema = options.schema
        this.validateRequest = options.validateRequest
        this.validateResponse = options.validateResponse
    }

    private validate(req, res, next) {
        console.log(this.schema) //undefined
    }

    public getValidator() {
        return this.validate
    }
}

Class declaration:
import {Validator} from './validator/validator'

export const validator = () => {
    const config = {
    schema,
    validateRequest: true,
    validateResponse: true
  }

  let v = new Validator(config)

  return v.getValidator()
}

Middleware usage:
import { validator } from './middleware'
app.use(validator())

How I can use this in returned middleware?

A: validate is a callback and should be bound to correct this, e.g. with class field:
private validate = (req, res, next) => { ... }


text:
Q: Generate AES key through IAIK PKCS#11 wrapper and show its value I would like to use PKCS#11 compatible cryptographic USB token to generate AES key and show its value on screen.
For that purpose I want to use IAIK PKCS#11 wrapper.
I tried to generate the key by the example provided with IAIK package but with no success. The key is generated but I can't see any value of key. What should I do to see the key value in order to show it on screen?
Here is my code:
Module pkcs11Module = null;
pkcs11Module = Module.getInstance("pkcs11.dll");

Session session = null;
pkcs11Module.initialize(null);

Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);

if (slots.length == 0) {
    output_.println("No slot with present token found!");
    throw new TokenException("No token found!");
}

Slot selectedSlot;
// slot 0
selectedSlot = slots[0];

Token token = selectedSlot.getToken();

session = token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null);

session.login(Session.UserType.USER, "12345678".toCharArray());

Mechanism keyGenerationMechanism = Mechanism.get(PKCS11Constants.CKM_AES_KEY_GEN);

AESSecretKey aesKey = new AESSecretKey();
aesKey.getValueLen().setLongValue(new Long(32));

AESSecretKey aesKeyNew = (AESSecretKey) session.generateKey(keyGenerationMechanism, aesKey);
output_.println("the AES Key is: ");
output_.println(aesKeyNew.toString());

session.closeSession();
pkcs11Module.finalize(null);

The results is as follows:
the AES Key is:
  Object Class: Secret Key
  Token: false
  Private: false
  Modifiable: true
  Label: <NULL_PTR>
  Key Type: AES
  ID: <NULL_PTR>
  Start Date: <NULL_PTR>
  End Date: <NULL_PTR>
  Derive: true
  Local: true
  Key Generation Mechanism: CKM_AES_KEY_GEN
  Allowed Mechanisms: <Attribute not present>
  Sensitive: false
  Encrypt: true
  Decrypt: true
  Sign: false
  Verify: false
  Wrap: true
  Unwrap: true
  Extractable: true
  Always Sensitive: false
  Never Extractable: true
  Check Value: <Attribute not present>
  Wrap With Trusted: <Attribute not present>
  Trusted: <Attribute not present>
  Wrap Template: <Attribute not present>
  Unwrap Template: <Attribute not present>
  Value (hex): <NULL_PTR>
  Value Length (dec): 0

There is Value (hex):  that I want to see and show on screen.
Is it about a specific configuration of cryptographic tokens? When I use different token then I see this value.

A: According to what you show us the PKCS#11 attribute CKA_SENSITIVE set to false indicates that you should be able to view the value. It is however likely that the token does not allow you to extract the value. Most of these kind of tokens do not fully implement PKCS#11 and only allow certain operations to take place. If this is true then it should not be possible to set CKA_SENSITIVE to false, but that's IT for you...
I would track down the manufacturer (or, if possible, the developer) of the token and ask for the specific functionality implemented by the token.


text:
Q: A user with the account name DOMAIN\user could not be found The query cannot be run for the following DataObject: GetUserProfileByName
InfoPath cannot run the specified query.
The SOAP response indicates that an error has occurred:

A user with the account name camel\username could not be found. An error was encountered while retrieving the user profile.

On the InfoPath 2010 preview or in the published site SharePoint 2010 has the same error.
Infopath security level is set to domain but still the same error.
SOAP address is http://qaserver:8000/_vti_bin/UserProfileService.asmx

A:
InfoPath Form Services does not support claims based authentication
  (that's what MS Support told us, when we faced a similar issue with
  Nintex Workflow.asmx about a month back).
If you look in the IIS logs you will see that the calls to the
  UserProfileService.asmx are getting made as nt authority\anonymous
  user instead of the currently logged in user. This happens because
  FormServer when making the call to the WS is able to use only Basic or
  Digest mode for passing credentials.
You can fix the issue temperorily by using the udcx:Authentication tag
  of the udcx file, either by speciying a hard coded user name and
  password or setting it up to use Secure store service. This fix works
  because the GetProfileByName method does not require the the currently
  logged in user to be imperonated when making the call.
But sooner or later you would come across a scenario in which you need
  to make a call to a Web Service that requires that the call be made
  using the logged in user's credentials (for eg:
  GetRunningWorkflowTasksForCurrentUser method in Nintex
  Workflow.asmx), which would fail if you are using InfoPath Form
  Services in a Claims based environment
Important:
The SharePoint application and code described in this article will not
  work if SharePoint is configured for forms-based authentication. To
  work correctly, the web application that hosts this SharePoint
  application must be configured to use classic-mode authentication.
  For more information about configuring SharePoint authentication, see
  Plan authentication methods (SharePoint Server 2010)".


text:
Q: Relacionamento entre as tabelas Tenho as seguintes tabelas:
TB_ESTOQUE
|COD_PRODUTO|QT_DISPONIVEL|COD_FILIAL|
|  0856322  |      5      |    41    |
|  0856351  |      2      |    41    |
|  0856322  |      9      |    114   |
|  0856720  |      3      |    20    |
|  0856322  |      8      |    128   |
|  0856322  |      12     |     35   |
|  0856322  |      4      |     9    |

TB_FILIAL
|COD_FILIAL|COD_LOCALADM|
|    41    |    114     |
|    128   |    114     |
|    114   |    114     |
|    10    |    156     |
|    56    |     12     |
|    35    |     12     |
|    9     |     12     |

TB_PRODUTO
|COD_PRODUTO|DESC_PRODUTO|
|  0856322  | CALCARIO   |
|  0856351  | ZINCO      |
|  0856321  | SEMENTE    |
|  0856720  | INSETICIDA |
|  0856752  | STE SOJA   |

Tabela desejada:
|COD_PRODUTO|DESC_PRODUTO|QT_DISPONIVEL|COD_FILIAL|
|  0856322  |   CALCARIO |       5     |    41    |
|  0856322  |   CALCARIO |       9     |    114   |
|  0856322  |   CALCARIO |       8     |    128   |

Estou executando o seguinte SQL:
SELECT
E.COD_PRODUTO,
P.DESC_PRODUTO,
E.QT_DISPONIVEL,
E.COD_FILIAL
FROM
TB_ESTOQUE E
LEFT JOIN TB_PRODUTO P
ON P.COD_PRODUTO = E.COD_PRODUTO
WHERE
E.COD_PRODUTO = 856322
ORDER BY
P.DESC_PRODUTO

Como eu relaciono no SQL a tabela TB_FILIAL, filtrando pelo código COD_LOCALADM?
Exemplo:
... WHERE
    E.COD_PRODUTO = 856322 AND
    TB_FILIAL.COD_LOCALADM = 114

A: Não existe COD_PRODUTO na tabela TB_ESTOQUE segundo o seu exemplo.
Experimente:
SELECT
E.PRODUTO,
P.DESC_PRODUTO,
E.QT_DISPONIVEL,
E.COD_FILIAL
FROM
TB_ESTOQUE E, TB_FILIAL F
LEFT JOIN TB_PRODUTO P
ON P.COD_PRODUTO = E.PRODUTO
WHERE
F.COD_FILIAL = E.COD_FILIAL AND
F.COD_LOCALADM = 114 AND
E.PRODUTO = 856322
ORDER BY
P.DESC_PRODUTO

A: Basta adicionar a tabela de filial na clausula FROM e adicionar os parâmetros para filtragem no WHERE, sem muita complicação:
SELECT
E.COD_PRODUTO,
P.DESC_PRODUTO,
E.QT_DISPONIVEL,
E.COD_FILIAL
FROM
TB_FILIAL F,
TB_ESTOQUE E
LEFT JOIN TB_PRODUTO P
ON P.COD_PRODUTO = E.COD_PRODUTO
WHERE
E.COD_PRODUTO = 856322
AND E.COD_FILIAL = F.COD_FILIAL
AND F.COD_LOCALADM = 114
ORDER BY
P.DESC_PRODUTO

A: Pode usar o código abaixo, pois acho que não haverá um cenário onde você guarda apenas uma filial no estoque sem produto, ou um produto sem uma filial.
Para o WHERE funcionar, basta apenas colocar as junções, e depois ir chamando Tabela.Campo de acordo com a necessidade.
SELECT
  P.COD_PRODUTO,
  P.DESC_PRODUTO,
  E.QT_DISPONIVEL,
  F.COD_FILIAL
FROM TB_ESTOQUE E
INNER JOIN TB_FILIAL F
  ON F.COD_FILIAL = E.COD_FILIAL
INNER JOIN TB_PRODUTO P
  ON P.COD_PRODUTO = E.COD_PRODUTO
WHERE P.COD_PRODUTO = 856322
  AND F.COD_FILIAL = 114
ORDER BY
  P.DESC_PRODUTO