text:
Q: Handling NameErrors caused by invalid parameters in Python functions So I've declared a function with parameters that take arguments, like so;
def getNumber(number = None, minimum = None, maximum = None):, but I don't know how to catch and handle NameErrors that arise when the user passes invalid parameters into them.
For example, the user calls the function like getNumber(apples). apples is just a placeholder, the user could enter any non-string/non-number. Note that the word apples isn't a string. When the code is run, it outputs: Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
getNumber(apples)
NameError: name 'apples' is not defined

How would I go about catching and handling the NameError that occurs?

A: If you want to catch the variables like apple that are not defined use something like below:
>>> def getNumber(number = None, minimum = None, maximum = None):
...     pass
...
>>>
>>> try:
...     getNumber(apples)
... except NameError as e:
...     print("ERROR {}. Please use proper variable.".format(e))
...
ERROR name 'apples' is not defined. Please use proper variable.

A: while calling the function, call it like this
try:
    getNumber(number, minimum, maximum)
except:
    print("Please pass in valid arguments")

If the argument given is not valid or incorrect, it will print out the statment which is written in the except: block


text:
Q: Flutter iOS app - testing app upgrade in TestFlight I am currently building a flutter app that involves checking if the user has the latest version of the app and prompting them to upgrade if not. On the Android part that's not a problem to test as I can install the apk after downloading it from our servers, my question is regarding the iOS part. I do realize then when the app is released I will use the app store, but I am wondering how will I test this feature before release. When I have my app on TestFlight, is there a way to upgrade this app programmatically from inside my code? Will there be a link to TestFlight app like there is to the app store app so when I can use url_launcher to open it (for testing).

A: To open the TestFlight page for your app, use this URL:
itms-beta://beta.itunes.apple.com/v1/app/XXX
Replace XXX with your app's ID in the App Store (find it in App Store Connect in the App Information section).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop for in a .mousemove function My problem is here :
    $(document).mousemove(function(e){
    for(i = 1; i < 7; i++){
        var tt = document.getElementById("tooltip"+i);
        document.getElementById("help"+i).onmousemove=function(event){
            if(tooltip == 1){
                $(tt).css({left:e.pageX+5, top:e.pageY+5});
                tt.style.visibility= "visible";
            }
        }
        document.getElementById("help"+i).onmouseout=function(event){
            tt.style.visibility= "hidden";
        }
    }
});

With this code, the
 is showing right next to the mouse, but it's always the last "tooltip"+i, in this case tooltip6 which is showing.
I managed that to work by simply removing the loop for, and writing 6 times that next, each with a different i :
    $(document).mousemove(function(e){
    var i = 1;
    var tt = document.getElementById("tooltip"+i);
    document.getElementById(i).onmousemove=function(){
        if(tooltip == 1){
            $(tt).css({left:e.pageX+5, top:e.pageY+5});
            tt.style.visibility= "visible";
        }
    }
    document.getElementById(i).onmouseout=function(){
        tt.style.visibility= "hidden";
    }
});

In this case, it does what i want. It shows the tooltip1, when the mouse is over the
, and (e.g.) tooltip4 over the
 if i use var i = 4.
I can obviously just write more and more like that as i add more tooltips, but i really don't understand why the adding of the loop is not working here.
My HTML code with the tooltips :
        Health points of the rock. Each time it gets to 0, you get some stone
        Deeper you go, harder it is.
        Power of the Pickaxe.
        Go To the Village.
        Go To the Blacksmith.
        You can sell stone in the village.

And HTML code with some of the help :

HP : 0

Deep Level : 0m

Pick Power : 0

Stone : 0

A: Okay, so after reading the comment, i edited my code to make it simpler, and not adding any other listener, to not crash the script :
$(document).mousemove(function(e){
if(tooltip == 1){
    var i = e.target.id;
    var tt = document.getElementById("tooltip"+i);
    tt.style.visibility = "visible";
    $(tt).css({left:e.pageX+5, top:e.pageY+5});
    document.getElementById(i).onmouseout=function(){
        tt.style.visibility= "hidden";
    }
}

});


text:
Q: Video Stabilization with spin product OpenCV I'm trying to stabilize video using OpenCV, but my video is a walkaround 360 spin like this spin, but the stabilize not perfect has a shaking because the optical flow not working perfectly with the spined video
can you find python code here
and I'm trying to use FFmpeg but still, have the same issue,
this command
INPUT=$1
STB_OUTPUT=stb1.mp4

ffmpeg -y -i "$INPUT" -vf vidstabdetect=stepsize=32:shakiness=5:accuracy=15:result="$TRF" -f null -

ffmpeg -y -i "$INPUT" -vf vidstabtransform=input="$TRF":smoothing=30,unsharp=5:5:0.8:3:3:0.4  "$STB_OUTPUT"


