text:
Q: Listen to all form submit events and perform a function before any other attached event handlers I'm trying to prevent CSRF attacks in a an existing large web app. I've opted for a token that is injected using JS into any form and a Java Servlet filter that will check for its presence before allowing the request to continue. Firstly we are happy to require the user has JS.
Secondly - how do I do it?
The simplest idea: $(document).live("submit", myTokenAddFn); doesn't work.
The token injection part is proving very tricky since, as I said, the web app is very large, and there a number of bridges to cross:

*

*There are forms that are created (using JS) after the page has loaded

*We make use of JSF (which has onclick attributes on anchor tags to submit forms)

*There are instances of jQuery form submits using AJAX

*There are plenty of onclick handlers attached to form submit elements already

I feel I am very close but I can't believe I'm not impacting performance on slower browsers. I am starting to think that there might be a better way.
What I have done:

*

*To overcome jQuery AJAX form submissions: Using the ajaxSend method to append my token to the real data values before the AJAX request is sent

*To add the token to simple form elements on the page that are there on page load: On page load effectively loop through forms and add the token, then add jQuery data that says this form has the token (to improve performance of next step)

*To overcome dynamically created forms: $("input[type='submit'],input[type='image'],button,a[onclick]").live("mousedown", myTokenAddFn);
The above line copes with a lot and the 'myTokenAddFn' actually just loops through the page again looking for all forms that don't have the jQuery data item I added on page load.
It copes with JSF forms that are submitted with an anchor tag's onclick attribute, buttons that don't reside in a form but submit a form and ensures that the token is always added before any other onclick handler submits the form (that might be present).

The latest issue:
A JS form is dynamically added to the page and the user submits it using the enter key while the cursor is in an input text field. The user (thanks to my Java Servlet) is logged out.
The easiest fix would be to include keypress listeners to all input elements, but the performance hit here worries me.
Any suggestions? Ideas for a fresh start?
Thanks in advance.

A: In your simple idea, you're binding the event to document, but I'd bind the live listener to "form" - selecting all form tags. Also, in the event listener, just add e.preventDefault(). Like so:
$("form").live("submit", submitListener);

function submitListener(e) {
   // your handling stuff goes here
   e.preventDefault();
}

I've done the above method on my forms before and it seems to work fine. Hope this does the trick!
EDIT: I just wanted to be sure this actually works, so here's a quick example. As you can see, it blocks the submission to google.com and flashes up with a "nope!" to show the submission was blocked.

A: Instead of messing too much with the HTML structure, I've created another approach. Set a cookie before the page unloads, and perform a check on the existence and validity of the cookie at the server's side.
$(window).unload(function(){
    //30 seconds SHOULD be enough to connect to the server
    document.cookie = "crf=" + myTokenAddFn() + "; max-age=30";
});

A: With newer versions of jQuery:
$(document).on("submit", "form", function(e){
    e.preventDefault();
});

With newer versions of jQuery, but allowing form submissions on forms that have data-bypass:
$(document).on("submit", "form:not([data-bypass])", function(e){
    e.preventDefault();
});

Reference:
http://addyosmani.github.io/backbone-fundamentals/
Look how Addy Osmani handles hijacking anchor tags.


text:
Q: Haskell: foldl error i'm trying to make a hamming codification in haskell, i have a function "calculateParity" that takes a list of pairs [(Char, Int)] which are the bit (as Char) and the index (Int, starting at 1) in the list of bits, the second parameter is the position of the parity bit i'm going to calculate. The first thing that came to my mind was to use fold left with the accumulator being the actual parity of the data bits related to the parity bit. The code i wrote for this is like:
calculateParity :: [(Char, Int)] -> Int -> Char
             calculateParity dataBits pos = intToDigit (foldl (\acc (bit, index) -> if pos .&. index /= 0 then acc xor (digitToInt bit) else acc) 0 dataBits)

When i try to compile it, this is the error:
 ? Couldn't match expected type 'Int'
              with actual type '(a0 -> a0 -> a0) -> Int -> t0'
? Probable cause: 'foldl' is applied to too few arguments
  In the first argument of 'intToDigit', namely
    '(foldl
        (\ acc (bit, index)
           -> if pos .&. index /= 0 then acc xor (digitToInt bit) else acc)
        0
        dataBits)'

I think it says the intToDigit isn't recieving an Int, instead it is taking son partial applied function, am i calling the foldl function wrongly?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript - Base an interface from a class The following code generates errors because of the private attribute e1. I wonder if the e1 is part of the interface I. I thought an interface is all about public elememts. May I know how to fix the code to make it to work (or how to base an interface on a class with private attributes.
Thanks for your helps,
Andre
class A {
        constructor(private e1: string, public e2: string) {}
    public displayValue(): string {
        return this.e1 + ":" + this.e2;
    }
}

interface I extends A {
    e3: string;
    displayValue2(): string;
}

class IA implements I {
    constructor(public e2: string, public e3: string, private e4: string) {}

    public displayValue(): string {
        return this.e2 + ":" + this.e3 + ":" + this.e4;
    }

    public displayValue2(): string {
        return "testing";
    }
}

var f: (a: A) => void = function(a: A) {
    console.log(a);
}

var a1: A = new A("teste1", "teste2");
var a2: IA = new IA("testiae2", "testiae3", "testiae4");

f(a1);
f(a2);

A: In TypeScript it is possible to "extend" a class while defining an interface, in this interface you will have all the members from the extended class including private, public, and protected.
try to do this:
var i: I;
i. // <-- The IDE will show you ONLY the public members of I, but will know about the privates

BUT, behind the scenes TypeScript "Knows" that this interface has some private members, this is why it will tell you that "e2" property is missing on "IA".
If you implement "I" you must take that into account, just like you would if a you would extend "A" (That has the private member)

A: class A {
    constructor(private e1: string, public e2: string) {}
    public displayValue(): string {
        return this.e1 + ":" + this.e2;
    }
}

interface I extends A {
    e3: string;
    displayValue2(): string;
}

var i: I;

class IA extends A implements I {
    constructor(public e3: string, private e4: string, e1: string, e2: string) {
        super(e1, e2);
    }

    public displayValue(): string {
        return this.e2 + ":" + this.e3 + ":" + this.e4;
    }

    public displayValue2(): string {
        return "testing";
    }
}

var f: (a: A) => void = function(a: A) {
    console.log(a);
    console.log(a.displayValue());
}

var a1: A = new A("teste1", "teste2");
var a2: IA = new IA("testiae2", "testiae3", "testiae4", "testiae1");

f(a1);
f(a2);


text:
Q: Is it possible to lay out several choice options horizontally for one selection field in a display file? I am trying to add a selection field to a display file using CHOICE DDS keyword. This selection field has three candidate values. By default all three options will be displayed in a single column. I want to lay them out horizontally on the same line. How to achieve this?

A: A menu bar will display options horizontally.  See the MNUBAR DDS keyword.
This is a record level keyword, so you would need to define a record format specifically for this, which might not always be what you had in mind.

A: If you need "selection choices" laid out horizontally, you have a variety of options. In increasing order of difficulty:
First, use a SFLSNGCHC (Subfile Single Choice Selection List) subfile. That's probably easiest, but there isn't much definition to go on here.
Next, use UIM. It's essentially a markup language related to HTML, so you might not find it difficult. The hardest part might be learning how to use the APIs and in coding any needed 'exit' functions. Knowing UIM can be worthwhile if you do a lot of green-screen display development.
Or use conditioning indicators. Line up a horizontal series of single-position input fields separated by output fields. Put variable text into the output fields as your options change. Condition however many of them you need across the line. Any fields on the right that aren't need can be DSPATR(PR ND).
Finally, use the Dynamic Screen Manager (DSM) APIs to make the screen work almost any way you choose. (This could also be done by a USRDFN (User-Defined) record format.)


