text:
Q: CakePHP: multiple checkbox with different html attribute Here is the situation:
i have table stages having following structure
 | id              |  name                                         | editable|
 -----------------------------------------------------------------------------
 | open            | Open                                          |    1    |
 | paysheet_review | Paysheet Submitted (Awaiting Office Approval) |    0    |
 | to_pay          | Paysheet Approved (Awaiting Payment)          |    0    |
 | paid            | Paid                                          |    1    |
 | purgatory       | Flip or Refund                                |    0    |
 | closed          | Deal Closed                                   |    1    |
 -----------------------------------------------------------------------------

I am creating a multiple checkbox block by
In Controller
<?php $_stages = $this->Stage->find("list");?>

In View
<?php echo $this->Form->input("stage", array("multiple" => "checkbox", "options" => $_stages));?>

which creates following html

 Stage
   <input type="hidden" value="" id="DealStage_" name="data[Deal][stage]">

    <input type="checkbox" id="DealStageOpen" value="open" name="data[Deal][stage][]">Open
    <input type="checkbox" id="DealStagePaysheetReview" value="paysheet_review" name="data[Deal][stage][]">Paysheet Submitted (Awaiting Office Approval)
    <input type="checkbox" id="DealStageToPay" value="to_pay" name="data[Deal][stage][]">Paysheet Approved (Awaiting Payment)
    <input type="checkbox" id="DealStagesPaid" value="paid" name="data[Deal][stage][]">Paid
    <input type="checkbox" id="DealStagePurgatory" value="purgatory" name="data[Deal][stage][]">Flip or Refund
    <input type="checkbox" id="DealStageClosed" value="closed" name="data[Deal][stage][]">Deal Closed

Now I want to pass the editablefrom Database column as a title for each checkbox.
Is there any way that we create a multiple checkbox in CakePHP and add a title as attribute to each input type checkbox. so that I can use jQuery to check OR uncheck only editable Stages.

A: Generate individual checkboxes
There's no means to give individual attributes to a checkbox if they are generated in one call, however it's easily achievable generating each checkbox individually. To do so ensure that the stages data is passed to the view:
// in Controller action
$stages = $this->Stage->find("all");
$this->set('stages', $stages);

And in the view simply iterate over the $stages variable to generate checkboxes:
// in view file
foreach ($stages as $stage) {
     $id = $stage['Stage']['id'];
     $name = $stage['Stage']['name'];
     $editable  = $stage['Stage']['editable'];

     echo $this->Form->input(
         'Deal.stage.' . $id,
         ['value' => $id, 'label' => $name, 'type' => 'checkbox', 'data-editable' => $editable]
     );
}

I don't quite follow what you want to do with this editable property - but to access it from js it would then be:
// in js file
$('input[type=checkbox]'].each(function() {
    var editable = $(this).data('editable');

    ...
});

A: Unfortunately, I can't find a way to add attributes to $options like you want. What I normally do is just do that part "by hand", forget the FormHelper and write old html.
If that's not an option for you and you want to keep using Formhelper for that, then I can suggest a js approach.
First you need to change the find('list') for a find('all') to get the editable attribute.
<?php $_stages = $this->Stage->find("all");?>

and pass it to the view. Now, in the view you need to modify the array so it looks like the old one
<?php
   $stageHelper = array();
   foreach($_stages as $stage)
      $stageHelper[$stage['Stage']['id']] = $stage['Stage']['name'];
   echo $this->Form->input("stage", array("multiple" => "checkbox", "options" => stageHelper));
?>

So far you have the same thing you have now. This is where js comes in. In the view, at the bottom preferably, add something like

Something along that lines should do.
Personally I find it less complicated to do it with html only. But there's an alternative approach to do it if you want one.

A: This type of solution you want is not exists in CakePHP right now. But you could create a new Form Helper i mean Custom method in Helper to override this method and create a new attribute in helper method like:
<?php echo $this->MyForm->input("stage", array("multiple" => "checkbox", "options" => $_stages, 'editable' => $editables));?>

For which you can get editable options using another find('list', array('fields' => array('id', 'editable') ));


text:
Q: Simplifying a Geometric Series with Two Power Terms
I have derived a geometric series below that I want to simplify but keep making a mess. Can anyone help?
  $$s = aq^{n-1}r^{0} + aq^{n-2}r^{1} + \dotsb + aq^{1}r^{n-2} + aq^{0}r^{n-1}$$

I get the following, but I know it's wrong
$$s = \frac{aq^{n-1} - (ar^{n})/q}{1 - (r/q)}$$

A: Note that
\begin{align}
S & = aq^{n-1}r^{0} + aq^{n-2}r^{1} + \cdots + aq^{1}r^{n-2} + aq^{0}r^{n-1}\\
& = aq^{n-1}\left(1+\frac{r}{q}+ \cdots  +\frac{r^{n-1}}{q^{n-1}}\right)\\
& = aq^{n-1} \frac{1-\frac{r^n}{q^n}}{1-\frac{r}{q}} \\
& = a\frac{q^n-r^n}{q-r}.
\end{align}

A: HINT
Recall that we have
$$A^n-B^n=(A-B)(A^{n-1}+A^{n-2}B+\ldots+AB^{n-2}+B^{n-1})$$
and therefore
$$A^{n-1}+A^{n-2}B+\ldots+AB^{n-2}+B^{n-1}=\frac{A^n-B^n}{A-B}=A^{n-1}\frac{1-\left(\frac B A\right)^n}{1-\frac B A}$$

A: Hint:
Use the high-school formula:
$$a^n-b^n=(a-b)(a^{n-1}+a^{n-2}b+\dots+ab^{n-2}+b^{n-1}). $$

A: To find the common ratio (and prove that it is common, and hence a geometric series), divide two successive terms:
$$\frac{aq^{n-1-(k+1)}r^{k+1}}{aq^{n-1-k}r^k} = \frac{r}{q}.$$
Note that this doesn't depend on $n$, so the ratio is common between all terms. The initial term is $aq^{n-1}$, and there are $n$ terms, so the sum is,
$$s = aq^{n-1} \frac{\left(\frac{r}{q}\right)^n - 1}{\frac{r}{q} - 1} = aq\frac{qr^n - 1}{r - q}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: "False reasoning" psychiatric term I am looking for a one word English equivalent for "false reasoning" of schizophrenia patients. There are two type of this - one is non pathological when low-educated people explain some phenomenon on a base of their own limited knowledge. The second type, is pathological - when people explain phenomenon as a consequence of a disease.
Thanks.

A: Could fallacy be the word you are looking for?

an incorrect or misleading notion or opinion based on inaccurate facts or invalid reasoning
2. unsound or invalid reasoning
3. the tendency to mislead
4. (Logic) logic an error in reasoning that renders an argument logically invalid
[C15: from Latin fallācia, from fallax deceitful, from fallere to deceive].

NOTE: having had another look at your question and having thought this through a bit, I'd say delusion is a better option as it applies to both states described (source: Merriam-Webster Online Dictionary):

a. a belief that is not true, a false idea
b. a false idea or belief caused by mental illness.

A: I think delirium can  be used to refer to   what you are describing:

*

*A temporary state of mental confusion and fluctuating consciousness resulting from high fever, intoxication, shock, or other causes. It is characterized by anxiety, disorientation, hallucinations, delusions, and incoherent speech.

Source: The American Heritage® Dictionary of the English Language.
Intrusive thoughts is another expression related to what you are asking. Intrusive thoughts may lead to delirium:

*

*An intrusive thought is a thought or image that pops into mind on a frequent, uncontrolled basis causing us distress, frustration, or upset. The intrusive thought could be anything that disturbs you, such as losing control, making a mistake, health worry, or unsettling thoughts about others. It is as if the more you try to block the thought or image out the more it comes back to hang you.

Source:http://www.spectrumhealth.ie/managing-intrusive-thoughts/


text:
Q: Upgrading neo4j minor version I have recently upgraded Neo4j from version 3.5 to version 4. The question is, in order to update Neo4j to the latest maintenance release, is it necessary to do all steps outlined in this link https://neo4j.com/docs/operations-manual/current/upgrade/, or it will be correct and sufficient to download the latest version and copy the data directory to the new Neo4j installation ?
The steps documented in the link has been done when moved from 3.5 to 4.0.3. I am going to update it from version 4.0.3 to version 4.0.4.

A: There is also a nice video from David Allen about the upgrade process
https://www.youtube.com/watch?v=GcaJ-aVLzr4


text:
Q: Does anyone know how to count the number of bytes in a string? If I have a string in JavaScript what's the best way to go about counting the number of bytes or bits the string takes up?
My first thought is that, since the EcmaScript spec (5.1) states in 8.4 that string elements in EcmaScript consist of 16 bits values, and that the languages uses UTF-16 character encoding, I should get the Decimal representation of that (charCodeAt), divide that by two, floor the result, and Bob's your father's brother.
But if I were to convert each character to binary (toString(2)), in order to count the bits, do I count the 0's as well as the 1's? Or just the 1's?
From what I've read online (and the information is sparse), I'm thinking it's something like:
Math.floor("A".charCodeAt(0) / 2); // 32 bits... No?

A: Um, if each element in the string is 16 bits, won't the number of bits the string takes up just be string.length * 16?

A:
@Charlie So 01000001 is simply 8 bits? Cool. Can you turn this into an
  answer so I can up vote it?

Exactly, see below.
You need to count both the 0's and 1's if someone asks you just to count the bits. Remember that "bit" is at heart a measure of information content. SO if you have a field that has an information content of 16 bits, that means there are 2^16 possible configurations, of which your current configuration is just one. Your bit string is one of those configurations, but you need the zeros to tell if from other configurations with 16 bits. – Charlie Martin yesterday

also, do you know of any good books on
  this? I'm self taught (until uni next year). :) – Tom yesterday

I don't, honestly.  I googled some, and I keep getting things that teach how to turn on the computer, something you've clearly already mastered.  You might try Think like a Computer Scientist.