text:
Q: C: client program reports SSL Certificate verify failed error with localCA I am writing a simple TLS client/server program to securely communicate over the network. Initially I am building and running both the client and server on the same machine running RHEL 8.2.
First, I am using custom self signned ssl certificate and key for my programs. I have placed the rootCA.crt (my custom CA certificate in /root/CA/rootCA.crt). Also copied the rootCA.pem to /etc/pki/ca-trust/source/anchors/ and executed update-ca-trust enable then update-ca-trust extract to install the certificate to the system. (Not sure if I need to reboot the system for it to take effect.)
Initially, the client and server were able to communicate usint TLS untill I added the certificate validation part of the code on the client side.
Certificate Verification snippet:
ctx = SSL_CTX_new(method);   /* Create new context */
    if ( ctx == NULL )
    {
        ERR_print_errors_fp(stderr);
        abort();
    }

    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);

    SSL_CTX_set_verify_depth(ctx, 4);

    const long flags = SSL_OP_NO_SSLv2 |
                        SSL_OP_NO_SSLv3 |
                        SSL_OP_NO_TLSv1 |
                        SSL_OP_NO_TLSv1_1 |
                        SSL_OP_NO_COMPRESSION;
    SSL_CTX_set_options(ctx, flags);

    if(SSL_CTX_load_verify_locations(ctx, NULL,
                "/root/CA/") == 0){
        ERR_print_errors_fp(stderr);
        abort();
    }

ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
    if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else
    {

        sprintf(acClientRequest, "%s", cpRequestMessage);   /* construct reply */
        printf("\n\nConnected with %s encryption\n", SSL_get_ciphe

}

when I run the server and client programs I see the following error messafe =>
Onclient:
140736372886336:error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed:ssl/statem/statem_clnt.c:1915:
On Server:
140736022137664:error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca:ssl/record/rec_layer_s3.c:1543:SSL alert number 48
Not sure, what is going wrong with the certificate validation process. Can anyone suggest me how to fix this error?

A: Just copying your rootCA.crt file into /root/CA/ is not enough.
SSL_CTX_load_verify_locations explicitly states that the files in this directory have to use a specific format:

If CApath is not NULL, it points to a directory containing CA
certificates in PEM format. The files each contain one CA certificate.
The files are looked up by the CA subject name hash value, which must
hence be available. If more than one CA certificate with the same name
hash value exist, the extension must be different (e.g. 9d66eef0.0,
9d66eef0.1 etc). The search is performed in the ordering of the
extension number, regardless of other properties of the certificates.
Use the c_rehash utility to create the necessary links.

Therefore make sure your rootCa.crt is in PEM format. And then generate the required hash and rename it accordingly. The following command generates the hashvalue. Rename the file to <hashvalue>.0.
openssl x509 -inform PEM -subject_hash_old -in rootCa.crt | head -1

If your code then still does not work I would first test if your code works at all. For doing so change the server URL to a real server that sues an HTTPS certificate that is already trusted on your system.


text:
Q: In the Doctor Who Universe, is the Master dead or still living? I remember seeing the Master die in the 8th Doctor movie. I also remember him dying when he attempted to take over the whole world in the final episode of season three of the new Doctor Who. I also remember him vanishing in the final 10th Doctor episode The End of Time, where the Time Lords on Gallifrey were trying to get out of a Temporal Loop.
I know the Master was destabilizing when he was reborn for The End of Time. What's become of the Master? Is he dead? Or living on with the Time Lords on Gallifrey in the Temporal Loop?

A: In the Tenth Doctor's final story,

 the master did simply disappear with no explanation.

I believe this was deliberately ambiguous, to allow future writers to bring back the character without too much retconning. In the "Whoniverse" it's safe to assume that even if you see someone die, he can come back again; especially a popular recurring villain like the master.
With the Master, after Roger Delgado (the actor who played him originally) died, the writers introduced plot-lines basically saying that the Master was at the end of his 13th and final life, and was constantly seeking ways to continue his life. In the 1996 movie you reference, he did appear to die at the end. However in the new 2005 series, it was stated that during the Time War, the Time Lords brought the Master back, essentially giving him a new cycle of regenerations (although this is not explained in detail). Thus the potential life of the character is still long, and he's such a popular villain that if they were going to kill him off permanently, viewers would know about it.
Edit: In the wake of Twelfth Doctor's Season 8 finale, this answer is now out of date, but I will leave it as-is.

A: The answer is really, unknown. In a 2008 episode of the tenth doctor david tennant, the master dies and refuses to regenerate, causing him to (supposedly) DIE, leaving the doctor as the last time lord left

(until Amy and Rory Pond conceive their child, Melody Pond (River Song) in the TARDIS when the TARDIS' time vortex was active (they were traveling through time)),

but he is apparently alive in the 2010 episode of the tenth doctor david tennant, when he dies again. SO, nobody knows. Just like nobody knows the Doctors name

except himself and his love, River Song.

A: There's a good chance that the Master is still alive. Even stuck in the Temporal Loop, he's a crafty character, and everyone loves the archenemy.
 He's died permanently so many times now it isn't even funny-more than the Daleks even-and with the fiftieth anniversary showing up....
Let's just say I'm hoping for my favorite villain to come back.

A: Basically, the master would not have died from the events of the episode but he would have to suffer some consequences for condemning his people but, as he is so skilled in battle; it is likely that he would have been given back his cycle to help with the war effort. we know from this episode that the doctor has already stolen the moment but we know from the day of the doctor that he won't use it. so the master is currently (and i use that term losely) wherever they are. after seeing the events of the time of the doctor, we know that this is through the cracks in the universe. so he is probably alive, but this hasn't been openly stated so that writers aren't obligated to bring back the master if they let gallifrey back through the crack.

A: It depends.
How do you determine 'still' in a universe where so much time travel happens?
The Master is alive near the very end of the universe, and I'm sure he visited the very start of the universe (or close to it) at some point.
Even if his last incarnation is deceased, and he will make no further actions, his past incarnations still exist at every point in time they visited.
Unfortunately, I haven't seen all the new series (I didn't see the end of Tennant's run) so I can't comment on the Temporal Loop.
That said, unless this has done something to prevent the Doctor from travelling in time, he could always run into a past version of the Master, interact with him, and potentially change the Master's future... which would potentially change the Doctor's past.
And now I've gone cross-eyed.
EDIT: Now that I have watched through the end of Tennant's run, I can safely say: The Master is dead and so are all the others, including the planet of Gallifrey.  They all died at the end of the Time War.  The Time Lord's actions on that episode almost brought them all back from the dead, but didn't.  They're dead, and never coming back.
Until another episode gives them a way back, that is.

UPDATE: Just a bit of an update on this: the episode that gives them a way back is "The Time of the Doctor", which is Matt Smith's last episode. The Master him (her)self also comes back in the season 8 finale, "Dark Water/Death in Heaven"

A: Using season 10 knowledge, we know that The Master (spoilers in link)

 survived the events of this question and returned for seasons 8, 9, and 10.  Was not shown escaping from the temporal loop.

Serious season 10 spoiler:

 Then died again.  Supposedly really truly dead this time.  But, who knows?

So make of that what you will.  You can read all the gory details on wikia, but that answers the question as of the end of season 10.
For those who don't know what a season is, it's the United States word for what would be called series in the United Kingdom.  In the US, Doctor Who is a series and one year's worth of episodes is a season.

A: Currently (and I stress the word "currently") Yes, the master is dead. However, it wouldn't be the first time, and I doubt it will be the last.
The Master has "died" properly three times:
In the TV movie, he fell into the Eye of Harmony, after opening it to steal the Doctor's body. He was later resurrected to fight in the Time War, but, to put not too fine a point on it, he freaked out and legged it to the end of the universe, and hid using a chameleon arch.
John Simm's Master died after being shot by his wife at the end of "Last of the Time Lords", and refusing to regenerate. However, in the 2 part Christmas special "The End of Time", he returns using a potion of life, created by his followers.
At some point after this, it would seem that his "condition" following using the potion of life was cured, stabilising his body. Following his regeneration into Missy, she was then killed by her previous incarnation as punishment for siding with the Doctor.
And this brings us to the present.
As the precedent has previously been set, if it suits the Time Lord's, or even the Doctor's interests, then the Master will be resurrected again, mainly because he/she is a great villain.

A: At the end of The Doctor Falls

two different incarnations of The Master kill each other.

I'm sure that when they need The Master again, he/she will return, but until then The Master is like Schrödinger's cat.

A: In the day of The Doctor

The Doctor goes back in time in a time vortex and see's his past regenerations and freezes Gallifrey into a picture.

So that means that you can make The Master see his past self, and his past self could help his future of being stuck on Gallifrey to never happen. That would put The Master back in the End of Time Movie, and he would need to slip away and leave it to The Doctor to close the portal from Gallifrey.

A: In the final episodes of Season 10 World Enough and Time and The Doctor Falls we find out that after the events of The End of Time, John Simm's The Master was pulled back into Gallifrey with Rassilon the other Time Lords.
Following this the Timelords fixed The Master's decaying body as thanks for helping stop Rassilon's plans as according to the Wikia

Upon getting back to Gallifrey, the Time Lords, grateful for the Master's help in preventing Rassilon from executing The Final Sanction, properly restored his body. With that done, the Time Lords kicked him off Gallifrey. However, the Master stole a TARDIS to go back into the universe; so he considers it a mutual being kicked out.

Source: The Doctor Falls (TV Story) > Plot (3rd Paragraph)
given the mention of "back into the universe" this would indicate that The Master's recovery was after the events of The Day of the Doctor after Gallifrey was removed from the universe rather than being destroyed by The Moment.
after this The Master arrived on the Mondasian colony ship and lived like a king until he was overthrown

After that, the Master landed on the colony ship, lived like a king and killed people at his leisure. However, the colonists eventually overthrew him and the Master attempted to flee. However, as his TARDIS was on the last level, too close to the event horizon, it burned out his dematerialisation circuit and left him stranded. "You never could drive could you?" the Doctor asks.

Source: The Doctor Falls (TV Story) > Plot (3rd Paragraph)
this is when time become wibbly wobbly as after some time Michelle Gomez's The Master (here-by referred to as Missy), who is the next form on John Simm's The Master, showed up. in The Doctor Falls Missy remembers when she was The Master on the colony ship being yelled at by "an angry woman" and carries a replacement dematerialisation circuit.
following this and the apparent betrayal of The Doctor Missy stabs The Master thus showing that this was the start of his Regeneration into Missy however as Missy leave The Master shoots her in a back and prevents her generation. as such The Master, now wounded and will begin regenerating, descend back down to his Tardis while Missy is dead.
Does this mean The Master is dead with Missy being the last? while it's unknown if The Master will return with the new writer for the series after Steven Moffat, but we do know that despite being fully dead The Master has been resurrected multiple times, the most recent resurrection was what lead to The Master's decaying state in The End of Time
so even if Missy never regenerated The Master could return for any reason and considering The Doctor said in Hell Bent

death is Time Lord for man flu

The Master's current status (as of 02/03/2018) would be sick with man flu until further notice

A: As it was is how I remember it as I remember all of the doctor who's what happened was the master tried to make all humans himself and rassilon (time Lord president) snapped the template with is metal glove and the doctor broke the link to send the time lords back to the time war to their certain death and when doctor broke it he shouted back into the time war rassilon back into hell was his exact words master got in his way and got sent with them by accident so as it seems it looks like he's dead but the villains always survive and make the good suffer occasionally they die but he could be living his live happily on gallifrey but he could be under the ground in trenzalore dead but who knows only you can think your ways

A: The master is stuck in the termporal loop. The timelords promised the master an extra regeneration cycle in the five doctors. The movie master survived and died. He was revived by the time lords, during the time war, to fulfil their promise. The master used a Chameleon Arch to turn him into a human during the Utopia episode. The master was reminded of timelords and died due to his wife (From the Tennant episode)
Then the master was brought back to life. He was sucked back into the time war. Due to the events in Day of the Doctor, it is revealed he is alive. He is supposed to be on Gallifrey. Gallifrey is in the pocket universe. Therefore, Stephen Moffet created a way that he could bring back the time lords (including the master) and Gallifrey.

A: I like to think that because the Master wasn't trapped in the Time Lock with the Timelords he can escape it. It was also said that if the Doctor killed the Timelord President he became President, so it's fair to say that by killing Rassilon the Master became the President, so he returned to Gallifrey on the brink of its destruction as President. He would then be given a new set of regenerations and a new body as the one he had was dying, and take whatever tools he wished -- such as the Hand of Omega -- and leave the Time Lock just as he sees Gallifrey burn and all his people die at the hands of the Doctor. This would renew his hatred of the Doctor and set him off to avenge his people.


text:
Q: ASP.NET MVC - Show raw DisplayName of an item of the Model e.g. i have a class
public class Car
 {
     public string Name { get; set; }
     public string Brand { get; set; }
     public string Color { get; set; }
 }

and i have a view with a model as a list
@model IEnumerable<Car>

Now i want to display the raw displayName of a property of a listItem (model).
Example code:
@model IEnumerable<Car>

//(..)

        "[@Html.DisplayName(Model.First().Name))]"
        Brand
        Color

How can I do it?
UPDATE
I found the solution in creating a new helper class:
click me

A: Use LabelFor
@Html.LabelFor(p => p.First().Name)

Don't forget the display Attribute on Car Class
[DisplayName("Car Name")]
public string Name { get; set; }

A: You can get
DisplayName

by using
@Html.DisplayNameFor(model => model.First().Name)

The solution you've used is quite old and doesn't use the built in helper.


text:
Q: how i can read file and store its containt in variable? I want to store number in file for example file number.txt contain 3242 I want to real this file and store its contant in variable for example variable number_var = number.txt so that number_var = 3242

A: number_var=$(cat number.txt)

A: The backtick is your friend:
[madhatta@risby tmp]$ cat foo
1234
[madhatta@risby tmp]$ fred=`cat foo`
[madhatta@risby tmp]$ echo $fred
1234

You had better be pretty sure the file is a one-liner, though; if you import the whole of /boot/vmlinuz into a shell variable, you may start putting pressure on memory!

A: In Bash, ksh and zsh:
number_var=$(<number.txt)


text:
Q: How do I get gradle incremental native c++ compilation to handle generated headers? I have a header that is generated at build time in a task that I make the compile task depend on, trouble is that the compilation task doesn't recognize when the header is changed in the incremental compilation. So even if the task is run it will not compile the source file.
I would have expected that the generated header should show up as a "Discovered include" and cause the source files to be rebuilt but not so.
Below is the best I have come up with but it does not work.
apply plugin: 'cpp'

model {
  binaries {
    all {
      cppCompiler.args "-I$buildDir/gen"
    }
  }
  components {
    test(NativeExecutableSpec) {
      sources {
        cpp {
          source {
            srcDir "."
            include "*.cpp"
          }
        }
      }
    }
  }
}

task generateHeader(type: Copy) {
  into "$buildDir/gen"
  from(rootProject.file('template.h')) {
    rename(/template/, 'generated')
    expand([text: 'foo'])
  }
}

tasks.all { task ->
  def match = task.name =~ /^compile.*Cpp$/
  if (match) {
    task.dependsOn generateHeader

    task.inputs.files project.fileTree(dir: "$buildDir/gen").matching {
      include '*.h'
    }
  }
}

Sample project: https://github.com/thejk/gradle-incremental-cpp-generated-header

A: Got help on the gradle forum, long story short: create a C(pp)SourceSet with generatedBy tasks.generateHeader and modify generateHeader to export headerDir and sourceDir properties. Link the source set to the real one with lib.
sources {
    headers(CppSourceSet) {
      generatedBy tasks.generateHeader
    }
    cpp {
      source {
        srcDir "."
        include "*.cpp"
      }
      lib sources.headers
    }
}

task generateHeader(type: HeaderGenerator) {
  template rootProject.file('template.h')
  headerDir project.file("$buildDir/gen")
}

class HeaderGenerator extends DefaultTask {
  @InputFile
  File template
  @OutputDirectory
  File headerDir
  @OutputDirectory
  @Optional
  File sourceDir

  @TaskAction
  void generate() {
    project.copy {
      into headerDir
      from(template) {
        rename(/template/, 'generated')
        expand([text: 'foo'])
      }
    }
  }
}


text:
Q: Stored Procedure doesn't show result in SQL Server I have created a stored procedure (to be used in SSRS) that has parameters whose values are more than one. When I execute this stored procedure in SSMS by providing the values for that parameter, SP doesn't return any result. It should return more than 1 rows
 CREATE PROCEDURE [dbo].[sp_tst_CSENG_JulieCapitalHours]
    @StartDate DATETIME ,
    @EndDate DATETIME ,
    @ProjHomeGrp NVARCHAR(MAX) ,
    @ProjHier NVARCHAR(MAX)
AS
    BEGIN

        SELECT  [Capital Project] ,
                [Capital Task] ,
                ResourceName ,
                ProjectName ,
                [Project Home Group] ,
                ActualWork ,
                TimeByDay ,
                ResourceStandardRate ,
                ActualWork * ResourceStandardRate AS Dollars ,
                [Project Hierarchy]
        FROM    [IR.CapOnly]
        WHERE   ( TimeByDay >= @StartDate )
                AND ( [Project Home Group] = ( @ProjHomeGrp ) )
                AND ( TimeByDay <= @EndDate )
                AND ( ActualWork > 0 )
                AND ( [Project Hierarchy] = ( @ProjHier ) )
        ORDER BY ProjectName ,
                ResourceName

    END

You can see that in the where clause, Project Home Group (@ProjHomeGrp) and Project Hierarchy (@ProjHier) are the parameters, whose value when supplied (more than 1) SP returns zero values.
The value that I'm passing are:
Start Date: 1/1/2011
End Date: 12/31/2012
@ProjHomeGrp : PHG1,PHG2,PHG3,PHG4,PHG5,PHG6,PHG7
@ProjHier: PROH1, PROH2, PROH3
Let me know for any questions!

A: You need to split your parameters into rows and use where ... in as a check.
Using a split function like this one your code could look like this.
CREATE PROCEDURE [dbo].[sp_tst_CSENG_JulieCapitalHours]
    @StartDate DATETIME ,
    @EndDate DATETIME ,
    @ProjHomeGrp NVARCHAR(MAX) ,
    @ProjHier NVARCHAR(MAX)
AS
BEGIN

    DECLARE @ProjHomeGrpTbl TABLE (Value NVARCHAR(4))

    INSERT INTO @ProjHomeGrpTbl(Value)
    SELECT LTRIM(RTRIM(s))
    FROM dbo.Split(',', @ProjHomeGrp);

    DECLARE @ProjHierTbl TABLE (Value NVARCHAR(5))

    INSERT INTO @ProjHierTbl(Value)
    SELECT LTRIM(RTRIM(s))
    FROM dbo.Split(',', @ProjHier);

    SELECT  [Capital Project] ,
            [Capital Task] ,
            ResourceName ,
            ProjectName ,
            [Project Home Group] ,
            ActualWork ,
            TimeByDay ,
            ResourceStandardRate ,
            ActualWork * ResourceStandardRate AS Dollars ,
            [Project Hierarchy]
    FROM    [IR.CapOnly]
    WHERE   ( TimeByDay >= @StartDate )
            AND ( [Project Home Group] in (SELECT Value FROM @ProjHomeGrpTbl) )
            AND ( TimeByDay <= @EndDate )
            AND ( ActualWork > 0 )
            AND ( [Project Hierarchy] in (SELECT Value FROM @ProjHierTbl) )
    ORDER BY ProjectName ,
            ResourceName

END


text:
Q: java IllegalStateException when using StackLayoutPanel and StackPanel I'm testing the GWT StackLayoutPanel class with this code
public class MenuView extends StackLayoutPanel {

    interface Binder extends UiBinder<StackLayoutPanel, MenuView> {
    }

    private static final Binder binder = GWT.create(Binder.class);

    @UiField Users users;

    @UiField Configurations configurations;

    public MenuView(Unit unit) {
        super(unit);
        initWidget(binder.createAndBindUi(this));
    }

    @Override
    public int getVisibleIndex() {
        return super.getVisibleIndex();
    }

    @Override
    public Widget getVisibleWidget() {
        return super.getVisibleWidget();
    }
}

————————————————————————

public class Users extends Composite {

    /**
     * Callback when user items are selected.
     */
    public interface Listener {
        void onUserSelected(User user);
    }

    /**
     * Sets the listener that will be notified when an item is selected.
     */
    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @SuppressWarnings("unused")
    private Listener listener;

    interface Binder extends UiBinder<Widget, Users> {
    }

    interface Style extends CssResource {
        String item();
    }

    private static final Binder binder = GWT.create(Binder.class);

    @UiField
    ComplexPanel panel;
    @UiField
    Style style;

    public Users() {
        initWidget(binder.createAndBindUi(this));
    }
}

MenuView.ui.xml File
<ui:UiBinder
  <g:StackLayoutPanel styleName='{style.menuview}' unit='EM'>
    <g:stack>
      <g:header size='3'>

 Users
</g:header>
      <sensport:Users ui:field='users'/>
    </g:stack>
  </g:StackLayoutPanel>
</ui:UiBinder>

user.ui.xml File
<ui:UiBinder>
  <g:FlowPanel styleName='{style.users}' ui:field='panel'/>
</ui:UiBinder>

When I running the test I obtain a java IllegalStateException. Have you on idea of this error ?
java.lang.IllegalStateException: Composite.initWidget() may only be called once.
    at com.google.gwt.user.client.ui.Composite.initWidget(Composite.java:127)
    at com.google.gwt.user.client.ui.ResizeComposite.initWidget(ResizeComposite.java:30)
    at be.lilab.sensport.client.MenuView.<init>(MenuView.java:26)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.build_menuView(Sensport_BinderImpl.java:122)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.get_menuView(Sensport_BinderImpl.java:118)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.build_f_SplitLayoutPanel2(Sensport_BinderImpl.java:106)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.get_f_SplitLayoutPanel2(Sensport_BinderImpl.java:100)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.build_f_DockLayoutPanel1(Sensport_BinderImpl.java:73)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.get_f_DockLayoutPanel1(Sensport_BinderImpl.java:66)
    at be.lilab.sensport.client.Sensport_BinderImpl$Widgets.access$0(Sensport_BinderImpl.java:65)
    at be.lilab.sensport.client.Sensport_BinderImpl.createAndBindUi(Sensport_BinderImpl.java:15)
    at be.lilab.sensport.client.Sensport_BinderImpl.createAndBindUi(Sensport_BinderImpl.java:1)
    at be.lilab.sensport.client.Sensport.onModuleLoad(Sensport.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:411)
    at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:200)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:526)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
    at java.lang.Thread.run(Thread.java:745)