text:
Q: Android background music game pauses before looping I'm working on Android game, and I'm using standard Android components for it.
I have media player object that should play background music over and over again.
I've composed some music, and rendered it...and it loops perfectly.
Now when I've added my music file into game...before every loop music stops for a moment...but it is very annoying. Why is that happening?
I've tested it on 2.3.3 phone device and ICS emulator...and the same thing happens every time.
This is my code:
/** Play background music */
public static void playMusic() {

    if (backgroundMusic == null) {
        backgroundMusic = new MediaPlayer();
        backgroundMusic.setVolume(0.5f, 0.5f);

        try {
            backgroundMusic.setDataSource(activity.getAssets()
                    .openFd("background_music.ogg")
                    .getFileDescriptor());
            backgroundMusic.prepare();
            backgroundMusic.setAudioStreamType(AudioManager.STREAM_MUSIC);
            backgroundMusic.setLooping(true);
            backgroundMusic.start();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

When I play the same file in some player on PC it loops and sounds very nice...
How to fix this? Tnx!

A: Well, unfortunately, it just works like that.
The problem is that he restarts the player, after it finished.
If you are using API 16 or greater, you can use the setNextMediaPlayer(MediaPlayer)-method. He then tries to start the next MediaPlayer in a way, that there is no pause.
If you are developing for API smaller than 16, I don't know how you can handle this with a MediaPlayer.
You might try to work with 2 MediaPlayers and start the second one right before the first one stops. But I don't know how good that works, since you somehow have to find out, when exactly to start the new player.
Edit:
After some more google work, I found this.
Someone suggested to convert the mp3-File to an ogg-File, what would make it possible to loop it without having a pause. But I didn't try that.
According to comments, this worked for one person, but not for another one.

A: I guess I found a way to make this work...
I've changed code to this:
/** Play background music */
public static void playMusic() {

    if (backgroundMusic == null) {
        backgroundMusic = new MediaPlayer();
        backgroundMusic.setVolume(0.5f, 0.5f);
        AssetFileDescriptor afd;
        try {
            afd = activity.getAssets().openFd(
                    "background_music.ogg");
            backgroundMusic.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            backgroundMusic.setLooping(true);
            backgroundMusic.prepare();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        backgroundMusic.start();
    }

}

Now it loops fine...the problem is that I don't really understand why...
Hope this will be helpful for some folks that had the same problem as me.
Cheers!


text:
Q: Can Select Same Date in NG-Bootstrap Datepicker in Angular I am using a date range datepicker using the ng-bootstrap datepicker. But I have a problem encountered. I should be able to select the same date. How will i able to fix this? Please check this link
CLICK HERE
onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

A:
remove third validator in else if

check examplerange-date-picker
original one
onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

fixed one
onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

A: Just replace your function

  onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

With

  onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

A: Replace
onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

with
onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date && (date.equals(this.fromDate)) || date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }


text:
Q: Issue with resizing custom view in appwidget, can't determine real size appwidget on android, especially on tablets I'm designing an AppWidget and I have run into such problem: I define in xml
android:minWidth ="296dp"
android:minHeight="146dp"

That means 4x2 cells size of my widget.
In my program code I am creating a custom view by drawing text and figures on canvas. For proper scaling of my custom view I must know the boundary dimensions of my appwidget's placement on homescreen. I couldn't have found any useful information how to determine real appwidget size on homescreen (the all resources have told - "you can't!" - is it really so?) and so I estimated my appwidget size using android:minWidth and android:minHeight="146dp".
The problem is that I can't give proper appearance of my widget on all devices which I've used for testing, especially
it concerned tablets.
I've read https://developer.android.com/guide/practices/ui_guidelines/widget_design.html and other official docs, but I can't come to the right conclusion.
1 -  I've found two formulas for determine size of one cell:
1)minWidth or minHeight = 70 * n - 30       and
2)minWidth or minHeight = 74 * n - 2

I've used the second and identified that it works perfectly for usual handsets (not for Samsung Galaxy Tab), but the officials offer to use the first one. If I used the first one on handsets it would work too, but I`ve got a less size widget components (size widget components - text, rects and etc. which I draw on canvas), hence the appwidget appearance
is worse than in second case.
In tablet case I've got an empty spaces at right/left of my custom view and having regard to my widget layout (where I have custom widget and two buttons) it looks bad. I think that empty spaces on tablet occured because of mismatch real and estimated width of appwidget.
How can I calculate a size widget that it would look proper on tablets?
2 - I can't use 9-patch resources because I create my view programmatically. I've tried using android:scaleType in layout widget
<ImageView
        android:id="@+id/custom_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:clickable="true"
        android:contentDescription="@string/image_description" />

but, for example, in Motorola Xoom I've got bad appearance of my appwidget after stretching custom view.
3 - I figured out that Android device resize widget by itself but I couldn't quiet catch the logic of such resizing.
After all, how to design appwidget size for handset and tablets in my case?
I'll be very grateful to you for your help.

A: I do not think it is possible - I had the same problem with my app widget.
Instead you can create different versions of your app widget (i.e. 1x4, 2x3 etc), but I know that is not what you really want to.
The scaling done within the app widget of for instance text inside TextView (even with sp) seeems to be beyond our control in appwidgets.


text:
Q: Filtering lines of two files based on a third list file I have 3 files: list_file, file1, and file2. I want to extract entire lines from file1 and file2 based on a list_file pairwise and concatenate the results on output.
Namely, I need to extract only lines from file1 and file2 with names on 4th column matching names on first and second column of list_file (respectively), then concatenate both entire lines on output following the same paired order displayed on list file.
Names in column 1 of list_file are present in file1, and names in column 2 of list_file are present in file2.
list_file:
uth1.g20066 uth2.g18511
uth1.g3149  uth2.g22348
uth1.g20067 uth2.g18512
uth1.g20068 uth2.g18514
uth1.g3154  uth2.g22355

file1
ut1A    11256   13613   uth1.g20065
ut1A    25598   47989   uth1.g20066
ut1A    39912   40142   uth1.g3148
ut1A    40324   40617   uth1.g3149
ut1A    40699   41034   uth1.g3150

file2
ut1B    16951   39342   uth2.g18511
ut1B    31265   31495   uth2.g22347
ut1B    31677   31970   uth2.g22348
ut1B    32052   32387   uth2.g22349
ut1B    41596   46862   uth2.g18522

Desired output:
ut1A    25598   47989   uth1.g20066 ut1B    16951   39342   uth2.g18511
ut1A    40324   40617   uth1.g3149  ut1B    31677   31970   uth2.g22348

In order to perform this task I tried the below python code and it works, however it is clumsy (many loops) and it is very slow on large input files, so it would be great to make it more concise. It would also be interesting to have entirely new script as an alternative, perhaps with awk. Thanks.
data = open("list_file.txt")

data1 = open("file1.txt")
all_lines1 = data1.readlines()

data2 = open("file2.txt")
all_lines2 = data2.readlines()

output = open("output.txt", "w")

for line in data:

    columns = line.split( )
    geneH1data = columns[0]
    geneH2data = columns[1]

    for line1 in all_lines1:

        columns1 = line1.split( )
        chr1 = columns1[0]
        start1 = int(columns1[1])
        end1 = int(columns1[2])
        geneH1data1 = columns1[3]

        for line2 in all_lines2:

            columns2 = line2.split( )
            chr2 = columns2[0]
            start2 = int(columns2[1])
            end2 = int(columns2[2])
            geneH2data2 = columns2[3]

            if geneH1data==geneH1data1 and geneH2data==geneH2data2:
                output.write(chr1 + " " + str(start1) + " " + str(end1) + " " + geneH1data + " " + chr2 + " " + str(start2) + " " + str(end2) + " " + geneH2data + '\n')

output.txt
ut1A 25598 47989 uth1.g20066 ut1B 16951 39342 uth2.g18511
ut1A 40324 40617 uth1.g3149 ut1B 31677 31970 uth2.g22348

A: Using GNU awk for ARGIND:
$ awk '
    ARGIND<3 { a[ARGIND,$4]=$0; next }
    ((1,$1) in a) && ((2,$2) in a) { print a[1,$1], a[2,$2] }
' file1 file2 list_file
ut1A    25598   47989   uth1.g20066 ut1B    16951   39342   uth2.g18511
ut1A    40324   40617   uth1.g3149 ut1B    31677   31970   uth2.g22348

If you don't have GNU awk just tweak it to:
$ awk '
    FNR==1 { argind++ }
    argind<3 { a[argind,$4]=$0; next }
    ((1,$1) in a) && ((2,$2) in a) { print a[1,$1], a[2,$2] }
' file1 file2 list_file
ut1A    25598   47989   uth1.g20066 ut1B    16951   39342   uth2.g18511
ut1A    40324   40617   uth1.g3149 ut1B    31677   31970   uth2.g22348

and then it'll work in any awk. If you want the output tab-separated instead of blank-separated just tweak it again:
$ awk '
    BEGIN { OFS="\t" }
    FNR==1 { argind++ }
    argind<3 { a[argind,$4]=$0; next }
    ((1,$1) in a) && ((2,$2) in a) { print a[1,$1], a[2,$2] }
' file1 file2 list_file
ut1A    25598   47989   uth1.g20066     ut1B    16951   39342   uth2.g18511
ut1A    40324   40617   uth1.g3149      ut1B    31677   31970   uth2.g22348


text:
Q: How can I skip errors and continue running the SQL-query? I am writing a piece of code with the intention of searching through all databases in the server for a certain table name, however I ran into some trouble since I do not have permission to read/access all databases in the server.
I am wondering if there is a way for the query to advance if one statement is not available due to security permissions (i.e. if I have ten databases in a particular server with no access to the fourth, I would want it to run 1-2-3 and then 5-6-7-8-9-10 with returned results).
I have tried using TRY-CATCH, but I cannot seem to get the code to bypass the initial problem which is stopping when the security permissions are not available.
declare @tabell varchar(254) = 'JE' -- table name which is supposed to be
--found.

-- STEP 1: lists all available databases in the server with a row number.
drop table if exists #steg1 select name, row_number() over (order by
name) as rownumber into #steg1 from sys.databases

-- STEP 2: generates code for all databases in order to identify those
--with the table name @tabell.
drop table if exists #steg2 select 1 Ordn,'use '+name+' drop table if
exists #hitta select * into #hitta from sys.tables where name =
'''+ltrim(@tabell)+'''' as script into #steg2 from #steg1 a
where rownumber =1
union
select 2 Ordn, 'use '+name+' insert into #hitta select * from sys.tables
where name = '''+ltrim(@tabell)+'''' from #steg1 a
where rownumber >1
union
select 3 Ordn,'select * from #hitta' as x

-- STEP 3: concatenate the generated code into a single string.
declare @string varchar(max)
select @string = concat(@string + ' ', '')+ script from #steg2
drop table if exists #steg3 select @string as string into #steg3