text:
Q: Perl calling methods with and without parentheses Some Perl books advise using parentheses when calling class methods, saying this helps to keep the parser from having to guess the intent of the code.  However almost all Perl code I have seen (including modules on cpan) very rarely uses the parentheses when calling methods without arguments.
Is it normal to leave off those parentheses or should I always type them.
I wrote a small test code to measure the difference between calling a method with and without parentheses and it really shows a small difference between 1% and 2% for a class with two methods only. I imagine this could raise up if the class is large.
here is the test script I used to benchmark:
#!/usr/bin/perl

use Benchmark qw(:all);

{
    package Messages;

    sub new {
        my ($self) = @_;
        return bless {}, $self;
    }

    sub message {
        my ($self) = @_;
        return "Hello world";
    }

    sub another {
        my ($self) = @_;
        return "Another Hello world";
    }
}

my $class = Messages->new();

cmpthese(10_000_000, {
    'with   ()  ' => sub { $class->message() },
    'without    ()  ' => sub { $class->message },
});

and this is the results of the benchmark:
                 Rate       without ()       with ()
without ()      3320053/s          --         -1%
with    ()      3338898/s          1%          --

I imagine if the application uses hundreds of modules and each module has hundreds of methods called without parentheses, should this adds up a lot of speed difference?
If so, why everyone is coding without parentheses?.

A: The 1% difference is system noise. Both version compile to exactly the same bytecode, so there can't be a systematic difference between them. Use whichever variant makes your code easier to read.
If you want to see what it compiles to, you can do that like this:
perl -MO=Concise -E '$foo->bar()'

A: I'm not sure the 1% time difference is all that meaningful, and I doubt you'd be able to measure any difference in a real program.
Some people think it looks neater without () at the end of a method-call. That's enough justification. You'll see it with functions too.
For me, I try to do so when I want to imply "no parameters required here". Mostly just with attribute getters and such.
If a method can take optional parameters and they're just being defaulted then I prefer not to, so I can distinguish between "no parameters required" and "I haven't supplied parameters, but could have".

A: There's some history here. If you don't want to read it all, know that the () resolve a particular parsing thing that lets Perl know that you're using a subroutine and not a bareword. I tend to always use () for empty argument lists. I'm curious which Perl books you think make that advice though.
What am I?
Perl uses sigils to denote namespaces (and access, but put that aside). Scalars have $, arrays have @, and so on. Before Perl 5, subroutines had & (and along with that had a crypto context). There's a difference between these two:
&uses_current_stack;  # subroutine uses the current @_
&no_arguments();      # subroutine with no arguments

Perl 5 did away with the need for an explicit & before subroutine calls. That allows for two more possibilities, one of which is now ambiguous:
&uses_current_stack;  # subroutine uses the current @_
&no_arguments();      # subroutine with no arguments
bareword;             # maybe a subroutine?
subroutine();         # subroutine with no arguments

That bareword might be a subroutine, but maybe it isn't. It depends on things that may have happened far away from its use.
This program compiles just fine, but as you see in the decompilation, Perl doesn't quite know what foo is:
$ perl -MO=Deparse -e 'foo'
'???';
-e syntax OK

This is the same problem even if the subroutine definition shows up later:
$ perl -MO=Deparse -e 'foo; sub foo { print 1 }'
'???';
sub foo {
    print(1);
}
-e syntax OK

If you forward declare that foo will be a subroutine name. Now the parser has a hint about what to do even though you never actually define the subroutine. A subroutine doesn't need a definition until you call it, and Perl is a dynamic language so that definition may show up later. You can also forward declare the subroutine but having its definition show up before its use (although most people put the subroutine definitions at the bottom of a program, out of the way):
$ perl -MO=Deparse -e 'use subs qw(foo); foo'
use subs ('foo');
foo();
-e syntax OK

$ perl -MO=Deparse -e 'sub foo { print 1 }  foo'
sub foo {
    print(1);
}
foo();
-e syntax OK

Arity
There's another thing to know about Perl. You can leave off the parentheses on subroutine calls, and Perl will try to figure out if the next tokens are arguments for that subroutine.
Consider a print, which takes a list of arguments. So, all of these become arguments to print:
print 1, 2, 3, 4, 5;   # 12345

But some things take a set number of arguments, rand knows it takes one argument. Where there was 4, there's now the result of rand. The 5 still comes from the 5 argument:
print 1, 2, 3, rand 4, 5; # 1232.764206311960175

It's easier for many people to read to use parens to denote the the reader what Perl already knows:
print 1, 2, 3, rand(4), 5; # 1232.764206311960175

Now consider functions that take a range of arguments, such as split. There's the pattern to use, the target string, and a maximum number of items. All of those arguments are optional though.
split;                # split on whitespace on $_, unlimited
split /\h+/;          # split on horizontal whitespace on $_, unlimited
split /\h+/, $var;    # same, with $var
split /\h+/, $var, 2; # split into limited number of items
split /\h+/, $var, 2; # split into limited number of items
split /\h+/, $var, 2, $arg; # oops

So now, looking at this, what do we intend for split? Turns out this is a trick because split complains about too many arguments:
print 1, 2, split /\./, '1.2.3.4', 4, 5;  # error

Parentheses resolve that:
print 1, 2, split( /\./, '1.2.3.4' ), 4, 5;

Or maybe you wanted to work on $_:
print 1, 2, split( /\./ ), '1.2.3.4', 4, 5;

It seems like a silly case, but more complicated examples boil down to the same thing.
On to methods
Perl methods always require parentheses around a non-zero list of arguments:
$invocant->method( 1, 2, 3 );

As an aside, Raku has the method colon to grab everything after it as arguments. I didn't like this at first, but now I miss it in Perl 5:
$invocant->method: 1, 2, 3;  # Raku

Perl does not require parens around zero arguments to a method, so either of these are fine:
$invocant->method();
$invocant->method;

The thing after the -> is the method, and arguments go in parentheses. There's no guessing there.
But, Perl being a dynamic language has another trick. You can have a method name in a variable and use that variable on the right side of the ->. This now requires the () again, even for an empty argument list:
my $method = 'some_sub';
$invocant->$method();

Wrapping up
But, you know that Perl 4 had this & going on and not using parens did the weird default argument thing, so you used () to make the empty argument list. And, you remember that there's the long range effects. So some people use () to denote what they want. Others are more comfortable knowing what Perl's going to do.
From that, some people like to do things the same everywhere. So even though one case might not need it, since they are doing that somewhere else, they do even when it's not needed. Other don't don't care as much.
In something like Learning Perl, we know you're going to see a lot of different things so we show a lot of different things. There's the code you write, but there's also the code you didn't write but have to read.

A: Because you can. Really. I think.
As Perl allows so much, people are using it. Sometimes for the good, as you are able to write very complicated stuff in short sequences, and sometimes for the worse as it often gets complicated (especially for people new to Perl).
As well it depends on what your program does. The difference should be only on compile time (I assume). Often times compile time is a short part of the full application lifecicle, where it doesn't matter so much.

A: I think there's a systematic error in your measurement. When I run your code, without    () beats  with   () every single time. But when I use strings of the same length in cmpthese e.g.:
cmpthese(10_000_000, {
    'with    ()' => sub { $class->message() },
    'without ()' => sub { $class->message },
});

I got these (rather expected) results:
                Rate with    () without ()
with    () 3412969/s         --        -1%
without () 3460208/s         1%         --

                Rate without () with    ()
without () 2994012/s         --        -0%
with    () 3003003/s         0%         --

                Rate without () with    ()
without () 3278689/s         --        -1%
with    () 3300330/s         1%         --

                Rate with    () without ()
with    () 3039514/s         --        -2%
without () 3105590/s         2%         --

                Rate without () with    ()
without () 3267974/s         --        -3%
with    () 3378378/s         3%         --

So I think it's only about the best practices.


text:
Q: SDL 2.0 Keyboard input issues When I try to Poll a keydown event in SDL 2.0 and hold down a key, I get multiple keydown events, one after the other. When I try running the same program using SDL 1.2.15 (with minor changes as SDL 1.2.15 does not support SDL_Window), I do not have this issue. The keydown event only occurs once like it is supposed to. I even tried executing the program on a different computer to make sure that it was not a computer specific issue.
The relevant code is as follows:
#include <iostream>
#include <SDL.h>
using namespace std;

SDL_Event event;
SDL_Window* screen = NULL;
int main(int argc, char* args[])
{
    if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        cout << "ERROR INIT";
        return 0;
    }
    screen = SDL_CreateWindow("My Game Window",
                          SDL_WINDOWPOS_UNDEFINED,
                          SDL_WINDOWPOS_UNDEFINED,
                          640, 480,
                          SDL_WINDOW_OPENGL);

    bool quit = false;
    while(!quit)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_KEYDOWN)
            {
                cout << "KEY PRESSED!" << endl;
            }
        }
    }
    return 0;
}

A: Ignore SDL_KEYDOWN events where event.key.repeat != 0.