A: You are extending StackLayoutpanel, which extends ResizeComposite.
In the constructor of the StackLayoutPanel, the method initWidget is called.
So, calling it again with:
public MenuView(Unit unit) {
    super(unit);
    initWidget(binder.createAndBindUi(this));
}

will cause the exception. In your case a possible solution will be, to extend Composite.
    public class MenuView extends Composite {

    interface Binder extends UiBinder<StackLayoutPanel, MenuView> {
    }

    private static final Binder binder = GWT.create(Binder.class);

    @UiField Users users;

    @UiField Configurations configurations;

    @UiField StackLayoutPanel panel;

    public MenuView(Unit unit) {
        super(unit);
        initWidget(binder.createAndBindUi(this));
    }

    @Override
    public int getVisibleIndex() {
        return panel.getVisibleIndex();
    }

    @Override
    public Widget getVisibleWidget() {
        return panel.getVisibleWidget();
    }
}

update your MenuViewui.xml:
<ui:UiBinder
  <g:StackLayoutPanel ui:field='panel' styleName='{style.menuview}' unit='EM'>
    <g:stack>
      <g:header size='3'>

 Users
</g:header>
      <sensport:Users ui:field='users'/>
    </g:stack>
  </g:StackLayoutPanel>
</ui:UiBinder>


text:
Q: Why is ThreadAbortException not catched in this code with two processes and output redirection? I have the code following below that is for problem illustration only. Please ignore the part where CodeDom is used to compile the sources. Also in case you try it it leaves the "other process" executable running and consuming CPU time for no good.
The real problem is I start the thread, then abort the thread and see "Thread abort initiated" message and there's

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll

message in the debugger output but neither catch nor finally blocks are invoked and there's no output from those blocks.
Of course because the extra threads created to handle the redirected output are not aborted the program hangs forever, but...
Why are catch and finally not invoked?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace ConsoleApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      new Program().payload();
    }

    private void payload()
    {
      var otherExecutableName = "OtherProcess.exe";
      compileOtherProcessExecutable(otherExecutableName);
      var thread = new System.Threading.Thread(() => threadFunc(otherExecutableName));
      thread.Start();
      Thread.Sleep( 1000 );
      thread.Abort();
      Debug.WriteLine("Thread abort initiated");
    }

    private void threadFunc( String secondExecutableName )
    {
        Process process = null;
        try {
            process = new Process();
            {
                process.StartInfo.FileName = secondExecutableName;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                process.OutputDataReceived += new DataReceivedEventHandler(outputHandler);
                process.ErrorDataReceived += new DataReceivedEventHandler(outputHandler);

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit();
            }
        } catch( Exception e ) {
            Debug.WriteLine( "Catch block: " + e.Message );
        } finally {
            Debug.WriteLine( "Finally block" );
            if( process != null ) {
                process.Kill();
                Debug.WriteLine( "Process killed" );
            }
        }
    }

    static void compileOtherProcessExecutable(string filePath)
    {
        using (var compiler = new CSharpCodeProvider())
        {
            var parameters = new CompilerParameters(null, filePath, true);
            parameters.GenerateExecutable = true;
            var compResult = compiler.CompileAssemblyFromSource( parameters, otherProcessCode);
            var errs = compResult.Errors;
            if (errs.HasErrors)
            {
                var err = errs.Cast<CompilerError>().First();
                throw new InvalidOperationException(String.Format(
                    "Compilation failed. Line {0}: {1}", err.Line, err.ErrorText));
            }
        }
    }

    private void outputHandler(object process, DataReceivedEventArgs output)
    {
    }

    static readonly String otherProcessCode =
        @"class Program {
            public static void Main(string[] args)
            {
                while( true ) {
                }
            }
        }";
  }
}

A: The problem is the WaitForExit call.  This managed call will eventually bottom out in a native frame.  When an Abort call occurs while the thread is in native code nothing will actually happen until the thread returns to managed code.  In this case the thread is waiting for the process to finish and hence won't actually return until you physically kill the process
Note: Even if the exception was thrown the catch block won't actually catch it.  The exception will be rethrown at the end of the block.  You need to catch it and call the ResetAbort method

A: You can read here:

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread.

But also, I think you should wrap the whole method inside the try.
Or, do you think your external process could have finished before the call to abort and hence the method with the catch, the one called threadFunc, is no longer executing?


text:
Q: RequireJS dependency not defined I am trying to load a util.js file that I've created in a separate utils folder into my Backbone application, but no matter what configuration I use for RequireJS, the file is loaded by Require (as I can see it in the dev tools as loaded), but is always undefined in the view itself.  As far as I can tell I seem to have defined the file correctly and have tried all different combinations of RequireJS configuration - defining the path in the paths var, defining paths and a shim that exports the name, not defining it in the require config at all but just declaring the path directly in the view define, but it is always undefined.
My folder structure is:

js
 - views
 - controllers
 (etc)
 - utils
   - util.js

The file I'm trying to load is this:
util.js

define(function() {
    return {
        showMessage: function() {
            console.log('show message');
        }
    };
});

And like I said I've tried all kinds of Require configs.  For example, currently I have:

require.config({
    paths : {
        underscore : 'lib/lodash',
        backbone   : 'lib/backbone-1.0.0',
        marionette : 'lib/backbone.marionette-1.1.0',
        jquery     : 'lib/jquery-2.0.3.min',
        //jquery     : 'lib/jquery-2.0.3',
        tpl        : 'lib/tpl',
        pnotify    : 'lib/jquery.pnotify',
        utils      : 'utils/util'
    },
    shim : {
        'lib/backbone-localStorage' : ['backbone'],
        underscore: {
            exports: '_'
        },
        backbone: {
            exports: 'Backbone',
            deps: ['jquery','underscore']
        },
        marionette: {
            exports: 'Backbone.Marionette',
            deps: ['jquery', 'underscore', 'backbone']
        },
        pnotify: ['jquery'],
        utils: {
            exports: 'utils'
        }
    }
});

require(['app'],function(app){
    app.start();
});

And in the calling view I have (modified to just show utils import):

define([
    'utils'
], function (utils) {
    "use strict";
return Marionette.Controller.extend({
    initialize: function() {
        console.log(utils); // undefined
    }
});

});

All of my other backbone code (views, models, collections, etc) load fine but I just can't get this file to load.  What am I missing here?

A: you shouldn't need the shim definition. The path declaration should cover your use case.
The shim that you defined tells requirejs that it should look for a global named 'utils' to provide to any module that lists utils/util.js as a dependency. Since you are using requirejs syntax in your utils/util.js and not creating a global, the shim should not be necessary.


text:
Q: SyntaxError: Unexpected identifier in module.exports What is the problem in the following code that causes the error?
Should I write let or function keyword before writing function?

module.exports = {
    postLogin=(req, res, next) => {
        const { mobile, password } = req.body;
        User.findByCredentials(mobile, password).then((user) => {
            return user.generateAuthToken().then((token) => {
                res.header('x-auth', token).send(user);
            });
        }).catch((e) => {
            res.status(400).send();
        });
    }
    getMe=(req, res, next) => {
        res.send(req.user);
    }
    getLogout=(req, res, next) => {
        req.user.removeToken(req.token).then(() => {
            res.status(200).send();
        }, () => {
            res.status(400).send();
        });
    }
}

A: The right one will be:
module.exports = {
postLogin: (req, res, next) => {
    const { mobile, password } = req.body;
    User.findByCredentials(mobile, password).then((user) => {
        return user.generateAuthToken().then((token) => {
            res.header('x-auth', token).send(user);
        });
    }).catch((e) => {
        res.status(400).send();
    });
},
getMe: (req, res, next) => {
    res.send(req.user);
},
getLogout: (req, res, next) => {
    req.user.removeToken(req.token).then(() => {
        res.status(200).send();
    }, () => {
        res.status(400).send();
    });
} }


text:
Q: Getting information form json encode main.html
<!DOCTYPE html>

    <title></title>

            <button onclick="cart(0)"> hi </button>

jsfile.js
function cart(id1)
{

    var id=id1;
    //alert("enterd "+id);
    document.getElementById("disp").innerHTML ="hi";
    if (window.jQuery) {
    // jQuery is available.

    // Print the jQuery version, e.g. "1.0.0":
    //alert(window.jQuery.fn.jquery);
}
        $.ajax({
        url:"add.php ",
        type:"POST",

        data:{
          item_id: id,
        },
        success:function(response) {

         document.getElementById("disp").innerHTML =response.value1;
       },
       error:function(){
        alert("error");
       }

      });

}

add.php
<?php
    if(isset($_POST['item_id'])){
    //if(count($_POST)>0)
        echo json_encode(array("value1" => "hello", "value2" => "hi"));

    }
?>

am collection the informaton from add.php to jsfile.js ... I am not able to get information from the json array.. I am trying to get information by respnse.value1. But it returns me undefined.. what might be the error??

A: You'll have to parse the JSON before using it. Change your success function to this -
success:function(response) {
     var res = JSON.parse(response);
     document.getElementById("disp").innerHTML = res.value1;
},


text:
Q: Did Leia know that Luke wasn't really there? In The Last Jedi as the Resistance was facing their end with The Last Order having blown open the doors to the Resistance Base and not receiving any replies for help, Luke appears and comforts Leia giving her a set of Golden Dice from the Falcon (assuming Han's).
After Kylo Ren fails to kill Luke with a barrage of blaster fire he and Luke fight and at the end Ren realizes that he was fighting a Force Projection and Luke was never on Crait but still at Ahch-To.
During the fight we see that unlike Ren, the Skimmers or energy blasts that hit the ground, Luke was not disturbing the dried white salt on the surface and though out the fight Luke never uses his Lightsaber1 instead dodges everything, this would suggest that a Force Projection have no solid presence and if their lightsabers connected Ren would realize that the fight was fruitless (for him).
Back to the Resistance Base i recall Luke holding Leia's hands when they were sitting down. So my question is, Did Leia know that Luke wasn't real when he was at the Resistance base?

1: in the video linked above around 15-17 second in it it's hard to see if Luke's Lightsaber connected with Ren's but i'm of the belief that if it did, Luke's movements obscured Ren's sight of the Lightsaber going right through Luke's

A: There's no direct canon answer yet (may be future novelization will say).
But the evidence in the film says "likely, no":

*

*If she knew, she'd know 100% he was buying them time. Yet, it took Poe to point that out, well after Leia should have if she had known.

*When leaving, she wistfully looked back at Luke (before wryly telling everyone to follow Poe). If she knew he was a Force Projection she would not have

*The Dice felt real to Kylo when he picked them up, so would have felt real to Leia. So, Luke can control his projection to be solid.

*She didn't look like she faked the touch.
Now, what I want to know is, why did Luke winked at C3PO as he walked by. Like C3P0 was in on the joke (having sensors, probably he was)

A: According to the film's official novelisation, Leia recognises what Luke is from his touch (or rather his lack of touch).

"No one's ever really gone," he said quietly, leaning forward to kiss
  her on the forehead as he took her hands in his.
When they touched, she immediately understood. A slight smile played
  at the corners of her mouth, and her eyes shone with the secret the
  two of them now shared.

A: Yes. Leia knows he isn't really there
According to a interview with Entertainment Weekly, it is confirmed that when Luke hands Leia Han's dice, she gives him a glance and "that is when she knows" that he isn't really there:

Those watching the film for the first time will likely miss this (they're supposed to), but Fisher also delivers a subtle, revealing glance during their interaction when Luke reaches out and hands her the pair of Han Solo's golden dice that were hanging inside the Millennium Falcon.
Her expression is not grief, but shock. And it's not about receiving this memento.
"That's when she knows," Hamill says.
Her brother isn't really there. And yet he is.

A: There is a reason to think the answer is:
Yes
When Luke first appeared, they went up into the control room and sat and talked. At this point, she had no reason to think it wasn't actually Luke. Then he reaches out and "takes her hand" and puts the dice in it. At that point she has a visible startled reaction. In my second viewing, I interpreted this as showing she knew she wasn't actually feeling anything at the time, that Luke was just a projection.
On my second viewing I read that reaction as a clear indication that she knows he is a projection. One argument against my view is that when Rey and Kylo "touch" via projection, it seems like they are making physical contact, or at least getting physical feedback from the touch. So it may be that you can "feel" a force projection and so Leia had her expression for a different reason.

A: TLDR

*

*She may have thought he was there at first, but only before thinking about it.

*Once he handed her the dice that would have been the giveaway he wasn't.

*How did Luke know that was where they were all headed for their last stand?

*Crait was not their final destination.

*And why did Luke have the dice to begin with?

So I think the biggest give away in this instance is that Luke was there. How did he know that that was where the rebels had chosen to go for their last stand. Luke had cut himself off from everyone in his self driven exile. He had no contact with the outside world, other than possibly using the force.
However, we are told that he had cut himself off from the Force prior to Rey showing up and we are expected to believe that up until he is confronted by Rey to that very point he has still been cut off from the Force entirely.
In addition, Crait (the planet of the last stand), was not their final destination. I can not think of a single case in ANY sci-fi series where you FTL to your destination, but then have to travel such a distance that your ships begin to run out of fuel before you get where you are trying to go... The plan was to jump away from the First Order, possibly to their new home base, but after completing the jump they traveled in a straight line long enough for their fuel reserves to run out and Crait just happened to be along that path. (I also like to think that it was at least a semi straight line or the First Order would have been smart enough to notice they were circling the planet Crait, thus giving away the destination, if it actually was where they were going.)
So the decision to go to that planet was an after thought, given the situation. Until they landed on the planet and sent out the request for aid no one had been contacted about their current location. And unless Luke pulled up his X-Wing to turn on the radio he had no way to hear that distress call.
Therefore, I believe it is safe to assume Luke only knew the location after finally reconnecting to the Force and reaching out to find Leia.
After first seeing Luke approaching her it is possible that Leia believed Luke was really there, but it is doubtful. Given his isolation and lack of communication the odds of him figuring out the rebels plan in such a short time (and Poe's lack of connecting the dots) and also flying all the way there, landing unseen and undetected, at the secret back door that she herself did not know about (or she would have spoken up sooner about it), and Luke telling everybody about the back door escape possiblility... that is very doubtful.
Luke was not there to facilitate the escape through the back door, he did not know it was there. He was there to buy time as best as he could hoping that the Force would provide another way or that someone would show up to help.
For the dice, we do not know if they had weight or any solidity to them. Hopefully a novelization will reveal that in the future; but it does not really matter. The question is Why did Luke have the dice to begin with? Luke had no reason to actually have them. They were Han's. Luke handing Leia something he shouldn't have was a clear indication that something was up. Luke couldn't have those dice and since that was a lie that likely would have been the point where she notice his being there was a lie as well.
He fabricated the dice as a non-verbal communication between himself and Leia, something only the two of them would understand. The dice were meant to represent Luke's sorrow for the loss of Han. That was it. They were just a symbol of Han that Leia would understand as unspoken sympathy given her recent loss.
And to the point of the dice being both held and picked up, I do no think that reveals much. For Luke to project himself across the universe he could have floated around the planet like a ghost... a Force Ghost to be exact... but he didn't. He simulated walking and everything else. It was all a show that he mentally built. He had to consciously think about "Ok, step here, this is a step down..." and simulate it all as if he was actually there... Given that shortly after their meeting Leia was out of that room and the dice were set down, it was likely a simple feat to 'leave the dice there' for Luke while he was fighting Kylo.


text:
Q: How To Use Controller For Novay WordTemplate Laravel? In Laravel I use Novay WordTemplate to generate a generated word template.
I took the code from github https://github.com/novay/laravel-word-template.
But I have a problem when I want to move the function to the Controller.
I move in the following way:
On my Route fill like this:
Route::get('/word', [WordController::class, 'word'])->name('word');

Then in the controller I made it like this:
<?php

namespace App\Http\Controllers;

use Novay\WordTemplate\Facade;

class WordController extends Controller
{
    public function word()
    {
        $file = public_path('surat_pernyataan.rtf');

        $array = array(
            '[NOMOR_SURAT]' => '015/BT/SK/V/2017',
            '[PERUSAHAAN]' => 'Bea Cukai Bekasi',
            '[NAMA]' => 'Melani Malik',
            '[NIP]' => '6472065508XXXX',
            '[ALAMAT]' => 'Jl. Manunggal Gg. 8 Loa Bakung, Samarinda',
            '[PERMOHONAN]' => 'Permohonan pengurusan pembuatan NPWP',
            '[KOTA]' => 'Samarinda',
            '[DIRECTOR]' => 'Noviyanto Rahmadi',
            '[TANGGAL]' => date('d F Y'),
        );

        $nama_file = 'surat-keterangan-kerja.doc';

        return WordTemplate::export($file, $array, $nama_file);
    }
}

But got error : Class "App\Http\Controllers\WordTemplate" not found. Please help me solve


text:
Q: Как сделать цикл от 0001 до 239000 Есть номера бланков от ЕН0001 До ЕН259899. Как реализовать цикл так, чтобы в 0001 нули не исчезали? Там может быть от 4 до 5 нулей.

A: Чтобы дополнить строку нуля в начале - можно использовать str_pad.
Например:
echo str_pad(1, 10, '0', STR_PAD_LEFT);  // 0000000001

дополнит строку 10-ю нулями перед цифрой 1

Зная это, можно организовывать просто цикл от 1, дополняя нулями впереди по необходимому количеству

для JS есть аналог:
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

A: Как уже сказал @teran, цикл вам не поможет, нужно форматировать вывод значения.

Относительно javascript
Есть встроенная функция .padStart() | поддержка.

console.log('1'.padStart(4, 0));
console.log('14'.padStart(4, 0));
console.log('321'.padStart(4, 0));
console.log('1232'.padStart(4, 0));

Ну или самопал:

function func(num, len) {
  return num >= 10**len ? num : (10**len + num+'').substr(1);
}

console.log(func(1, 4));
console.log(func(14, 4));
console.log(func(321, 4));
console.log(func(1232, 4));

В первый параметр передаётся число которое нужно форматировать, во второй длину строчки, например func(1, 2) - 01, func(134, 5) - 00134 и т.п.


text:
Q: How to save UIWebView font size? I know that I can increase/decrease font size, by using -webkit-text-size-adjust, but I ran into problem with saving this font size into NSUserDefaults, because -webkit-text-size-adjust can only use percents.
For example. My font-size is 100%, I increase it to 110% and save it in NSUserDefaults. Next time when I want to increase it to 115% it will be much bigger than if I have increased 100% to 115%, and this happens because 1,1 * 1,15 != 1,0 * 1,15. I've tried to fix it so this equality became true, but then I found out that after I have saved it and opened WebView, fontSize would be different.
UPDATE:
1) First time font-size:110%

2)Let's increase font-size to 125%