-- STEP 4: exec the code concatenated in the previous step.
declare     @cmd    varchar(max)
begin
set @cmd = (select string from #steg3)
exec (@cmd)
end

Getting the error message: Msg 916, level 14, state 1, stating that the user cannot access the database under the current security context.

A: I managed to solve my issue using has_dbaccess(database), below you can see how I incorporated it into the code.
declare @tabell varchar(254) = 'JE' -- table name which is
supposed to be found.

-- STEP 1: lists all available databases in the server with a row number.
drop table if exists #steg1 select name, row_number() over (order by name) as rownumber
into #steg1 from (SELECT name, has_dbaccess(name) access FROM sys.databases) a where
access = 1

-- STEP 2: generates code for all databases in order to identify those with the table
--name @tabell.
drop table if exists #steg2 select 1 Ordn,'use '+name+' drop table if exists #hitta
select name as [Table], cast('''+name+'''as varchar(max)) as [Databas] into #hitta from
sys.tables where name = '''+ltrim(@tabell)+'''' as script into #steg2 from #steg1 a
where rownumber =1
union
select 2 Ordn, 'use '+name+' insert into #hitta select name as [Table],
cast('''+name+'''as varchar(max)) as [Databas] from sys.tables where name =
'''+ltrim(@tabell)+'''' from #steg1 a
where rownumber >1
union
select 3 Ordn,'select * from #hitta' as x

-- STEP 3: concatenate the generated code into a single string.
declare @string varchar(max)
select @string = concat(@string + ' ', '')+ script from #steg2
drop table if exists #steg3 select @string as string into #steg3

-- STEP 4: exec the code concatenated in the previous step.
declare     @cmd    varchar(max)
begin
set @cmd = (select string from #steg3)
exec (@cmd)
end


text:
Q: How to reverse second object in stacked ggplot? How can I reverse the variable in my ggplot, so to variable 'Bananas' starts from 1 and Kiwis from 0, and the gray area in the middle?
  p <- ggplot(data=df, aes(x=t, y=value, colour=fruits, fill=fruit))+
  geom_area(position = 'stack')+
  theme_bw()

A: We don't have your data, so let's reproduce it:
df <- data.frame(t      = rep(0:100, 2),
                 value  = c(2 * (0.95/(1 + exp(-0.1 * (0:100))) - 0.475),
                            2 * (0.05/(1 + exp(-0.1 * (0:100))) - 0.025)),
                 fruits = factor(rep(c("Bananas", "Kiwis"), each = 101),
                                 c("Kiwis", "Bananas")))

ggplot(data = df, aes(x = t, y = value, colour = fruits, fill = fruits)) +
  geom_area(position = 'stack')

To get the Kiwi at the top and bananas at the bottom, you can't use geom_area - you will need to use geom_ribbon, and manipulate the data to get the top and bottom edges of your ribbon:
df$min <- 0
df$max <- 1
df$min[df$fruits == "Kiwis"] <- 1 - df$value[df$fruits == "Kiwis"]
df$max[df$fruits == "Bananas"] <- df$value[df$fruits == "Bananas"]

ggplot(data = df, aes(x = t, y = value, colour = fruits, fill = fruits)) +
  geom_ribbon(aes(ymin = min, ymax = max))


text:
Q: Scala Comparing Values in 2 Spark Dataframes I am trying to write a condition statement for joining 2 Spark dataframes together in Scala:
val joinCondition = when($"filteredRESULT.key" == $"allDataUSE.key" && $"allDataUSE.timestamp" >=  $"filteredRESULT.tripStart" && $"allDataUSE.timestamp" <= $"filteredRESULT.tripEND", $"allDataUSE.tripid" === $"filteredRESULT.tripid").otherwise($"allDataUSE.tripid" === 0)

The filteredRESULT df is very small, and includes a tripID, tripStart time, tripEnd time. My goal is to use filteredRESULT as a lookup table, where a row from the allDataUSE df is compared against the entries in filteredRESULT. For example:
If in allDataUSE, a row matches filteredRESULT key, a timestamp >= a trip's start time, and <= a trip's end time, then the tripid column in allDataUSE should receive the value of tripid in the filteredRESULT df.
I am getting a boolean error when I run the above conditional statement. How can I perform this operation? Thank you!!

A: You Are getting The boolean error because where condition expect the condition to return boolean,but the operator === in spark return the column as ouput.becuase of that you are getting that error.
below i am sharing the link to spark document you see that.
https://spark.apache.org/docs/2.0.0/api/java/org/apache/spark/sql/Column.html#equals(java.lang.Object)
public Column equalTo(Object other)
Equality test.

   // Scala:
   df.filter( df("colA") === df("colB") )

   // Java
   import static org.apache.spark.sql.functions.*;
   df.filter( col("colA").equalTo(col("colB")) );

Parameters:
other - (undocumented)
Returns:
(undocumented)

so remove that === and replace with == it work


text:
Q: How to calculate interpolation error with repeated nodes
Given $f(x)=\cos(\pi x)$
a) Calculate the interpolation polynomial such that $p(-1)=f(-1)$, $p'(-1)=f'(-1)$, $p(0)=f(0)$, $p(1)=f(1)$ and $p'(1)=f'(1)$.
b) Show that $|f(x)-p(x)|\leq\frac{\pi^5}{120}$ for every $x\in[-1,1]$

So I managed to do item a) and obtain $p(x)=2x^4-4x^2+1$. However, when I try to do item b) and bound my error, I have repeated nodes, $x_0=-1$ and $x_2=1$ and therefore im not sure if I can use the bound I would like to use, say:
$$||W_{n+1}(x)||_{\infty}\leq\left(\frac{b-a}{2}\right)^{n+1}$$
Since my nodes are equidistant. Is there an aditional condition I should add because of the repetition of my nodes?


text:
Q: TI-RTOS and MSP-EXP430F5438 porting I want to use TI-RTOS on a experimenal board MSP-EXP430F5430 that has MSP430F5438A uC. For this I have tried to compile the driverlibs for my board. I have modified the the tirtos.mak file at MSP430DEVLIST to compile for my board. After compilation I opened a project in Code Composer for MSP-EXP430F5529LP board and modify the proprieties. My problem is that after the compilation of drivers I can't find my .lib files.
Here is my output from the console:
**** Build of configuration Debug for project gpiointerrupt_MSP_EXP430F5529LP_TI_MSP430F5529 ****

"C:\\ti\\ccsv6\\utils\\bin\\gmake" -k all
'Building file: ../gpiointerrupt.cfg'
'Invoking: XDCtools'
"C:/ti/xdctools_3_32_00_06_core/xs" --xdcpath="C:/ti/tirtos_msp43x_2_16_01_14/packages;C:/ti/tirtos_msp43x_2_16_01_14/products/bios_6_45_02_31/packages;C:/ti/tirtos_msp43x_2_16_01_14/products/tidrivers_msp43x_2_16_01_13/packages;C:/ti/tirtos_msp43x_2_16_01_14/products/uia_2_00_05_50/packages;C:/ti/ccsv6/ccs_base;" xdc.tools.configuro -o configPkg -t ti.targets.msp430.elf.MSP430X -p ti.platforms.msp430:MSP430F5438 -r release -c "C:/ti/ccsv6/tools/compiler/ti-cgt-msp430_15.12.1.LTS" --compileOptions "-vmspx --data_model=restricted --use_hw_mpy=F5 --include_path=\"C:/ti/ccsv6/ccs_base/msp430/include\" --include_path=\"D:/Projects/Code Composer/gpiointerrupt_MSP_EXP430F5529LP_TI_MSP430F5529\" --include_path=\"C:/ti/tirtos_msp43x_2_16_01_14/products/msp430_driverlib_2_21_00_08a/driverlib/MSP430F5xx_6xx\" --include_path=\"C:/ti/ccsv6/tools/compiler/ti-cgt-msp430_15.12.1.LTS/include\" --advice:power_severity=suppress --advice:power=all -g --define=ccs --define=MSP430WARE --define=__MSP430F5438A__ --diag_warning=225 --diag_warning=255 --display_error_number --diag_wrap=off --silicon_errata=CPU21 --silicon_errata=CPU22 --silicon_errata=CPU23 --silicon_errata=CPU40 --abi=eabi --printf_support=minimal  " "../gpiointerrupt.cfg"
making package.mak (because of package.bld) ...
generating interfaces for package configPkg (because package/package.xdc.inc is older than package.xdc) ...
configuring gpiointerrupt.xe430X from package/cfg/gpiointerrupt_pe430X.cfg ...
generating custom ti.sysbios library makefile ...
generating custom ti.sysbios.family.msp430 Hwi stubs ...
Starting build of library sources ...
making D:/Projects/CODECO~1/gpiointerrupt_MSP_EXP430F5529LP_TI_MSP430F5529/src/sysbios/sysbios.ae430X ...
gmake[1]: Entering directory `D:/Projects/CODECO~1/gpiointerrupt_MSP_EXP430F5529LP_TI_MSP430F5529/src/sysbios'
cle430X C:/ti/tirtos_msp43x_2_16_01_14/products/bios_6_45_02_31/packages/ti/sysbios/BIOS.c ...
gmake[1]: Leaving directory `D:/Projects/CODECO~1/gpiointerrupt_MSP_EXP430F5529LP_TI_MSP430F5529/src/sysbios'
Build of libraries failed.
C:/Users/DEVELO~1/AppData/Local/Temp/make15088-1.sh: 1: Syntax error: Unterminated quoted string
gmake[1]: *** [BIOS.obj] Error 2
gmake: *** [D:/Projects/CODECO~1/gpiointerrupt_MSP_EXP430F5529LP_TI_MSP430F5529/src/sysbios/sysbios.ae430X] Error 2
error: xdc.cfg.SourceDir: "C:/ti/xdctools_3_32_00_06_core/packages/xdc/cfg/SourceDir.xs", line 209: xdc.cfg.SourceDir : Build of generated source libraries failed: exit status = 2:

js: "C:/ti/xdctools_3_32_00_06_core/packages/xdc/cfg/Main.xs", line 160: Error: Configuration failed!
gmake.exe: *** [package/cfg/gpiointerrupt_pe430X.xdl] Error 1
gmake.exe: *** Deleting file `package/cfg/gpiointerrupt_pe430X.xdl'
gmake.exe: *** [package/cfg/gpiointerrupt_pe430X.xdl] Deleting file `package/cfg/gpiointerrupt_pe430X.h'
gmake.exe: *** [package/cfg/gpiointerrupt_pe430X.xdl] Deleting file `package/cfg/gpiointerrupt_pe430X.c'
js: "C:/ti/xdctools_3_32_00_06_core/packages/xdc/tools/Cmdr.xs", line 51: Error: xdc.tools.configuro: configuration failed due to earlier errors (status = 2); 'linker.cmd' deleted.
gmake: *** No rule to make target 'configPkg/linker.cmd', needed by 'configPkg/compiler.opt'.
gmake: *** No rule to make target 'configPkg/linker.cmd', needed by 'configPkg/compiler.opt'.
gmake: Target 'all' not remade because of errors.

**** Build Finished ****

Could you give me any guidance?


text:
Q: Windows Phone: How to disable button background when is pressed programmatically? I have a button in my windows phone app. When I am pressing it, its background color turns to yellow. How can I disable this feature, then instead of having a yellow color I want to see no change.
enter code here

 Button btn = new Button();

thanks,Bahador

A: Either use Blend to edit the pressed state or override the theme accent brushes


text:
Q: Android phone filters multicast Environment:
Phone: Motorola Xoom, model MZ601, Android 3.0.1
Router: Netgear WNR3500U/WNR3500L
Problem:
There is a piece of simple Java multicast listener on Android:
    public void listenMulticast(){
    try{
        WifiManager wifi = (WifiManager)App.getContext().getSystemService( Context.WIFI_SERVICE );

        /*****Get multicast lock*****/
        MulticastLock multicastLock = wifi.createMulticastLock("MyApp");
        multicastLock.setReferenceCounted(true);
        multicastLock.acquire();

        /*****Create a socket*****/
        MulticastSocket socket = new MulticastSocket(PORT);
        socket.joinGroup(InetAddress.getByName(HOST));

        /*****Receive a message*****/
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        socket.setSoTimeout(TIME_OUT);
        socket.receive(packet);
        ...
    } catch()

}

The application receives multicast in a local range (tried with a group 224.0.0.250 and port 6791) but does not see (timeout exception in socket.receive() method) multicast in a public range: 228.5.6.7 (and the same port 6791 for example).
Security permissions are standard:
<uses-sdk android:minSdkVersion="4"  android:targetSdkVersion="8"></uses-sdk>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"></uses-permission>

I tried with different android phones in the same network and they received multicast on group 228.5.6.7. But this Motorola Xoom receives local multicast only.
Thank you for some ideas what possibly can be wrong.


text:
Q: How to implement left join on data range in hive I want to convert the below oracle logic to hive.
Logic:
Select a.id,a.name,b.desc from table a left join table b on
a.num between b.min_num and b.max_num;

Could any one help me out to achieve the above logic in hive.

A: With this solution you have the control on the performance.
b ranges are being split to sub-ranges, small as you want (x).

*

*Too big x will practically cause a CROSS JOIN.

*Too small x might generate a huge set from b (x=1 will generate all b ranges' values).

set hivevar:x=100;

select  a.id
       ,a.name
       ,b.desc

from        table_a as a

        left join

            (select  a.id
                   ,b.desc

            from        table_a as a

                    inner join

                       (select   b.min_num div ${hivevar:x} + pe.pos    as sub_range_id
                                ,b.*

                        from        table_b as b
                                lateral view
                                    posexplode(split(space(cast (b.max_num div ${hivevar:x} - b.min_num div ${hivevar:x} as int)),' ')) pe
                        ) as b

                    on          a.num div ${hivevar:x}  =
                                b.sub_range_id

            where   a.num between b.min_num and b.max_num
            ) b

        on          b.id   =
                    a.id
;

A: select  a.id
       ,a.name
       ,b.desc

from                table_a as a

        left join  (select  a.id
                           ,b.desc

                    from                table_a as a
                            cross join  table_b as b

                    where   a.num between b.min_num and b.max_num
                    ) b

        on          b.id   =
                    a.id
;

A: select  a.id
       ,a.name
       ,b.desc

from                table_a as a

        left join  (select  b.min_num + pe.pos  as num
                           ,b.desc

                    from    table_b as b
                                lateral view
                                    posexplode(split(space(b.max_num-b.min_num),' ')) pe
                    ) b

        on          b.num   =
                    a.num
;


text:
Q: How to compare strings based on caracters similarity in SQL? I'm working on redirecting people if they type a "not really wrong url".
For example I have a good URL http://www.website.com/category/foo-bar-if-bar-foo/.
This one works so if a user enter to my website with it, I can retrieve the article corresponding.
But if someone enter to my website with a not really wrong url like http://www.website.com/category/foo-bar-foo/ because an another website has referenced a wrong url, I should redirect him to the right one instead of having a 404 status code...
So how should I do this? and Most important, should I do this ?
I actually use Eloquent with Laravel 4.2.
Thank you in advance.
EDIT
I was wrong about stackoverflow, thanks for your comment. It uses the unique ID of a post.
EDIT 2
I Looked at SOUNDEX function in SQL, it's really good if there is a small difference like a character or two missing. But if my url is as broken as my example, it's not working anymore obviously. But thanks it's gonna be usefull.

A: Just thinking off the top of my head, you could create a SQL table (with Full-Text indexing enabled) containing all your paths (it might already exist).
In the event that a 404 is triggered, hijack that and do a MATCH (Full Text Search) and return the path with the highest scoring MATCH (you can also consider using a score threshold to prevent nonsensical matches).


text:
Q: Error on React-Native Android hardaware BackButton click "Undefined is not a function(evaluating '_this2.close()') " I have installed the react-native-orientation-loading-overlay package for applying the loader on the screen.
When user clicks on the hardware back button, the backAndroid's addEventListener is called. Depending on the condition, loader's animating property is set to true and the orientation loader starts loading.
While loading, the another function this.fetchData() is started running which fetches data by running the webservice and display in listview of same page i.e mainPage.
And while loading, if the user has again pressed the back button the red screen with the error "Undefined is not a function(evaluating _this2.close()) in onRequestClose method of react-native-orienation-loading-overlay\src\index.js file" displays .I have tried to BackAndroid.removeEventListener('hardwareBackPress', () => {}); after the loader's animating property is set to true but its not
working.
Please give me any solution.
  import OrientationLoadingOverlay from 'react-native-orientation-loading-overlay';

   <OrientationLoadingOverlay
     visible={this.state.animating}
     color="#6495ed"
     indicatorSize="large"
     messageFontSize={16}
     message="Loading..."
   />

My hardware backbutton click event listener code is as follows:
   BackAndroid.addEventListener('hardwareBackPress', () => {
     if(this.state.drawerState===true) {
       this.refs['draw'].closeDrawer();
     } else {
       if(this.props.navigator.getCurrentRoutes().length===1&&
         this.state.tagPressed===false){
         if (stack.length===0){
           Alert.alert(
             'Exit',
             'Are you sure?',
             [
               {text: 'Cancel', onPress: () => {return true;}},
               {text: 'Yes', onPress: () => BackAndroid.exitApp()},
             ],
           )
         } else {
           this.backButtonEvent();
         }
       } else {
         if(this.props.navigator.getCurrentRoutes().length===1&&
           this.state.tagPressed===true) {
           this.setState({ animating: true });
           this.setState({ tagPressed: false });
           this.setState({ title: 'Repository' });
           this.fetchData();
         } else {
           this.props.navigator.pop();
         }
       }
     }
     return true;
   });

Here the stack.length is the length of array of navigated routes. And my backButtonEvent() function is as follows:
   backButtonEvent() {
     if(stack.length===0) {
       this.refs['draw'].openDrawer();
     } else{
       this.setState({animating:true});
       dirPath = stack.pop();
       title = this.titleStack.pop();
       if(stack.length===0) {
         this.setState({srcUrl:require('../image/drawer1.png')});
         this.setState({drawerLock:'unlocked'});
       }
       this.fetchData();
     }
   }

 <ListView
   dataSource={this.state.dataSource}
   renderRow={(this.renderItem.bind(this))}
   enableEmptySections = {true}
 />

fetchData(data){
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(data)
  });
}

A: Refer to the line 82 of source code of the react-native-orientation-loading-overlay, it uses the function this.close() to close the Modal but when refer to the RN 0.41 Documentation, this.close() is not pre-defined function for Modal, therefore it triggered the mentioned error when typeof this.props.children === 'undefined'. It is a bug for the package. It might have new state to control the on/off of the Modal, and allow this.close() function to change the state to off the Modal.


text:
Q: Javascript dynamic varible in $.each statement I have a catalog of items which are all shown through a while loop all items have a description, which can be copied with the ZeroClipboard plugin.
I need to make the code below create a client for each of the .itemDescriptionContainer's. So that i copies the correct data.
I created an attribute with the id of the item containing the description .itemDescriptionContainer

Current Code - I tried (and not working)
HTML
//While Loop

Copy Description

//endwhile

Javascript
$(".itemDescriptionContainer").each(function(index){
    var client = new ZeroClipboard( document.getElementById("copy-button") );

    client.on("ready", function(readyEvent) {
        client.on("aftercopy", function(event) {
            event.target.innerHTML = "Description Copied!";
        });
    });
});

*The following code is kinda working, it only copies the description of the first item in the whileloop
HTML
//While Loop

id}}}">

id}}}" data-clipboard-target="copyDescription-{{{$item->id}}}">Copy Description

id}}}">

//endwhile

Javascript
    var itemID = $(this).attr('data-itemID');
    // Attach itemID to client somehow to make a client instance unique.

    var client = new ZeroClipboard( document.getElementById("copy-button") );

    client.on("ready", function(readyEvent) {
        client.on("aftercopy", function(event) {
            event.target.innerHTML = "Description Copied!";
        });
    });

A: I fixed the problem with the use of the window function, i hope some can find this useful.
$(".itemDescriptionContainer").each(function(){
   var itemID = $(this).attr('data-itemID');

   // Copy Item Description
   var dynamic = window["client" + itemID] = new ZeroClipboard(document.getElementById("copy-button-"+itemID));

   dynamic.on("ready", function(readyEvent){
      dynamic.on("aftercopy", function(event){
         event.target.innerHTML = "Description copied!";
      });
   });

});


text:
Q: How to set icon to my jar using Visual studio Hi I am using Visual Studio,
             I want to set icon to my jar file. But I donot know how to set icon file to my Jar file. So How can I set icon to my Jar file.
Thanks
Sunil Kumar Sahoo

A: I'm assuming that you are creating a Setup project in VS and have a .jar file as an installable item. I might be wrong but I don't think you can change the icon of this file as the OS has a standard icon associated with all file types. If you're yourself creating a .net .exe then you get the option to specify an icon for this assembly through Project Properties -> Application -> Icon and manifest setting.
If you want to change the icon associated with .jar files (all .jar files on your system and not just one .jar file), then try this:
http://www.online-tech-tips.com/computer-tips/change-file-icon/
The above change will change the default icon associated to a file type (.jar in our case) and will show the icon of your choice. But I think this setting will work only on your system. On the target system where you aim to deploy this .jar file, it'll show the icon that is configured for .jar files on that system.
Let me know if I got the question wrong.


text:
Q: Sketching graph of $F(x)=\left(\frac{x-4}{4x}+\frac{x-12}{4x-16}-\frac{x+4}{4x-x^2}\right):\frac{1}{2x}$
Sketch the graph of:$$F(x)=\left(\dfrac{x-4}{4x}+\dfrac{x-12}{4x-16}-\dfrac{x+4}{4x-x^2}\right):\dfrac{1}{2x}$$

So, we start with the domain: $D: x\ne0, x\ne 4; x\in(-\infty;0)\cup(0;4)\cup(4;+\infty).$ When I simplify, I get $F(x)=x-4.$ I am trying to sketch the graph of the function. By a theorem, point $A(0;-4)$ lies on it but in the domain $x\ne 0$. How should I make it?

A: Assuming your statements are correct, the graph should just be the straight line $F(x)=x-4$ with holes in the line corresponding to the points where $x=-4,0,4$  What theorem says $(0,-4)$ is on the graph?  As you say, the function is not defined at $x=0$.  You can the limit of the function as $x$ approaches each of these points and get a finite answer.  These are called removable singularities because you can "fill them in" to get a continuous function.


text:
Q: Storing a c++ struct of unknown type in a void pointer - What struct property is required? I want to use my function assign below, to store a struct of unknown type at a specific memory address stored in a void pointer. This works fine for some structs (e.g. with Test1), but for other structs it does not work (e.g. with Test2). Unfortunately, I could not find any pattern for what sort of structs it will work, as it has worked for some POD and non-POD structs.
What criteria must be fulfilled for a struct in order to store it this way?
#include <vector>

template <typename T>
void assign(void* p, T obj){
    T* t = reinterpret_cast<T*>(p);
    *t = obj;
}

struct Test1{
    int i1;
    int i2;
};

struct Test2{
    std::vector<int> i;
};

int main()
{
    void* p = new char[100];
    Test1 test1;
    test1.i1 = 0;
    test1.i2 = 0;
    Test2 test2;
    test2.i = std::vector<int>();

    assign(p, test1);
    assign(p, test2);

    delete[] p;
    return 0;
}

Edit:
Why do I want to have this? I am currently implementing a game engine that uses an entity-component-system model (An entity is a game object, a component is kind of its attribute(s) and a system implements the logic to modify components.). There is a class that stores and manages entities (not surprisingly called EntityManager). Some programmer that uses my engine can define components (simply structs, only meant to contain data and no functionality) for an entity. The EntityManager therefore needs to store objects whose type is not known beforehand. A further restriction is that the components should be stored in an efficient way, i.e. behind each other in memory. This is the reason why a simple approach like having a base class Component and then having a member variable vector<vector<Component*>> is not appropriate.
My solution is that the EntityManager allocates enough space to store a certain user-defined maximal number of entities beforehand. A given component can then be stored with the assign function above.


text:
Q: Cannot open link in emacs org-mode I am trying to open a hyperlink inside emacs. Inside the org file, I tried to C-c C-o on the link, but instead of opening the link, emacs says "No match - create this  as a new heading? (y or n)"
Where am I going wrong?

A: Maybe you missed the http:// in front of the web-address?
A full link looks like that: http://www.google.com or that: [[http://www.google.de]] or that: [[http://www.google.de][your description here]].
See C-h i g (org) External links.


text:
Q: clang++ library not found even when providing library path I was trying to create a new OpenGL project with glfw and glad using vs code on an m1 Mac, and setup the files such that I have the include folder and lib folder which contains the necessary headers and library (libglfw3.a) files and the src folder that contains the glad.c and main.cpp, all in my workspace folder.
I have modified the tasks.json file like such:
{
"version": "2.0.0",
"tasks": [
    {
        "type": "cppbuild",
        "label": "C/C++: clang++ build active file",
        "command": "/usr/bin/clang++",
        "args": [
            "-fdiagnostics-color=always",
            "-g",
            "-std=c++17",
            "-I${workspaceFolder}/include",
            "-L${workspaceFolder}/lib",
            "${workspaceFolder}/src/*.cpp",
            "${workspaceFolder}/src/glad.c",
            "-llibglfw3",
            "-o",
            "${workspaceFolder}/game"
        ],
        "options": {
            "cwd": "${fileDirname}"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "detail": "compiler: /usr/bin/clang++"
    }
]

}
However, I get the following error:
ld: library not found for -llibglfw3
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I thought that I had properly included the path to the glfw library, but it says that it could not find the library. What am I doing wrong?
As a side-note, I have followed this tutorial to setup the program, but this post assumes that you have a windows machine, so I had downloaded/changed some things to my knowledge of what would work with the m1 mac.

A: Normally when you give libraries to link with the -l flag, you omit the lib prefix. For example: "-lglfw3" links the file "libglfw3.a". It looks like you should change your -llibglfw3 option.


text:
Q: Jacoco Report missing I'm trying to create a jacoco report on my project. The project is in java 12 version and the jacoco-maven-plugin is on version 0.8.5.
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.5</version>
                <executions>
                    <execution>
                        <id>pre-unit-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

I launch a mvn clean site
mvn clean install site

And I obtain:
[INFO] --- jacoco-maven-plugin:0.8.5:prepare-agent (pre-unit-test) @ bowling-game ---
[INFO] argLine set to -javaagent:/home/baptiste/.m2/repository/org/jacoco/org.jacoco.agent/0.8.5/org.jacoco.agent-0.8.5-runtime.jar=destfile=/home/baptiste/IdeaProjects/Bowling-Game/target/jacoco.exec

...
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ bowling-game ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.keywer.kata.bowling.game.frame.state.FrameStateTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.064 s - in com.keywer.kata.bowling.game.frame.state.FrameStateTest
[INFO] Running com.keywer.kata.bowling.game.BowlingGameTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 s - in com.keywer.kata.bowling.game.BowlingGameTest
...
[INFO] --- jacoco-maven-plugin:0.8.5:report (post-unit-test) @ bowling-game ---
[INFO] Skipping JaCoCo execution due to missing execution data file.

I'm looking for the report but indeed it was not created, due to the following line:
[INFO] Skipping JaCoCo execution due to missing execution data file.
What I have forget ?

A: My project is write in java 12 version and I enabled preview feature like this.
<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
    <configuration>
      <argLine>--enable-preview</argLine> <=== This line
    </configuration>
</plugin>

The issue was that maven was not able to generate jacoco.exec.
I find the awnser thanks to @Jacek Laskowski with this comment https://stackoverflow.com/a/23605812/8591625
I just replace by
<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
    <configuration>
       <argLine>${argLine} --enable-preview</argLine> <=== Here I adding ${argLine} in order to not override argument
    </configuration>
</plugin>


text:
Q: How can I show an error message if ajax post failed? I have an ajax post request that works well if the user is logged in but gives an error if the user is logged out.
The error that gets thrown in the console

POST http://localhost/r2/public/votes 500 (Internal Server Error)

I have an authentication gate forbidding users to vote if they're not logged in. All is good so far.
But I would like to show a customized an error message, perhaps in a simple modal window.
at the moment, I am trying to console.log() but it's not printing anything, I keep getting the same error as above.
$('.topic').upvote();

$('.vote').on('click', function (e) {
    e.preventDefault();
    var $button = $(this);
    var postId = $button.data('post-id');
    var value = $button.data('value');
    $.post('http://localhost/r2/public/votes', {postId:postId, value:value}, function(data) {
    if (data.status == 'failure')
    {
       console.log('You are not logged in.');
    }
   }, 'json');
});

A: See http://api.jquery.com/jquery.post/
var jqxhr = $.post( "example.php", function() {
  alert( "success" );
}).fail(function() {
  alert( "error" );
});

And it is not ideal to use 500 for authentication errors as there is 401 for that.


text:
Q: Horizontal Recyclerview not scrolling inside FramLayout or CoordinatorLayout   <android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/carousal_parent_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="?attr/actionBarSize">

    </FrameLayout>
  </android.support.design.widget.CoordinatorLayout>

and in Inner FrameLayout i am adding a Horizontal Recyclerview with fixed Size .
carousel_parent_layout = findViewById(R.id.carousal_parent_layout);
 carouselPager = view.findViewById(R.id.carouselPager);
    carouselPagerAdapter = new CarouselPagerAdapter(mContext, carouselData, carouselPager);
    carouselPager.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
    carouselPager.setHasFixedSize(true);

carousel_parent_layout.addView(carouselPager);

But on touching Recyclerview it is not flinging . I have tried with SnapHelper and  android:descendantFocusability="blocksDescendants" but nothing is working. Any help is highly appreciated. Thanks a lot in advance for reading the question.


text:
Q: How do I open the previous active tab when returning from a new html page How do I return back to the previous active tab if I am moving back from another html page?
I am having 5 tabs and within content of each tab there are links to another set of html pages. For example I am having a page called 'school.html' and it has 5 tabs. In tab 2 content (it shows individual student details) I am having a link to "Add new student" to a new page named addNewStudent.html.
After adding a new student in addNewStudent.html, I need to automatically comeback to original page with tabs (window.location = 'school.html'). So how to make tab 2 active showing the tab 2 content (student details).

A: This can be done in two ways depends upon your usage..
1)if you use browser back in addNewStudent.html to go to school.html.Better to use cookie concept.
 For ex: when going to addNewStudent.html from school.html setcookie("tabchange","tab2")
         when coming back from addNewStudent.html to school.html(onload of school.html check whether the cookie exist or not,if exists depends upon cookie enable your tab);
2) if you use any button or link in addNewStudent.html to go to school.html.Better to use queryparams.
 for ex: pass tabchange queryparam for school.html to addNewStudent.html?tabchange=tab1
         get that queryparam from addNewStudent.html and assign to link or button your as        href="/school.html?tabchange=tab1"
       after clicking that button onload of school.html get the queryparam and enable the tab..


text:
Q: using cloudsql proxy without credentials I'm currently trying to deploy phpmyadmin on GKE to use with google cloud SQL.
I'm following this tutorial https://cloud.google.com/sql/docs/mysql/connect-kubernetes-engine.
But is there some way to connect to google cloud SQL without supplying credentials to cloudsql-proxy pod?
I'd like to have the phpmyadmin users to supply their own credentials using browser and not having to update the phpmyadmin deployment when they change - they are unnecessary to store in this case I think. PHPMyAdmin will not try to connect to SQL server on its own.
I've tried to add my GKE cluster to authorized networks of google cloud SQL, but I got an error saying, that internal networks are not allowed.
What should I do in this case ?

A: I've re-read the docs and realized that db-credentials and instance-credentials are different thing. I created service account which is used by cloudsql-proxy to access the cloud SQL instance. DB credentials is not something that I should supply to cloudsql-proxy.


text:
Q: Robocopy - File names with an Ampersand So I have a pretty basic batch script that looks at an incoming folder and based on file type moves files where I want them. Now folders that show up with "&" in them break it. How do you go about fixing this? I couldn't find an obvious answer online.
robocopy.exe "%location%" "%destination%" /E /tee /LOG+:C:\Users\etc\Log.txt

EDIT 2:
OK thanks to the comments bellow and a bunch of trail and error I figured that it was a quotation issue. Now after a bunch of trial and error found a combination of quotes and no quotes that worked, I have no idea why though. If some one is able to explain why this works and other combinations didn't I would appreciate it haha...batch is so weird.
Input -> Test.bat "C:\etc\etc\" - Path in quotes
set location=%1 - No Quotes
set type="%~2" - Quotes
set destination="C:\Users\xxxx\Desktop\Destination" - Quotes
set logfile="C:\Users\xxxx\Desktop\robolog.txt" - Quotes
robocopy.exe %location% "%destination%" /E /tee /LOG+:%logfile% - Source with no quotes but destination in quotes???
Do quotes cancel each other out? I'm confused why adding quotes would make it not work, but only work in some cases?
Also having %~1 vs %1 vs "%1" vs "%~1" produced different results.

A: I tested this:
@ECHO OFF &SETLOCAL
SET "location=this & that"
SET "destination=more & more"
robocopy.exe "%location%" "%destination%" /E /tee /LOG+:"%destination%\Log.txt"

And I got no error:
-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows     ::     Version XP010
-------------------------------------------------------------------------------

  Started : Wed Jul 31 09:59:55 2013

   Source : C:\TEST\this & that\
     Dest : C:\TEST\more & more\

    Files : *.*

  Options : *.* /TEE /S /E /COPY:DAT /R:1000000 /W:30

------------------------------------------------------------------------------

------------------------------------------------------------------------------

                Total    Copied   Skipped  Mismatch    FAILED    Extras
     Dirs :         1         0         1         0         0         0
    Files :        81        81         0         0         0         1
    Bytes :    28.3 k    28.3 k         0         0         0         0
    Times :   0:00:00   0:00:00                       0:00:00   0:00:00

    Speed :              184585 Bytes/sec.
    Speed :              10.562 MegaBytes/min.

    Ended : Wed Jul 31 09:59:55 2013


text:
Q: Getting table header info on $connection->selectall_array($command) I am using $connection->selectall_array($command) to grab data from MySQL. I am curious if there is a different command where my return is the same, except the first element will be the data column's name?
Obviously I know them already.  But would be convenient if there was a way.
Thanks


text:
Q: PHP/JS : Preventing doubleinserting with function Yes im having a issue i thought i didn't have.
When you submit it runs a javascript function, that runs an ajax call. This function have this right under it´s name(first line in the function):
 $('#submitWall').attr('disabled', true);

This works very well, but not so well for the faster humans...I tried to click/pressing enter really fast, and it inserted to the database 2-3 times.
And I want to prevent this. As i said i have the above, which didn't solve it 100%.
Is there a solution for this in JS/jquery or maybe in PHP, so there's like a 1 second timelimit somehow..?
Here's my function:
    function DoWallInsert(BuID, uID){
     $('#submitWall').attr('disabled', true);
  var wrapperId = '#wall_insert';
    $.ajax({
       type: "POST",
       url: "misc/insertWall.php",
    data: {
    value: 'y',
    BuID : BuID,
    uID : uID,
    message : $('#message').val()
    },
       success: function(msg){
$('#submitWall').attr('disabled', false);
     $(wrapperId).prepend(msg);
     $(wrapperId).children().first().slideDown('slow');
     $('#message').val("");
        }
     });
}

A: Don't just set the attribute to disabled, also remove the onclick value.  Then, use setTimeout() to replace it after X time.
document.getElementById('submitWall').onclick='';
setTimeout("document.getElementById('submitWall').onclick='DoWallInsert';", 1000);

That code may need tweaking, I'm not on my web development machine and can't test it.

A: I think the problem here is that the attribute change does not come into effect until the function ends due to the fact that javascript runs single thread.
If you setTimeout to another function with minimum delay and have that function do all the rest of the processing, and maybe also have the first function test the attribute first and bailout if it is already disabled it might prevent this.
Since Javascript is single thread, even if the first function is run twice in a row before gui is updated the second call should still see it as disabled and ignore your click.
It might even be enough to check the attribute first, and if it is disabled, exit function.
 if($('#submitWall').attr('disabled'))
      return ;


text:
Q: Why not signing in causes error "Google Play in-app billing API version is less than 3" When Google Play has not been signed in, running BillingClient.startConnection() results in BillingResult returned by onBillingSetupFinished() showing billingResult.getDebugMessage():

Google Play In-app Billing API version is less than 3

This error is gone as soon as Google Play is signed in.
Is there a way to get an accurate error for this situation?

A: The message indicates that you are using a Google Play Developer API that is lower than v3.
The Google Play Developer API will only support the v3 endpoint after 1 December, 2019. Here is the blog post:
https://android-developers.googleblog.com/2019/03/changes-to-google-play-developer-api.html
For more context, the Google Play Billing Library (currently 2.1.0) is the client API used in your Android app.
The Google Play Developer API (currently v3) is the server API used for managing purchases and managing your app on Google Play.


text:
Q: Deal with huge JSON responses I think I need to rewrite some modules of my app because when the number of entities that are rendered increases, it fails and errors too. At this moment, I'm using Jackson and HttpClient.  As much as I trust in Jackson, something tells me that the problem is the second lib. Can HttpClient deal with large responses? (e.g. this one that is about 400 lines)
Besides that, in my app, the way I parse the request goes something like this:
public Object handle(HttpResponse response, String rootName) {
    try {
        String json = EntityUtils.toString(response.getEntity());
        // better "new BasicResponseHandler().handleResponse(response)" ????
        int statusCode = response.getStatusLine().getStatusCode();
        if ( statusCode >= 200 && statusCode < 300 ) {
            return createObject(json, rootName);
        }
        else{
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public Object createObject (String json, String rootName) {
    try {
        this.root = this.mapper.readTree(json);
        String className = Finder.findClassName(rootName);
        Class clazz = this.getObjectClass(className);
        return mapper.treeToValue(root.get(rootName), clazz);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

How I can improve this piece of code to be more efficient with large responses?
Thanks in advance!

A: There's no need to create the String json, as ObjectMapper#readTree can accept an InputStream as well. For example, this will be slightly more efficient:
public Object handle(HttpResponse response, String rootName) {
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ( statusCode >= 200 && statusCode < 300 ) {
            return createObject(response.getEntity().getContent(), rootName);
        }
        else{
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

public Object createObject (InputStream json, String rootName) {
    try {
        this.root = this.mapper.readTree(json);
        String className = Finder.findClassName(rootName);
        Class clazz = this.getObjectClass(className);
        return mapper.treeToValue(root.get(rootName), clazz);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

A: Ive had 1000+ line json responses handled without issue, so that shouldnt be a problem. As for better ways of doing it, Google GSON is amazing, itll map your json to you java object with no special parsing code whatsoever.

A: I guess you could read data to a good old StringBuffer. Something like
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
    InputStream is = AndroidHttpClient.getUngzippedContent(httpEntity);
    br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder(8192);
    String s;
    while ((s = br.readLine()) != null) sb.append(s);
}


text:
Q: Limit friendship based on activity points In Social Engine, is there a way to restrict user sending friend request unless he has activity points?

A: No, There is no way to restrict to sending the friend request. You need to customize the code for that.


text:
Q: Redirect in Chrome Custom tab is not captured for deep link I'd like to capture a redirect that occurs in a Chrome Custom tab to ensure the user stays in a native mobile application.
Here's how the Chrome Custom Tab is launched:
val url = "https://demo.company.com/sso/oidc/start/?idp_connection_id=Username-Password-Authentication&status_response_url=https://member.example.com/urgent"
val builder = CustomTabsIntent.Builder()
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(this, Uri.parse(url))

That web page redirects to the URL given as the status_response_url parameter after the user authenticates. The mobile app registers for the appropriate scheme:
 <intent-filter android:autoVerify="true">
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data
         android:host="member.example.com"
         android:scheme="https" />
  </intent-filter>

Unfortunately, the system does not seem to capture the redirect. Why?

A: This is a well known problem with App Links and SSO, due to the lack of a user gesture.
You are using the preferred Claimed HTTPS Schemes option but an interstitial web page is needed for it to work reliably.
My blog post has further info on this, including a code sample you can run to review the UX.


text:
Q: comparing strings doesnt work i can't understand why in the 7-6 line (for the end) when i input the same book name it doesn't get into the "if". i wrote the printf line above it to check if the print is any different but it is'nt. it's printed the same stuff for both a.name and bookz[r].name.
thanks!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BOOK_NUM        50
#define NAME_LENGTH     200
#define AUTHOR_NAME_LENGTH  100
#define PUBLISHER_NAME_LENGTH   50
#define GENRE_LENGTH        50

typedef struct book {
    char name[NAME_LENGTH];
    char author[AUTHOR_NAME_LENGTH];
    char publisher[PUBLISHER_NAME_LENGTH];
    char genre[GENRE_LENGTH];
    int year;
    int num_pages;
    int copies;
} Book;

int main()
{
    int opt = 1;
    int i = 0, r = 0, k = 0, years, pagess, copiess, copies_to_add;
    Book bookz[50];
    int zeros[5] = { 0, 0, 0 ,0 ,0 };
    Book a;
    char c;
        // Add book to library
        printf("Please enter book name: ");
        scanf("\n%[^\n]s", &a.name);
        for (i = 0; i < BOOK_NUM; i++)
        {
            if (zeros[i] == 0)
            {
                scanf("\n%[^\n]s", &a.author);
                scanf("\n%[^\n]s", &a.publisher);
                printf("Please enter book genre: ");
                scanf("\n%[^\n]s", &a.genre);
                scanf("%d", &a.year);
                scanf("%d", &a.num_pages);
                scanf("%d", &a.copies);
                k = i;
                bookz[k] = a;
                zeros[i] = 1;
                printf("The book %s was successfully added!", a.name);
                break;
            }
            else
            {
                for (r = 0; r < i+1; r++)
                {
                    printf("%s %s", bookz[r].name, a.name);
                    if (bookz[r].name == a.name)
                    {
                        printf("The book already exists. Please enter the number of copies to add:");
                        scanf("%d, &copies_to_add");
                        bookz[i].copies = bookz[i].copies + copies_to_add;
                        printf("Additional copies (%d) of book %s were successfully added!", copies_to_add, a.name);
                        break;
                    }
                }

            }
        }

A: String comparison in C is best achieved using strcmp().


text:
Q: HTTParty Digest Auth Can anyone provide an example of using HTTParty using digest auth? I can't find examples on the net and was hoping someone could provide some help. Thanks.

A: Rob's answer worked for me, but there's another way that doesn't affect the entire class. You could thus change the values for each call.
The following is slightly modified from the HTTParty doc:
class Twitter
  include HTTParty
  base_uri 'twitter.com'

  def initialize(u, p)
    @auth = {:username => u, :password => p}
  end

  def post(text)
    options = { :body => {:status => text}, :digest_auth => @auth }
    self.class.post('/statuses/update.json', options)
  end
end

See the digest_auth part? I changed that from the original example's basic_auth.

A: you can set the username and password using the digest_auth method when defining your class
class Foo
  include HTTParty
  digest_auth 'username', 'password'
end


text:
Q: How to globalize/translate numbers in Angular based on locale I am using ngx-translate library to take care of localization support in my Angular8 app. In one specific feature module, it is required to show row numbers for each row of the table. There is also an option to create a new row and the newly created row should have a row number which is the next integer that follows the previous row number.
Is it possible to localize the row numbers being displayed depending on the user locale (both the existing row numbers and the dynamically created row numbers). So, if the locale is 'en_US' and the row number is "twelve", it should be displayed as "12" whereas for Chinese locale the row number should be displayed as "十二".


text:
Q: Could not load requested file in assets folder I can not load my assets folder that is outside my application / view folder
<?php $this->load->view('assets/parts/webpage/header'); ?>

My directory is like this

Assets > parts > webpage > header

But on my screen this appears
Unable to load the requested file: /assets/parts/webpage/header.php

A: if you want to load assets folder outside of application then you have to set view directory in index.php file.
$view_folder = '';


text:
Q: "Thank you in each case" usage I was wondering is the phrase "Thank you in each case" appropriate to say at the end of question asking someone for some help, in formal or informal situations. I very often use it, and was thinking it was okay, but now it has occured me it may look "cold" to people (informally) or not so professional.. Can someone tell me what do English language experts think about that phrase, and what should be better used instead expressing gratitude? (i'm not native in English)
Thank you very much for consideration.


text:
Q: Bug: Select2 Ajax Multiselect Checkbox Does't Delete (Deselect) When You Double Click(Toggle) On Select This is Select2 library
Checkbox normally works after double clicks. It carries out the Add and Delete operation.
But when I use the ajax multiselect checkbox, it can add but I cannot delete it through select.
When I want to delete, I can only delete it by pressing x on the top.
This is my code : https://codepen.io/tolga-kurtulu/pen/KKaOVXp?editors=1011
enter image description here
HTML
   <select class="select2" style="width: 100%;" multiple="multiple"></select>

Javascript
$(document).ready(function() {
  $("select.select2").select2({
        closeOnSelect: false,
        placeholder: "Placeholderr",
        // allowHtml: true,
        allowClear: true,
        tags: true,
        // debug: true,
    ajax: {
      url: "https://api.github.com/search/repositories",
      dataType: 'json',
      data: (params) => {
        return {
          q: params.term,
        }
      },
      processResults: (data, params) => {
        const results = data.items.map(item => {
          return {
            id: item.id,
            text: item.full_name || item.name,
          };
        });
        return {
          results: results,
        }
      },
    },
  });
})


text:
Q: How do I make my modal close in x seconds? I am using ReactJS and a Bootstrap modal. I can open the modal just fine, but I would like it to close after 3 seconds.
I tried setTimeout as you can see below, but it doesn't close. I gave setTimeout a callback of handleClose, but after console logging, I can see that handleClose is not being called.
Here is the ItemDetailView Component:
    import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Card, CardImg, CardText, CardBody,
  CardTitle, CardSubtitle } from 'reactstrap';
import { addToCart } from '../actions/addToCartAction';
import './ItemDetailView.css';
import ItemAddedModal from './ItemAddedModal';

class ItemDetailView extends Component {
  constructor(props) {
    super(props);

    this.state = {
      modalOpen: false
    }
    // this.toggle = this.toggle.bind(this);
  };

  // toggle() {
  //   this.setState({
  //     modalOpen: !this.state.modalOpen
  //   });
  // };

  handleOpen = () => {
    console.log("Cart Open", this.state.modalOpen);
    this.setState({
      modalOpen: true
    },() => {setTimeout(this.handleClose(), 3000)});
    // setTimeout(this.handleClose(), 3000);
  };

  handleClose = () => {
    this.setState({
      modalOpen: false
    });
    console.log('handleClose fired!')
  };

  addToCartHandler = () => {
    this.props.addToCart(this.props.card);
    console.log('addToCart++', this.props.quantity);
    this.handleOpen()
    // this.setState({
    //   modalOpen: true
    // });
  };

  render() {
    if (!this.props.title) {
      return null;
    }

    return (

        <Card className="text-center detail-view-card">
          {/* <CardImg top width="100%" src={"/" + this.props.img} alt={this.props.title} /> */}
          <CardImg className="detail-view-img" top width="100%" src={"/" + this.props.img} alt={this.props.title} />
          <CardBody>
            <CardTitle className={"card-title"}>{this.props.title}</CardTitle>
            <CardSubtitle>${this.props.price}</CardSubtitle>
            <CardText>{this.props.description}</CardText>
            {/* <SvgIcon className="cart-icon" onClick={() => this.addToCartHandler()} >
              <AddShoppingCart />
            </SvgIcon> */}
            <button className= "add-to-cart-button" onClick={() => this.addToCartHandler()}>Add To Cart</button>
          </CardBody>
        </Card>
        <ItemAddedModal open={this.state.modalOpen} toggle={this.toggle} />

    );
  }
}

const mapStateToProps = state => {
  if (!state.data.cardData) {
    return {
      title: null,
      img: null,
      description: null,
      price: null
    }
  }
  const card = state.data.cardData[state.card.id]
  return {
    card: card,
    title: card.title,
    id: card.id,
    img: card.img,
    description: card.description,
    price: card.price,
    quantity: 0
  };
}

export default connect(mapStateToProps, { addToCart })(ItemDetailView);

Here is the ItemAddedModal:
import React from 'react';
import { Modal, ModalHeader } from 'reactstrap';
import './ItemAddedModal.css';

class ItemAddedModal extends React.Component {

  render () {
    return (

          <Modal className="item-added-modal" isOpen={this.props.open} toggle={this.props.toggle} className={this.props.className}>
            <ModalHeader className="item-added-modal-header">

Item Added To Cart

            </ModalHeader>
          </Modal>

    )
  };
}
export default ItemAddedModal;

A: To perform an action after a state is set, we need to pass a callback to setState.
 this.setState({
  modalOpen: true
},()=>{
console.log(this.state.modalOpen);});


text:
Q: Xamarin Forms Video Player (MediaManager Plugin) I am very new to Xamarin...
I am trying to create a youtube like app. I have no idea how to play video inside of my app. Ive tried to use the MediaManager plugin https://github.com/martijn00/XamarinMediaManager but simply cannot figure it out.
If anyone could suggest a different plugin, or explain IN DETAIL how to use the MediaManager Plugin, that would be fantastic.
The docs on the plugin are atrocious, i cannot understand it at all.
Heres what I have so far: I am simply trying to play a video through a button click.
Xaml file:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Video_Play_Page"
         Title="Video_Play_Page"
         BackgroundColor="#4B1388">
<ContentPage.Content>
    <StackLayout Padding="10, 10, 10, 10">

        <Label Text="video Player..." />

        <Button Clicked="PlayVideo" Text="Play me!"/>
    </StackLayout>
</ContentPage.Content>

Xaml.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using Plugin.MediaManager;

namespace App2
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Video_Play_Page : ContentPage
{
    public Video_Play_Page()
    {
        InitializeComponent();
    }

    private void PlayVideo(object sender, EventArgs e)
    {
        CrossMediaManager.Current.Play("https://www.youtube.com/watch?v=Gm8bQxnold0");
    }
}
}

NOTE: I dont know if I have installed everything correctly. If someone could please explain that, it would be great too.

A: You have almost everything there.
you need to instantiate the player like
In .xaml file
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="App2.Video_Play_Page"
    Title="Video_Play_Page"
    BackgroundColor="#4B1388"
    xmlns:forms="clr-namespace:Plugin.MediaManager.Forms;assembly=Plugin.MediaManager.Forms">
    <ContentPage.Content>
        <StackLayout Padding="10, 10, 10, 10">

            <Label Text="video Player..." />
            <forms:VideoView />
            <Button Clicked="PlayVideo" Text="Play me!"/>
        </StackLayout>
    </ContentPage.Content>

or in .xaml.cs file
new VideoView { };

but with your code i suggest the first option.
Then you will say to the plugin that you want to reproduce video and not audio.
private void PlayVideo(object sender, EventArgs e)
{
    CrossMediaManager.Current.Play("https://www.youtube.com/watch?v=Gm8bQxnold0", MediaFileType.Video);
}

I'm not shure if the plugin reproduces videos with youtube url, if this doesn't work you should replace the url with an absolute url like

https://sec.ch9.ms/ch9/37af/240037cc-e74a-421a-9946-7ce4205d37af/DiAndIocForXamarinForms.mp4

Here is a video to help you

A: You should put forms:VideoView in your Xaml file
Here is a sample to use it in Xamarin.Forms, check this
https://github.com/martijn00/XamarinMediaManager/tree/develop/Samples/Forms

A: Xamarin Community Toolkit
I would recommend checking out the MediaElement in Xamarin.Community.Toolkit
It is a cross platform video player which is well documented at:
https://learn.microsoft.com/en-us/xamarin/community-toolkit/views/mediaelement
You can generate the MediaElement in C# the same way you would any other control that can be created in Xamarin. It is very similar to the Image control in the way it works: allowing you to set aspect, whether or not to show the platform default video controls, etc...
In case you're quite new to Xamarin, heres the example from the link above:
<MediaElement Source="https://sec.ch9.ms/ch9/5d93/a1eab4bf-3288-4faf-81c4-294402a85d93/XamarinShow_mid.mp4"
              ShowsPlaybackControls="True" />

And the equivalent in C#:
MediaElement videoPlayer = new MediaElement
{

    Source = "https://sec.ch9.ms/ch9/5d93/a1eab4bf-3288-4faf-81c4294402a85d93/XamarinShow_mid.mp4",
    ShowsPlaybackControls = false

};

Which can be added to any view in the same way you would add a Label, Button or any other control that inherits the View class.
A handy tutorial from Gerald Versluis (a member of the Xamarin team) can be found here which details all of the things you can do with the plugin (and also some common errors and how to fix them):
https://www.youtube.com/watch?v=yJAKkz17WDo

A: If any still interested, this is an easy working sample for both Android and iOS which use Xamarin.CommunityToolkit's MediaElement
xam-mediaelement-sample


text:
Q: Prevent overriding some property in application.properties - Spring Boot I want to move some configuration in my property file, but don't want it to be overwritten at runtime, for security purpose. Is it possible to do it in spring boot?
Thanks,
Manish

A: Something like this should work, anything in secure.properties will not be able to be overridden as it will be added to the start of the env (from the properties file), regardless of what has been overridden.
@Configuration
public class SecurePropertiesConfig {

    @Autowired
    public void setConfigurableEnvironment(ConfigurableEnvironment env) {
        try {
            final Resource resource = new ClassPathResource("secure.properties");
            env.getPropertySources().addFirst(new PropertiesPropertySource(resource.getFilename(), PropertiesLoaderUtils.loadProperties(resource)));
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

A: I tried the SecurePropertiesConfig method posted here and interestingly what is happening for me is the property value is different based on if I use a @Value annotation or just load the Environment. The @Value annotation is resolving before the setConfigurableEnvironment method resolves. So @Value will resolve to property file values set directly in the classpath while the Environment variable will have the secure (un-overridable) property value once the method is actually running. It works if I just use Environment, but unfortunately that makes it a bit brittle to a future code change accidentally using @Value instead, thinking it is "secure". I modified the SecurePropertiesConfig.java to be a ApplicationContextInitializer to force it to load the properties first.
SecureProperties.java
public class SecurePropertiesConfig implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        try {
            final Resource resource = new ClassPathResource("secure.properties");
            environment.getPropertySources().addFirst(new PropertiesPropertySource(resource.getFilename(), PropertiesLoaderUtils.loadProperties(resource)));
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

And then add the initializer in your application.properties:
context.initializer.classes=package.path.config.SecureProperties


text:
Q: WCF service. Where to add . svc file I have created a new "WCF service library" type project. I have created a file for my contract and one file which implements the interface. Both files have the .cs extension.
Please can anyone tell me how can I consume it. I mean where should I add my .svc file

A: You have to create another project - Web application or WCF Service application (generally it is the same as Web application with some added references). Then you have to reference your service library in the new project and add .svc file. Delete code behind file from newly created .svc file and open markup of that file. Modify Service attribute of @ServiceHost directive. The attribute has to point to your service implemented in library (full name with namespace). Then add configuration to web config.
If you use WCF 4.0 you don't have to create configuration (default will be used) and you even don't need to define .svc file. WCF 4.0 supports configuration based activation.


text:
Q: What is the best type to use for an index variable in a for loop in C++? There have already been some questions on this topic (1, 2, 3). The thing is that there doesn't seem to be a clear-cut answer. Some answers suggest size_t (1, 2), some suggest ptrdiff_t (1, 2). Other options include int, uint32_t, auto or using decltype on .size() of a container or the member type size_type.
This question may seem unsuitable as being opinion-based, but I don't think that's the case. Just because there isn't already a consensus on which type to use, doesn't mean that there cannot exist an objective answer. This is due to the fact that the different choices aren't only aesthetical, but can actually influence the behavior of the code.
For example, using an index variable type with mismatched signedness in the loop condition will cause compiler warnings, like this. Also, using a type that has a range that is too small can cause an overflow, which in the case of signed types is UB. At the same time, in some cases changing the loop counter type can cause "crazy performance deviations".
I also wanted to find out what is the most popular, though not necessarily the best, way to create for loop, so I used GitHub* search to find out. Here are the results:

Loop type
Code result count on GitHub (averaged; "manual" loop + range-based)

for (int
15.8m

for (size_t
11.6m

for (auto
7.5m

for (uint32_t
2.3m

std::for_each
501k

for (ptrdiff_t
98.7k

for (decltype
77.5k

There are certainly large differences in occurrence count between the different loop types, however, there doesn't seem to be a clear outstanding leader.
As such I post this question asking, what is the best type to use for the index variable in a for loop in C++ or what are the rules or conditions based on which this type should be chosen?
*: The GitHub search tool produces varying results for "code results" (count) each time, so I averaged 26 values. As the search is text-based it includes both results of the form for (int i = 0; i < n; ++i) and for (int i : vec).


text:
Q: Best way to create entity objects with TypeScript? I'm just getting started with TypeScript and wanted to know if this is the best approach on initializing entity objects with data coming from an API.
How I did it before with JavaScript:
class Entity {
  constructor(apiResponseData = {}) {
    this.id = apiResponseData.id
    this.set = apiResponseData.set
    ...
  }

  toObject() {
    return { id: this.id, ... }
  }
}

For my approach with TypeScript:
interface EntityData {
  id: string
  set: string,
  ...
}

class Entity {
  id: string
  set: string

  constructor(apiResponseData: EntityData) {
    this.id = apiResponseData.id
    this.set = apiResponseData.set
    ...
  }

  toObject() {
    return { id: this.id, ... }
  }
}

Is there a better way to do this in TypeScript? It duplicates a lot of code due to declaring types multiple times and so it gets big the more properties I need to define.
An alternate way I thought of could be:
interface EntityData {
  id: string
  set: string,
  ...
}

interface Entity extends EntityData {
  toObject: () => EntityData
}

const buildEntity = (apiResponseData: EntityData) => {
  return {
    id: apiResponseData.id,
    set: apiResponseData.set,
    ...
    toObject: () => ({ id: apiResponseData.id, ... }) // imagine if method does some other operations to the data
  }
}

My only concern for this approach is if member data is changed (ex. id=1 => id=2 after entity is built), then toObject() will be incorrect.
Any ideas or other approaches?

A: the best way is to do it in TypeScript but there are some things you can do simpler.
interface EntityData {
    id: string;
    set: string,
}

// don't declare two properties,
// just create an interface
interface Entity extends EntityData {}

class Entity {
    // destruct data
    constructor({id, set}: EntityData) {
        this.id = id;
        this.set = set;
    }

    toObject(): EntityData {
        // destruct all own properties
        // (not methods in prototype)
        return {...this};
    }
}

I used destructing which is ECMAScript 6 standard. If you don't know it, see MDN docs for more info.


text:
Q: Как отписаться от post запроса Angular? У меня есть простой post запрос, который я использую для создания сообщений. Проблема в том, что функция sendMessage() будет работать абсолютно одинаково всегда после ее первого вызова, отправляя одно и то же сообщение в БД даже после того, как я изменю его текст, пока не пересоздам таблицу. Обновление странички ничего не дает, так что проблема видимо в запросе. Я пытался отписаться от запроса сразу же после его выполнения, но в таком случае сообщение даже не появляется в БД. Я также хотел использовать Observer.complete() или что-то в этом роде, но понятия не имею, как использовать лямбда-выражение не в новом Observable, а в методе create().
Буду признателен за любую помощь. В ангуляре новичок.
Сервис
@Injectable({
  providedIn: 'root',
})
export class MessageService {
  private url = environment.apiUrl + '/message';

  constructor(private http: HttpClient) {}

  public create(request: CreateMessageRequest): Observable<void> {
    return this.http.post<void>(this.url, request);
  }
}

функция
public sendMessage(message: string){
    let request: CreateMessageRequest = {
      Message:  message,
    }
    const req = this.messageService.create(request).subscribe();
    //req.unsubscribe();
  }

HTML
 <form>
      <textarea #refVariable [value]="test" type="text" placeholder="Write message"></textarea>
      <button class="buttonTwo" type="submit" (click)="sendMessage(refVariable.value)"></button>
  </form>

P.S.: был также попробован такой код, но с идентичным результатом
TS
export class DialogsComponent implements OnInit, OnDestroy {
constructor(private messageService: MessageService){}

private unsubscribe$ = new Subject<void>();
ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

public sendMessage(message: string){
    let request:
      Message: message,
    }
    this.messageService.create(request)
    .pipe(takeUntil(this.unsubscribe$))
    .subscribe();
  }
}

P.P.S.: Не знаю, насколько это имеет значение, но после выполнения кода функции в network отображается Request Method: OPTIONS 204 No Content и Request Method: POST 200 OK.


text:
Q: How do I transfer varibles through functions in Python I am trying to read from keyboard a number and validate it
This is what I have but it doesn't work.
No error but it doesn't remember the number I introduced
def IsInteger(a):
    try:
        a=int(a)
        return True
    except ValueError:
        return False

def read():
    a=input("Nr: ")
    while (IsInteger(a)!=True):
        a=input("Give a number: ")

a=0
read()
print(a)

A: a is a local variable to the two functions and isn't visible to the rest of your code as is.  The best way to fix your code is by returning a from your read() function.  Also, the spacing is off in your IsInteger() function.
def IsInteger(b):
    try:
        b=int(b)
        return True
    except ValueError:
        return False

def read():
    a=input("Nr: ")
    while not IsInteger(a):
        a=input("Give a number: ")
    return a

c = read()
print(c)

A: I think this is what you are trying to achieve.
def IsInteger(a):
    try:
        a=int(a)
        return True
    except ValueError:
        return False

def read():
    global a
    a=input("Nr: ")
    while (IsInteger(a)!=True):
        a=input("Give a number: ")

a=0
read()
print(a)

You need to use global expression in order to overwrite the global variable without a need to create return inside the function and typing a = read().
But I would highly recommend u to use the return and re-assigned the value of 'a', as someone stated below.

A: It appears as though you are not returning the result of the read() function.
The last line of your read function should be "return a"
And then when you call the read function you would say "a = read()"


text:
Q: How to read a csv file from url using pandas I would like to load a csv into a pandas dataframe and the data is available on a remote server.
The goal is to read it directly to a dataframe without writing the data to disk.
url = https://dev.azure.com/tankerkoenig/tankerkoenig-data/_git/tankerkoenig-data?path=/prices/2022/07/2022-07-01-prices.csv
I am thinking about an approach like this:
import requests
import pandas as pd

r = requests.get(url)
df = pd.read_csv(r.content)

Does anyone know if something like this is possible?

A: You can call read_csv method directly.
import pandas as pd

url="https://dev.azure.com/tankerkoenig/tankerkoenig-data/_git/tankerkoenig-data?path=/prices/2022/07/2022-07-01-prices.csv"
df=pd.read_csv(url)

OR if you want the text in string and read
from io import StringIO

import pandas as pd
import requests
url='https://dev.azure.com/tankerkoenig/tankerkoenig-data/_git/tankerkoenig-data?path=/prices/2022/07/2022-07-01-prices.csv'
s=requests.get(url).text

df=pd.read_csv(StringIO(s))


text:
Q: R in conda environment displays version 3.6.1 rather than 4.1.3
On my anaconda prompt, using these conda-forge packages to install r-base, i was expecting that when creating the environment i'll see r-base version 4.1.3 but instead it displays that the highest version of r available on my windows is version 3.6.1 as in the second screenshot. Please i'll need some help or pointers to where i might have gotten it wrong

A: The first screenshot is from conda-forge, which is a repository that is not being searched by default. The highest available version in the default repositories is 3.6. You need to add conda-forge as a channel to the environment, but I'm not sure how that works in the GUI. In the anaconda prompt you can do this
conda config --add channels conda-forge

in an activated environment.
Also r and r-base are different packages.