text:
Q: ScrollView doesn't work in RefreshView .net Maui I have a ScrollView in my .net Maui application. It contains a RefreshView with a CollectionView. It worked fine but yesterday it doesn't scroll anymore.
Here a video of the issue: https://de.files.fm/u/3rhsdu786
I tested the ScrollView with some Frames and it worked, so there must be a problem with the RefreshView or with the combination. I also tried to create a new page and inserted the old code but it also didn't work.
Here is my xaml code:
<ScrollView>
        <StackLayout>
            <!--Der Frame ist Visible, wenn für den Tag eine für den Schüler betreffende Nachricht existiert ansonsten bleibt diese Nachricht unsichtbar-->
            <Button Text="Neue Nachrichten unter Aktuelles!" Command="{Binding OnMessage}" IsVisible="{Binding IsVisibleInfo}" CornerRadius="30" Margin="0,15,0,0" HorizontalOptions="Center"/>

            <Frame IsVisible="{Binding IsVisibleNoAlert}" HorizontalOptions="Center" BackgroundColor="Transparent">
                <StackLayout VerticalOptions="Start" HorizontalOptions="Center">
                    <Label Text="Keine Vertretung!" FontSize="Title" HorizontalTextAlignment="Center" VerticalOptions="Start" Margin="10"/>
                    <Label Text="Heute hast du keine Vertretung. Dein Tag findet ganz normal statt." HorizontalTextAlignment="Center"/>
                    <Label Text="{Binding Status}" HorizontalOptions="Center" Margin="20" TextColor="Gray" VerticalOptions="StartAndExpand" IsVisible="{Binding IsVisibleNoAlert}"/>
                </StackLayout>
            </Frame>

            <RefreshView x:DataType="vm:TodayViewModel" Command="{Binding LoadStandInsCommand}" IsRefreshing="{Binding IsBusy, Mode=TwoWay}" IsEnabled="{Binding RefreshIsEnabled}" Margin="30,10,30,30">
                <StackLayout Orientation="Vertical">
                    <Label Text="{Binding Status}" HorizontalOptions="Center" TextColor="Gray" VerticalOptions="StartAndExpand" IsVisible="{Binding IsVisibleView}"/>
                    <CollectionView ItemsSource="{Binding StandIns}" SelectionMode="None" IsVisible="{Binding IsVisibleView}">
                        <CollectionView.ItemTemplate>
                            <DataTemplate>
                                <StackLayout x:DataType="model:StandIn" Margin="0,10,0,10">
                                    <Frame HeightRequest="110" BackgroundColor="{AppThemeBinding Light={StaticResource WhiteMode2nd}, Dark={StaticResource DarkMode2nd}}" BorderColor="{Binding Color}" CornerRadius="10">
                                        <StackLayout Margin="-20" Orientation="Horizontal">
                                            <Line BackgroundColor="{Binding Color}" HeightRequest="170" WidthRequest="5" HorizontalOptions="Start"/>
                                            <Grid HorizontalOptions="FillAndExpand" Margin="10,5,10,5">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="*"/>
                                                    <RowDefinition Height="*"/>
                                                    <RowDefinition Height="0.75*"/>
                                                </Grid.RowDefinitions>
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="0.7*"/>
                                                    <ColumnDefinition Width="0.3*"/>
                                                </Grid.ColumnDefinitions>
                                                <Label Text="{Binding Stunde}" Style="{StaticResource LableStyleStandIn}"  Margin="5,0,0,0"/>
                                                <Label Text="{Binding Fach}" Style="{StaticResource LableStyleStandIn}" Grid.Row="1"/>
                                                <Label Text="{Binding Art}" FontSize="17" Style="{StaticResource LableStyleStandIn}" Grid.Row="2"/>
                                                <Label Text="{Binding Raum}" Style="{StaticResource LableStyleStandIn}" Grid.Column="1" Grid.Row="1"/>
                                                <Label Text="{Binding Lehrer}" FontSize="17" Style="{StaticResource LableStyleStandIn}" Grid.Column="1" Grid.Row="2"/>
                                            </Grid>
                                        </StackLayout>
                                    </Frame>
                                </StackLayout>
                            </DataTemplate>
                        </CollectionView.ItemTemplate>
                    </CollectionView>
                </StackLayout>
            </RefreshView>
        </StackLayout>
    </ScrollView>

    <!--Der Button um in die Refreshview entweder die Vertretung für heute oder morgen zu laden-->
    <Frame Style="{StaticResource ButtonStyleSwitchDay}" >
        <Grid Margin="-15">
            <Button Command="{Binding ChangeSide}" Background="Transparent" BorderColor="Transparent"/>
            <Image Source="{Binding ButtonImageDay}"/>
        </Grid>
    </Frame>
</Grid>

The ViewModel workes fine, so there is no problem with it.
Thanks for helping me.

A: Credits: ewerspej
RefreshView must be on the outside and ScrollView on the inside like below:
<RefreshView >
    <ScrollView>

        ````
    </ScrollView>
</RefreshView>

Ref: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/refreshview?view=net-maui-7.0


text:
Q: Is dynamically creating object stores on indexeddb good? I'm new to indexeddb. Consider I have a unique page. That page will have tons of records or objects(50k+) which I have to save. So if I put all those records from different pages to one object store, does this affect the query performance? (consider the store is indexed)
Another option is creating object stores dynamically and querying the corresponding object stores. So I just tried that with dexie.
https://jsfiddle.net/sju8vj5h/
var storeName = "s"+new Date().valueOf();
var stores = {};
stores[storeName] = '++id,name,age';
var db = new Dexie("MyFriendDB");
db.version(1).stores(stores);

But this doesn't work on running 2nd time. I found that, to add a store dynamically need to change the version and the upgrade will trigger.
So is this a good pattern to add object stores dynamically?
I have already read IndexedDB - Dexie JS : Dynamically create stores but that didn't help for this situation.


text:
Q: not able to call jquery ajax I understand this question might be the same. I have googled, unfortunately i might have have missed something similar. I apologies for the same.
I have created a dynamic table in js based on some json response and updated the table accordingly. Now i have a submit button which posts currently selected raw data as an ajax call. But i am unable to call jquery.
Following are the codes :
JS :
$(document).ready(function(){
$('#ajax-button').click(function() {
    var formData=$("#careers").serialize();
    console.log("This is the skills : "+formData);
        $.ajax({
            type : "POST",
            url : "currentopening",
            //data : "skills="+skills,
            data:formData,
            dataType : "json",
            async: true,
            success : function(response) {
                var obj = JSON.parse(response);

                console.log("length of json response : "+obj.length)
                if(obj.length>0){
                //for (var i = 0; i < obj.length; i++)
                //{
                    console.log("the characteristics : "+obj[0].title);
                    addRow(obj);
                //}
                }
                else{
                    document.getElementById("dynamictable").innerHTML="No jobs found!";
                }
            }
        });
    });

});function addRow(obj) {

var table_1 = document.getElementById("dynamictable");

for(var i=0;i<obj.length;i++){

var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
btn.id="apply-button";

var input = document.createElement("input");
input.setAttribute("id",obj[i].jobID);
input.setAttribute("type", "hidden");
input.setAttribute("name", "jobID");
input.setAttribute("value", obj[i].jobID);

var rowCount = table_1.getElementsByTagName("tr").length;

var row1 = table_1.insertRow(rowCount);
row1.id="x";

var cell0=row1.insertCell(0);
var cell1=row1.insertCell(1);
var cell2=row1.insertCell(2);
var cell3=row1.insertCell(3);
var cell4=row1.insertCell(4);
var cell5=row1.insertCell(5);
var cell6=row1.insertCell(6);
var cell7=row1.insertCell(7);
var cell8=row1.insertCell(8);
var cell9=row1.insertCell(9);

cell0.headers="title"; cell1.headers="qualification"; cell2.headers="salary"; cell3.headers="companyName"; cell4.headers="tags"; cell5.headers="location";
cell6.headers="experience"; cell7.headers="aboutCompany";cell8.id="hidden-element";
cell9.id="doit";

cell0.innerHTML= obj[i].title;
cell1.innerHTML= obj[i].qualification;
cell2.innerHTML= obj[i].salary;
cell3.innerHTML= obj[i].companyName;
cell4.innerHTML= obj[i].tags;
cell5.innerHTML= obj[i].location;
cell6.innerHTML= obj[i].experience;
cell7.innerHTML= obj[i].aboutCompany;
document.getElementById("doit").appendChild(btn);
document.getElementById("hidden-element").appendChild(input);}};$('#apply-button').click(function() {
console.log("id of current element : ");
    var formData=document.getElementById(this);
    console.log("id of current element : "+formData);
    //console.log("This is the filter : "+formData);
        $.ajax({
            type : "GET",
            url : "apply",
            //data : "skills="+skills,
            data:"jobID="+formData,
            dataType : "text",
            async: true,
            success : function(response) {console.log("The response : "+response);

            }
        });
    });

I suspect that since id apply-button is created dynamically and it is not under document.load  function, my button is not able to work.Please let me know if more information is required.
I would appreciate a response on this.

A: You need to include event.preventDefault()
$(document).on("click", "#ajax-button", function (event) {
  ...
  ...
  ...
  event.preventDefault();
}

This stops the form from submitting, which is the default action on a submit button on a form, and it's why your page is getting refreshed.
Edit:
As mentioned in the comments, since the form is being dynamically generated, you will need a delegator, not a binding. Above code has been revised.

A: Alternatively, you can try
$().click(){
    return false;
}

Stop execution of post back


text:
Q: How to prevent AWS RDS instances from changing AZs after Multi AZ true/false I have an RDS instance that has a waiting required OS update, So I decided to open Multi AZ while applying the update. Update is finished, everything is fine, but I realized that AWS RDS instance is staying in us-east-1b, I was using us-east-1a. I closed the Multi AZ and configured DB as single AZ again, but my AZ config wasn't be applied back. it's still in us-east-1b. However,  most of my resources are in us-east-1a and I don't want to pay for extra inter-AZ networking cost.
Is there a workaround for this,
Any help will be highly appreciated,
Thank you very much.

A: AWs doesn't give the option to choose in which zone to create seconday rds. If you can have a maintenace period of let's say 1 hour(depends on how big is the RDS), you can create the db from snapshot in the AZ of your choice but if it's not possible, the only option is to change to MultiAZ and hope the secondary DB is created in us-east-1a. Once you have it here, turn off MultiAZ.

A: *

*Tur on multiAZ again

*Restart database with force failover parameter.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RebootInstance.html

*Turn off multiAZ

A: You can create DB subnet zone in your preferred AZ, then create a snapshot of your database. From the snapshot you can restore a new database and assign the  create subnet group while restoring that database which will create your instance in AZ of your choice. Hope this resolves your issue!


text:
Q: Adding a formula field in the Visualforce email template I have a formula field on custom object called "RE_Opps with AccountID". This formula field is a link to one of the reports. The formula goes like this
IF(
  Regional_Account_Assigned__c,
    HYPERLINK("/00O130000090Ae6","Opportunity Report"),
  HYPERLINK("/00O130000090AdD?pv0="&Customer_Account__c,"Opportunity Report")
)

I have created an email template which holds the details on the custom object except  "RE_Opps with AccountID". I want this field to be shown in email like an output link. Can someone tell me how to do it.

RE_Opps with AccountID:
      <apex:outputlink
              value="{!LEFT($Api.Partner_Server_URL_140,
                       FIND('.com',$Api.Partner_Server_URL_140)+4) +
                       relatedTo.RE_Opps_with_AccountID__c}">
                             {!relatedTo.RE_Opps_with_AccountID__c}
      </apex:outputlink>