3)We have saved font-size:125% in NSUserDefaults. Let's restart application. So the first font-size will be 125%

As you can see the font sizes are different. I can provide more screenshots with more strange behaviors, like when you hit decrease font-size from it's actually is getting bigger, but I thing now you understand my problem more accurately.


text:
Q: What does this scene represent? In the seventh episode of Arcane, we see a fight between

Ekko and Jinx

Since the fight is primarily conducted in a more cartoonish style, certain elements are hard to make sense of. We see a young, stylized version of Ekko moving toward Jinx (looking like Powder) while she fires paintballs at him, until one makes contact with his chest plate. Then everything reverses and moves backwards, and we see the full, CGI fight. Ekko does not appear to have taken the shot, and he dodges his way toward Jinx and knocks her down.
Does this sequence represent what actually happened in the fight scene? Is it Ekko predicting the results of the fight with his intellect? (If so, his predictions of where she would fire were extraordinarily precise). Or does he actually have some sort of temporal power?

A: I don't think I adequately back this up with source material as I don't think this is explained within the remainder of the show...BUT
Powder(Jinx) and Ekko are previously shown to be friends when they were much younger, and it isn't much of a stretch to assume that they played together. We also know from episode 3(?) that Powder had a paintball gun when she was younger. So the way I interpret this scene is that Ekko was remembering when he played with Powder when they were younger, and that the challenge was for him to reach her with his fake sword before his timer ran out and/or he got hit with a paintball. In the flashback he fails and gets hit.
In the present, because of this learned experience, he can anticipate Jinx and therefore dodge her attacks and close to melee range.
As an aside, in the Lore, Ekko does have power over time with his Z-Drive (which allows him to rewind time), although we don't see this in season 1. I guess this is a bit of an easter egg scene for fans.

A: According to this tweet by a writer of the show,
the scene was portraying Ekko's mental thought processes, not a particular temporal power:

He was imagining the moves in his head and remembering his past "fights" with Powder as they [sic] way he was able to anticipate what she would do and beat her.

This is also close to what was speculated in the other answer
.
That said, while this answer is undoubtedly canonical, it feels slightly peculiar. In his pre-battle mental simulation, Ekko's guesses as to when and where Jinx would fire were almost exactly on target, down to the number of shots, the intervals between them (adjusted for the slow motion), and their rough location relative to where he was when each shot was fired.
And indeed, to dodge four bullets, given the speed that they move at and the fact that Jinx can also adjust her shots based on where he is, he would have to almost know exactly where the bullets would be. Unless Jinx, who is notoriously chaotic, always fires in the exact same pattern that she did when she was a child, Ekko looks less like he is good at predicting how people will fight and more like he can literally see the future. The fact that the rewind effect is a dead match for his temporal powers from the games does not help dispel this impression.


text:
Q: Map superclass and subclass to different tables in Hibernate I want to map a class to a table and a subclass to another table. I'm not sure if you can do this in a proper way. I tried this so far:
@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "MyTable1")
public class MyClass

@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "MyTable2")
public class MySubclass extends MyClass

It works but in the generated SQL both tables are joined and I want to keep them seperated.
Another approach was to use the same as above but change JOINED to TABLE_PER_CLASS. This does not work because there is a UNION ALL on both tables in the SQL when I query MyClass.
I also tried to use @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT) and @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.IMPLICIT) but with no effect.
So my question is if there is a way to map this in Hibernate. Any suggestions?
Thanks!

Using Hibernate 3.6.1

A: It seems you want to consider the two entities as completely unrelated, except for the fields they have in common. It's not really an inheritance relationship since when you search for a MyClass, you don't want MySubclass instances to be found, although MySubClass instances are instances of MyClass in your design.
The best solution is thus probably to use a MappedSuperclass (see chapter 2.2.4.4) which contains the common fields and methods, and to create two completely separate entities which extend this mapped super class.

A: TABLE_PER_CLASS should do what you want.
Note that when you execute a query like from MyClass m, Hibernate loads all objects of class MyClass, including subclasses, hence the UNION ALL clause. If you need only MyClass without subclasses, you need to use the following query: from MyClass m where m.class = MyClass.


text:
Q: Render a partial view in Express 4.x framework using Express-Handlebars view engine I'm trying to create a nodejs app using Express framework with express-handlebars as the view engine but got stuck with below error when trying to view the home page:
Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed [object Object]
can anyone let me know whats going wrong here.
link to github repo: https://github.com/bdinesh/LearningNode.git
Below is code that I'm trying to run:
index.js
var express = require('express'),
    app = express(),
    hbs = require('express-handlebars'),
    // Create `ExpressHandlebars` instance with a default layout.
    hbsInstance = hbs.create({
        defaultLayout: 'main', extname: '.hbs'
    }),
    fortune = require('./lib/fortune.js'),
    weatherData = require('./lib/weather.js');

app.engine('hbs', hbsInstance.engine);
app.set('view engine', 'hbs');
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/public'));

app.use(function(req, res, next) {
    if (!res.locals.partials) {
        res.locals.partials = {};
    }

    res.locals.partials.weather = weatherData.getWeatherData();
    next();
});

app.get('/', function(req, res) {
    res.render('home');
});

app.listen(app.get('port'), function() {
    console.log('Express started on http://localhost:' + app.get('port'));
});

weather.js this is placed in lib folder
exports.getWeatherData = function getWeatherData() {
    return {
        locations: [
            {
                name: 'Portland',
                forecastUrl: 'http://www.wunderground.com/US/OR/Portland.html',
                iconUrl: 'http://icons-ak.wxug.com/i/c/k/cloudy.gif',
                weather: 'Overcast',
                temp: '54.1 F (12.3 C)',
            },
            {
                name: 'Bend',
                forecastUrl: 'http://www.wunderground.com/US/OR/Bend.html',
                iconUrl: 'http://icons-ak.wxug.com/i/c/k/partlycloudy.gif',
                weather: 'Partly Cloudy',
                temp: '55.0 F (12.8 C)',
            },
            {
                name: 'Manzanita',
                forecastUrl: 'http://www.wunderground.com/US/OR/Manzanita.html',
                iconUrl: 'http://icons-ak.wxug.com/i/c/k/rain.gif',
                weather: 'Light Rain',
                temp: '55.0 F (12.8 C)',
            },
        ],
    };
};