I tried it this way but it doesn't work. Any help is appreciated.

A: You will need an intermediate formula field that is the /reportId?params
Report_URL__c = IF (Regional_Account_Assigned__c,
                    "/00O130000090Ae6",
                    "/00O130000090AdD?pv0=" & Customer_Account__c
                    )

and change your hyperlink formula field to:
HYPERLINK(Report_URL__c,"Opportunity Report")

then, your Email template can use:

RE_Opps with AccountID:
  <apex:outputlink
          value="{!LEFT($Api.Partner_Server_URL_370,
                   FIND('.com',$Api.Partner_Server_URL_370)+4) +
                   relatedTo.Report_URL__c}">
                        Opportunity Report
  </apex:outputlink>

This all presumes the recipient is a Salesforce user.  Non-users can't view SFDC reports


text:
Q: How to integrate lush with j2me Polish 2.1.4 I am working on j2me polish 2.1.4 and I want to use LUSH UI for symbian mobile application development. I could not find anything in my current version of j2me polish.
When I use the css from the website (http://www.enough.de/products/j2me-polish/documentation/lush-ui/visual-guide-to-backgrounds/gui-background-partial.html) it gives me the following error:
D:\Mobile development\rising\build.xml:87: Invalid CSS: The CSS setting "type: horizontal-gradient;" is not supported. Please check style "recordbg" in your "polish.css" file(s).
BUILD FAILED (total time: 6 seconds).

A: I have found the answer of my own question.
Actually Lush UI is already integrated into J2me Polish and I was doing a mistake, I was using nested property of CSS for the main property so I was receiving this error.


text: Q: TypeORM createConnection takes long time We have a lambda function running for multi-tenants, and we noticed from time to time the createConnection call takes 3-4 seconds. Could that be related to typeorm having to parse all entity definitions when creating new connections (which doesn't make sense to me) or there are other reasons that could make it to take such a long time?


text:
Q: Erro selecionar texto com o mouse, Formulários dentro de tabcontrol Encontrei uma solução elegante em como trabalhar com MDI Tabbed Interface, estou criando em tempo de execução um tabcontrol dentro do meu form MDI, e estou criando uma nova aba para cada formulário. da forma citada abaixo !
form.TopLevel = false;
superTabControlPanel.Controls.Add(form);
form.Show();
form.BringToFront();

Porém já rodei toda a internet e tentei vários posts e nenhum deu realmente certo, o Formulário é adicionado corretamente, porem ao tentar selecionar algum texto dentro de um textbox usando o mouse, simplesmente não da certo, eu só consigo selecionar texto se eu retirar as bordas do formulário, e eu não queria fazer isso, agradeço desde já !


text:
Q: the meaning of the phrase: "she sucks badly at it" What does the phrase: "she sucks badly at it" mean?
My hypotheses are:

*

*She doesn't like it

*She is bad at doing it

It is a passage from the Emily Giffin's book "Where We Belong".
If you need more context here it is:

"My dad typically picks up the story from there, telling me how he cut himself shaving, his hands shaking so much that he almost let my mother drive to the hospital, something he never does because she sucks so badly at it. Then he skips ahead to the papers they hurriedly signed, and the moment the lady from the agency returned with a baby—me—swaddled in a pink fleece blanket."

A: OP's option 2 is correct.  idiomeaning.com defines it as:

to be terrible at something

In this instance, their definition is correct.


text:
Q: When to say that system has converged, in case of distance vector routing protocol? I understand that distance vector routing protocol is a distributed version of Bellman-Ford algorithm.
It is used to find the shortest-path from every node to every other node in the network.
So, every node advertises it's routing table information (computed distances to all other nodes in the network) to its neighbors and at the same learns from the neighboring nodes.
So, my question is how long does these advertisement keeps happening between the neighbors? ie, since this is a distributed system, how does each node gets to know that the entire system has converged and I should stop advertising.
Like in case of Bellman-Ford (centralized) algorithm, we can say that convergence has happened when the number of iteration is equal to one shy of number of edges in the graph (one shy of number of links in the network), and we can stop the algorithm execution...

A: Little bit of more learning on the topic and search different article brought me to this below conclusion.
Below is the excerpt from Wikipedia - https://en.wikipedia.org/wiki/Distance-vector_routing_protocol#Example

None of the routers have any new shortest-paths to broadcast.
  Therefore, none of the routers receive any new information that might
  change their routing tables. The algorithm comes to a stop.

So what this indicates is - In the distributed network using distance vector protocol, the nodes stop advertising the information when there is no more change to their estimated shortest-path distance. And at this stage, you can call the distributed network has got converged.

*

*The node in the network starts advertising its initial table (which will contain the distance information to the directly connected nodes) once it is part of the network.

*And it keeps advertising the distance information to its neighbors until there is change to its table.

A: Periodically Routers send distance vectors  to neighbours ,, it updates only if the new information present in the distance vector by comparing with old distance vector of neighbour v which is already present at the  router... There is no stopping of algorithm...


text:
Q: Rolling Standard Deviation of past n days (weekday vs week-end) I have a df as follows:
Date       Day of Week Value
01/02/2022 Sunday      35666
01/03/2022 Monday      38945
01/04/2022 Tuesday     39411
01/05/2022 Wednesday   40058

Essentially, I would like to be computing Averages of Values based on weekday (Monday to Friday) versus week-end (Saturday to Sunday) and their respecting Standard Deviations.
I have been trying to use group by and rolling averages, but I am not sure how to be doing this to establish a limit of past n days (say, 3 months/quarter).
Thank you in advance!

A: The first thing to do when you work with time data is to change the column type to datetime with pandas.to_datetime. Then you can create a new column to indicate if the day is on the weekend :
df["is_weekend"] = df["Date"].apply(lambda row: 0 if row.day_of_week in range(0, 5) else 1)

With this new column, you can use pandas.DataFrame.rolling with pandas.DataFrame.mean and pandas.DataFrame.std


text:
Q: Parsing JSON in R: lexical error - invalid char in json text I have a file ("my_file") in R that looks something like this:
  NAME                                                                                Address_Parse
1 name1 [('372', 'StreetNumber'), ('river', 'StreetName'), ('St', 'StreetType'), ('S', 'StreetDirection'), ('toronto', 'Municipality'), ('ON', 'Province'), ('A1C', 'PostalCode'), ('9R7', 'PostalCode')]
2 name2 [('208', 'StreetNumber'), ('ocean', 'StreetName'), ('St', 'StreetType'), ('E', 'StreetDirection'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('J8N', 'PostalCode'), ('1G8', 'PostalCode')]

In case the structure is confusing, here is how the file looks like
my_file = structure(list(NAME = c("name1", "name2"), Address_Parse = c("[('372', 'StreetNumber'), ('river', 'StreetName'), ('St', 'StreetType'), ('S', 'StreetDirection'), ('toronto', 'Municipality'), ('ON', 'Province'), ('A1C', 'PostalCode'), ('9R7', 'PostalCode')]",
"[('208', 'StreetNumber'), ('ocean', 'StreetName'), ('St', 'StreetType'), ('E', 'StreetDirection'), ('Toronto', 'Municipality'), ('ON', 'Province'), ('J8N', 'PostalCode'), ('1G8', 'PostalCode')]"
)), class = "data.frame", row.names = c(NA, -2L))

Objective: For each row, I would like to take each of the "elements" (e.g. "StreetNumber", "StreetName", "StreetType", etc.) and convert it into a new column. This would look something like this:
   name StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode
1 name1          372      river         St               S      toronto       ON     A1C9R7
2 name2          208      ocean         St               E      Toronto       ON     J8N1G8

To me, it appears that the address field is in JSON format (I could be wrong about this). I tried to look at different ways I could parse the JSON. For example, I tried to apply the answer provided here (R: convert nested JSON in a data frame column to addtional columns in the same data frame):
library(dplyr)
library(tidyr)
library(purrr)
library(jsonlite)

final = my_file %>%
  mutate(
    json_parsed = map(Address_Parse, ~ fromJSON(., flatten=TRUE))
  ) %>%
  unnest(json_parsed)

However, this is giving me the following error:
Error in `mutate()`:
! Problem while computing `json_parsed = map(Address_Parse, ~fromJSON(., flatten = TRUE))`.
Caused by error:
! lexical error: invalid char in json text.
                                      [('372', 'StreetNumber'), ('rive
                     (right here) ------^
Run `rlang::last_error()` to see where the error occurred.

I then tried another approach:
final <- my_file %>%
          rowwise() %>%
          do(data.frame(fromJSON(.$Address_Parse , flatten = T))) %>%
          ungroup() %>%
          bind_cols(my_file  %>% select(-Address_Parse ))

But I now get a new error:
Error: lexical error: invalid char in json text.
                                      [('372', 'StreetNumber'), ('rive
                     (right here) ------^

Can someone please show me to resolve this?
Thank you!

A: You might have to rejig the formatting of the JSON slightly to get it to work.
I've used the stream_in function instead of fromJSON as it is usually quicker and takes care of a lot of stuff somewhat automatically.
library(jsonlite)
out <- stream_in(textConnection(chartr("()'", '[]"', my_file$Address_Parse)))
s <- seq(1, ncol(out)/2)
setNames(out[s], unlist(out[1, -s]))

#  StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode PostalCode
#1          372      river         St               S      toronto       ON        A1C        9R7
#2          208      ocean         St               E      Toronto       ON        J8N        1G8

A: We may need some modifications in the text before using fromJSON - i.e. keep the format as "key":value instead of (value, 'key') and also insert the {, } after, before the [, ]
library(dplyr)
library(purrr)
library(stringr)
library(jsonlite)
library(tidyr)
my_file  %>%
  mutate(Address_Parse = str_replace_all(Address_Parse,
      "\\(([^,]+),\\s*([^)]+)\\)", "\\2:\\1") %>%
   str_replace(fixed("["), "[{") %>%
   str_replace(fixed("]"), "}]") %>%
   str_replace_all(fixed("'"), '"') %>%
   map(fromJSON)) %>%
   unnest(Address_Parse) %>%
 type.convert(as.is = TRUE)

-output
 A tibble: 2 × 8
  NAME  StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode
  <chr>        <int> <chr>      <chr>      <chr>           <chr>        <chr>    <chr>
1 name1          372 river      St         S               toronto      ON       A1C
2 name2          208 ocean      St         E               Toronto      ON       J8N

Or using reticulate as it seems to be tuple
library(reticulate)
py_run_string(paste0("tmp=", paste(my_file$Address_Parse,
            collapse = ",")))
out <- cbind(my_file[1], do.call(rbind, lapply(py$tmp, \(x)
  do.call(cbind, lapply(x, \(y) setNames(data.frame(y[[1]]),
    y[[2]]))))))

-output
> out
   NAME StreetNumber StreetName StreetType StreetDirection Municipality Province PostalCode PostalCode
1 name1          372      river         St               S      toronto       ON        A1C        9R7
2 name2          208      ocean         St               E      Toronto       ON        J8N        1G8


text:
Q: System of algebraic equations concerning rates I'm not even sure where to start on the problem. Is this possible to solve without logarithms?
"A certain type of bacteria doubles every 6.5 hours. If there were 60 bacteria to start with, what is the hourly growth rate of the bacteria? How many bacteria will there be after a day and a half? Solve using algebra."


text:
Q: Save file outside the root directory vb.net Hi I am developing web application in vb.net. I was facing problem while uploading my file from client side to the server side folder using this code
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim ext As String = System.IO.Path.GetExtension(fileName)
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/EmployeeSignature/../../") + "IMG12345" & ext)

Here is root and target folders structure

Here is my site internal structure (UploadingTest)

Problem is that at this line
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/EmployeeSignature/../../") + "IMG12345" & ext)

I am getting error message
Cannot use a leading .. to exit above the top directory.

My requirement is to save file above the root directory , try alot but unable to solve problem , Kindly suggest any solution! Thanks

A: You can't use .. in the logical path to step outside the folder of your web root when you use MapPath to convert it. Move those outside the MapPath call:
Server.MapPath("~") + "\..\EmployeeSignature\IMG12345" + ext

A: In IIS, Add Virtual Directories inside you Website

*

*EmployeeSignature

*Images

Now you can access the folders using below code
HttpContext.Current.Server.MapPath("EmployeeSignatures")
HttpContext.Current.Server.MapPath("Images")


text:
Q: Serve vue-cli project with valet I'm trying to serve a local website using valet, but unsuccessfully.
vue create my-project
cd my-project

If I serve the project with:
npm run serve

I get the default page with Vue logo.
But if I serve the project using valet (with park or link option), I get a blank page.
How can I serve vue-cli project using valet ?

A: While this doesn't work with vue-cli-service serve, I have found a workaround that works with build.
You can serve static sites using this driver.
After installing the driver:
$ cd my-vue-project
$ yarn build

$ cd dist
$ touch static
$ valet link acme
$ mkdir public
$ mv ./* public

You can then view the built Vue site at http://acme.test.  The downside is needing to rebuild everytime you make a change, but it works for testing when needed.


text:
Q: No visible @interface for 'RTCPeerConnection' declares the selector 'setLocalDescription:' I'm a little confused on what needs to be done here to include webRTC into my app. I followed this tutorial on the webRTC website to add webRTC onto my IOS app first. Everything went well until the end where i came across these errors. Unfortunately, I can not find any information online about these errors or how to include webRTC on IOS.
The end goal is to have a cross-platform video calling service.
.h
#import "RTCPeerConnectionDelegate.h"
#import "RTCSessionDescriptionDelegate.h"
...

<RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate>

.m
    #import "RTCICEServer.h"
    #import "RTCPeerConnectionFactory.h"
    #import "RTCMediaStream.h"
    #import "RTCVideoCapturer.h"
    #import "RTCPeerConnection.h"
    #import "RTCAudioSource.h"
    #import "RTCAudioTrack.h"
    #import "RTCMediaConstraints.h"
    #import "RTCSessionDescription.h"
    #import "RTCPair.h"
    #import "RTCEAGLVideoView.h"
    #import "RTCICECandidate.h"

    //The code below is for the webRTC

RTCICEServer *iceServer;
RTCMediaConstraints *constraints;
RTCPeerConnection *peerConnectionRTC;

- (void) setUpVideoCall{
    //Set up for my TURN and STUN servers
    iceServer = [[RTCICEServer alloc] initWithURI:[NSURL URLWithString:@""]
                                                   username:@""
                                                   password:@""];

    NSMutableArray *iceServers = [[NSMutableArray alloc] init];
    [iceServers addObject: iceServer];

    //Creating the RTCPeerConnection
    // Enable SSL globally for WebRTC in our app
    [RTCPeerConnectionFactory initializeSSL];
    RTCPeerConnectionFactory *pcFactory = [[RTCPeerConnectionFactory alloc] init];

    // Create the peer connection using the ICE server list and the current class as the delegate
    peerConnectionRTC = [pcFactory peerConnectionWithICEServers: iceServers
                                                                       constraints:nil delegate:self];

    //Use this code when the call is ended or the app closes
    //[RTCPeerConnectionFactory deinitializeSSL];

    RTCMediaStream *localStream = [pcFactory mediaStreamWithLabel:@"uniqueStreamLabel"];
    RTCAudioTrack *audioTrack = [pcFactory audioTrackWithID:@"audio0"];
    [localStream addAudioTrack:audioTrack];

    // Find the device that is the front facing camera
    AVCaptureDevice *device;
    for (AVCaptureDevice *captureDevice in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] ) {
        if (captureDevice.position == AVCaptureDevicePositionFront) {
            device = captureDevice;
            break;
        }
    }

    // Create a video track and add it to the media stream
    if (device) {
        RTCVideoSource *videoSource;
        RTCVideoCapturer *capturer = [RTCVideoCapturer capturerWithDeviceName:device.localizedName];
        videoSource = [pcFactory videoSourceWithCapturer:capturer constraints:nil];
        RTCVideoTrack *videoTrack = [pcFactory videoTrackWithID: @"videoId" source:videoSource];
        [localStream addVideoTrack:videoTrack];
    }

    [peerConnectionRTC addStream:localStream];

    constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:
    @[
      [[RTCPair alloc] initWithKey:@"OfferToReceiveAudio" value:@"true"],
      [[RTCPair alloc] initWithKey:@"OfferToReceiveVideo" value:@"true"]
      ]
optionalConstraints: nil];

    //[peerConnectionRTC createOfferWithConstraints:constraints];

}

//The two delaget methods below are for the RTCSessionDescriptionDelegate
- (void)peerConnection:(RTCPeerConnection *)peerConnection didCreateSessionDescription:(RTCSessionDescription *)sdp error:(NSError *)error;{

    [peerConnection setLocalDescription:sdp];

}

- (void)peerConnection:(RTCPeerConnection *)peerConnection
didSetSessionDescriptionWithError:(NSError *)error;{
    if (peerConnection.signalingState == RTCSignalingHaveLocalOffer) {
        RTCSessionDescription *remoteDesc = [[RTCSessionDescription alloc] initWithType:@"offer" sdp: @"sdp"];
        [peerConnection setRemoteDescription:remoteDesc];
    }

    // If we have a local offer we should signal it
    if (peerConnection.signalingState == RTCSignalingHaveLocalOffer) {

        RTCSessionDescription *remoteDesc = [[RTCSessionDescription alloc] initWithType:@"answer" sdp:sdp];
        [peerConnection setRemoteDescription:remoteDesc];

    } else if (peerConnection.signalingState == RTCSignalingHaveRemoteOffer) {
        // If we have a remote offer we should add it to the peer connection
        [peerConnection createAnswerWithConstraints:constraints];
    }

    // If we have a local offer OR answer we should signal it
    if ((peerConnection.signalingState == RTCSignalingHaveLocalOffer) | RTCSignalingHaveLocalPrAnswer ) {
        // Send offer/answer through the signaling channel of our application
    } else if (peerConnection.signalingState == RTCSignalingHaveRemoteOffer) {
        // If we have a remote offer we should add it to the peer connection
        [peerConnection createAnswerWithConstraints:constraints];
    }
}

- (void)peerConnection:(RTCPeerConnection *)peerConnection
       gotICECandidate:(RTCICECandidate *)candidate
{
    RTCICECandidate *candidate = [[RTCICECandidate alloc] initWithMid:SDP_MID
                                                                index:SDP_M_LINE_INDEX
                                                                  sdp:SDP_CANDIDATE];
    [self.rtcPeerConnection addICECandidate:candidate];
}

RTCEAGLVideoView *renderView;
- (void)peerConnection:(RTCPeerConnection *)peerConnection addedStream:(RTCMediaStream *)stream
{
    // Create a new render view with a size of your choice
    renderView = [[RTCEAGLVideoView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [stream.videoTracks.lastObject addRenderer:self.renderView];

    // RTCEAGLVideoView is a subclass of UIView, so renderView
    // can be inserted into your view hierarchy where it suits your application.
}

//More RTC delagate methods below that i need

- (void)peerConnection:(RTCPeerConnection *)peerConnection iceConnectionChanged:(RTCICEConnectionState)newState{

}

- (void)peerConnection:(RTCPeerConnection *)peerConnection iceGatheringChanged:(RTCICEGatheringState)newState{

}

- (void)peerConnection:(RTCPeerConnection *)peerConnection removedStream:(RTCMediaStream *)stream{

}

- (void)peerConnection:(RTCPeerConnection *)peerConnection signalingStateChanged:(RTCSignalingState)stateChanged{

}

- (void)peerConnection:(RTCPeerConnection *)peerConnection didOpenDataChannel:(RTCDataChannel *)dataChannel{

}

- (void)peerConnectionOnRenegotiationNeeded:(RTCPeerConnection *)peerConnection{

}

Any help is appreciated and information like documentation or tutorials are very helpful! Thank you!

A: You are getting compilation error because with latest libjingle version, peerconnection apis got change. e.g Setting remote description changed to below api
    [peerconnection setRemoteDescriptionWithDelegate:<#(id<RTCSessionDescriptionDelegate>)#> sessionDescription:<#(RTCSessionDescription *)#>]

You can check apprtc demo app provided by google to integrate webrtc apis in your app.


text:
Q: Replace string values in a list with similar values R This question is related to  Replace the string value with value in the find list in R.  However my string and replacement vectors have similar characters:
replacement = c("10deg AC45", "10deg TA45", "15deg AC45", "AC45", "TA45")
string = c("10deg - 02 AC45", ""10deg -05 AC45" , "10deg-02 AC45", "10deg-05 TA45", "15deg-10 AC45", "AC45-10", "TA45-1")

Hence trying:
replaced=string
replaced=''

for (i in 1:length(replacement))
{
  replaced[which(grepl(replacement[i],string))]=replacement[i]
}
replaced[is.na(replaced)]=''

Results in:
[1] "AC45", "AC45", "AC45" "TA45" "AC45" "AC45" "TA45"

Rather than:
"10deg AC45","10deg AC45", "10deg AC45", "10deg TA45", "15deg AC45", "AC45", "TA45"
Any suggestions?
Thanks


text:
Q: Minimum Node+Express+TypeScript With Angular. I got "CORS policy" problem I'm new in this area. I start with Node+Typescript example on local. Hear the code:
import express from 'express';
const app = express();

var counter: number=0;

app.get('/', (req, res) => {res.send('Hello World! ${counter}' + counter.toString()); counter++;} );

app.listen(3000, () => console.log('Example app listening on port 3000!'));

As well I wrote some Angular code for client:
@Component({
  selector: 'test',
  template: '
Simple Http: {{counter}}
<button (click)="onClickMe()">Click me!</button>'
})
export class test {
  counter: any="Not yet";

  constructor(private http: HttpClient) { }

  onClickMe() {
    this.counter = 'Try read from server..';
    this.http.get("http://localhost:3000/").subscribe(val=>this.counter=val);
  }
}

I run the client by npm: "ng serve" at http://localhost:4200/
I got error:

Access to XMLHttpRequest at 'http://localhost:3000/' from origin
  'http://localhost:4200' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

I understand there is library named "cors". But I not sure how install it with Typescript or how use with it.

A: Thanks all. I add hear fixed minimum code and instruction for Angule+Node+Express for get data by HttpClient. I wrote it simple as possible.
The server code (Base on Node+Express starter)
import express from 'express';
import cors from 'cors';

const app = express();

var counter: number=0;

app.get('/', cors() ,(req, res) => {res.json({ counter: `${counter}`}); counter++;} );

app.listen(3000, () => console.log('Example app listening on port 3000!'));

Notice, you should install cors:
npm install cors

You also may want install type script for it (it's not required)
npm install @types/cors

Now, build and run the node project:
npm run-script build
npm start

Now add follow code to your angular project:
import { Component } from '@angular/core';
import { HttpClient, HttpHandler, HttpRequest, HttpEvent } from '@angular/common/http';

@Component({
  selector: 'TestHttp',
  template: '
Simple Http: {{counter}}
<button (click)="onClickMe()">Click me!</button>'
})
export class TestHttp {
  counter: number=null;

  constructor(private http: HttpClient) { }

  onClickMe() {
    this.counter = -1;
    let obs: any = this.http.get("http://localhost:3000/");
    obs.subscribe(val=>this.counter=val['counter']);
  }
}

As you can see, this example call http from in view component. This is wrong pattern. But it's show how is simple to use with Http against the server.
Also, this example not use directly with Injectable or Observable (rxjs). And even not use with pipe function to retrieve the data. It's just inject the HttpClient by add it as constructor parameter, and add provide in app.module.ts:
providers: [HttpClient]

A: You have to configure and enable cors in your server side, in this case, in NodeJs. In Express docs you have a complete tutorial of how to do this with Express. It is quite simple:

*

*Install cors with npm install cors

*Instantiate cors in your index.js file with var cors = require('cors')

*Finally, apply cors to your entiry API with app.use(cors())
There are plenty of options and configurations within the docs, check them out!
Hope it helps!

A: Or you could do it without cors library.
Just by setting headers in middleware:
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

So your code on the server will look like this:
import express from 'express';
const app = express();

var counter: number=0;

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

app.get('/', (req, res) => {res.send('Hello World! ${counter}' + counter.toString()); counter++;} );

app.listen(3000, () => console.log('Example app listening on port 3000!'));

The reason why are getting CORS warning is that because of the security reasons your server shouldn't allow data to some other website (in your case it's two different ports which are exactly as two different websites)
More info you could read there: https://www.html5rocks.com/en/tutorials/cors/#toc-introduction
Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?


text:
Q: Connecting UNIX through VB and return the results for the commands fired in a variable I tried connecting UNIX from visual basic but unable create a connection object like we can do with other programming Languages like Java/python.
I tried some commands like Call Shell etc but really not getting anywhere closer .
please point to the right direction with this issue .
Thanks in Advance :>


text:
Q: Search Filters with pagination? I have a database that is being used to keep track of customer information and equipment.  I've have a working search page that merges all the data together into a readable format.  It is set to displays only one result per page.
I'm trying to add filtering into the search.  This way if you're only searching for the Last Name it won't waste time searching though the equipment database.  It will only search the Last Name field from the Customers table.  I've got that to work the problem is the when the next page is pressed it gets zero results.
I have an idea why its happening.  It's because I'm using isset with checkboxes to do the filters.
$SLastName = $_GET['LastName'];
$SFirstName = $_GET['FirstName'];
$SAddress = $_GET['Address'];
$SAP = $_GET['AP'];
$SEquipment = $_GET['Equipment'];
$SEverything = $_GET['Everything'];

if (isset($SLastName)){
        $construct .="(customers.LastName LIKE '%$search_each%')";
        if (isset($SFirstName)){
        $construct .=" OR (customers.FirstName LIKE '%$search_each%')";
        }
        if (isset($SAddress)){
        $construct .=" OR (customers.Address LIKE '%$search_each%')";
        }
        if (isset($SAP)){
        $construct .=" OR (aps.AP LIKE '%$search_each%')";
        }
        if (isset($SEquipment)){
        $construct .=" OR (equipment.ESN LIKE '%$search_each%')
                OR (equipment.WMAC LIKE '%$search_each%')
                OR (equipment.SN LIKE '%$search_each%')
                OR (equipment.Manufacturer LIKE '%$search_each%')";
        }
        if (isset($SEverything)){
        $construct .=" OR (customers.Account LIKE '%$search_each%')
                OR (customers.AlternatePhone LIKE '%$search_each%')
                OR (customers.Phone LIKE '%$search_each%')
                OR (routableip.routable_IP LIKE '%$search_each%')
                OR (unitip.UNITIP_new LIKE '%$search_each%')";
        }
    }
    else if(isset($SFirstName)){
        $construct .="(customers.FirstName LIKE '%$search_each%')";
        if (isset($SAddress)){
        $construct .=" OR (customers.Address LIKE '%$search_each%')";
        }
        if (isset($SAP)){
        $construct .=" OR (aps.AP LIKE '%$search_each%')";
        }
        if (isset($SEquipment)){
        $construct .=" OR (equipment.ESN LIKE '%$search_each%')
                OR (equipment.WMAC LIKE '%$search_each%')
                OR (equipment.SN LIKE '%$search_each%')
                OR (equipment.Manufacturer LIKE '%$search_each%')";
        }
    }
    else if(isset($SAddress)){
        $construct .="(customers.Address LIKE '%$search_each%')";
        if (isset($SAP)){
        $construct .=" OR (aps.AP LIKE '%$search_each%')";
        }
        if (isset($SEquipment)){
        $construct .=" OR (equipment.ESN LIKE '%$search_each%')
                OR (equipment.WMAC LIKE '%$search_each%')
                OR (equipment.SN LIKE '%$search_each%')
                OR (equipment.Manufacturer LIKE '%$search_each%')";
        }
    }
    else if(isset($SAP)){
        $construct .="(aps.AP LIKE '%$search_each%')";
        if (isset($SEquipment)){
        $construct .=" OR (equipment.ESN LIKE '%$search_each%')
                OR (equipment.WMAC LIKE '%$search_each%')
                OR (equipment.SN LIKE '%$search_each%')
                OR (equipment.Manufacturer LIKE '%$search_each%')";
        }
    }
    else if(isset($SEquipment)){
        $construct .="(equipment.ESN LIKE '%$search_each%')
                OR (equipment.WMAC LIKE '%$search_each%')
                OR (equipment.SN LIKE '%$search_each%')
                OR (equipment.Manufacturer LIKE '%$search_each%')";
}

The search input page uses checkboxes. The boxes are checked on the submit page to see what fields are set. The set fields determine what the sql is going to be.
Like I said this works fine for finding the first result.
Here the parts of my code pertaining to the pagination.
$start = isset($_GET['start']) ? $_GET['start']: '';
    $max_pages = ceil($foundnum / $per_page);

    if(!$start)
        $start=0;

//Pagination Starts
        $prev = $start - $per_page;
        $next = $start + $per_page;
        $adjacents = 3;
        $last = $max_pages - 1;

        if($max_pages > 1){
        //previous button
            if (!($start<=0)) {
                $PrevButton .= "Prev ";
            }
            else{
                $PrevButton .= "Prev ";
            }
            $current =$next;

        //next button
        if (!($start >=$foundnum-$per_page)){
            $NextButton = "Next";
        }
        else {
            $NextButton = "Next ";
        }
        }

For example if I search for the Last name Smith.  It will show result 1 of 10.  Then when I press the next button it comes up with the error I have built in for when it does not find any results with the searched keyword.
I think what is happening is when the next button is pressed it changes the GET url to show page 2 but when that happens it looses the value of the search sql because it does not see that $SLastName isset anymore.
I'm lost on how to fix this.

A: Yes you Right you have to store your search keyword in a session variable and from there you can get keyword in any page and on the basis of that you have to run your query hope this will help you


text:
Q: In Durandal how can you get a handle to the active VM in debug or developer tool console? Building an app with Duranrdal for the first time and I'd like to be able to use the chrome developer tools console to inspect values of my view models on various pages as they are loaded.
the problem is there is no window.Durandal or window.MainApp that i can see.  I could do this in main.js define function:
window.myApp = app;

but that seems like a hack, and it doesn't really get me a handle to the current viewmodel.  I thought about just doing similar code in the router, but this is also really ugly.
Is my app & current VM accessable in some clearner way? perhaps the require.js when it loads the modules puts that reference on the dom somewhere? I suppose if i can get a handle to the router i'd be ok.
I'm also interested in getting a handle to the VM backing a modal dialog..not sure if you can get to that off the router or some other piece.

A: In chrome developer tools you can put break points in your viewmodels and step through the code.  Also, durandal logs your viewmodel objects that have been composed to the console.log so you can see the state at which they were bound to a view.
Here is another way which is just making use of the mechanics of requirejs to get a reference to your viewmodel object programmatically.  Just type something like this into your chrome console:
require(['durandal/pluggins/router','yourViewModel'], function (router, vm) {
    // here you can do whatever you want now to your router or vm.
    vm.someproperty('changed');
    router.activateRoute('page2');
});

You can even make a global reference to the objects you want to change by doing this in the console:
require(['durandal/pluggins/router','yourViewModel'], function (router, vm) {
    window.TestVM = vm;
    window.router = router;
});

Then you can access those objects like so:
TestVM.someproperty('changed');
router.activateRoute('page2');

A: In the console just enter:
viewmodel = require('viewmodels/myviewmodel')


text:
Q: How to add epics asynchronously? I am able to add asynchronous reducer, but unable to add asynchronous epics
Following this link Adding New Epics Asynchronously, I tried using epic$.next() but was unable to add new epic.
import { applyMiddleware, createStore, compose } from 'redux';
import { createEpicMiddleware, combineEpics } from 'redux-observable';
import { BehaviorSubject } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import createReducer from '../reducers';
import mainEpic from '../config/epics';

Middleware configuration is given below:
const epicMiddleware = createEpicMiddleware();

const epic$ = new BehaviorSubject(mainEpic);
const rootEpic = (action$, state$) =>
  epic$.pipe(mergeMap(epic => epic(action$, state$)));

Store Enhancers for redux dev tools
const composeEnhancers =
  // compose;
  process.env.NODE_ENV === 'development' &&
  window.navigator.platform !== 'iPad' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    : compose;

This is the instantiation of store
export default () => {
  const store = createStore(
    createReducer(),
    composeEnhancers(applyMiddleware(epicMiddleware))
  );

  epicMiddleware.run(rootEpic);

  // Extra functionality to the store
  store.asyncReducers = {};

Here, I call injectRepics (Repics for reducer and epics) with parameters key, reducer, newEpic when new component is bound asynchronously
  store.injectRepics = (key, reducer, newEpic) => {
    if (!store.getState()[key]) {

      // here I get newEpic
      console.log(newEpic);

      // new reducer is added to asyncreducer object
      store.asyncReducers[key] = reducer;
      // new reducer is created and replaced
      store.replaceReducer(createReducer(store.asyncReducers));

      // -------------------------------------
            But, I'm unable to replace epic
      // -------------------------------------
      newEpic && epic$.next(newEpic);

      // epicMiddleware.run(rootEpic);
      // newEpic && addNewEpic(newEpic);
    }
  };

  return store;
};

A: There was a simple mistake.
I forgot to add combineEpics in new epic.
So, the code becomes newEpic && epic$.next(combineEpics(...newEpic))


text:
Q: Android Gradle 3.0.0 - add library dependency for specific flavors My app includes a library and a 3 flavor debug, release and custom.
I don't want my app to include the library in 'custom' flavor
Prior to gradle 3.0 I used :
releaseCompile project(path: ':myLib', configuration: "release")
debugCompile project(path: ':..:myLib', configuration: "debug")
// 'custom' ignored

according to google migrate to android plugin for 3.0 I need to use implementation keyword with matchingFallbacks for 'custom' flavor.
I don't want to use 'matchingFallbacks' because I don't want my app to include the lib in 'custom' flavor.
Any idea how can I compile the lib only in debug and release?
edit
maybe its possible to add 'if' statement i.e:
if(flavor != custom){
    implementation project 'myLib'
}

A: I think you can achieve it by using something like this:
dependencies {
   // use only mylib for debug and release
   releaseImplementation project(path: ':mylib')
   debugImplementation project(path: ':mylib')

   // this will be used by all the flavor
   implementation "com.android.support:appcompat-v7:27.0.2'
}


text:
Q: How to find all commits having a particular parent? How may I find all commits in a repository that have a specific parent?
For example, if I have a commit A, I would like to find all other commits that share the parent with A. What would be the most effective, i.e. performant yet correct way to do this in LibGit2Sharp?

A: That's a tricky question ;-)
The Git object allows to retrieve the parents of a commit. However, there's no easy way to find the children of a commit.
The following code would however partially solve this. The idea is to perform a git log from all the references of the repository (heads, tags, ...) and, along the way, select every commit which bear a parent with the requested SHA.
As the walk is being done from the most recent commits down the ancestor path, it may take some time, if you're searching for the children of a very early commit in a repository with a very large history and many branches.
[Fact]
public void CanRetrieveChildrenOfASpecificCommit()
{
    TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoPath);
    using (var repo = new Repository(path.RepositoryPath))
    {
        const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";

        var filter = new Filter
                         {
                             /* Revwalk from all the refs (git log --all) ... */
                             Since = repo.Refs,

                             /* ... and stop when the parent is reached */
                             Until = parentSha
                         };

        var commits = repo.Commits.QueryBy(filter);

        var children = from c in commits
                    from p in c.Parents
                    let pId = p.Id
                    where pId.Sha == parentSha
                    select c;

        var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd",
                                        "4a202b346bb0fb0db7eff3cffeb3c70babbd2045" };

        Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha));
    }
}

Limits:

*

*This will not retrieve commits that have been rewritten (through amend or rebase, for instance) as LibGit2Sharp doesn't expose a way to access the reflog (yet)

*Unreachable (dangling) commits won't either be retrieved with this proposal.

Test repository:
The content of the repository being queried is show below
$ git log --all --graph
* commit 4c062a6361ae6959e06292c1fa5e2822d9c96345
| Author: gor <gorbach.alexey@gmail.com>
| Date:   Thu Apr 14 18:44:16 2011 +0300
|
|     directory was added
|
*   commit be3563ae3f795b2b4353bcce3a527ad0a4f7f644
|\  Merge: 9fd738e c47800c
| | Author: Scott Chacon <schacon@gmail.com>
| | Date:   Tue May 25 11:58:27 2010 -0700
| |
| |     Merge branch 'br2'
| |
| | * commit e90810b8df3e80c413d903f631643c716887138d
| | | Author: Vicent Marti <tanoku@gmail.com>
| | | Date:   Thu Aug 5 18:42:20 2010 +0200
| | |
| | |     Test commit 2
| | |
| | * commit 6dcf9bf7541ee10456529833502442f385010c3d
| |   Author: Vicent Marti <tanoku@gmail.com>
| |   Date:   Thu Aug 5 18:41:33 2010 +0200
| |
| |       Test commit 1
| |
| | *   commit a4a7dce85cf63874e984719f4fdd239f5145052f
| | |\  Merge: c47800c 9fd738e
| |/ /  Author: Scott Chacon <schacon@gmail.com>
| | /   Date:   Tue May 25 12:00:23 2010 -0700
| |/
|/|         Merge branch 'master' into br2
| |
* | commit 9fd738e8f7967c078dceed8190330fc8648ee56a
| | Author: Scott Chacon <schacon@gmail.com>
| | Date:   Mon May 24 10:19:19 2010 -0700
| |
| |     a fourth commit
| |
* | commit 4a202b346bb0fb0db7eff3cffeb3c70babbd2045
| | Author: Scott Chacon <schacon@gmail.com>
| | Date:   Mon May 24 10:19:04 2010 -0700
| |
| |     a third commit
| |
| * commit c47800c7266a2be04c571c04d5a6614691ea99bd
|/  Author: Scott Chacon <schacon@gmail.com>
|   Date:   Tue May 25 11:58:14 2010 -0700
|
|       branch commit one
|
* commit 5b5b025afb0b4c913b4c338a42934a3863bf3644
| Author: Scott Chacon <schacon@gmail.com>
| Date:   Tue May 11 13:38:42 2010 -0700
|
|     another commit
|
* commit 8496071c1b46c854b31185ea97743be6a8774479
  Author: Scott Chacon <schacon@gmail.com>
  Date:   Sat May 8 16:13:06 2010 -0700

      testing

* commit 41bc8c69075bbdb46c5c6f0566cc8cc5b46e8bd9
| Author: Scott Chacon <schacon@gmail.com>
| Date:   Tue May 11 13:40:41 2010 -0700
|
|     packed commit two
|
* commit 5001298e0c09ad9c34e4249bc5801c75e9754fa5
  Author: Scott Chacon <schacon@gmail.com>
  Date:   Tue May 11 13:40:23 2010 -0700

      packed commit one

A: This worked for me (replace $CHILD_COMMIT with your actual commit):
for commit in `git rev-list --all`; do echo "$commit <- `git log --pretty=%P -n 1 $commit`" | grep $CHILD_COMMIT; done

it will find all refs where the commit is a child or a parent in child <- parent1 parent2... format


text:
Q: Pyspark 3.0.1 to 3.2.1 dataframe write functions error out with: attribute "_fill_function" not found I'm not very experienced with tuning spark, and all of its nuances, but I've upgrade my spark cluster from 3.0.1 to 3.2.1 and upgraded pyspark to 3.2.1 in the python code. After these changes, we can't write our spark dataframes to postgresql. This is the error that I'm seeing:
  File "/usr/spark/python/lib/pyspark.zip/pyspark/worker.py", line 586, in main
    func, profiler, deserializer, serializer = read_command(pickleSer, infile)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/worker.py", line 69, in read_command
    command = serializer._read_with_length(file)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 160, in _read_with_length
    return self.loads(obj)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 430, in loads
    return pickle.loads(obj, encoding=encoding)
AttributeError: Can't get attribute '_fill_function' on <module 'pyspark.cloudpickle' from '/usr/spark/python/lib/pyspark.zip/pyspark/cloudpickle/__init__.py'>
        at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:517)
        at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:652)
        at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:635)
        at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:470)
        at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:489)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage3.processNext(Unknown Source)
        at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
        at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:755)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:132)
        at org.apache.spark.shuffle.ShuffleWriteProcessor.write(ShuffleWriteProcessor.scala:59)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:52)
        at org.apache.spark.scheduler.Task.run(Task.scala:131)
        at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:498)
        at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1439)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:501)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
2022-05-27 15:06:50,779 ERROR scheduler.TaskSetManager: Task 1 in stage 3.0 failed 4 times; aborting job

: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 3.0 failed 4 times, most recent failure: Lost task 1.3 in stage 3.0 (TID 208) (10.244.2.32 executor 2):                                                 org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/spark/python/lib/pyspark.zip/pyspark/worker.py", line 586, in main
    func, profiler, deserializer, serializer = read_command(pickleSer, infile)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/worker.py", line 69, in read_command
    command = serializer._read_with_length(file)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 160, in _read_with_length
    return self.loads(obj)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 430, in loads
    return pickle.loads(obj, encoding=encoding)
AttributeError: Can't get attribute '_fill_function' on <module 'pyspark.cloudpickle' from '/usr/spark/python/lib/pyspark.zip/pyspark/cloudpickle/__init__.py'>
        at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:517)
        at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:652)
        at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:635)
        at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:470)
        at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:489)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage3.processNext(Unknown Source)
        at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
        at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:755)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:132)
        at org.apache.spark.shuffle.ShuffleWriteProcessor.write(ShuffleWriteProcessor.scala:59)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:52)
        at org.apache.spark.scheduler.Task.run(Task.scala:131)
        at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:498)
        at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1439)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:501)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Driver stacktrace:
        at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:2303)
        at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:2252)
        at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:2251)
        at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
        at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
        at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
        at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:2251)
        at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1(DAGScheduler.scala:1124)
        at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1$adapted(DAGScheduler.scala:1124)
        at scala.Option.foreach(Option.scala:407)
        at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:1124)
        at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2490)
        at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2432)
        at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2421)
        at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
        at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:902)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:2196)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:2217)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:2236)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:2261)
        at org.apache.spark.rdd.RDD.$anonfun$foreachPartition$1(RDD.scala:1020)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
        at org.apache.spark.rdd.RDD.withScope(RDD.scala:414)
        at org.apache.spark.rdd.RDD.foreachPartition(RDD.scala:1018)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$.saveTable(JdbcUtils.scala:854)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:82)
        at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:46)
        at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)
        at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)
        at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:90)
        at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:180)
        at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:218)
        at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
        at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:215)
        at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:176)
        at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:132)
        at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:131)
        at org.apache.spark.sql.DataFrameWriter.$anonfun$runCommand$1(DataFrameWriter.scala:989)
        at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:103)
        at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:163)
        at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:90)
        at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
        at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64)
        at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:989)
        at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:438)
        at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:415)
        at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:301)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/usr/spark/python/lib/pyspark.zip/pyspark/worker.py", line 586, in main
    func, profiler, deserializer, serializer = read_command(pickleSer, infile)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/worker.py", line 69, in read_command
    command = serializer._read_with_length(file)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 160, in _read_with_length
    return self.loads(obj)
  File "/usr/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 430, in loads
    return pickle.loads(obj, encoding=encoding)