weather.hbs (Partial view) this is placed in views/partials folder.

    {{#each partials.weather.locations}}

{{name}}

            {{weather}}, {{temp}}

    {{/each}}
    Source: Weather Underground

home.hbs placed in views folder

Welcome to Meadowlark travel

{{> weather}}

A: Please change your code as follows:

{{#each partials.weatherData.locations}}

{{name}}

        {{weather}}, {{temp}}

{{/each}}
Source: Weather Underground

There are unfortunately some outdated parts and mistakes in amazing Web Development with Node and Express.
Please refer here for errata: http://www.oreilly.com/catalog/errata.csp?isbn=0636920032977
And here for the problem you have: https://github.com/EthanRBrown/web-development-with-node-and-express/issues/28


text:
Q: Ransack Searching Full Name with White Spaces I have a user model with the fields
:first_name
:last_name

I wanna a single search box that says full_name where the user can search for
John Doe

in my user.rb
ransacker :full_name do |parent|
  Arel::Nodes::NamedFunction.new('concat_ws', [' ',    parent.table[:first_name], parent.table[:last_name]])
end

in my views i have
= f.text_field :full_name_cont, placeholder: 'full name'

however when a user creates a name with a space in front of it
 first_name: 'John'
 last_name: ' Doe'

and i search for
 'John Doe'
 - no results

but if i search for
  'John  Doe' (two spaces in between)
   - 'John Doe'

How can i prevent this from happening
I know ideally i would want to sanitize the data before creating by stripping white spaces....but what would be the most unobtrusive way of getting around this bug.
Thanks


text:
Q: findViewById() returns null for a view found by getChildAt() I'm making some modifications to the AOSP SystemUI app, and have run into a very particular problem when trying to run it on an arbitrary device: findViewById() returns null, while navigating through the its children reveals that it's really there.
I'm working with this AOSP source code and building it through lunch full-eng and make. It compiles fine, but SystemUI crashes with the IllegalArgumentException in the logic following line 337:
mRecentsContainer = (ViewGroup) findViewById(R.id.recents_container);
[...]
if (mRecentsContainer instanceof RecentsHorizontalScrollView){
    [...]
} else if (mRecentsContainer instanceof RecentsVerticalScrollView){
    [...]
}
else {
    throw new IllegalArgumentException("missing Recents[Horizontal]ScrollView");
}

A bit of debugging reveals that mRecentsContainer is in fact null.
I considered that perhaps a layout was being inflated that didn't contain that particular view, so to check, I navigated recursively through all the view's children using getChildCount() and getChildAt(). That wasn't the case; @id/recents_container was right there, two levels deep:
> @id/recents_root (7f0e0070) [RecentsPanelView]: (2 children)
--> @id/recents_bg_protect (7f0e0071) [FrameLayout]: (2 children)
----> @id/recents_container (7f0e0072) [RecentsVerticalScrollView]: (1 children)
------> @id/recents_linear_layout (7f0e0073) [LinearLayout]: (0 children)
----> @id/recents_no_apps (7f0e0074) [FrameLayout]: (1 children)
------> [unnamed] (ffffffff) [TextView]
--> @id/recents_dismiss_button (7f0e0075) [View]

A singular hint appears in Logcat from system_process when installing the app:

12-11 22:38:01.090: W/ResourceType(165): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)

Inspecting R.java in the SystemUI_intermediates directory reveals that it points to a seemingly unrelated status_bar_recents_app_label_color, which is simply a defined color in res/values/color.xml.
What can be causing this? Is the layout not inflating correctly because I'm running it on a device I didn't compile against? I considered that perhaps the problem may be SystemUI's references to internal Android resources, which might not map correctly to those on my device. Is that possible?

A: Evidently some generated files were sticking around.
Rebuilding the source from scratch through make clean resolved it.
Alternatively, I've figured out that deleting the following intermediate directories makes for a faster build, but am not 100% sure that this covers all directories:
rm -rf out/target/product/generic/obj/APPS/SystemUI_intermediates/
rm -rf out/target/common/R/com/android/systemui
rm -rf out/target/product/generic/obj/APPS/framework-res_intermediates/
rm -f /out/target/common/R/com/android/internal/R.java
rm -rf out/target/product/generic/obj/PACKAGING/
rm -f out/target/product/generic/system/app/SystemUI.apk


text:
Q: TypeError: Cannot read property 'title' of undefined. Vue.js Making a hackernews clone using the axios API. Data is not passed to the NewItem.vue component. Returns an error — TypeError: Cannot read property 'title' of undefined. Tell me what's wrong with the code. Why is data not transmitted? Can the problem be in props?
NewItem.vue:
<template>

        {{ story.title }}

</template>

Home.vue:
<template>

        1/23

            <news-item v-for="story in stories" :key="story.id">
            </news-item>

</template>

A: You are not passing the prop from the parent to the child component, to do this:
<news-item v-for="story in stories" :key="story.id" :story="story"></news-item>


text:
Q: Login error user not activated I use joomla 1.5.25 had some registered users and admins on the site. a few days ago I put new user registration activation to YES and have jwlogin module as login to front end.
The problem is now Admins can't login to backend error message: administrator/index.php?option=com_jwuser&view=error&error=User%20is%20not%20activated
How do I activate Super Admin? Is this possible in MySQL database?
Neither front or backend logins are working.

A: That should have affected existing users at all. Turning activation one means that the user must click the activation link in the email before their account is active. When it is off, accounts are automatically activated when they are created.
You can look in jos_users table at the block and activation fields. Block should be 0 and activation should be empty.


text:
Q: How can I run this stored procedure with options? CREATE TABLE Docente
(
    opcion varchar2(10),
    id_Docente NUMBER,
    nombre VARCHAR2(30),
    apellido VARCHAR2(30),
    cedula NUMBER,
    titulo VARCHAR2(100),
    observaciones VARCHAR2(200),
    estado VARCHAR2(10),
    mensaje varchar2(50) NULL,
    CONSTRAINT PK_Docente PRIMARY KEY (id_Docente)
);

CREATE OR REPLACE PROCEDURE sp_crud_docente(
p_opcion    varchar2,
p_id_Docente NUMBER,
p_nombre VARCHAR2,
p_apellido VARCHAR2,
p_cedula NUMBER,
p_titulo VARCHAR2,
p_observaciones VARCHAR2,
p_estado VARCHAR2,
p_mensaje out varchar2)
as
v_valor int;
v_row Docente%rowtype;
    begin
        if (p_opcion = 'I') then
              begin
             Select  MAX(id_Docente)+ 1  into v_valor from Docente;
            if v_valor is null then
            v_valor := 1;
              p_mensaje:= 'Registro inserted...';
             DBMS_OUTPUT.PUT_LINE(p_mensaje);
            insert into Docente
            values (p_opcion,v_valor,p_id_Docente,p_nombre,p_apellido,p_cedula,p_titulo,p_observaciones,p_estado);
        end if;
        end;

          else if (p_opcion = 'U') then

            update Docente set  opcion=p_opcion,
                                id_Docente=p_id_Docente,
                                nombre=p_nombre,
                                apellido=p_apellido,
                                cedula=p_cedula,
                                titulo=p_titulo,
                                observaciones=p_observaciones,
                                estado=p_estado
                           where id_Docente=p_id_Docente;
             p_mensaje:= 'Registro updated...';
               DBMS_OUTPUT.PUT_LINE(p_mensaje);
          else if (p_opcion = 'S') then
           begin
            Select
            opcion,
            id_Docente,
            nombre,
            apellido,
            cedula,
            titulo,
            observaciones,
            estado,
            mensaje
            into v_row
            from Docente;
        p_mensaje := ('Ok');

DBMS_OUTPUT.PUT_LINE(p_mensaje||' --> '||v_row.opcion||'|'||v_row.id_Docente||'|'||v_row.nombre||'|'||v_row.apellido||'|'||v_row.cedula||'|'||v_row.titulo||'|'||v_row.observaciones||'|'||v_row.estado||'|'||v_row.mensaje);
         end;

             else if (p_opcion = 'D') then

                Delete from Docente where id_Docente=p_id_Docente;

                    p_mensaje := ('Proceso ejecutado correctamente');

    DBMS_OUTPUT.PUT_LINE(p_mensaje);
    commit;

          end if;
           end if;
           end if;
            end if;

         EXCEPTION
           WHEN OTHERS then
           p_mensaje := ('ERROR. No se pudo ejecutar el proceso');
           rollback;
          end;

A: Take out the length of the incoming parameters:
create or replace procedure sp_crud_docente (
p_opcion    varchar2,
p_id_Docente NUMBER,
p_nombre VARCHAR2,
p_apellido VARCHAR2,
p_cedula NUMBER,
p_titulo VARCHAR2,
p_observaciones VARCHAR2,
p_estado VARCHAR2,
p_mensaje out varchar2)

See 8.7.1 Formal and Actual Subprogram Parameters section of the 19c manual "Database PL/SQL Language Reference"
Bobby

A: Apart from the fact that varchar2 parameters can't have size, this is practically unsolvable without you posting the docente table description.
Bad habits kick; you're wrongly relying on the fact that you know what you're doing, but it turns out you don't.
I can't figure out how many nor which columns docente contains, and in which order.
insert into docente should explicitly mention all columns you're inserting into, one-by-one. Code you wrote suggests that table contains 9 columns (opcion, id_docente, nombre, apellido, cedula, titulo, observaciones, estado).
update, on the other hand, updates only 6 of them (nombre, apellido, cedula, tutlo, observaciones, estado) which doesn't collide with insert; it is OK if you don't update all columns.
However, p_opcion = 'S' selects only 7 columns into v_row which is declared as docente%rowtype. Out of those 7 columns, I believe you "forgot" a comma between id_docente and nombre - those are two columns, it's not that nombre is id_docente's alias, right? Suppose it is 8 columns that are selected after all. Now, that collides with number of columns you used in insert (9 of them). If you're selecting into %rowtype, you must select ALL columns in EXACT ORDER.
I suggest you review code you wrote, pay attention about what I said and fix those errors.


text: Q: Equivalent of mvn install:install-file in sbt land ? I can install locally build jar with mvn install:install-file command. I'm trying to move to sbt for as many of my projects as possible and therefore looking for a way to achieve this in sbt. Any ideas how this can be done with sbt ?


text:
Q: Place Drawable on Imageview using PorterDuff.Mode.SRC_ATOP I have an ImageView:
ImageView imageView = findViewById(R.id.imageView);

I would like to achieve something like this (Atop figure)

drawable1 is the original ImageView image, drawable2 is the one I want to place over it:
Drawable drawable1 =  AppCompatResources.getDrawable(context, drawable1);
Drawable drawable2 = AppCompatResources.getDrawable(context, drawable2);

LD layerDrawable = new LD(new Drawable[]{
       drawable1,
       drawable2,
});
imageView.setImageDrawable(layerDrawable);

LD class:
public class LD extends LayerDrawable
{
    private Paint p = new Paint();

    public LD(Drawable[] layers) {
        super(layers);
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        int count = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG);

        for (int i = 0, numberOfLayers = getNumberOfLayers(); i < numberOfLayers; ++i) {
            this.getDrawable(i).draw(canvas);
            canvas.saveLayer(null, p, Canvas.ALL_SAVE_FLAG);
        }
        canvas.restoreToCount(count);

    }
}

However this doesn't work, because the image I place over (drawable2) is placed over the whole imageView, not just over the non-transparent contents of the drawable1 image.
How do I achieve Atop figure (placing drawable2 only over the 'filled content' of drawable1)?
Edit:
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
canvas.drawBitmap(bitmap1, 0, 0, null);
canvas.drawBitmap(bitmap2, 0, 0, p);


text:
Q: EntityFieldQuery throws an error while using fieldCondition and addTag('node_access') I use Drupal 7.
This code:
$query = new EntityFieldQuery();
$resFirstName = $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'user')
            ->fieldCondition('field_user_first_name', 'value', $str, 'RLIKE')
            ->range(0, 15)
            ->addTag('node_access')
            ->execute();

when site's user isn't Admin throws the following error:
"PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_user_first_name0.nid' in 'where clause': SELECT field_data_field_user_first_name0.entity_type AS entity_type, ..."
If I remove ->fieldCondition('field_user_first_name', 'value', $str, 'RLIKE') or ->addTag('node_access') - no error.
Thanks

A: I had a somewhat similar case. I was able to solve it modifying the fieldCondition like this while retaining all other conditions and parameters:
  ->fieldCondition('field_user', 'first_name', $str, 'RLIKE')

A: I ran into a similar issue.
I has node_access tag added to a query, I could not remove it since other
modules relied on it to influence site queries globally.
I had to add a fieldCondition, so in my case the solution was
$query->addMetadata('account', user_load(1));
https://www.drupal.org/node/997394#comment-5096664


text:
Q: Как изменить отображение объектов не меня их во vue таблице? У меня есть условная таблица во vue (+vuetify). Как изменить вывод значений sogl: "null, true false" на "пусто, да, нет". Изменить именно отображение объектов в таблице? Данные объекты приходят с сервера.
  <v-data-table
    :headers="headers"
    :items="tableOne.memb"
    :items-per-page="5"
    item-key="id"
    class="elevation-1"
  >
  </v-data-table>

Массив с сервера
[ { "id": "1", "info": { "ban": "track", "numbers": "3223", "sogl": true }},
{ "id": "2", "info": { "ban": "track", "numbers": "12312", "sogl": true }} ,
{ "id": "3", "info": { "ban": "track", "numbers": "455", "sogl": null}} ,
{ "id": "4", "info": { "ban": "track", "numbers": "423", "sogl": true }}]

Скрипт

A: Необходимо использовать v-slot:item="props".

const app = new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      tableRowsSelected: [],
      headers: [{
          text: 'Номер',
          align: 'center',
          sortable: false,
          value: 'id',
        },
        {
          text: 'Блок',
          value: 'info.ban'
        },
        {
          text: 'Номер',
          value: 'info.numbers'
        },
        {
          text: 'Согласие',
          value: 'info.sogl'
        },
      ],
      items: [{
          "id": "1",
          "info": {
            "ban": "track",
            "numbers": "3223",
            "sogl": false
          }
        },
        {
          "id": "2",
          "info": {
            "ban": "track",
            "numbers": "12312",
            "sogl": true
          }
        },
        {
          "id": "3",
          "info": {
            "ban": "track",
            "numbers": "455",
            "sogl": null
          }
        },
        {
          "id": "4",
          "info": {
            "ban": "track",
            "numbers": "423",
            "sogl": true
          }
        }
      ]
    }
  },
  methods:{
    convertSogl(val) {
      if (val) {
        return 'Да';
      } else if (val === false) {
        return 'Нет';
      } else {
        return 'Пусто';
      }
    }
  },
})
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

  <template>
    <v-data-table
      :headers="headers"
      :items="items"
      :items-per-page="5"
      item-key="id"
      class="elevation-1"
    >
      <template
        v-slot:item="props"
      >

          {{ props.item.id }}
          {{ props.item.info.ban }}
          {{ props.item.info.numbers }}
          {{ convertSogl(props.item.info.sogl) }}

      </template>
    </v-data-table>
  </template>