AttributeError: Can't get attribute '_fill_function' on <module 'pyspark.cloudpickle' from '/usr/spark/python/lib/pyspark.zip/pyspark/cloudpickle/__init__.py'>
        at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.handlePythonException(PythonRunner.scala:517)
        at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:652)
        at org.apache.spark.api.python.PythonRunner$$anon$3.read(PythonRunner.scala:635)
        at org.apache.spark.api.python.BasePythonRunner$ReaderIterator.hasNext(PythonRunner.scala:470)
        at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:489)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage3.processNext(Unknown Source)
        at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
        at org.apache.spark.sql.execution.WholeStageCodegenExec$$anon$1.hasNext(WholeStageCodegenExec.scala:755)
        at scala.collection.Iterator$$anon$10.hasNext(Iterator.scala:458)
        at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:132)
        at org.apache.spark.shuffle.ShuffleWriteProcessor.write(ShuffleWriteProcessor.scala:59)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:99)
        at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:52)
        at org.apache.spark.scheduler.Task.run(Task.scala:131)
        at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:498)
        at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1439)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:501)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        ... 1 more
[INFO] 2022-05-27 15:06:50,971 [6bee0320-ddca-11ec-8da3-e278eeb7624f] NetworkConnectivity - ERROR
[INFO] 2022-05-27 15:06:50,971 [6bee0320-ddca-11ec-8da3-e278eeb7624f] NetworkConnectivity - Traceback (most recent call last):
  File "/src/analytic/jobs/main.py", line 144, in nc_main
    execute_raw_analytics(version_number, spark, log)
  File "/src/analytic/jobs/raw_analytics.py", line 273, in execute_raw_analytics
    calculate_population_stat(spark, log)
  File "/src/analytic/jobs/raw_analytics.py", line 449, in calculate_population_stat
    save_intermediate_data('final_distance', final_distance_df)
  File "/src/analytic/jobs/data_helper.py", line 433, in save_intermediate_data
    write_to_postgres_append(df, table_name)
  File "/usr/local/lib/python3.6/site-packages/analyticsframework/datastoreconnector/PostgresSqlSparkConnector.py", line 65, in write_to_postgres_append
    .mode("Append") \
  File "/usr/local/lib/python3.6/site-packages/pyspark/sql/readwriter.py", line 825, in save
    self._jwrite.save()
  File "/usr/local/lib/python3.6/site-packages/py4j/java_gateway.py", line 1305, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/usr/local/lib/python3.6/site-packages/pyspark/sql/utils.py", line 131, in deco
    return f(*a, **kw)
  File "/usr/local/lib/python3.6/site-packages/py4j/protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o185.save.