text:
Q: XMLNS attribute removed by Slow Cheetah transformation I'm trying to use Slow Cheetah to transform a Windows scheduled task config file.  I'm simply trying to add "repetition" node information, like so:
ORIGINAL:
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2013-01-02T09:32:12.2196371</Date>
    <Author>xxx</Author>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2013-01-10T01:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
.....
</Task>

REQUIRED, ADDITIONAL XML
<CalendarTrigger>
   <Repetition>
     <Interval>PT300S</Interval>
   </Repetition>
</CalendarTrigger>

To do this, I have the following transformation file:
<?xml version="1.0" encoding="utf-16" ?>
<Task version="1.2">
  <Triggers>
    <CalendarTrigger xdt:Transform="Insert">
      <Repetition>
        <Interval>PT300S</Interval>
      </Repetition>
    </CalendarTrigger>
  </Triggers>
</Task>

The problem I'm having is that all attributes outside of the CalendarTrigger node are removed (and therefore making the resultant transformation config an invalid scheduled task format).
I have tried adding
xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xdt:Transform="SetAttributes" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"

to the Task node, but the attribute is then generated at CalendarTrigger level (and I cannot put this attribute on the original, because I then get "No element in the source document matches '/Task/Triggers' ").
Any pointers?
UPDATE:
The problem seems to be isolated to the xmlns attribute; if I try to include this in the 'Task' node of the original, I get "No element in the source document matches '/Task/Triggers'" - BUT changing this attribute to 'xmlns2' works fine and produces exactly what I need (albeit with an 'xmlns2' attribute!).  Is this a known limitation of Slow Cheetah?  Anyone know of a potential work-around?

A: That's because your xdt:Transform="Insert" is one level to high.
This should work:
<?xml version="1.0" encoding="utf-16" ?>
<Task xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
    <Triggers>
      <CalendarTrigger>
        <Repetition xdt:Transform="Insert">
          <Interval>PT300S</Interval>
        </Repetition>
      </CalendarTrigger>
    </Triggers>
</Task>


text:
Q: ha hdfs : Initialization failed for Block pool  (Datanode Uuid unassigned) I get the following error trying to start datanodes in HA HDFS cluster

2016-01-06 22:54:58,064 INFO org.apache.hadoop.hdfs.server.common.Storage: Storage directory [DISK]file:/home/data/hdfs/dn/ has already been used.
  2016-01-06 22:54:58,082 INFO org.apache.hadoop.hdfs.server.common.Storage: Analyzing storage directories for bpid BP-1354640905-10.146.52.232-1452117061014
  2016-01-06 22:54:58,083 WARN org.apache.hadoop.hdfs.server.common.Storage: Failed to analyze storage directories for block pool BP-1354640905-10.146.52.232-1452117061014
  java.io.IOException: BlockPoolSliceStorage.recoverTransitionRead: attempt to load an used block storage: /home/data/hdfs/dn/current/BP-1354640905-10.146.52.232-1452117061014
      at org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceStorage.loadBpStorageDirectories(BlockPoolSliceStorage.java:210)
      at org.apache.hadoop.hdfs.server.datanode.BlockPoolSliceStorage.recoverTransitionRead(BlockPoolSliceStorage.java:242)
      at org.apache.hadoop.hdfs.server.datanode.DataStorage.addStorageLocations(DataStorage.java:396)
      at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:477)
      at org.apache.hadoop.hdfs.server.datanode.DataNode.initStorage(DataNode.java:1338)
      at org.apache.hadoop.hdfs.server.datanode.DataNode.initBlockPool(DataNode.java:1304)
      at org.apache.hadoop.hdfs.server.datanode.BPOfferService.verifyAndSetNamespaceInfo(BPOfferService.java:314)
      at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.connectToNNAndHandshake(BPServiceActor.java:226)
      at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:867)
      at java.lang.Thread.run(Thread.java:745)
  2016-01-06 22:54:58,084 WARN org.apache.hadoop.hdfs.server.common.Storage: Failed to add storage for block pool: BP-1354640905-10.146.52.232-1452117061014 : BlockPoolSliceStorage.recoverTransitionRead: attempt to load an used block storage: /home/data/hdfs/dn/current/BP-1354640905-10.146.52.232-1452117061014
  2016-01-06 22:54:58,084 FATAL org.apache.hadoop.hdfs.server.datanode.DataNode: Initialization failed for Block pool  (Datanode Uuid unassigned) service to master3/10.146.52.232:8020. Exiting.
  java.io.IOException: All specified directories are failed to load.
      at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:478)
      at org.apache.hadoop.hdfs.server.datanode.DataNode.initStorage(DataNode.java:1338)
      at org.apache.hadoop.hdfs.server.datanode.DataNode.initBlockPool(DataNode.java:1304)
      at org.apache.hadoop.hdfs.server.datanode.BPOfferService.verifyAndSetNamespaceInfo(BPOfferService.java:314)
      at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.connectToNNAndHandshake(BPServiceActor.java:226)
      at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:867)
      at java.lang.Thread.run(Thread.java:745)
  2016-01-06 22:54:58,084 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: Ending block pool service for: Block pool  (Datanode Uuid unassigned) service to master3/10.146.52.232:8020
  2016-01-06 22:54:58,084 FATAL org.apache.hadoop.hdfs.server.datanode.DataNode: Initialization failed for Block pool  (Datanode Uuid unassigned) service to master2/10.146.52.231:8020. Exiting.
  org.apache.hadoop.util.DiskChecker$DiskErrorException: Invalid volume failure  config value: 3
      at org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl.(FsDatasetImpl.java:261)
      at org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetFactory.newInstance(FsDatasetFactory.java:34)
      at org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetFactory.newInstance(FsDatasetFactory.java:30)
      at org.apache.hadoop.hdfs.server.datanode.DataNode.initStorage(DataNode.java:1351)
      at org.apache.hadoop.hdfs.server.datanode.DataNode.initBlockPool(DataNode.java:1304)
      at org.apache.hadoop.hdfs.server.datanode.BPOfferService.verifyAndSetNamespaceInfo(BPOfferService.java:314)
      at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.connectToNNAndHandshake(BPServiceActor.java:226)
      at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:867)
      at java.lang.Thread.run(Thread.java:745)
  2016-01-06 22:54:58,085 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: Ending block pool service for: Block pool  (Datanode Uuid unassigned) service to master2/10.146.52.231:8020
  2016-01-06 22:54:58,185 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: Removed Block pool  (Datanode Uuid unassigned)

I have already check the clusters ID in namenode and datanode and they are similar...
I tried to reformat everything several times...
Thanks for your help !

A: I have seen messages like this in the log file when the file system for the DataNode is corrupt. Perhaps, try running fsck -y on each of the disks used by the DataNode. In your case:
fsck -y /home/data/hdfs

Once the disk(s) is(are) clean you should be able to start the DataNode. The NameNode will work ensure that the replication factor is fixed for any lost blocks.

A: I had a similar problem (but don't know without more logs, but mine didn't say "Datanode Uuid unassigned"), and fsck didn't solve it.
In my case, I had moved a subset of disks from one node to another node that already had disks, and disabled the old node, so there was a problem with the disks not matching the DatanodeUuid of the new machine.
Above those lines in the log, there were entries like:
2016-04-11 19:32:02,991 WARN org.apache.hadoop.hdfs.server.common.Storage: org.apache.hadoop.hdfs.server.common.InconsistentFSStateException: Directory /archive14/dfs/data is in an inconsistent state: Root /archive14/dfs/data: DatanodeUuid=5ba6418e-2c24-4582-8225-3e7f7fff9feb, does not match 519c1e34-a573-41f7-9e80-dca606fce704 from other StorageDirectory.

To solve that, I ran:
    sed -i -r "s/${olduuid}/${olduuid}/' /mountpoints*/dfs/data/current/VERSION
This replaces the old UUID in the VERSION file with the new one. Then starting the datanode works.
Maybe in your case, you had a missing UUID rather than an incorrect one.

A: Deleting the name node directory and the data node directory and then creating the new directories worked for me. Use this technique assuming that you will lost the data.

A: For my case,I reinstall hdfs by CM6.2.0 and instance two namenodes for HA.
Then reformat these namenode each other,but this option cause the error below.
Initialization failed for Block pool BP-666417012-10.253.76.213-1557044865448 (Datanode Uuid 5132035c-8d6a-4617-af7e-7d07355a905b) service to hzd-t-vbdl-02/10.253.76.222:8022 Blockpool ID mismatch: previously connected to Blockpool ID BP-666417012-10.253.76.213-1557044865448 but now connected to Blockpool ID BP-1262695848-10.253.76.222-1557045124181

Process method:
ansible all -m shell -a " more /XXX/hdfs/dfs/nn/current/VERSION "
hzd-t-vbdl-01 | CHANGED | rc=0 >>
Sun May 05 16:27:45 CST 2019
namespaceID=732385684
clusterID=cluster54
cTime=1557044865448
storageType=NAME_NODE
blockpoolID=BP-666417012-10.253.76.213-1557044865448
layoutVersion=-64

hzd-t-vbdl-02 | CHANGED | rc=0 >>
Sun May 05 16:32:04 CST 2019
namespaceID=892287385
clusterID=cluster54
cTime=1557045124181
storageType=NAME_NODE
blockpoolID=BP-1262695848-10.253.76.222-1557045124181
layoutVersion=-64

Finally copy the context from hzd-t-vbdl-01(early formated) to hzd-t-vbdl-02,and restart namenodes and datanodes


text:
Q: "Nice" functions on infinite-dimensional space of germs of continuous functions at a point Consider set of all germs of continuous functions at some point.
Question: What are some functions ("any/nice/constructive/whatever") from this set to R (reals) ? (Except evalution at point and made of it).
Before trying to be more precise with "nice" let me add some examples of "nice" in similar setups.
Example 1. If one considers germs of analytical functions, then derivatives at point are those
"nice" functions  and moreover they are "coordinates"  - i.e.  if one knows all derivatives
- one knows the germ itself and so any other function on germs can be expressed via them.
Examples 2a,b. If one considers not the germs, but continuous functions themselves on say [0 1], then evaluation functionls at points [0 1] are those "nice" functions.
And again they are "coordinates". As another set of functionals one can take   Fourier coefficints.
"Counter" Examples: Recent MO question shows that there are NO continuous functions on germs in certain topology on germs. Comments to unasnwered question on Math.SE tells something like if there would be something "nice", then everyone would know it.
Motivational Examples If I am not mistaking then, there are certain functions
which are "nice".
1) Holder exponent. I.e. sup of h: |f(x+a)-f(x)| < c x^h (it depends only on germ, right ? or I missed something ?), hmmmmm this sup can be inifinity and I want functions to take values in reals,  let us cook way round: if this sup is more than 1, let my function to be equal be to 1 by hands.
2) Fractal dimension of graph of function. I.e. Consider continuous function y=f(x).
Consider it on the interval [0 1/n]. Calculate fractal dimension of graph of f(x).
Take upper limit of those dimensions with $n-> \infty$. (It depends only on germ, right ? or I missed something ?)

Above is revised version of question. Let me preserve old version.
"Understanding an infinitesimal neighbourhood of a point in the realm of continuous functions"
For analytic functions, the set of all derivatives at a point, $f^{(n)}(a)$ for $n = 0,1,\ldots$, give a set "coordinates" on the space of all functions (germs). So $\operatorname{Spec}(C[[(x-a)]])$ is an "infinitesimal neighbourhood" of the point $x=a$.
Now consider not analytic, but continuous functions and a point $x=a$. Consider the germs of continuous functions at this point.
Question: How to understand the "algebra" of functionals on the space of germs of continuous functions?
Are there good "coordinates" (like the derivatives in the analytic case)? Are there some nice examples of such functionals? Can one express fractal dimensions or Hölder exponents via "coordinates/nice functions"?
Motivation: I was thinking about various fractal dimensions of graphs of functions (or of germs). There are many of them and it is difficult to understand the relation between them, it would be nice if they can be expressed via something canonical.

A: First an easy observation: The closure of the ideal $\lbrace f\in C(\mathbb R): f=0 \text{ near } 0\rbrace$ in $C(\mathbb R)$ with respect to the compact open topology equals the ideal $\lbrace f\in C(\mathbb R): f(0)=0\rbrace$. Thus, if you want your functional on the space $C_0$ of germs of continuous functions to be continuous when composed with the quotient mapping $C(\mathbb R)\to C_0$, then it is $f\mapsto F(f(0))$ for some map $F$.
On the other hand, consider the modulus of continuity mapping
$\rho(f)(|x|) = \max\lbrace |f(y)-f(0)|: |y|\le |x|\rbrace$ which induces a nonlinear map $\rho: C_0\to C_0$. So if you can find a "nice" functional on the set of germs of symmetric monotone continuous functions which vanish at 0, then you are done. For example,
the $\sup$ of all $k\in \mathbb N$ with $\rho(f)(x)\ge C (\exp^k(x)-\exp^k(0)$ for some $C>0$, where
$\exp^k = \exp\circ\dots\circ\exp$ (k-times), might be a candidate.


text:
Q: jQuery else if with Ajax I want to say else if (delete_box is clicked) how can I do that in the else if (currently empty)? They both (man and delete_box) have the same purpose but if you click on one or the other then something slightly different happens.
$(man).add(delete_box).click(function(){
        if(App.manager != true){
            overlay.fadeIn('fast',function(){
                box_2.animate({'top':'200px'},500);

                    $('#manager_pass').submit(function(evt){

                        evt.preventDefault();

                        data = {
                            managerPassword: $('#token').attr('value'),
                            action: 'passwordManager'
                        };

                        App.manager = $('#token').attr('value'); // set the manager token to the one inserted so that it's stored inside the page

                            $.ajax({
                                url: App.URL_manager,
                                data : data,
                                dataType: 'json',
                                type: 'POST',
                                success: function(r){
                                    if (r.success) {
                                           box_2.animate({'top':'-250px'},500,function(){
                                           overlay.fadeOut('fast');
                                           });

                                            $('.action_wrapper').fadeOut(1000,function(){
                                                    $('.add_staff').fadeIn(1000);
                                            })
                                    }

                                    else {
                                            $('#manager_pass').fadeOut(1000,function(){
                                                $('.error').fadeIn(1000);
                                            })
                                         }
                                }

                            });

                    });

                });
        }

        else if()

        else{
            action_wrapper.fadeOut(1000, function(){
                $('#add_staff').fadeIn(1000);

            })
        }

});

A: You can use is method.
$(man).add(delete_box).click(function(event){
    // ...
    else if ($(event.target).is(delete_box)) {
       // ...
    }
})

http://jsfiddle.net/9gcdQ/


text:
Q: Fmap over a list containing single elements and lists I have a data structure like so
data ShoppingList a
  = Empty
  | Item a
  | Listofitems [ShoppingList a]
  deriving (Show)

I am trying to write the fmap for this
instance Functor ShoppingList where
  fmap f Empty    = Empty
  fmap f (Item i) = Item (f i)
  fmap f (Listofitems [Empty]) = Empty
  fmap f (Listofitems ((Item a):Listofitems [as])) = Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])

This is what I wrote so far ,but its not compiling ,can you please help me understand what the problem here is , an explanation would be awesome .
The two errors that I am getting
src\Ml.hs:19:33: error:
    * Couldn't match expected type `[ShoppingList a]'
                  with actual type `ShoppingList a0'
    * In the pattern: Listofitems [as]
      In the pattern: (Item a) : Listofitems [as]
      In the pattern: Listofitems ((Item a) : Listofitems [as])
    * Relevant bindings include
        a :: a (bound at src\Ml.hs:19:30)
        f :: a -> b (bound at src\Ml.hs:19:8)
        fmap :: (a -> b) -> ShoppingList a -> ShoppingList b
          (bound at src\Ml.hs:16:3)
   |
19 |   fmap f (Listofitems ((Item a):Listofitems [as])) = Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])
   |                                 ^^^^^^^^^^^^^^^^

src\Ml.hs:19:68: error:
    * Couldn't match expected type `b -> [ShoppingList b]'
                  with actual type `ShoppingList b'
    * The function `fmap' is applied to three arguments,
      but its type `(a -> b) -> ShoppingList a -> ShoppingList b'
      has only two
      In the second argument of `($)', namely
        `(fmap f (Item a)) (fmap f Listofitems [as])'
      In the expression:
        Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])
    * Relevant bindings include
        f :: a -> b (bound at src\Ml.hs:19:8)
        fmap :: (a -> b) -> ShoppingList a -> ShoppingList b
          (bound at src\Ml.hs:16:3)
   |
19 |   fmap f (Listofitems ((Item a):Listofitems [as])) = Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])
   |                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Basically if I have a list = [ Item Apple ,Empty , [Item Banana ,Empty ] ]
I want fmap (++ M )list  to return [Item AppleM .Empty .[Item BananaM ,Empty]]

A: Note on the data type
First of all, your data type is overly complicates. A list of items should indeed be a list, so you can should define data ShoppingList' a = ShoppingList' [a] as you are using lists in yours anyways. There is no need a Shopping List should be nested.
Solution to your question
If, however, you need it that way, this is a solution. Note I assumed you did not need a list of ShoppingLists, as your data definition already has a list in it. So you can call
--fmap :: (a -> b) -> ShoppingList a -> ShoppingList b
fmap _ Empty = Empty
fmap f (Item i) = Item (f i)
fmap f (Listofitems ls) = Listofitems $ map (fmap f) ls

>>fmap (++ "M") $ Listofitems [Item "Apple", Empty, Listofitems [Item "Banana", Empty]]
Listofitems [Item "AppleM",Empty,Listofitems [Item "BananaM",Empty]]

Note:

*

*You need quotes around your strings,

*You need to call it on a Listofitems

Also remember the String append operations is not efficient with long strings in case you need performance