I've tried scaling down the memory and executor requests for the spark job. I've switch to a hadoop 3.3 and added it to my spark container, in an effort to resolve a different issue Spark 3.2.1 OOM.
We've kept the same spark config for since 2.4.3, to my knowledge.
config = SparkConf() \
        .setAppName(app_name) \
        .setMaster(spark_master_url) \
        .set("spark.driver.host", pod_ip) \
        .set("spark.executor.memory", '12g') \
        .set("spark.executor.cores", '2') \
        .set("spark.dynamicAllocation.enabled", True) \
        .set("spark.shuffle.service.enabled", True) \
        .set("spark.hadoop.fs.s3a.endpoint", minio['minio_host']) \
        .set("spark.hadoop.fs.s3a.connection.ssl.enabled", "false") \
        .set("spark.hadoop.fs.s3a.access.key", minio['access_key']) \
        .set("spark.hadoop.fs.s3a.secret.key", minio['secret_key']) \
        .set("spark.hadoop.fs.s3a.path.style.access", "true") \
        .set("spark.sql.execution.pyspark.udf.simplifiedTraceback.enabled" , "false")

This is the is the function we are using to write the dataframe to postgresql.
def write_to_postgres_append(dataset, db_table):
    """
    Write dataframe to postges database using Overwrite protocol
    :param dataset:Spark SQL Dataframe to be written to database
    :param db_table: Database table used for writing. Include schema (e.g. schema.table_name)
    :return: None
    """
    postgres_login = __get_postgres_login()
    postgres_url = __get_postgres_url()

    # stringtype unspecified  allows saving JSON directly to PostgreSQL
    dataset.write \
        .format("jdbc") \
        .option("url", postgres_url) \
        .option("dbtable", db_table) \
        .option("user", postgres_login.get('user')) \
        .option("password", postgres_login.get('password')) \
        .option("isolationLevel", "NONE") \
        .option("stringtype", "unspecified") \
        .mode("Append") \
        .save()

I've tried downgrading to spark 3.1.3, and still facing the same issue. I didn't see any property changes from 3.1 and 3.2 that seemed related to the issue we're seeing, but that could be due to my inexperience with spark.


text:
Q: How to stop the video if the slide has changed? I need to stop the video when the slide is changed. The current code reacts to changing the variable, but does not stop the video. I use Clappr ^0.3.3, Vue-cli ^3.5.0 and Swiper ^4.5.0.
I change the boolean value to use it for the trigger in the player:
data: () => ({
    slider_is_move: false,
}),

After request:
.then(() => {

    // init slider
    new Swiper('.content__slider', {
        // Note: I removed extra options
        on: {
            slideChange: function () {
                this.slider_is_move = true; // if slide is change

                setTimeout(() => {
                    this.slider_is_move = false; // set the previous value
                }, 1500);
            }
        }
    });

    // init clappr (video player)
    if ( document.querySelector('.content-video') ) {
        for (let i = 0; i < this.project_videos.length; i++) {
            new Clappr.Player({
                source: '/storage/' + this.project_videos[i],
                parentId: '#container_' + (this.project_images.length + i),
                mute: true,
                width: document.querySelector('.content-item').offsetWidth,
                height: document.querySelector('.content-item').offsetHeight,
                events: {
                    onPlay: () => {
                        setInterval(() => {
                            if (this.slider_is_move === true) {
                                this.pause();
                            }
                        }, 1000);
                    }
                }
            });
        }
    }

});

If I add a console.log(), the code will work as it should, but it will not stop the video.
onPlay: () => {
    setInterval(() => {
        if (this.slider_is_move === true) {
            this.pause();
        }
    }, 1000);
}

A: You should watch the data attribute slider_is_move, and react to any changes in the state.
watch: {
    slider_is_move: {
        handler(nowMoving) {
            if (nowMoving) {
                this.pause();
            }
        },
    }
}

A: To make the video stop when you change the slide, you need to add a few lines in the code:
add name to object
let player_video = new Clappr.Player...

and pause it
player_video.pause();